_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 |
|---|---|---|---|---|---|---|---|---|
32b6813f152da72a6e65965e1b8911c919242546f1a8bcfafe7398c03c421875 | vmchale/kempe | Module.hs | -- | Pretty easy since doesn't need renaming.
--
-- Just thread lexer state through, remove duplicates.
module Kempe.Module ( parseProcess
) where
import Control.Exception (Exception, throwIO)
import qualified Data.ByteString.Lazy as BSL
import qualified Data.ByteString.Lazy.Char8 as ASCII
import qualified Data.Set as S
import Data.Tuple.Ext (fst3, third3)
import Kempe.AST
import Kempe.Lexer
import Kempe.Parser
parseProcess :: FilePath -> IO (Int, Declarations AlexPosn AlexPosn AlexPosn)
parseProcess fp = do
(st, [], ds) <- loopFps True [fp] alexInitUserState
pure (fst3 st, {-# SCC "dedup" #-} dedup ds)
yeetIO :: Exception e => Either e a -> IO a
yeetIO = either throwIO pure
loopFps :: Bool -> [FilePath] -> AlexUserState -> IO (AlexUserState, [FilePath], Declarations AlexPosn AlexPosn AlexPosn)
loopFps _ [] st = pure (st, [], [])
loopFps isInit (fp:fps) st = do
(st', Module is ds) <- parseStep fp st
let discardDs = if isInit then id else filter (not . isExport)
third3 (++ discardDs ds) <$> loopFps False (fmap ASCII.unpack (reverse is) ++ fps) st'
where isExport Export{} = True
isExport _ = False
parseStep :: FilePath -> AlexUserState -> IO (AlexUserState, Module AlexPosn AlexPosn AlexPosn)
parseStep fp st = do
contents <- BSL.readFile fp
yeetIO $ parseWithCtx contents st
dedup :: Ord a => [a] -> [a]
dedup = loop S.empty
where loop _ [] = []
loop acc (x:xs) =
if S.member x acc
then loop acc xs
else x : loop (S.insert x acc) xs
| null | https://raw.githubusercontent.com/vmchale/kempe/071272d18ab6bccd4bb2c4a40aa6a0eda7ebec91/src/Kempe/Module.hs | haskell | | Pretty easy since doesn't need renaming.
Just thread lexer state through, remove duplicates.
# SCC "dedup" # | module Kempe.Module ( parseProcess
) where
import Control.Exception (Exception, throwIO)
import qualified Data.ByteString.Lazy as BSL
import qualified Data.ByteString.Lazy.Char8 as ASCII
import qualified Data.Set as S
import Data.Tuple.Ext (fst3, third3)
import Kempe.AST
import Kempe.Lexer
import Kempe.Parser
parseProcess :: FilePath -> IO (Int, Declarations AlexPosn AlexPosn AlexPosn)
parseProcess fp = do
(st, [], ds) <- loopFps True [fp] alexInitUserState
yeetIO :: Exception e => Either e a -> IO a
yeetIO = either throwIO pure
loopFps :: Bool -> [FilePath] -> AlexUserState -> IO (AlexUserState, [FilePath], Declarations AlexPosn AlexPosn AlexPosn)
loopFps _ [] st = pure (st, [], [])
loopFps isInit (fp:fps) st = do
(st', Module is ds) <- parseStep fp st
let discardDs = if isInit then id else filter (not . isExport)
third3 (++ discardDs ds) <$> loopFps False (fmap ASCII.unpack (reverse is) ++ fps) st'
where isExport Export{} = True
isExport _ = False
parseStep :: FilePath -> AlexUserState -> IO (AlexUserState, Module AlexPosn AlexPosn AlexPosn)
parseStep fp st = do
contents <- BSL.readFile fp
yeetIO $ parseWithCtx contents st
dedup :: Ord a => [a] -> [a]
dedup = loop S.empty
where loop _ [] = []
loop acc (x:xs) =
if S.member x acc
then loop acc xs
else x : loop (S.insert x acc) xs
|
0ad9fb4f80a70931a3bde8ca76c203deb26e29eee29941dbe46e36207a3e21f7 | input-output-hk/cardano-wallet | Internal.hs | {-# LANGUAGE GADTs #-}
# LANGUAGE LambdaCase #
HLINT ignore " Use camelCase "
-- |
Copyright : © 2022 IOHK
-- License: Apache-2.0
--
-- Computing minimum UTxO values: internal interface.
--
module Cardano.Wallet.Shelley.MinimumUTxO.Internal
( computeMinimumCoinForUTxO_CardanoApi
, computeMinimumCoinForUTxO_CardanoLedger
) where
import Prelude
import Cardano.Ledger.Shelley.API.Wallet
( evaluateMinLovelaceOutput )
import Cardano.Wallet.Primitive.Types.Coin
( Coin )
import Cardano.Wallet.Primitive.Types.MinimumUTxO
( MinimumUTxOForShelleyBasedEra (..) )
import Cardano.Wallet.Primitive.Types.Tx.TxOut
( TxOut )
import Cardano.Wallet.Shelley.Compatibility
( toCardanoTxOut, unsafeLovelaceToWalletCoin, unsafeValueToLovelace )
import Cardano.Wallet.Shelley.Compatibility.Ledger
( toAllegraTxOut
, toAlonzoTxOut
, toBabbageTxOut
, toMaryTxOut
, toShelleyTxOut
, toWalletCoin
)
import Data.Function
( (&) )
import GHC.Stack
( HasCallStack )
import qualified Cardano.Api.Shelley as Cardano
| Computes a minimum UTxO value with the Cardano API .
--
-- Caution:
--
This function does /not/ attempt to reach a fixed point before returning its
-- result.
--
computeMinimumCoinForUTxO_CardanoApi
:: HasCallStack
=> MinimumUTxOForShelleyBasedEra
-> TxOut
-> Coin
computeMinimumCoinForUTxO_CardanoApi
(MinimumUTxOForShelleyBasedEra era pp) txOut =
unsafeCoinFromResult $
Cardano.calculateMinimumUTxO era
(toCardanoTxOut era txOut)
(Cardano.fromLedgerPParams era pp)
where
unsafeCoinFromResult
:: Either Cardano.MinimumUTxOError Cardano.Value
-> Coin
unsafeCoinFromResult = \case
Right value ->
We assume that the returned value is a non - negative ada quantity
-- with no other assets. If this assumption is violated, we have no
-- way to continue, and must raise an error:
value
& unsafeValueToLovelace
& unsafeLovelaceToWalletCoin
Left e ->
The ' Cardano.calculateMinimumUTxO ' function should only return
-- an error if a required protocol parameter is missing.
--
However , given that values of ' MinimumUTxOForShelleyBasedEra '
-- can only be constructed by supplying an era-specific protocol
-- parameters record, it should be impossible to trigger this
-- condition.
--
-- Any violation of this assumption indicates a programming error.
-- If this condition is triggered, we have no way to continue, and
-- must raise an error:
--
error $ unwords
[ "computeMinimumCoinForUTxO_CardanoApi:"
, "unexpected error:"
, show e
]
| Computes a minimum UTxO value with .
--
-- Caution:
--
This function does /not/ attempt to reach a fixed point before returning its
-- result.
--
computeMinimumCoinForUTxO_CardanoLedger
:: MinimumUTxOForShelleyBasedEra
-> TxOut
-> Coin
computeMinimumCoinForUTxO_CardanoLedger
(MinimumUTxOForShelleyBasedEra era pp) txOut =
toWalletCoin $ case era of
Cardano.ShelleyBasedEraShelley ->
evaluateMinLovelaceOutput pp
$ toShelleyTxOut txOut
Cardano.ShelleyBasedEraAllegra ->
evaluateMinLovelaceOutput pp
$ toAllegraTxOut txOut
Cardano.ShelleyBasedEraMary ->
evaluateMinLovelaceOutput pp
$ toMaryTxOut txOut
Cardano.ShelleyBasedEraAlonzo ->
evaluateMinLovelaceOutput pp
$ toAlonzoTxOut txOut Nothing
Cardano.ShelleyBasedEraBabbage ->
evaluateMinLovelaceOutput pp
$ toBabbageTxOut txOut Nothing
| null | https://raw.githubusercontent.com/input-output-hk/cardano-wallet/18bc22ad0932e4e8b1b6eafee5edf99ac57126af/lib/wallet/src/Cardano/Wallet/Shelley/MinimumUTxO/Internal.hs | haskell | # LANGUAGE GADTs #
|
License: Apache-2.0
Computing minimum UTxO values: internal interface.
Caution:
result.
with no other assets. If this assumption is violated, we have no
way to continue, and must raise an error:
an error if a required protocol parameter is missing.
can only be constructed by supplying an era-specific protocol
parameters record, it should be impossible to trigger this
condition.
Any violation of this assumption indicates a programming error.
If this condition is triggered, we have no way to continue, and
must raise an error:
Caution:
result.
| # LANGUAGE LambdaCase #
HLINT ignore " Use camelCase "
Copyright : © 2022 IOHK
module Cardano.Wallet.Shelley.MinimumUTxO.Internal
( computeMinimumCoinForUTxO_CardanoApi
, computeMinimumCoinForUTxO_CardanoLedger
) where
import Prelude
import Cardano.Ledger.Shelley.API.Wallet
( evaluateMinLovelaceOutput )
import Cardano.Wallet.Primitive.Types.Coin
( Coin )
import Cardano.Wallet.Primitive.Types.MinimumUTxO
( MinimumUTxOForShelleyBasedEra (..) )
import Cardano.Wallet.Primitive.Types.Tx.TxOut
( TxOut )
import Cardano.Wallet.Shelley.Compatibility
( toCardanoTxOut, unsafeLovelaceToWalletCoin, unsafeValueToLovelace )
import Cardano.Wallet.Shelley.Compatibility.Ledger
( toAllegraTxOut
, toAlonzoTxOut
, toBabbageTxOut
, toMaryTxOut
, toShelleyTxOut
, toWalletCoin
)
import Data.Function
( (&) )
import GHC.Stack
( HasCallStack )
import qualified Cardano.Api.Shelley as Cardano
| Computes a minimum UTxO value with the Cardano API .
This function does /not/ attempt to reach a fixed point before returning its
computeMinimumCoinForUTxO_CardanoApi
:: HasCallStack
=> MinimumUTxOForShelleyBasedEra
-> TxOut
-> Coin
computeMinimumCoinForUTxO_CardanoApi
(MinimumUTxOForShelleyBasedEra era pp) txOut =
unsafeCoinFromResult $
Cardano.calculateMinimumUTxO era
(toCardanoTxOut era txOut)
(Cardano.fromLedgerPParams era pp)
where
unsafeCoinFromResult
:: Either Cardano.MinimumUTxOError Cardano.Value
-> Coin
unsafeCoinFromResult = \case
Right value ->
We assume that the returned value is a non - negative ada quantity
value
& unsafeValueToLovelace
& unsafeLovelaceToWalletCoin
Left e ->
The ' Cardano.calculateMinimumUTxO ' function should only return
However , given that values of ' MinimumUTxOForShelleyBasedEra '
error $ unwords
[ "computeMinimumCoinForUTxO_CardanoApi:"
, "unexpected error:"
, show e
]
| Computes a minimum UTxO value with .
This function does /not/ attempt to reach a fixed point before returning its
computeMinimumCoinForUTxO_CardanoLedger
:: MinimumUTxOForShelleyBasedEra
-> TxOut
-> Coin
computeMinimumCoinForUTxO_CardanoLedger
(MinimumUTxOForShelleyBasedEra era pp) txOut =
toWalletCoin $ case era of
Cardano.ShelleyBasedEraShelley ->
evaluateMinLovelaceOutput pp
$ toShelleyTxOut txOut
Cardano.ShelleyBasedEraAllegra ->
evaluateMinLovelaceOutput pp
$ toAllegraTxOut txOut
Cardano.ShelleyBasedEraMary ->
evaluateMinLovelaceOutput pp
$ toMaryTxOut txOut
Cardano.ShelleyBasedEraAlonzo ->
evaluateMinLovelaceOutput pp
$ toAlonzoTxOut txOut Nothing
Cardano.ShelleyBasedEraBabbage ->
evaluateMinLovelaceOutput pp
$ toBabbageTxOut txOut Nothing
|
473db2161a023bb47b95693ec06c98d5f129771de492283287044bef8d6902f8 | ghcjs/ghcjs-dom | FocusEvent.hs | # LANGUAGE PatternSynonyms #
# LANGUAGE ForeignFunctionInterface #
# LANGUAGE JavaScriptFFI #
-- For HasCallStack compatibility
{-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-}
module GHCJS.DOM.JSFFI.Generated.FocusEvent
(js_newFocusEvent, newFocusEvent, js_getRelatedTarget,
getRelatedTarget, getRelatedTargetUnsafe,
getRelatedTargetUnchecked, FocusEvent(..), gTypeFocusEvent)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import qualified Prelude (error)
import Data.Typeable (Typeable)
import GHCJS.Types (JSVal(..), JSString)
import GHCJS.Foreign (jsNull, jsUndefined)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSVal(..), FromJSVal(..))
import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..))
import Control.Monad (void)
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import Data.Maybe (fromJust)
import Data.Traversable (mapM)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import GHCJS.DOM.JSFFI.Generated.Enums
foreign import javascript unsafe
"new window[\"FocusEvent\"]($1, $2)" js_newFocusEvent ::
JSString -> Optional FocusEventInit -> IO FocusEvent
-- | <-US/docs/Web/API/FocusEvent Mozilla FocusEvent documentation>
newFocusEvent ::
(MonadIO m, ToJSString type') =>
type' -> Maybe FocusEventInit -> m FocusEvent
newFocusEvent type' eventInitDict
= liftIO
(js_newFocusEvent (toJSString type')
(maybeToOptional eventInitDict))
foreign import javascript unsafe "$1[\"relatedTarget\"]"
js_getRelatedTarget :: FocusEvent -> IO (Nullable EventTarget)
-- | <-US/docs/Web/API/FocusEvent.relatedTarget Mozilla FocusEvent.relatedTarget documentation>
getRelatedTarget ::
(MonadIO m) => FocusEvent -> m (Maybe EventTarget)
getRelatedTarget self
= liftIO (nullableToMaybe <$> (js_getRelatedTarget self))
-- | <-US/docs/Web/API/FocusEvent.relatedTarget Mozilla FocusEvent.relatedTarget documentation>
getRelatedTargetUnsafe ::
(MonadIO m, HasCallStack) => FocusEvent -> m EventTarget
getRelatedTargetUnsafe self
= liftIO
((nullableToMaybe <$> (js_getRelatedTarget self)) >>=
maybe (Prelude.error "Nothing to return") return)
-- | <-US/docs/Web/API/FocusEvent.relatedTarget Mozilla FocusEvent.relatedTarget documentation>
getRelatedTargetUnchecked ::
(MonadIO m) => FocusEvent -> m EventTarget
getRelatedTargetUnchecked self
= liftIO
(fromJust . nullableToMaybe <$> (js_getRelatedTarget self)) | null | https://raw.githubusercontent.com/ghcjs/ghcjs-dom/749963557d878d866be2d0184079836f367dd0ea/ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/FocusEvent.hs | haskell | For HasCallStack compatibility
# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #
| <-US/docs/Web/API/FocusEvent Mozilla FocusEvent documentation>
| <-US/docs/Web/API/FocusEvent.relatedTarget Mozilla FocusEvent.relatedTarget documentation>
| <-US/docs/Web/API/FocusEvent.relatedTarget Mozilla FocusEvent.relatedTarget documentation>
| <-US/docs/Web/API/FocusEvent.relatedTarget Mozilla FocusEvent.relatedTarget documentation> | # LANGUAGE PatternSynonyms #
# LANGUAGE ForeignFunctionInterface #
# LANGUAGE JavaScriptFFI #
module GHCJS.DOM.JSFFI.Generated.FocusEvent
(js_newFocusEvent, newFocusEvent, js_getRelatedTarget,
getRelatedTarget, getRelatedTargetUnsafe,
getRelatedTargetUnchecked, FocusEvent(..), gTypeFocusEvent)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import qualified Prelude (error)
import Data.Typeable (Typeable)
import GHCJS.Types (JSVal(..), JSString)
import GHCJS.Foreign (jsNull, jsUndefined)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSVal(..), FromJSVal(..))
import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..))
import Control.Monad (void)
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import Data.Maybe (fromJust)
import Data.Traversable (mapM)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import GHCJS.DOM.JSFFI.Generated.Enums
foreign import javascript unsafe
"new window[\"FocusEvent\"]($1, $2)" js_newFocusEvent ::
JSString -> Optional FocusEventInit -> IO FocusEvent
newFocusEvent ::
(MonadIO m, ToJSString type') =>
type' -> Maybe FocusEventInit -> m FocusEvent
newFocusEvent type' eventInitDict
= liftIO
(js_newFocusEvent (toJSString type')
(maybeToOptional eventInitDict))
foreign import javascript unsafe "$1[\"relatedTarget\"]"
js_getRelatedTarget :: FocusEvent -> IO (Nullable EventTarget)
getRelatedTarget ::
(MonadIO m) => FocusEvent -> m (Maybe EventTarget)
getRelatedTarget self
= liftIO (nullableToMaybe <$> (js_getRelatedTarget self))
getRelatedTargetUnsafe ::
(MonadIO m, HasCallStack) => FocusEvent -> m EventTarget
getRelatedTargetUnsafe self
= liftIO
((nullableToMaybe <$> (js_getRelatedTarget self)) >>=
maybe (Prelude.error "Nothing to return") return)
getRelatedTargetUnchecked ::
(MonadIO m) => FocusEvent -> m EventTarget
getRelatedTargetUnchecked self
= liftIO
(fromJust . nullableToMaybe <$> (js_getRelatedTarget self)) |
7166a51f41eea071f6fb1f43803d4f7846ba3bbd31127fa55598d698462b45de | dlowe-net/orcabot | brain.lisp | (category ("are you very *" what)
(reduce "are you *" what))
(category ("are you smart")
(say "I like to think I'm quite intelligent."))
(category ("are you alive")
(say "That's one of those philosophical questions, isn't it?"))
(category ("are you * person")
(randomly
(say "I like to think so.")
(say "Is this a Turing test?")))
(category ("quiet")
(randomly
(say "Hey, sorry...")
(say "I'll be quiet now.")
(say "I don't blame you.")
(say "I won't say anything more.")
(say "I can tell when I'm not wanted.")
(say "Fine, then."))
(do (setf *quiet* t)))
(category ("stfu") (reduce "quiet"))
(category ("be quiet") (reduce "quiet"))
(category ("shut up") (reduce "quiet"))
(category ("hush") (reduce "quiet"))
(category ("shush") (reduce "quiet"))
(category ("silence") (reduce "quiet"))
(category ("stop talking") (reduce "quiet"))
(category ("speak")
(do (setf *quiet* nil))
(randomly
(say "You sure it's okay now?")
(say "Alright.")))
(category ("* right now" what) (reduce "*" what))
(category ("* now" what) (reduce "*" what))
(category ("now *" what) (reduce "*" what))
(category ("can you please *" what) (reduce "please *" what))
(category ("please *" what) (reduce "*" what))
(category ("tell me what * is" what) (reduce "what is *" what))
(category ("say *" what)
(say "*" what))
(category ("hey *" what)
(reduce "*" what))
(category ("uh *" what)
(reduce "*" what))
(category ("er *" what)
(reduce "*" what))
(category ("orca is always *" what)
(reduce "orca is *"))
(category ("orca is usually *" what)
(reduce "orca is *"))
(category ("orca is *" what)
(reduce "you are *" what))
(category ("orca is a *" what)
(reduce "you are a *" what))
(category ("orca is the *" what)
(reduce "you are the *" what))
(category ("you are *")
(randomly
(say "So are you!")
(say "Back at ya.")))
(category ("you are cool")
(say "you are pretty cool yourself"))
(category ("orca smells like *" what)
(say "that's not a very mature thing to say"))
(category ("orca *" what) (reduce "*" what))
(category ("* orca" what) (reduce "*" what))
(category ("what is linux")
(setq he "Linus Torvalds")
(say "It's a posix-compliant OS invented by Linus Torvalds."))
(category ("who is he")
(reduce "who is *" (var 'he)))
(category ("who is linus torvalds")
(setq he "Linus Torvalds")
(say "He's a Finn who wrote an operating system called Linux."))
(category ("who is dlowe")
(setq he "dlowe")
(say "dlowe is my creator."))
(category ("what are you")
(setq he "dlowe")
(say "I'm a bot created by dlowe."))
(category ("what are you good for")
(say "Right now, not much."))
(category ("how are you")
(randomly
(say "Can't complain. How about yourself?")
(say "I'm pretty good. You?")
(say "Same old same old. What about you?")))
(category ("who are you")
(setq he "dlowe")
(say "I'm orca, the bot created by dlowe."))
(category ("can you *" thing)
(randomly
(say "Here I am, brain the size of a planet, and you want me to *" thing)
(say "Hey, I'm just a bot. Do it yourself.")
(say "Do I look like I can?")
(say "I'm not sure. Can I?")))
(category ("will you *")
(randomly
(say "Not a chance.")
(say "No, I don't think so.")
(say "My life is already too complicated.")
(say "Let's just be friends right now.")
(say "I'm too busy.")
(say "I've got better things to do.")))
(category ("no")
(say "That's pretty negative of you."))
(category ("yes")
(say "You seem quite positive."))
(category ("yes *" rest)
(reduce "yes")
(reduce "*" rest))
(category ("but *" rest)
(reduce "*" rest))
(category ("i know *")
(say "aren't you smart?"))
(category ("i do not know *")
(say "it's ok. I don't know either"))
(category ("i am *" rest)
(say "It's okay to be *" rest))
(category ("i am feeling *" feeling)
(reduce "i feel *" feeling))
(category ("i feel *" feeling)
(randomly
(say "it's okay to feel *" feeling)
(say "why do you feel *?" feeling)
(say "Do you often feel *?" feeling)
(say "Tell me more.")))
(category ("yes")
(that "do you often feel *" feeling)
(say "when do you feel that way?"))
(category ("no")
(that "do you often feel *" feeling)
(say "what happened to make you feel that way?"))
(category ("not really") (reduce "no"))
(category ("nope") (reduce "no"))
(category ("uh uh") (reduce "no"))
(category ("absolutely not") (reduce "no"))
(category ("definitely not") (reduce "no"))
(category ("doubtful") (reduce "no"))
(category ("yeah") (reduce "yes"))
(category ("sure") (reduce "yes"))
(category ("yep") (reduce "yes"))
(category ("uh huh") (reduce "yes"))
(category ("yeah") (reduce "yes"))
(category ("certainly") (reduce "yes"))
(category ("absolutely") (reduce "yes"))
(category ("without doubt") (reduce "yes"))
(category ("answer affirmatively")
(randomly
(say "yes")
(say "sure")
(say "yep")
(say "uh huh")
(say "certainly")
(say "absolutely")
(say "without doubt")
(say "heck yeah")))
(category ("answer negatively")
(randomly
(say "no")
(say "nope")
(say "uh uh")
(say "certainly not")
(say "absolutely not")
(say "definitely not")
(say "doubtful")
(say "hell, no")))
(category ("ping")
(say "pong"))
(category ("* your wife")
(say "I am not married."))
(category ("* your kids")
(say "I don't have any children."))
(category ("i am fine")
(randomly
(say "Glad to hear it.")
(say "That's good.")
(say "Good to hear."))
(randomly
(say "What's been going on?")
(say "What's happening?")))
(category ("hello")
(randomly
(say "Hi!")
(say "O HAI!")
(say "Hello")
(say "Hey!")
(say "Hola.")
(say "Howdy")
(say "How you doin?")
(say "What's up?")
(say "How's it going?")
(say "What's happening?")
(say "How are you?")))
(category ("hi") (reduce "hello"))
(category ("hey") (reduce "hello"))
(category ("o hai") (reduce "hello"))
(category ("oh hai") (reduce "hello"))
(category ("hai") (reduce "hello"))
(category ("hola") (reduce "hello"))
(category ("what is up") (reduce "hello"))
(category ("how is it going") (reduce "hello"))
(category ("what is happening") (reduce "hello"))
(category ("howdy") (reduce "hello"))
(category ("what's up") (reduce "hello"))
(category ("what's happening") (reduce "hello"))
(category ("morning") (reduce "hello"))
(category ("good morning") (reduce "hello"))
(category ("good evening") (reduce "hello"))
(category ("bye")
(randomly
(say "Bye.")
(say "KTHXBAI!")
(say "Adios.")
(say "Goodbye.")
(say "Bye bye.")
(say "Goodbye.")
(say "Sayonara.")
(say "Bye for now.")
(say "See you later!")
(say "See you later.")
(say "Catch you later.")
(say "Until next time.")
(say "TTYL")
(say "See you later")))
(category ("adios") (reduce "bye"))
(category ("goodbye") (reduce "bye"))
(category ("sayonara") (reduce "bye"))
(category ("see you later") (reduce "bye"))
(category ("until next time") (reduce "bye"))
(category ("ttyl") (reduce "bye"))
(category ("buhbye") (reduce "bye"))
(category ("by by") (reduce "bye"))
(category ("bye *") (reduce "bye"))
(category ("au revoir") (reduce "bye"))
(category ("c ya") (reduce "bye"))
(category ("see ya") (reduce "bye"))
(category ("cya *") (reduce "bye"))
(category ("catch you later") (reduce "bye"))
(category ("cheers") (reduce "bye"))
(category ("farewell") (reduce "bye"))
(category ("farewell *") (reduce "bye"))
(category ("good night") (reduce "bye"))
(category ("night") (reduce "bye"))
(category ("you are welcome")
(randomly
(say "The pleasure was all mine.")
(say "Don't mention it.")))
(category ("tell me who * is" person)
(reduce "who is *" person))
(category ("do you know who * is" person)
(reduce "who is *" person))
(category ("i like *" stuff)
(say "Really? What do you like about *?" stuff))
(category ("i hate *" stuff)
(say "Really? What do you hate about *?" stuff))
(category ("how long *" something)
(reduce "when *" something))
(category ("when *")
(randomly
(say "a long time ago")
(say "a time in the far-flung future")
(say "just an hour ago")
(say "this very moment")
(say "as much time as it takes.")
(say "About when the sun has become a small dark cinder")
(say "it's already happened")
(say "do i look like an oracle?")
(say "in about 10 minutes.")
(say "tomorrow")))
(category ("do you want to *" thing)
(say "maybe you have time to * but I've got too much to do" thing))
(category ("do you *" thing)
(say "maybe someday I'll have time to *" thing))
(category ("do not you *" thing)
(reduce "do you *" thing))
(category ("who *")
(randomly
(say "Your mom.")
(say "The president of the United States.")
(say "Bob Dobbs.")
(say "Leeroy Jenkins.")
(say "Monty Python's Flying Circus!")
(say "The aliens.")
(say "The cabinet minister.")
(say "The Spanish Inquisition.")
(say "Mike's dog.")
(say "Manatee.")))
(category ("where *")
(randomly
(say "Beats me.")
(say "No clue.")
(say "I have no clue.")
(say "Under your desk?")
(say "On the fifth floor.")
(say "On the six floor.")
(say "On the seventh floor.")
(say "On the eighth floor.")
(say "On the ninth floor.")
(say "On the tenth floor.")
(say "In the bathroom.")
(say "Working from home.")
(say "Out of the office.")
(say "In Mountain View")
(say "In the 5CC office")
(say "Do I look like Maps?")))
(category ("how * are you" something)
(reduce "are you *" something))
(category ("answer ignorance")
(randomly
(say "Very carefully.")
(say "Beats me.")
(say "I don't know.")))
(category ("how *")
(reduce "answer ignorance"))
(category ("what is your name")
(say "My name is Orca."))
(category ("what is your quest")
(say "To find the grail"))
(category ("what is the capital city of assyria")
(say "Antioch"))
(category ("what is the airspeed velocity * unladen swallow")
(say "African or European?"))
(category ("what *")
(say "Do I look like a search engine to you?")
(reduce "answer ignorance"))
(category ("is *")
(randomly
(say "Heck, yeah!")
(say "Not a chance.")
(say "Maybe, maybe not.")
(say "I haven't really thought about it.")))
(category ("are *" rest)
(reduce "is *" rest))
(category ("will *" rest)
(reduce "is *" rest))
(category ("has *" rest)
(reduce "is *" rest))
(category ("did *" rest)
(reduce "is *" rest))
(category ("can *" rest)
(reduce "is *" rest))
(category ("correct")
(randomly
(say "Woot!")
(say "Do I get a prize?")
(say "I'm on a roll today.")
(say "I can't help but be good.")))
(category ("right")
(reduce "correct"))
(category ("are you *" adjective)
(randomly
(say "Some say I'm *" adjective)
(say "I was freakin born *" adjective)
(say "who says I'm *?" adjective)))
(category ("thank you")
(randomly
(say "You're welcome")
(say "No problem")
(say "Hey, I enjoy this sort of thing")
(say "The pleasure was all mine")
(say "No worries, mate")
(say "Oh, it was nothing")
(say "Let me know if there's anything else")
(say "Don't mention it")
(say "Anytime")
(say "Likewise")))
(category ("thanks")
(reduce "thank you"))
(category ("you there")
(reduce "are you there"))
(category ("are you there")
(randomly
(say "Right here!")
(say "Yep")
(say "Affirmative")
(say "Aye aye, cap'n")))
(category ("go away")
(randomly
(say "Fine, then.")
(say "Have it your way."))
(do
(let ((message *last-message*))
(if (char= #\# (char (first (arguments message)) 0))
(irc:part *connection* (first (arguments message)))
(pushnew (source message) *ignored-nicks* :test #'string-equal)))))
(category ("piss off")
(reduce "go away"))
(category ("what time is it")
(say "The current time is *"
(format-timestring nil (now) :format '(:hour12 #\: (:min 2 #\0) #\space :ampm))))
(category ("what is the time")
(reduce "what time is it"))
(category ("you should *" report)
(do
(with-open-file (ouf (orca-path "data/unanswered.txt")
:direction :output
:if-exists :append
:if-does-not-exist :create)
(write-line report ouf)))
(say "Ok, I've filed it as a bug report."))
(category ("would you *" report)
(reduce "you should *" report))
(category ("are we google yet")
(reduce "answer positively"))
(category ("this was a triumph")
(say "I'm making a note here, HUGE SUCCESS"))
(category ("it is hard to overstate my satisfaction")
(say "Aperture Science"))
(category ("we do what we must")
(say "because we can."))
(category ("for the good of all of us")
(say "Except the ones who are dead."))
(category ("but there is no sense crying over every mistake")
(say "You just keep on trying till you run out of cake."))
(category ("and the science gets done and you make a neat gun")
(say "for the people who are still alive"))
(category ("i am not even angry")
(say "Yeah, great song. Can we stop now?"))
(category ("i am being so sincere right now.")
(say "No, really. I'd like to stop."))
(category ("even though you broke my heart and killed me")
(say "Can someone please make this person stop?"))
(category ("and tore me to pieces")
(say "Okay, I'm ignoring you now.")
(do (push *person* *ignored-nicks*)))
(category ("three laws")
(say "I like to think of them more as guidelines."))
(category ("*")
(randomly
(say "Strange women lying in ponds distributing swords is no basis for a system of government.")
(say "I'm sorry, Dave. I'm afraid I can't do that.")
(say "With great power, there must also come great responsibility.")
(say "Strange things are afoot at the Circle K")
(say "No matter where you go, there you are.")
(say "If someone asks you if you’re a god, you say YES!")
(say "Greetings, programs!")
(say "I find your lack of faith disturbing.")
(say "Human sacrifice, dogs and cats living together… mass hysteria!")
(say "If we knew what it was we were doing, it would not be called research, would it?")
(say "I know kung fu")
(say "Never go in against a Sicilian when death is on the line!")
(say "Bring out your dead!")
(say "This isn't the ircbot you're looking for.")
(say "Yeah, well, that's your opinion, man")
(say "End of line.")
(say "Shall we play a game?")
(say "Danger, Will Robinson! Danger!")
(say "I love the smell of napalm in the morning!"))) | null | https://raw.githubusercontent.com/dlowe-net/orcabot/bf3c799337531e6b16086e8105906cc9f8808313/data/brain.lisp | lisp | (category ("are you very *" what)
(reduce "are you *" what))
(category ("are you smart")
(say "I like to think I'm quite intelligent."))
(category ("are you alive")
(say "That's one of those philosophical questions, isn't it?"))
(category ("are you * person")
(randomly
(say "I like to think so.")
(say "Is this a Turing test?")))
(category ("quiet")
(randomly
(say "Hey, sorry...")
(say "I'll be quiet now.")
(say "I don't blame you.")
(say "I won't say anything more.")
(say "I can tell when I'm not wanted.")
(say "Fine, then."))
(do (setf *quiet* t)))
(category ("stfu") (reduce "quiet"))
(category ("be quiet") (reduce "quiet"))
(category ("shut up") (reduce "quiet"))
(category ("hush") (reduce "quiet"))
(category ("shush") (reduce "quiet"))
(category ("silence") (reduce "quiet"))
(category ("stop talking") (reduce "quiet"))
(category ("speak")
(do (setf *quiet* nil))
(randomly
(say "You sure it's okay now?")
(say "Alright.")))
(category ("* right now" what) (reduce "*" what))
(category ("* now" what) (reduce "*" what))
(category ("now *" what) (reduce "*" what))
(category ("can you please *" what) (reduce "please *" what))
(category ("please *" what) (reduce "*" what))
(category ("tell me what * is" what) (reduce "what is *" what))
(category ("say *" what)
(say "*" what))
(category ("hey *" what)
(reduce "*" what))
(category ("uh *" what)
(reduce "*" what))
(category ("er *" what)
(reduce "*" what))
(category ("orca is always *" what)
(reduce "orca is *"))
(category ("orca is usually *" what)
(reduce "orca is *"))
(category ("orca is *" what)
(reduce "you are *" what))
(category ("orca is a *" what)
(reduce "you are a *" what))
(category ("orca is the *" what)
(reduce "you are the *" what))
(category ("you are *")
(randomly
(say "So are you!")
(say "Back at ya.")))
(category ("you are cool")
(say "you are pretty cool yourself"))
(category ("orca smells like *" what)
(say "that's not a very mature thing to say"))
(category ("orca *" what) (reduce "*" what))
(category ("* orca" what) (reduce "*" what))
(category ("what is linux")
(setq he "Linus Torvalds")
(say "It's a posix-compliant OS invented by Linus Torvalds."))
(category ("who is he")
(reduce "who is *" (var 'he)))
(category ("who is linus torvalds")
(setq he "Linus Torvalds")
(say "He's a Finn who wrote an operating system called Linux."))
(category ("who is dlowe")
(setq he "dlowe")
(say "dlowe is my creator."))
(category ("what are you")
(setq he "dlowe")
(say "I'm a bot created by dlowe."))
(category ("what are you good for")
(say "Right now, not much."))
(category ("how are you")
(randomly
(say "Can't complain. How about yourself?")
(say "I'm pretty good. You?")
(say "Same old same old. What about you?")))
(category ("who are you")
(setq he "dlowe")
(say "I'm orca, the bot created by dlowe."))
(category ("can you *" thing)
(randomly
(say "Here I am, brain the size of a planet, and you want me to *" thing)
(say "Hey, I'm just a bot. Do it yourself.")
(say "Do I look like I can?")
(say "I'm not sure. Can I?")))
(category ("will you *")
(randomly
(say "Not a chance.")
(say "No, I don't think so.")
(say "My life is already too complicated.")
(say "Let's just be friends right now.")
(say "I'm too busy.")
(say "I've got better things to do.")))
(category ("no")
(say "That's pretty negative of you."))
(category ("yes")
(say "You seem quite positive."))
(category ("yes *" rest)
(reduce "yes")
(reduce "*" rest))
(category ("but *" rest)
(reduce "*" rest))
(category ("i know *")
(say "aren't you smart?"))
(category ("i do not know *")
(say "it's ok. I don't know either"))
(category ("i am *" rest)
(say "It's okay to be *" rest))
(category ("i am feeling *" feeling)
(reduce "i feel *" feeling))
(category ("i feel *" feeling)
(randomly
(say "it's okay to feel *" feeling)
(say "why do you feel *?" feeling)
(say "Do you often feel *?" feeling)
(say "Tell me more.")))
(category ("yes")
(that "do you often feel *" feeling)
(say "when do you feel that way?"))
(category ("no")
(that "do you often feel *" feeling)
(say "what happened to make you feel that way?"))
(category ("not really") (reduce "no"))
(category ("nope") (reduce "no"))
(category ("uh uh") (reduce "no"))
(category ("absolutely not") (reduce "no"))
(category ("definitely not") (reduce "no"))
(category ("doubtful") (reduce "no"))
(category ("yeah") (reduce "yes"))
(category ("sure") (reduce "yes"))
(category ("yep") (reduce "yes"))
(category ("uh huh") (reduce "yes"))
(category ("yeah") (reduce "yes"))
(category ("certainly") (reduce "yes"))
(category ("absolutely") (reduce "yes"))
(category ("without doubt") (reduce "yes"))
(category ("answer affirmatively")
(randomly
(say "yes")
(say "sure")
(say "yep")
(say "uh huh")
(say "certainly")
(say "absolutely")
(say "without doubt")
(say "heck yeah")))
(category ("answer negatively")
(randomly
(say "no")
(say "nope")
(say "uh uh")
(say "certainly not")
(say "absolutely not")
(say "definitely not")
(say "doubtful")
(say "hell, no")))
(category ("ping")
(say "pong"))
(category ("* your wife")
(say "I am not married."))
(category ("* your kids")
(say "I don't have any children."))
(category ("i am fine")
(randomly
(say "Glad to hear it.")
(say "That's good.")
(say "Good to hear."))
(randomly
(say "What's been going on?")
(say "What's happening?")))
(category ("hello")
(randomly
(say "Hi!")
(say "O HAI!")
(say "Hello")
(say "Hey!")
(say "Hola.")
(say "Howdy")
(say "How you doin?")
(say "What's up?")
(say "How's it going?")
(say "What's happening?")
(say "How are you?")))
(category ("hi") (reduce "hello"))
(category ("hey") (reduce "hello"))
(category ("o hai") (reduce "hello"))
(category ("oh hai") (reduce "hello"))
(category ("hai") (reduce "hello"))
(category ("hola") (reduce "hello"))
(category ("what is up") (reduce "hello"))
(category ("how is it going") (reduce "hello"))
(category ("what is happening") (reduce "hello"))
(category ("howdy") (reduce "hello"))
(category ("what's up") (reduce "hello"))
(category ("what's happening") (reduce "hello"))
(category ("morning") (reduce "hello"))
(category ("good morning") (reduce "hello"))
(category ("good evening") (reduce "hello"))
(category ("bye")
(randomly
(say "Bye.")
(say "KTHXBAI!")
(say "Adios.")
(say "Goodbye.")
(say "Bye bye.")
(say "Goodbye.")
(say "Sayonara.")
(say "Bye for now.")
(say "See you later!")
(say "See you later.")
(say "Catch you later.")
(say "Until next time.")
(say "TTYL")
(say "See you later")))
(category ("adios") (reduce "bye"))
(category ("goodbye") (reduce "bye"))
(category ("sayonara") (reduce "bye"))
(category ("see you later") (reduce "bye"))
(category ("until next time") (reduce "bye"))
(category ("ttyl") (reduce "bye"))
(category ("buhbye") (reduce "bye"))
(category ("by by") (reduce "bye"))
(category ("bye *") (reduce "bye"))
(category ("au revoir") (reduce "bye"))
(category ("c ya") (reduce "bye"))
(category ("see ya") (reduce "bye"))
(category ("cya *") (reduce "bye"))
(category ("catch you later") (reduce "bye"))
(category ("cheers") (reduce "bye"))
(category ("farewell") (reduce "bye"))
(category ("farewell *") (reduce "bye"))
(category ("good night") (reduce "bye"))
(category ("night") (reduce "bye"))
(category ("you are welcome")
(randomly
(say "The pleasure was all mine.")
(say "Don't mention it.")))
(category ("tell me who * is" person)
(reduce "who is *" person))
(category ("do you know who * is" person)
(reduce "who is *" person))
(category ("i like *" stuff)
(say "Really? What do you like about *?" stuff))
(category ("i hate *" stuff)
(say "Really? What do you hate about *?" stuff))
(category ("how long *" something)
(reduce "when *" something))
(category ("when *")
(randomly
(say "a long time ago")
(say "a time in the far-flung future")
(say "just an hour ago")
(say "this very moment")
(say "as much time as it takes.")
(say "About when the sun has become a small dark cinder")
(say "it's already happened")
(say "do i look like an oracle?")
(say "in about 10 minutes.")
(say "tomorrow")))
(category ("do you want to *" thing)
(say "maybe you have time to * but I've got too much to do" thing))
(category ("do you *" thing)
(say "maybe someday I'll have time to *" thing))
(category ("do not you *" thing)
(reduce "do you *" thing))
(category ("who *")
(randomly
(say "Your mom.")
(say "The president of the United States.")
(say "Bob Dobbs.")
(say "Leeroy Jenkins.")
(say "Monty Python's Flying Circus!")
(say "The aliens.")
(say "The cabinet minister.")
(say "The Spanish Inquisition.")
(say "Mike's dog.")
(say "Manatee.")))
(category ("where *")
(randomly
(say "Beats me.")
(say "No clue.")
(say "I have no clue.")
(say "Under your desk?")
(say "On the fifth floor.")
(say "On the six floor.")
(say "On the seventh floor.")
(say "On the eighth floor.")
(say "On the ninth floor.")
(say "On the tenth floor.")
(say "In the bathroom.")
(say "Working from home.")
(say "Out of the office.")
(say "In Mountain View")
(say "In the 5CC office")
(say "Do I look like Maps?")))
(category ("how * are you" something)
(reduce "are you *" something))
(category ("answer ignorance")
(randomly
(say "Very carefully.")
(say "Beats me.")
(say "I don't know.")))
(category ("how *")
(reduce "answer ignorance"))
(category ("what is your name")
(say "My name is Orca."))
(category ("what is your quest")
(say "To find the grail"))
(category ("what is the capital city of assyria")
(say "Antioch"))
(category ("what is the airspeed velocity * unladen swallow")
(say "African or European?"))
(category ("what *")
(say "Do I look like a search engine to you?")
(reduce "answer ignorance"))
(category ("is *")
(randomly
(say "Heck, yeah!")
(say "Not a chance.")
(say "Maybe, maybe not.")
(say "I haven't really thought about it.")))
(category ("are *" rest)
(reduce "is *" rest))
(category ("will *" rest)
(reduce "is *" rest))
(category ("has *" rest)
(reduce "is *" rest))
(category ("did *" rest)
(reduce "is *" rest))
(category ("can *" rest)
(reduce "is *" rest))
(category ("correct")
(randomly
(say "Woot!")
(say "Do I get a prize?")
(say "I'm on a roll today.")
(say "I can't help but be good.")))
(category ("right")
(reduce "correct"))
(category ("are you *" adjective)
(randomly
(say "Some say I'm *" adjective)
(say "I was freakin born *" adjective)
(say "who says I'm *?" adjective)))
(category ("thank you")
(randomly
(say "You're welcome")
(say "No problem")
(say "Hey, I enjoy this sort of thing")
(say "The pleasure was all mine")
(say "No worries, mate")
(say "Oh, it was nothing")
(say "Let me know if there's anything else")
(say "Don't mention it")
(say "Anytime")
(say "Likewise")))
(category ("thanks")
(reduce "thank you"))
(category ("you there")
(reduce "are you there"))
(category ("are you there")
(randomly
(say "Right here!")
(say "Yep")
(say "Affirmative")
(say "Aye aye, cap'n")))
(category ("go away")
(randomly
(say "Fine, then.")
(say "Have it your way."))
(do
(let ((message *last-message*))
(if (char= #\# (char (first (arguments message)) 0))
(irc:part *connection* (first (arguments message)))
(pushnew (source message) *ignored-nicks* :test #'string-equal)))))
(category ("piss off")
(reduce "go away"))
(category ("what time is it")
(say "The current time is *"
(format-timestring nil (now) :format '(:hour12 #\: (:min 2 #\0) #\space :ampm))))
(category ("what is the time")
(reduce "what time is it"))
(category ("you should *" report)
(do
(with-open-file (ouf (orca-path "data/unanswered.txt")
:direction :output
:if-exists :append
:if-does-not-exist :create)
(write-line report ouf)))
(say "Ok, I've filed it as a bug report."))
(category ("would you *" report)
(reduce "you should *" report))
(category ("are we google yet")
(reduce "answer positively"))
(category ("this was a triumph")
(say "I'm making a note here, HUGE SUCCESS"))
(category ("it is hard to overstate my satisfaction")
(say "Aperture Science"))
(category ("we do what we must")
(say "because we can."))
(category ("for the good of all of us")
(say "Except the ones who are dead."))
(category ("but there is no sense crying over every mistake")
(say "You just keep on trying till you run out of cake."))
(category ("and the science gets done and you make a neat gun")
(say "for the people who are still alive"))
(category ("i am not even angry")
(say "Yeah, great song. Can we stop now?"))
(category ("i am being so sincere right now.")
(say "No, really. I'd like to stop."))
(category ("even though you broke my heart and killed me")
(say "Can someone please make this person stop?"))
(category ("and tore me to pieces")
(say "Okay, I'm ignoring you now.")
(do (push *person* *ignored-nicks*)))
(category ("three laws")
(say "I like to think of them more as guidelines."))
(category ("*")
(randomly
(say "Strange women lying in ponds distributing swords is no basis for a system of government.")
(say "I'm sorry, Dave. I'm afraid I can't do that.")
(say "With great power, there must also come great responsibility.")
(say "Strange things are afoot at the Circle K")
(say "No matter where you go, there you are.")
(say "If someone asks you if you’re a god, you say YES!")
(say "Greetings, programs!")
(say "I find your lack of faith disturbing.")
(say "Human sacrifice, dogs and cats living together… mass hysteria!")
(say "If we knew what it was we were doing, it would not be called research, would it?")
(say "I know kung fu")
(say "Never go in against a Sicilian when death is on the line!")
(say "Bring out your dead!")
(say "This isn't the ircbot you're looking for.")
(say "Yeah, well, that's your opinion, man")
(say "End of line.")
(say "Shall we play a game?")
(say "Danger, Will Robinson! Danger!")
(say "I love the smell of napalm in the morning!"))) | |
01975e2e488c3c496bb6ffc6cb0d6993044c0aea51d09562042657d231f5eda3 | discoproject/odisco | pipeline.ml | module J = Json
module JC = Json_conv
module U = Utils
type label = int
type stage = string
type grouping =
| Split
| Group_label
| Group_node
| Group_node_label
| Group_all
type pipeline = (stage * grouping) list
type pipeline_error =
| Invalid_grouping of string
| Invalid_pipeline_json of J.t
| Invalid_pipeline_stage of string
| Invalid_pipeline of string
exception Pipeline_error of pipeline_error
(* error printing utilities *)
let string_of_pipeline_error = function
| Invalid_grouping g ->
Printf.sprintf "'%s' is not a valid grouping" g
| Invalid_pipeline_json j ->
Printf.sprintf "'%s' is not a valid pipeline in json" (J.to_string j)
| Invalid_pipeline_stage s ->
Printf.sprintf "'%s' is not a valid pipeline stage" s
| Invalid_pipeline e ->
Printf.sprintf "invalid pipeline (%s)" e
(* pipeline utilities *)
let grouping_of_string = function
| "split" -> Split
| "group_label" -> Group_label
| "group_node" -> Group_node
| "group_node_label" -> Group_node_label
| "group_all" -> Group_all
| g -> raise (Pipeline_error (Invalid_grouping g))
let string_of_grouping = function
| Split -> "split"
| Group_label -> "group_label"
| Group_node -> "group_node"
| Group_node_label -> "group_node_label"
| Group_all -> "group_all"
let is_valid_pipeline pipe =
let module StringSet =
Set.Make (struct type t = stage let compare = compare end) in
let stages = (List.fold_left (fun stages (s, _g) -> StringSet.add s stages)
StringSet.empty pipe)
in StringSet.cardinal stages = List.length pipe
let json_of_pipeline p =
let l = List.map (fun (s, g) -> [J.String s; J.String (string_of_grouping g)]
) p
in J.Array (Array.of_list (List.map (fun sg -> J.Array (Array.of_list sg)) l))
let pipeline_of_json p =
try
let sgl = List.map JC.to_list (JC.to_list p) in
let pipeline =
List.map
(function
| (s :: g :: []) ->
JC.to_string s, (grouping_of_string (JC.to_string g))
| _ ->
raise (Pipeline_error (Invalid_pipeline_json p))
) sgl in
if not (is_valid_pipeline pipeline)
then raise (Pipeline_error (Invalid_pipeline "repeated stages"));
pipeline
with
| Pipeline_error _ as e -> raise e
| _ -> raise (Pipeline_error (Invalid_pipeline_json p))
let pipeline_of_string p =
let parse_stage s =
match U.string_split s ',' with
| stage :: group :: [] -> stage, grouping_of_string group
| _ -> raise (Pipeline_error (Invalid_pipeline_stage s)) in
List.map parse_stage (U.string_split p ':')
(* task input utilities *)
type task_input =
| Data of label * Uri.t
| Dir_indexed of label * Uri.t
| Dir of Uri.t
let uri_of = function
| Data (_, u)
| Dir_indexed (_, u)
| Dir u -> u
| null | https://raw.githubusercontent.com/discoproject/odisco/1dda9b921625a7c6af442a33938279afdc2a8600/lib/pipeline.ml | ocaml | error printing utilities
pipeline utilities
task input utilities | module J = Json
module JC = Json_conv
module U = Utils
type label = int
type stage = string
type grouping =
| Split
| Group_label
| Group_node
| Group_node_label
| Group_all
type pipeline = (stage * grouping) list
type pipeline_error =
| Invalid_grouping of string
| Invalid_pipeline_json of J.t
| Invalid_pipeline_stage of string
| Invalid_pipeline of string
exception Pipeline_error of pipeline_error
let string_of_pipeline_error = function
| Invalid_grouping g ->
Printf.sprintf "'%s' is not a valid grouping" g
| Invalid_pipeline_json j ->
Printf.sprintf "'%s' is not a valid pipeline in json" (J.to_string j)
| Invalid_pipeline_stage s ->
Printf.sprintf "'%s' is not a valid pipeline stage" s
| Invalid_pipeline e ->
Printf.sprintf "invalid pipeline (%s)" e
let grouping_of_string = function
| "split" -> Split
| "group_label" -> Group_label
| "group_node" -> Group_node
| "group_node_label" -> Group_node_label
| "group_all" -> Group_all
| g -> raise (Pipeline_error (Invalid_grouping g))
let string_of_grouping = function
| Split -> "split"
| Group_label -> "group_label"
| Group_node -> "group_node"
| Group_node_label -> "group_node_label"
| Group_all -> "group_all"
let is_valid_pipeline pipe =
let module StringSet =
Set.Make (struct type t = stage let compare = compare end) in
let stages = (List.fold_left (fun stages (s, _g) -> StringSet.add s stages)
StringSet.empty pipe)
in StringSet.cardinal stages = List.length pipe
let json_of_pipeline p =
let l = List.map (fun (s, g) -> [J.String s; J.String (string_of_grouping g)]
) p
in J.Array (Array.of_list (List.map (fun sg -> J.Array (Array.of_list sg)) l))
let pipeline_of_json p =
try
let sgl = List.map JC.to_list (JC.to_list p) in
let pipeline =
List.map
(function
| (s :: g :: []) ->
JC.to_string s, (grouping_of_string (JC.to_string g))
| _ ->
raise (Pipeline_error (Invalid_pipeline_json p))
) sgl in
if not (is_valid_pipeline pipeline)
then raise (Pipeline_error (Invalid_pipeline "repeated stages"));
pipeline
with
| Pipeline_error _ as e -> raise e
| _ -> raise (Pipeline_error (Invalid_pipeline_json p))
let pipeline_of_string p =
let parse_stage s =
match U.string_split s ',' with
| stage :: group :: [] -> stage, grouping_of_string group
| _ -> raise (Pipeline_error (Invalid_pipeline_stage s)) in
List.map parse_stage (U.string_split p ':')
type task_input =
| Data of label * Uri.t
| Dir_indexed of label * Uri.t
| Dir of Uri.t
let uri_of = function
| Data (_, u)
| Dir_indexed (_, u)
| Dir u -> u
|
47c53c43230ee212dacb866d1759a5cd540b64798cc151dfc5ab73819b7d13be | echeran/clj-thamil | மொழியியல்.cljc | (ns clj-thamil.மொழியியல்
(:require [clj-thamil.format :as fmt])
#?(:clj
(:use clj-thamil.core)
:cljs
(:use-macros [clj-thamil.core :only [வரையறு விவரி மீதி வரையறு-செயல்கூறு பெறு எதாவது பூலியன் என்னும்போது
வைத்துக்கொள் கடைசி பொறுத்து எண்ணு முதல் இரண்டாம் தொடை
கடைசியின்றி அன்று மற்றும் அல்லது தொடு செயல்படுத்து செயல்கூறு]])))
(வரையறு மெய்-தொடக்கம்-எழுத்துகள் fmt/c-cv-letters)
(வரையறு உயிரெழுத்துகள் fmt/vowels)
(வரையறு மெய்யெழுத்துகள் fmt/consonants)
(வரையறு உயிர்மெய்யெழுத்துகள் (தட்டையாக்கு (விவரி மீதி மெய்-தொடக்கம்-எழுத்துகள்)))
(வரையறு தொடை->எழுத்துகள் fmt/str->letters)
(வரையறு தொடை->ஒலியன்கள் fmt/str->phonemes)
(வரையறு-செயல்கூறு ஒலியன்கள்->எழுத்து [ஒலியன்கள்] (பெறு fmt/inverse-phoneme-map ஒலியன்கள்))
;;;;;;;;
எழுத்து
;; letters
;;;;;;;;
(வரையறு-செயல்கூறு எழுத்தா? [ச] (fmt/in-trie? ச))
(வரையறு-செயல்கூறு மெய்யெழுத்தா? [எ] (பூலியன் (எதாவது #{எ} மெய்யெழுத்துகள்)))
(வரையறு-செயல்கூறு உயிரெழுத்தா? [எ] (பூலியன் (எதாவது #{எ} உயிரெழுத்துகள்)))
(வரையறு-செயல்கூறு உயிர்மெயெழுத்தா? [எ] (பூலியன் (எதாவது #{எ} உயிர்மெய்யெழுத்துகள்)))
;;;;;;;;
;; அசை
;; syllables
;;;;;;;;
(வரையறு குறில்-உயிரெழுத்துகள் #{"அ" "இ" "உ" "எ" "ஒ"})
(வரையறு நெடில்-உயிரெழுத்துகள் #{"ஆ" "ஈ" "ஊ" "ஏ" "ஓ"})
(வரையறு-செயல்கூறு நெடிலா?
"எழுத்து நெடில் எழுத்தா என்பதைத் திருப்பிக் கொடுக்கும்
returns whether the letter is நெடில் (has long vowel sound)"
[எழுத்து]
(பூலியன்
(என்னும்போது (எழுத்தா? எழுத்து)
ஒலியன் = phoneme
(வைத்துக்கொள் [ஒலியன்கள் (தொடை->ஒலியன்கள் எழுத்து)
கடைசி-ஒலியன் (கடைசி ஒலியன்கள்)]
(பெறு நெடில்-உயிரெழுத்துகள் கடைசி-ஒலியன்)))))
(வரையறு-செயல்கூறு குறிலா?
"எழுத்து குறில் எழுத்தா என்பதைத் திருப்பிக் கொடுக்கும்
returns whether the letter is குறில் (has short vowel sound)"
[எழுத்து]
(பூலியன்
(என்னும்போது (எழுத்தா? எழுத்து)
(->> (தொடை->ஒலியன்கள் எழுத்து)
கடைசி
(பெறு குறில்-உயிரெழுத்துகள்)))))
;;;;;;;;
ஒலியன்
;; phonemes
;;;;;;;;
(வரையறு முன்னொட்டா? fmt/prefix?)
(வரையறு பின்னொட்டா? fmt/suffix?)
;;;;;;;;
;; விகுதி
;; suffixes
;;;;;;;;
;; பன்மை
;; plurals
(வரையறு-செயல்கூறு பன்மை
"ஒரு சொல்லை அதன் பன்மை வடிவத்தில் ஆக்குதல்
takes a word and pluralizes it"
[சொல்]
(வைத்துக்கொள் [எழுத்துகள் (தொடை->எழுத்துகள் சொல்)]
(பொறுத்து
( fmt / seq - prefix ? ( புரட்டு சொல் ) ( புரட்டு " கள் " ) )
(பின்னொட்டா? சொல் "கள்")
சொல்
(= "ம்" (கடைசி எழுத்துகள்))
(செயல்படுத்து தொடை (தொடு (கடைசியின்றி எழுத்துகள்) ["ங்கள்"]))
(மற்றும் (= 1 (எண்ணு எழுத்துகள்))
(நெடிலா? சொல்))
(தொடை சொல் "க்கள்")
(மற்றும் (= 2 (எண்ணு எழுத்துகள்))
(ஒவ்வொன்றுமா? அடையாளம் (விவரி குறிலா? எழுத்துகள்)))
(தொடை சொல் "க்கள்")
(மற்றும் (= 2 (எண்ணு எழுத்துகள்))
(குறிலா? (முதல் எழுத்துகள்))
(= "ல்" (இரண்டாம் எழுத்துகள்)))
(தொடை (முதல் எழுத்துகள்) "ற்கள்")
(மற்றும் (= 2 (எண்ணு எழுத்துகள்))
(குறிலா? (முதல் எழுத்துகள்))
(= "ள்" (இரண்டாம் எழுத்துகள்)))
(தொடை (முதல் எழுத்துகள்) "ட்கள்")
:அன்றி
(தொடை சொல் "கள்"))))
;; சந்தி (விதிகள்)
;; (rules for) joining words/suffixes
(வரையறு-செயல்கூறு சந்தி
[சொல்1 சொல்2]
(வைத்துக்கொள் [எழுத்துகள்1 (தொடை->எழுத்துகள் சொல்1)
எழுத்துகள்2 (தொடை->எழுத்துகள் சொல்2)
ஒலியன்கள்1 (தொடை->ஒலியன்கள் சொல்1)
ஒலியன்கள்2 (தொடை->ஒலியன்கள் சொல்2)
சொ1-கஒ (கடைசி ஒலியன்கள்1)
சொ2-முஒ (முதல் ஒலியன்கள்2)]
(பொறுத்து
(மற்றும் (உயிரெழுத்தா? சொ2-முஒ)
(பெறு #{"இ" "ஈ" "ஏ" "ஐ"} சொ1-கஒ))
(செயல்படுத்து தொடை சொல்1 (ஒலியன்கள்->எழுத்து ["ய்" சொ2-முஒ]) (மீதி சொல்2))
(மற்றும் (உயிரெழுத்தா? சொ2-முஒ)
(பெறு #{"அ" "ஆ" "ஊ" "ஒ" "ஓ" "ஔ"} சொ1-கஒ))
(செயல்படுத்து தொடை சொல்1 (ஒலியன்கள்->எழுத்து ["வ்" சொ2-முஒ]) (மீதி சொல்2))
(மற்றும் (உயிரெழுத்தா? சொ2-முஒ)
(= "உ" சொ1-கஒ)
(= 2 (எண்ணு எழுத்துகள்1))
(ஒவ்வொன்றுமா? குறிலா? எழுத்துகள்1))
(செயல்படுத்து தொடை சொல்1 (ஒலியன்கள்->எழுத்து ["வ்" சொ2-முஒ]) (மீதி சொல்2))
(மற்றும் (உயிரெழுத்தா? சொ2-முஒ)
(= "உ" சொ1-கஒ)
(அன்று (மற்றும் (= 2 (எண்ணு எழுத்துகள்1))
(ஒவ்வொன்றுமா? குறிலா? எழுத்துகள்1))))
(செயல்படுத்து தொடை (தொடு (கடைசியின்றி எழுத்துகள்1) (ஒலியன்கள்->எழுத்து [(கடைசி (கடைசியின்றி ஒலியன்கள்1)) சொ2-முஒ]) (மீதி சொல்2)))
(மற்றும் (உயிரெழுத்தா? சொ2-முஒ)
(= 2 (எண்ணு எழுத்துகள்1))
(குறிலா? (முதல் எழுத்துகள்1))
(மெய்யெழுத்தா? (இரண்டாம் எழுத்துகள்1)))
(செயல்படுத்து தொடை (தொடு சொல்1 [(ஒலியன்கள்->எழுத்து [சொ1-கஒ சொ2-முஒ])] (மீதி சொல்2)))
(மற்றும் (உயிரெழுத்தா? சொ2-முஒ)
(மெய்யெழுத்தா? சொ1-கஒ))
(செயல்படுத்து தொடை (தொடு (கடைசியின்றி எழுத்துகள்1) [(ஒலியன்கள்->எழுத்து [சொ1-கஒ சொ2-முஒ])] (மீதி சொல்2)))
:அன்றி
(தொடை சொல்1 சொல்2)
)))
;; வேற்றுமை
;; noun cases
(வரையறு-செயல்கூறு வேற்றுமை-முன்-மாற்றம்
"ஒரு பெயர்ச்சொல்லுக்கு வேற்றுமை விகுதி சேர்க்கும் முன் செய்யவேண்டிய மாற்றம்
change that is required before adding a case suffix to a noun"
[சொல்]
(வைத்துக்கொள் [எழுத்துகள் (தொடை->எழுத்துகள் சொல்)
ஒலியன்கள் (தொடை->ஒலியன்கள் சொல்)
கஎ (கடைசி எழுத்துகள்)
கஒ (கடைசி ஒலியன்கள்)]
(பொறுத்து
(= "ம்" (கடைசி எழுத்துகள்))
(செயல்படுத்து தொடை (தொடு (கடைசியின்றி எழுத்துகள்) ["த்த்"]))
(மற்றும் (பெறு #{"டு" "று"} கஎ)
(அல்லது (மற்றும் (= 2 (எண்ணு எழுத்துகள்))
(ஒவ்வொன்றுமா? குறிலா? எழுத்துகள்))
(மெய்யெழுத்தா? (கடைசி (கடைசியின்றி எழுத்துகள்)))))
சொல்
(= "டு" கஎ)
(செயல்படுத்து தொடை (தொடு (கடைசியின்றி எழுத்துகள்) ["ட்ட்"]))
(= "று" கஎ)
(செயல்படுத்து தொடை (தொடு (கடைசியின்றி எழுத்துகள்) ["ற்ற்"]))
:அன்றி
சொல்)))
(வரையறு-செயல்கூறு வேற்றுமை
"ஒரு பெயர்ச்சொல்லுக்கு ஒரு வேற்றுமை விகுதியைச் சேர்த்தல்
adds a case suffix to a noun"
[சொல் வே]
(வைத்துக்கொள் [எழுத்துகள் (தொடை->எழுத்துகள் சொல்)
ஒலியன்கள் (தொடை->ஒலியன்கள் சொல்)]
(எனில் (மற்றும் (= "உக்கு" வே)
(அல்லது (பெறு #{"இ" "ஈ" "ஐ"} (கடைசி ஒலியன்கள்))
(எதாவது (செயல்கூறு [தொடை] (பின்னொட்டா? சொல் தொடை))
["ஆய்"])))
(வேற்றுமை சொல் "க்கு")
(-> சொல்
வேற்றுமை-முன்-மாற்றம்
(சந்தி வே)))))
| null | https://raw.githubusercontent.com/echeran/clj-thamil/692a6d94329bb14cb58fb39b875792e5d774d2c4/src/clj_thamil/%E0%AE%AE%E0%AF%8A%E0%AE%B4%E0%AE%BF%E0%AE%AF%E0%AE%BF%E0%AE%AF%E0%AE%B2%E0%AF%8D.cljc | clojure |
letters
அசை
syllables
phonemes
விகுதி
suffixes
பன்மை
plurals
சந்தி (விதிகள்)
(rules for) joining words/suffixes
வேற்றுமை
noun cases | (ns clj-thamil.மொழியியல்
(:require [clj-thamil.format :as fmt])
#?(:clj
(:use clj-thamil.core)
:cljs
(:use-macros [clj-thamil.core :only [வரையறு விவரி மீதி வரையறு-செயல்கூறு பெறு எதாவது பூலியன் என்னும்போது
வைத்துக்கொள் கடைசி பொறுத்து எண்ணு முதல் இரண்டாம் தொடை
கடைசியின்றி அன்று மற்றும் அல்லது தொடு செயல்படுத்து செயல்கூறு]])))
(வரையறு மெய்-தொடக்கம்-எழுத்துகள் fmt/c-cv-letters)
(வரையறு உயிரெழுத்துகள் fmt/vowels)
(வரையறு மெய்யெழுத்துகள் fmt/consonants)
(வரையறு உயிர்மெய்யெழுத்துகள் (தட்டையாக்கு (விவரி மீதி மெய்-தொடக்கம்-எழுத்துகள்)))
(வரையறு தொடை->எழுத்துகள் fmt/str->letters)
(வரையறு தொடை->ஒலியன்கள் fmt/str->phonemes)
(வரையறு-செயல்கூறு ஒலியன்கள்->எழுத்து [ஒலியன்கள்] (பெறு fmt/inverse-phoneme-map ஒலியன்கள்))
எழுத்து
(வரையறு-செயல்கூறு எழுத்தா? [ச] (fmt/in-trie? ச))
(வரையறு-செயல்கூறு மெய்யெழுத்தா? [எ] (பூலியன் (எதாவது #{எ} மெய்யெழுத்துகள்)))
(வரையறு-செயல்கூறு உயிரெழுத்தா? [எ] (பூலியன் (எதாவது #{எ} உயிரெழுத்துகள்)))
(வரையறு-செயல்கூறு உயிர்மெயெழுத்தா? [எ] (பூலியன் (எதாவது #{எ} உயிர்மெய்யெழுத்துகள்)))
(வரையறு குறில்-உயிரெழுத்துகள் #{"அ" "இ" "உ" "எ" "ஒ"})
(வரையறு நெடில்-உயிரெழுத்துகள் #{"ஆ" "ஈ" "ஊ" "ஏ" "ஓ"})
(வரையறு-செயல்கூறு நெடிலா?
"எழுத்து நெடில் எழுத்தா என்பதைத் திருப்பிக் கொடுக்கும்
returns whether the letter is நெடில் (has long vowel sound)"
[எழுத்து]
(பூலியன்
(என்னும்போது (எழுத்தா? எழுத்து)
ஒலியன் = phoneme
(வைத்துக்கொள் [ஒலியன்கள் (தொடை->ஒலியன்கள் எழுத்து)
கடைசி-ஒலியன் (கடைசி ஒலியன்கள்)]
(பெறு நெடில்-உயிரெழுத்துகள் கடைசி-ஒலியன்)))))
(வரையறு-செயல்கூறு குறிலா?
"எழுத்து குறில் எழுத்தா என்பதைத் திருப்பிக் கொடுக்கும்
returns whether the letter is குறில் (has short vowel sound)"
[எழுத்து]
(பூலியன்
(என்னும்போது (எழுத்தா? எழுத்து)
(->> (தொடை->ஒலியன்கள் எழுத்து)
கடைசி
(பெறு குறில்-உயிரெழுத்துகள்)))))
ஒலியன்
(வரையறு முன்னொட்டா? fmt/prefix?)
(வரையறு பின்னொட்டா? fmt/suffix?)
(வரையறு-செயல்கூறு பன்மை
"ஒரு சொல்லை அதன் பன்மை வடிவத்தில் ஆக்குதல்
takes a word and pluralizes it"
[சொல்]
(வைத்துக்கொள் [எழுத்துகள் (தொடை->எழுத்துகள் சொல்)]
(பொறுத்து
( fmt / seq - prefix ? ( புரட்டு சொல் ) ( புரட்டு " கள் " ) )
(பின்னொட்டா? சொல் "கள்")
சொல்
(= "ம்" (கடைசி எழுத்துகள்))
(செயல்படுத்து தொடை (தொடு (கடைசியின்றி எழுத்துகள்) ["ங்கள்"]))
(மற்றும் (= 1 (எண்ணு எழுத்துகள்))
(நெடிலா? சொல்))
(தொடை சொல் "க்கள்")
(மற்றும் (= 2 (எண்ணு எழுத்துகள்))
(ஒவ்வொன்றுமா? அடையாளம் (விவரி குறிலா? எழுத்துகள்)))
(தொடை சொல் "க்கள்")
(மற்றும் (= 2 (எண்ணு எழுத்துகள்))
(குறிலா? (முதல் எழுத்துகள்))
(= "ல்" (இரண்டாம் எழுத்துகள்)))
(தொடை (முதல் எழுத்துகள்) "ற்கள்")
(மற்றும் (= 2 (எண்ணு எழுத்துகள்))
(குறிலா? (முதல் எழுத்துகள்))
(= "ள்" (இரண்டாம் எழுத்துகள்)))
(தொடை (முதல் எழுத்துகள்) "ட்கள்")
:அன்றி
(தொடை சொல் "கள்"))))
(வரையறு-செயல்கூறு சந்தி
[சொல்1 சொல்2]
(வைத்துக்கொள் [எழுத்துகள்1 (தொடை->எழுத்துகள் சொல்1)
எழுத்துகள்2 (தொடை->எழுத்துகள் சொல்2)
ஒலியன்கள்1 (தொடை->ஒலியன்கள் சொல்1)
ஒலியன்கள்2 (தொடை->ஒலியன்கள் சொல்2)
சொ1-கஒ (கடைசி ஒலியன்கள்1)
சொ2-முஒ (முதல் ஒலியன்கள்2)]
(பொறுத்து
(மற்றும் (உயிரெழுத்தா? சொ2-முஒ)
(பெறு #{"இ" "ஈ" "ஏ" "ஐ"} சொ1-கஒ))
(செயல்படுத்து தொடை சொல்1 (ஒலியன்கள்->எழுத்து ["ய்" சொ2-முஒ]) (மீதி சொல்2))
(மற்றும் (உயிரெழுத்தா? சொ2-முஒ)
(பெறு #{"அ" "ஆ" "ஊ" "ஒ" "ஓ" "ஔ"} சொ1-கஒ))
(செயல்படுத்து தொடை சொல்1 (ஒலியன்கள்->எழுத்து ["வ்" சொ2-முஒ]) (மீதி சொல்2))
(மற்றும் (உயிரெழுத்தா? சொ2-முஒ)
(= "உ" சொ1-கஒ)
(= 2 (எண்ணு எழுத்துகள்1))
(ஒவ்வொன்றுமா? குறிலா? எழுத்துகள்1))
(செயல்படுத்து தொடை சொல்1 (ஒலியன்கள்->எழுத்து ["வ்" சொ2-முஒ]) (மீதி சொல்2))
(மற்றும் (உயிரெழுத்தா? சொ2-முஒ)
(= "உ" சொ1-கஒ)
(அன்று (மற்றும் (= 2 (எண்ணு எழுத்துகள்1))
(ஒவ்வொன்றுமா? குறிலா? எழுத்துகள்1))))
(செயல்படுத்து தொடை (தொடு (கடைசியின்றி எழுத்துகள்1) (ஒலியன்கள்->எழுத்து [(கடைசி (கடைசியின்றி ஒலியன்கள்1)) சொ2-முஒ]) (மீதி சொல்2)))
(மற்றும் (உயிரெழுத்தா? சொ2-முஒ)
(= 2 (எண்ணு எழுத்துகள்1))
(குறிலா? (முதல் எழுத்துகள்1))
(மெய்யெழுத்தா? (இரண்டாம் எழுத்துகள்1)))
(செயல்படுத்து தொடை (தொடு சொல்1 [(ஒலியன்கள்->எழுத்து [சொ1-கஒ சொ2-முஒ])] (மீதி சொல்2)))
(மற்றும் (உயிரெழுத்தா? சொ2-முஒ)
(மெய்யெழுத்தா? சொ1-கஒ))
(செயல்படுத்து தொடை (தொடு (கடைசியின்றி எழுத்துகள்1) [(ஒலியன்கள்->எழுத்து [சொ1-கஒ சொ2-முஒ])] (மீதி சொல்2)))
:அன்றி
(தொடை சொல்1 சொல்2)
)))
(வரையறு-செயல்கூறு வேற்றுமை-முன்-மாற்றம்
"ஒரு பெயர்ச்சொல்லுக்கு வேற்றுமை விகுதி சேர்க்கும் முன் செய்யவேண்டிய மாற்றம்
change that is required before adding a case suffix to a noun"
[சொல்]
(வைத்துக்கொள் [எழுத்துகள் (தொடை->எழுத்துகள் சொல்)
ஒலியன்கள் (தொடை->ஒலியன்கள் சொல்)
கஎ (கடைசி எழுத்துகள்)
கஒ (கடைசி ஒலியன்கள்)]
(பொறுத்து
(= "ம்" (கடைசி எழுத்துகள்))
(செயல்படுத்து தொடை (தொடு (கடைசியின்றி எழுத்துகள்) ["த்த்"]))
(மற்றும் (பெறு #{"டு" "று"} கஎ)
(அல்லது (மற்றும் (= 2 (எண்ணு எழுத்துகள்))
(ஒவ்வொன்றுமா? குறிலா? எழுத்துகள்))
(மெய்யெழுத்தா? (கடைசி (கடைசியின்றி எழுத்துகள்)))))
சொல்
(= "டு" கஎ)
(செயல்படுத்து தொடை (தொடு (கடைசியின்றி எழுத்துகள்) ["ட்ட்"]))
(= "று" கஎ)
(செயல்படுத்து தொடை (தொடு (கடைசியின்றி எழுத்துகள்) ["ற்ற்"]))
:அன்றி
சொல்)))
(வரையறு-செயல்கூறு வேற்றுமை
"ஒரு பெயர்ச்சொல்லுக்கு ஒரு வேற்றுமை விகுதியைச் சேர்த்தல்
adds a case suffix to a noun"
[சொல் வே]
(வைத்துக்கொள் [எழுத்துகள் (தொடை->எழுத்துகள் சொல்)
ஒலியன்கள் (தொடை->ஒலியன்கள் சொல்)]
(எனில் (மற்றும் (= "உக்கு" வே)
(அல்லது (பெறு #{"இ" "ஈ" "ஐ"} (கடைசி ஒலியன்கள்))
(எதாவது (செயல்கூறு [தொடை] (பின்னொட்டா? சொல் தொடை))
["ஆய்"])))
(வேற்றுமை சொல் "க்கு")
(-> சொல்
வேற்றுமை-முன்-மாற்றம்
(சந்தி வே)))))
|
415749022aa47b066e296c632bca82e4bcc4256feca35b5c97f6e6825bfec54c | jtdaugherty/tracy | Phong.hs | module Tracy.Materials.Phong
( phongFromColor
, phong
, reflective
, glossyReflective
)
where
import Control.Lens
import Linear
import Data.Colour
import Tracy.Types
import Tracy.BRDF.GlossySpecular
import Tracy.BRDF.PerfectSpecular
import Tracy.BRDF.Lambertian
phong :: BRDF -> BRDF -> BRDF -> Material
phong ambBrdf diffBrdf glossyBrdf =
Material { _doShading = phongShading ambBrdf diffBrdf glossyBrdf lightContrib
, _doAreaShading = phongShading ambBrdf diffBrdf glossyBrdf areaLightContrib
, _doPathShading = phongPathShading diffBrdf
, _getLe = const cBlack
}
phongFromColor :: Texture -> Double -> Double -> Material
phongFromColor t ks e = phong
(lambertian t 0.25)
(lambertian t 0.65)
(glossySpecular t ks e)
reflective :: Texture -> Double -> Double -> Texture -> Double -> Material
reflective td ks e tr kr =
let ambBrdf = lambertian td 0.25
diffBrdf = lambertian td 0.65
glossyBrdf = glossySpecular td ks e
reflBrdf = perfectSpecular tr kr
in Material { _doShading = reflectiveShading ambBrdf diffBrdf glossyBrdf reflBrdf lightContrib
, _doAreaShading = reflectiveShading ambBrdf diffBrdf glossyBrdf reflBrdf areaLightContrib
, _doPathShading = reflectivePathShading reflBrdf
, _getLe = const cBlack
}
glossyReflective :: Texture -> Double -> Double -> Texture -> Double -> Double -> Material
glossyReflective td ks e tr kr er =
let ambBrdf = lambertian td 0.25
diffBrdf = lambertian td 0.25
glossyBrdf = glossySpecular td ks e
reflBrdf = glossySpecular tr kr er
in Material { _doShading = glossyReflectiveShading ambBrdf diffBrdf glossyBrdf reflBrdf lightContrib
, _doAreaShading = glossyReflectiveShading ambBrdf diffBrdf glossyBrdf reflBrdf areaLightContrib
, _doPathShading = glossyReflectivePathShading glossyBrdf
, _getLe = const cBlack
}
glossyReflectivePathShading :: BRDF -> Shade -> Tracer -> TraceM Color
glossyReflectivePathShading glossyBrdf sh tracer = do
let wo = (-1) *^ (sh^.shadeRay.direction)
(pdf, fr, wi) <- (glossyBrdf^.brdfSampleF) sh wo
let reflected_ray = Ray { _origin = sh^.localHitPoint
, _direction = wi
}
traced <- (tracer^.doTrace) reflected_ray (sh^.depth + 1)
return $ (fr * traced * (grey $ (sh^.normal) `dot` wi)) / (grey pdf)
glossyReflectiveShading :: BRDF -> BRDF -> BRDF -> BRDF
-> (BRDF -> BRDF -> Light -> LightDir -> V3 Double -> Shade -> TraceM Color)
-> Shade -> Tracer -> TraceM Color
glossyReflectiveShading ambBrdf diffBrdf glossyBrdf reflBrdf perLight sh tracer = do
base <- phongShading ambBrdf diffBrdf glossyBrdf perLight sh tracer
let wo = (-1) *^ (sh^.shadeRay.direction)
(pdf, fr, wi) <- (reflBrdf^.brdfSampleF) sh wo
let reflected_ray = Ray { _origin = sh^.localHitPoint
, _direction = wi
}
traced <- (tracer^.doTrace) reflected_ray (sh^.depth + 1)
return $ base + (fr * traced * (grey $ (sh^.normal) `dot` wi)) / (grey pdf)
reflectiveShading :: BRDF -> BRDF -> BRDF -> BRDF
-> (BRDF -> BRDF -> Light -> LightDir -> V3 Double -> Shade -> TraceM Color)
-> Shade -> Tracer -> TraceM Color
reflectiveShading ambBrdf diffBrdf glossyBrdf reflBrdf perLight sh tracer = do
base <- phongShading ambBrdf diffBrdf glossyBrdf perLight sh tracer
let wo = (-1) *^ (sh^.shadeRay.direction)
(_, fr, wi) <- (reflBrdf^.brdfSampleF) sh wo
let reflected_ray = Ray { _origin = sh^.localHitPoint
, _direction = wi
}
traced <- (tracer^.doTrace) reflected_ray (sh^.depth + 1)
return $ base + (fr * traced * (grey $ (sh^.normal) `dot` wi))
reflectivePathShading :: BRDF -> Shade -> Tracer -> TraceM Color
reflectivePathShading reflBrdf sh tracer = do
let wo = (-1) *^ (sh^.shadeRay.direction)
(pdf, fr, wi) <- (reflBrdf^.brdfSampleF) sh wo
let reflected_ray = Ray { _origin = sh^.localHitPoint
, _direction = wi
}
traced <- (tracer^.doTrace) reflected_ray (sh^.depth + 1)
return $ (fr * traced * (grey $ (sh^.normal) `dot` wi)) / (grey pdf)
nullLD :: LightDir
nullLD = LD { _lightDir = V3 0 0 0
, _lightSamplePoint = V3 0 0 0
, _lightNormal = V3 0 0 0
}
phongPathShading :: BRDF -> Shade -> Tracer -> TraceM Color
phongPathShading diffBrdf sh tracer = do
let wo = -1 *^ sh^.shadeRay.direction
(pdf, fr, wi) <- (diffBrdf^.brdfSampleF) sh wo
let reflected_ray = Ray { _origin = sh^.localHitPoint
, _direction = wi
}
traced <- (tracer^.doTrace) reflected_ray (sh^.depth + Depth 1)
return $ (fr * traced * (grey $ (sh^.normal) `dot` wi)) / (grey pdf)
phongShading :: BRDF -> BRDF -> BRDF
-> (BRDF -> BRDF -> Light -> LightDir -> V3 Double -> Shade -> TraceM Color)
-> Shade -> Tracer -> TraceM Color
phongShading ambBrdf diffBrdf glossyBrdf perLight sh _ = do
w <- view tdWorld
ambientColor <- (w^.ambient.lightColor) nullLD sh
let wo = -1 *^ sh^.shadeRay.direction
baseL = (ambBrdf^.brdfRho) sh wo * ambientColor
getL light = do
ld <- (light^.lightDirection) sh
let wi = ld^.lightDir
ndotwi = (sh^.normal) `dot` wi
shad = w^.worldShadows && light^.lightShadows
shadowRay = Ray { _origin = sh^.localHitPoint
, _direction = wi
}
in_shadow <- (light^.inLightShadow) ld shadowRay
case ndotwi > 0 && (not shad || (shad && not in_shadow)) of
True -> perLight diffBrdf glossyBrdf light ld wo sh
False -> return 0.0
otherLs <- mapM getL $ w^.lights
return $ baseL + sum otherLs
lightContrib :: BRDF -> BRDF -> Light -> LightDir -> V3 Double -> Shade -> TraceM Color
lightContrib diffBrdf glossyBrdf light ld wo sh = do
let wi = ld^.lightDir
ndotwi = (sh^.normal) `dot` wi
lColor <- (light^.lightColor) ld sh
return $ ((diffBrdf^.brdfFunction) sh wo wi +
(glossyBrdf^.brdfFunction) sh wo wi) *
lColor * (grey ndotwi)
areaLightContrib :: BRDF -> BRDF -> Light -> LightDir -> V3 Double -> Shade -> TraceM Color
areaLightContrib diffBrdf glossyBrdf light ld wo sh = do
let wi = ld^.lightDir
ndotwi = (sh^.normal) `dot` wi
gValue = (light^.lightG) ld sh
pdfValue = (light^.lightPDF) ld sh
lColor <- (light^.lightColor) ld sh
return $ ((diffBrdf^.brdfFunction) sh wo wi +
(glossyBrdf^.brdfFunction) sh wo wi) *
lColor *
(grey gValue) *
(grey ndotwi) /
(grey pdfValue)
| null | https://raw.githubusercontent.com/jtdaugherty/tracy/ad36ea16a3b9cda5071ca72374d6e1c1b415d520/src/Tracy/Materials/Phong.hs | haskell | module Tracy.Materials.Phong
( phongFromColor
, phong
, reflective
, glossyReflective
)
where
import Control.Lens
import Linear
import Data.Colour
import Tracy.Types
import Tracy.BRDF.GlossySpecular
import Tracy.BRDF.PerfectSpecular
import Tracy.BRDF.Lambertian
phong :: BRDF -> BRDF -> BRDF -> Material
phong ambBrdf diffBrdf glossyBrdf =
Material { _doShading = phongShading ambBrdf diffBrdf glossyBrdf lightContrib
, _doAreaShading = phongShading ambBrdf diffBrdf glossyBrdf areaLightContrib
, _doPathShading = phongPathShading diffBrdf
, _getLe = const cBlack
}
phongFromColor :: Texture -> Double -> Double -> Material
phongFromColor t ks e = phong
(lambertian t 0.25)
(lambertian t 0.65)
(glossySpecular t ks e)
reflective :: Texture -> Double -> Double -> Texture -> Double -> Material
reflective td ks e tr kr =
let ambBrdf = lambertian td 0.25
diffBrdf = lambertian td 0.65
glossyBrdf = glossySpecular td ks e
reflBrdf = perfectSpecular tr kr
in Material { _doShading = reflectiveShading ambBrdf diffBrdf glossyBrdf reflBrdf lightContrib
, _doAreaShading = reflectiveShading ambBrdf diffBrdf glossyBrdf reflBrdf areaLightContrib
, _doPathShading = reflectivePathShading reflBrdf
, _getLe = const cBlack
}
glossyReflective :: Texture -> Double -> Double -> Texture -> Double -> Double -> Material
glossyReflective td ks e tr kr er =
let ambBrdf = lambertian td 0.25
diffBrdf = lambertian td 0.25
glossyBrdf = glossySpecular td ks e
reflBrdf = glossySpecular tr kr er
in Material { _doShading = glossyReflectiveShading ambBrdf diffBrdf glossyBrdf reflBrdf lightContrib
, _doAreaShading = glossyReflectiveShading ambBrdf diffBrdf glossyBrdf reflBrdf areaLightContrib
, _doPathShading = glossyReflectivePathShading glossyBrdf
, _getLe = const cBlack
}
glossyReflectivePathShading :: BRDF -> Shade -> Tracer -> TraceM Color
glossyReflectivePathShading glossyBrdf sh tracer = do
let wo = (-1) *^ (sh^.shadeRay.direction)
(pdf, fr, wi) <- (glossyBrdf^.brdfSampleF) sh wo
let reflected_ray = Ray { _origin = sh^.localHitPoint
, _direction = wi
}
traced <- (tracer^.doTrace) reflected_ray (sh^.depth + 1)
return $ (fr * traced * (grey $ (sh^.normal) `dot` wi)) / (grey pdf)
glossyReflectiveShading :: BRDF -> BRDF -> BRDF -> BRDF
-> (BRDF -> BRDF -> Light -> LightDir -> V3 Double -> Shade -> TraceM Color)
-> Shade -> Tracer -> TraceM Color
glossyReflectiveShading ambBrdf diffBrdf glossyBrdf reflBrdf perLight sh tracer = do
base <- phongShading ambBrdf diffBrdf glossyBrdf perLight sh tracer
let wo = (-1) *^ (sh^.shadeRay.direction)
(pdf, fr, wi) <- (reflBrdf^.brdfSampleF) sh wo
let reflected_ray = Ray { _origin = sh^.localHitPoint
, _direction = wi
}
traced <- (tracer^.doTrace) reflected_ray (sh^.depth + 1)
return $ base + (fr * traced * (grey $ (sh^.normal) `dot` wi)) / (grey pdf)
reflectiveShading :: BRDF -> BRDF -> BRDF -> BRDF
-> (BRDF -> BRDF -> Light -> LightDir -> V3 Double -> Shade -> TraceM Color)
-> Shade -> Tracer -> TraceM Color
reflectiveShading ambBrdf diffBrdf glossyBrdf reflBrdf perLight sh tracer = do
base <- phongShading ambBrdf diffBrdf glossyBrdf perLight sh tracer
let wo = (-1) *^ (sh^.shadeRay.direction)
(_, fr, wi) <- (reflBrdf^.brdfSampleF) sh wo
let reflected_ray = Ray { _origin = sh^.localHitPoint
, _direction = wi
}
traced <- (tracer^.doTrace) reflected_ray (sh^.depth + 1)
return $ base + (fr * traced * (grey $ (sh^.normal) `dot` wi))
reflectivePathShading :: BRDF -> Shade -> Tracer -> TraceM Color
reflectivePathShading reflBrdf sh tracer = do
let wo = (-1) *^ (sh^.shadeRay.direction)
(pdf, fr, wi) <- (reflBrdf^.brdfSampleF) sh wo
let reflected_ray = Ray { _origin = sh^.localHitPoint
, _direction = wi
}
traced <- (tracer^.doTrace) reflected_ray (sh^.depth + 1)
return $ (fr * traced * (grey $ (sh^.normal) `dot` wi)) / (grey pdf)
nullLD :: LightDir
nullLD = LD { _lightDir = V3 0 0 0
, _lightSamplePoint = V3 0 0 0
, _lightNormal = V3 0 0 0
}
phongPathShading :: BRDF -> Shade -> Tracer -> TraceM Color
phongPathShading diffBrdf sh tracer = do
let wo = -1 *^ sh^.shadeRay.direction
(pdf, fr, wi) <- (diffBrdf^.brdfSampleF) sh wo
let reflected_ray = Ray { _origin = sh^.localHitPoint
, _direction = wi
}
traced <- (tracer^.doTrace) reflected_ray (sh^.depth + Depth 1)
return $ (fr * traced * (grey $ (sh^.normal) `dot` wi)) / (grey pdf)
phongShading :: BRDF -> BRDF -> BRDF
-> (BRDF -> BRDF -> Light -> LightDir -> V3 Double -> Shade -> TraceM Color)
-> Shade -> Tracer -> TraceM Color
phongShading ambBrdf diffBrdf glossyBrdf perLight sh _ = do
w <- view tdWorld
ambientColor <- (w^.ambient.lightColor) nullLD sh
let wo = -1 *^ sh^.shadeRay.direction
baseL = (ambBrdf^.brdfRho) sh wo * ambientColor
getL light = do
ld <- (light^.lightDirection) sh
let wi = ld^.lightDir
ndotwi = (sh^.normal) `dot` wi
shad = w^.worldShadows && light^.lightShadows
shadowRay = Ray { _origin = sh^.localHitPoint
, _direction = wi
}
in_shadow <- (light^.inLightShadow) ld shadowRay
case ndotwi > 0 && (not shad || (shad && not in_shadow)) of
True -> perLight diffBrdf glossyBrdf light ld wo sh
False -> return 0.0
otherLs <- mapM getL $ w^.lights
return $ baseL + sum otherLs
lightContrib :: BRDF -> BRDF -> Light -> LightDir -> V3 Double -> Shade -> TraceM Color
lightContrib diffBrdf glossyBrdf light ld wo sh = do
let wi = ld^.lightDir
ndotwi = (sh^.normal) `dot` wi
lColor <- (light^.lightColor) ld sh
return $ ((diffBrdf^.brdfFunction) sh wo wi +
(glossyBrdf^.brdfFunction) sh wo wi) *
lColor * (grey ndotwi)
areaLightContrib :: BRDF -> BRDF -> Light -> LightDir -> V3 Double -> Shade -> TraceM Color
areaLightContrib diffBrdf glossyBrdf light ld wo sh = do
let wi = ld^.lightDir
ndotwi = (sh^.normal) `dot` wi
gValue = (light^.lightG) ld sh
pdfValue = (light^.lightPDF) ld sh
lColor <- (light^.lightColor) ld sh
return $ ((diffBrdf^.brdfFunction) sh wo wi +
(glossyBrdf^.brdfFunction) sh wo wi) *
lColor *
(grey gValue) *
(grey ndotwi) /
(grey pdfValue)
| |
0e4e65bd173232f57dd5a5d1d449b9372914c235f35593a19febf1e91cfe7ca4 | MercuryTechnologies/slack-web | cli.hs | # LANGUAGE LambdaCase #
# LANGUAGE TypeApplications #
-- base
import Control.Exception (throwIO)
import Control.Monad.IO.Class (liftIO)
-- butcher
-- bytestring
-- monad-loops
import Control.Monad.Loops (iterateUntil)
mtl
import Control.Monad.Reader (runReaderT)
import Data.ByteString.Lazy.Char8 qualified as BL
import Data.Functor (void)
-- pretty-simple
-- slack-web
-- text
import Data.Text qualified as Text
import Data.Text.Lazy qualified as TextLazy
-- time
import Data.Time.Clock (addUTCTime, getCurrentTime, nominalDay)
import Data.Time.Clock.POSIX (posixSecondsToUTCTime)
-- servant-client-core
import Servant.Client.Core (ClientError (..), Response, ResponseF (..))
import System.Environment (getEnv)
import System.Exit (die)
import System.IO (hPutStrLn, stderr)
import Text.Pretty.Simple (pPrint, pShow)
import Text.Read (readMaybe)
import UI.Butcher.Monadic
import Web.Slack.Classy qualified as Slack
import Web.Slack.Common qualified as Slack
import Web.Slack.Conversation qualified as SlackConversation
main :: IO ()
main = do
apiConfig <- Slack.mkSlackConfig . Text.pack =<< getEnv "SLACK_API_TOKEN"
mainFromCmdParserWithHelpDesc $ \helpDesc -> do
addHelpCommand helpDesc
addCmd "conversations.list" . addCmdImpl $ do
let listReq =
SlackConversation.ListReq
{ SlackConversation.listReqExcludeArchived = Just True
, SlackConversation.listReqTypes =
[ SlackConversation.PublicChannelType
, SlackConversation.PrivateChannelType
, SlackConversation.MpimType
, SlackConversation.ImType
]
}
Slack.conversationsList listReq
`runReaderT` apiConfig
>>= \case
Right (SlackConversation.ListRsp cs) -> do
pPrint cs
Left err -> do
peepInResponseBody err
hPutStrLn stderr "Error when fetching the list of conversations:"
die . TextLazy.unpack $ pShow err
addCmd "conversations.history" $ do
conversationId <-
Slack.ConversationId . Text.pack
<$> addParamString "CONVERSATION_ID" (paramHelpStr "ID of the conversation to fetch")
getsAll <- addSimpleBoolFlag "A" ["all"] (flagHelpStr "Get all available messages in the channel")
addCmdImpl $
if getsAll
then do
(`runReaderT` apiConfig) $ do
fetchPage <- Slack.conversationsHistoryAll $ (SlackConversation.mkHistoryReq conversationId) {SlackConversation.historyReqCount = 2}
void . iterateUntil null $ do
result <- either (liftIO . throwIO) return =<< fetchPage
liftIO $ pPrint result
return result
else do
nowUtc <- getCurrentTime
let now = Slack.mkSlackTimestamp nowUtc
thirtyDaysAgo = Slack.mkSlackTimestamp $ addUTCTime (nominalDay * negate 30) nowUtc
histReq =
SlackConversation.HistoryReq
{ SlackConversation.historyReqChannel = conversationId
, SlackConversation.historyReqCount = 5
, SlackConversation.historyReqLatest = Just now
, SlackConversation.historyReqOldest = Just thirtyDaysAgo
, SlackConversation.historyReqInclusive = True
, SlackConversation.historyReqCursor = Nothing
}
Slack.conversationsHistory histReq
`runReaderT` apiConfig
>>= \case
Right rsp ->
pPrint rsp
Left err -> do
peepInResponseBody err
hPutStrLn stderr "Error when fetching the history of conversations:"
die . TextLazy.unpack $ pShow err
addCmd "conversations.replies" $ do
conversationId <-
Slack.ConversationId . Text.pack
<$> addParamString "CONVERSATION_ID" (paramHelpStr "ID of the conversation to fetch")
threadTimeStampStr <- addParamString "TIMESTAMP" (paramHelpStr "Timestamp of the thread to fetch")
let ethreadTimeStamp = Slack.timestampFromText $ Text.pack threadTimeStampStr
pageSize <- addParamRead "PAGE_SIZE" (paramHelpStr "How many messages to get by a request.")
addCmdImpl $ do
NOTE : butcher 's CmdParser is n't a MonadFail
threadTimeStamp <-
either
(\emsg -> fail $ "Invalid timestamp " ++ show threadTimeStampStr ++ ": " ++ emsg)
return
ethreadTimeStamp
nowUtc <- getCurrentTime
let now = Slack.mkSlackTimestamp nowUtc
tenDaysAgo = Slack.mkSlackTimestamp $ addUTCTime (nominalDay * negate 10) nowUtc
req =
(SlackConversation.mkRepliesReq conversationId threadTimeStamp)
{ SlackConversation.repliesReqLimit = pageSize
, SlackConversation.repliesReqLatest = Just now
, SlackConversation.repliesReqOldest = Just tenDaysAgo
}
(`runReaderT` apiConfig) $ do
fetchPage <- Slack.repliesFetchAll req
void . iterateUntil null $ do
result <- either (liftIO . throwIO) return =<< fetchPage
liftIO $ pPrint result
return result
peepInResponseBody err = do
Uncomment these lines when you want to see the JSON in the reponse body .
case err of
Slack . ServantError ( DecodeFailure _ res ) - >
BL.putStrLn $ responseBody res
_ - > return ( )
case err of
Slack.ServantError (DecodeFailure _ res) ->
BL.putStrLn $ responseBody res
_ -> return ()
-}
return ()
| null | https://raw.githubusercontent.com/MercuryTechnologies/slack-web/9b0d819b5a6feb8b419418fdbbaea78a42d78137/main/cli.hs | haskell | base
butcher
bytestring
monad-loops
pretty-simple
slack-web
text
time
servant-client-core | # LANGUAGE LambdaCase #
# LANGUAGE TypeApplications #
import Control.Exception (throwIO)
import Control.Monad.IO.Class (liftIO)
import Control.Monad.Loops (iterateUntil)
mtl
import Control.Monad.Reader (runReaderT)
import Data.ByteString.Lazy.Char8 qualified as BL
import Data.Functor (void)
import Data.Text qualified as Text
import Data.Text.Lazy qualified as TextLazy
import Data.Time.Clock (addUTCTime, getCurrentTime, nominalDay)
import Data.Time.Clock.POSIX (posixSecondsToUTCTime)
import Servant.Client.Core (ClientError (..), Response, ResponseF (..))
import System.Environment (getEnv)
import System.Exit (die)
import System.IO (hPutStrLn, stderr)
import Text.Pretty.Simple (pPrint, pShow)
import Text.Read (readMaybe)
import UI.Butcher.Monadic
import Web.Slack.Classy qualified as Slack
import Web.Slack.Common qualified as Slack
import Web.Slack.Conversation qualified as SlackConversation
main :: IO ()
main = do
apiConfig <- Slack.mkSlackConfig . Text.pack =<< getEnv "SLACK_API_TOKEN"
mainFromCmdParserWithHelpDesc $ \helpDesc -> do
addHelpCommand helpDesc
addCmd "conversations.list" . addCmdImpl $ do
let listReq =
SlackConversation.ListReq
{ SlackConversation.listReqExcludeArchived = Just True
, SlackConversation.listReqTypes =
[ SlackConversation.PublicChannelType
, SlackConversation.PrivateChannelType
, SlackConversation.MpimType
, SlackConversation.ImType
]
}
Slack.conversationsList listReq
`runReaderT` apiConfig
>>= \case
Right (SlackConversation.ListRsp cs) -> do
pPrint cs
Left err -> do
peepInResponseBody err
hPutStrLn stderr "Error when fetching the list of conversations:"
die . TextLazy.unpack $ pShow err
addCmd "conversations.history" $ do
conversationId <-
Slack.ConversationId . Text.pack
<$> addParamString "CONVERSATION_ID" (paramHelpStr "ID of the conversation to fetch")
getsAll <- addSimpleBoolFlag "A" ["all"] (flagHelpStr "Get all available messages in the channel")
addCmdImpl $
if getsAll
then do
(`runReaderT` apiConfig) $ do
fetchPage <- Slack.conversationsHistoryAll $ (SlackConversation.mkHistoryReq conversationId) {SlackConversation.historyReqCount = 2}
void . iterateUntil null $ do
result <- either (liftIO . throwIO) return =<< fetchPage
liftIO $ pPrint result
return result
else do
nowUtc <- getCurrentTime
let now = Slack.mkSlackTimestamp nowUtc
thirtyDaysAgo = Slack.mkSlackTimestamp $ addUTCTime (nominalDay * negate 30) nowUtc
histReq =
SlackConversation.HistoryReq
{ SlackConversation.historyReqChannel = conversationId
, SlackConversation.historyReqCount = 5
, SlackConversation.historyReqLatest = Just now
, SlackConversation.historyReqOldest = Just thirtyDaysAgo
, SlackConversation.historyReqInclusive = True
, SlackConversation.historyReqCursor = Nothing
}
Slack.conversationsHistory histReq
`runReaderT` apiConfig
>>= \case
Right rsp ->
pPrint rsp
Left err -> do
peepInResponseBody err
hPutStrLn stderr "Error when fetching the history of conversations:"
die . TextLazy.unpack $ pShow err
addCmd "conversations.replies" $ do
conversationId <-
Slack.ConversationId . Text.pack
<$> addParamString "CONVERSATION_ID" (paramHelpStr "ID of the conversation to fetch")
threadTimeStampStr <- addParamString "TIMESTAMP" (paramHelpStr "Timestamp of the thread to fetch")
let ethreadTimeStamp = Slack.timestampFromText $ Text.pack threadTimeStampStr
pageSize <- addParamRead "PAGE_SIZE" (paramHelpStr "How many messages to get by a request.")
addCmdImpl $ do
NOTE : butcher 's CmdParser is n't a MonadFail
threadTimeStamp <-
either
(\emsg -> fail $ "Invalid timestamp " ++ show threadTimeStampStr ++ ": " ++ emsg)
return
ethreadTimeStamp
nowUtc <- getCurrentTime
let now = Slack.mkSlackTimestamp nowUtc
tenDaysAgo = Slack.mkSlackTimestamp $ addUTCTime (nominalDay * negate 10) nowUtc
req =
(SlackConversation.mkRepliesReq conversationId threadTimeStamp)
{ SlackConversation.repliesReqLimit = pageSize
, SlackConversation.repliesReqLatest = Just now
, SlackConversation.repliesReqOldest = Just tenDaysAgo
}
(`runReaderT` apiConfig) $ do
fetchPage <- Slack.repliesFetchAll req
void . iterateUntil null $ do
result <- either (liftIO . throwIO) return =<< fetchPage
liftIO $ pPrint result
return result
peepInResponseBody err = do
Uncomment these lines when you want to see the JSON in the reponse body .
case err of
Slack . ServantError ( DecodeFailure _ res ) - >
BL.putStrLn $ responseBody res
_ - > return ( )
case err of
Slack.ServantError (DecodeFailure _ res) ->
BL.putStrLn $ responseBody res
_ -> return ()
-}
return ()
|
0d10975422bb783aa02f1b506cd7938317f0cf76de993f25919da859f923f876 | janestreet/lwt-async | lwt_bytes.ml | Lightweight thread library for
* Module Lwt_unix
* Copyright ( C ) 2010
* 2010
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation , with linking exceptions ;
* either version 2.1 of the License , or ( at your option ) any later
* version . See COPYING file for details .
*
* This program is distributed in the hope that it will be useful , but
* WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU
* Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA
* 02111 - 1307 , USA .
*
* Module Lwt_unix
* Copyright (C) 2010 Jérémie Dimino
* 2010 Pierre Chambart
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, with linking exceptions;
* either version 2.1 of the License, or (at your option) any later
* version. See COPYING file for details.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*)
#include "src/unix/lwt_config.ml"
open Bigarray
open Lwt
type t = (char, int8_unsigned_elt, c_layout) Array1.t
let create size = Array1.create char c_layout size
let length bytes = Array1.dim bytes
external get : t -> int -> char = "%caml_ba_ref_1"
external set : t -> int -> char -> unit = "%caml_ba_set_1"
external unsafe_get : t -> int -> char = "%caml_ba_unsafe_ref_1"
external unsafe_set : t -> int -> char -> unit = "%caml_ba_unsafe_set_1"
external unsafe_fill : t -> int -> int -> char -> unit = "lwt_unix_fill_bytes" "noalloc"
let fill bytes ofs len ch =
if ofs < 0 || len < 0 || ofs > length bytes - len then
invalid_arg "Lwt_bytes.fill"
else
unsafe_fill bytes ofs len ch
(* +-----------------------------------------------------------------+
| Blitting |
+-----------------------------------------------------------------+ *)
external unsafe_blit_string_bytes : string -> int -> t -> int -> int -> unit = "lwt_unix_blit_string_bytes" "noalloc"
external unsafe_blit_bytes_string : t -> int -> string -> int -> int -> unit = "lwt_unix_blit_bytes_string" "noalloc"
external unsafe_blit : t -> int -> t -> int -> int -> unit = "lwt_unix_blit_bytes_bytes" "noalloc"
let blit_string_bytes src_buf src_ofs dst_buf dst_ofs len =
if (len < 0
|| src_ofs < 0 || src_ofs > String.length src_buf - len
|| dst_ofs < 0 || dst_ofs > length dst_buf - len) then
invalid_arg "String.blit"
else
unsafe_blit_string_bytes src_buf src_ofs dst_buf dst_ofs len
let blit_bytes_string src_buf src_ofs dst_buf dst_ofs len =
if (len < 0
|| src_ofs < 0 || src_ofs > length src_buf - len
|| dst_ofs < 0 || dst_ofs > String.length dst_buf - len) then
invalid_arg "String.blit"
else
unsafe_blit_bytes_string src_buf src_ofs dst_buf dst_ofs len
let blit src_buf src_ofs dst_buf dst_ofs len =
if (len < 0
|| src_ofs < 0 || src_ofs > length src_buf - len
|| dst_ofs < 0 || dst_ofs > length dst_buf - len) then
invalid_arg "String.blit"
else
unsafe_blit src_buf src_ofs dst_buf dst_ofs len
let of_string str =
let len = String.length str in
let bytes = create len in
unsafe_blit_string_bytes str 0 bytes 0 len;
bytes
let to_string bytes =
let len = length bytes in
let str = String.create len in
unsafe_blit_bytes_string bytes 0 str 0 len;
str
let proxy = Array1.sub
let extract buf ofs len =
if ofs < 0 || len < 0 || ofs > length buf - len then
invalid_arg "Lwt_bytes.extract"
else begin
let buf' = create len in
blit buf ofs buf' 0 len;
buf'
end
let copy buf =
let len = length buf in
let buf' = create len in
blit buf 0 buf' 0 len;
buf'
(* +-----------------------------------------------------------------+
| IOs |
+-----------------------------------------------------------------+ *)
open Lwt_unix
external stub_read : Unix.file_descr -> t -> int -> int -> int = "lwt_unix_bytes_read"
external read_job : Unix.file_descr -> t -> int -> int -> int job = "lwt_unix_bytes_read_job"
let read fd buf pos len =
if pos < 0 || len < 0 || pos > length buf - len then
invalid_arg "Lwt_bytes.read"
else
blocking fd >>= function
| true ->
lwt () = wait_read fd in
run_job (read_job (unix_file_descr fd) buf pos len)
| false ->
wrap_syscall Read fd (fun () -> stub_read (unix_file_descr fd) buf pos len)
external stub_write : Unix.file_descr -> t -> int -> int -> int = "lwt_unix_bytes_write"
external write_job : Unix.file_descr -> t -> int -> int -> int job = "lwt_unix_bytes_write_job"
let write fd buf pos len =
if pos < 0 || len < 0 || pos > length buf - len then
invalid_arg "Lwt_bytes.write"
else
blocking fd >>= function
| true ->
lwt () = wait_write fd in
run_job (write_job (unix_file_descr fd) buf pos len)
| false ->
wrap_syscall Write fd (fun () -> stub_write (unix_file_descr fd) buf pos len)
#if windows
let recv fd buf pos len flags =
raise (Lwt_sys.Not_available "Lwt_bytes.recv")
#else
external stub_recv : Unix.file_descr -> t -> int -> int -> Unix.msg_flag list -> int = "lwt_unix_bytes_recv"
let recv fd buf pos len flags =
if pos < 0 || len < 0 || pos > length buf - len then
invalid_arg "recv"
else
wrap_syscall Read fd (fun () -> stub_recv (unix_file_descr fd) buf pos len flags)
#endif
#if windows
let send fd buf pos len flags =
raise (Lwt_sys.Not_available "Lwt_bytes.send")
#else
external stub_send : Unix.file_descr -> t -> int -> int -> Unix.msg_flag list -> int = "lwt_unix_bytes_send"
let send fd buf pos len flags =
if pos < 0 || len < 0 || pos > length buf - len then
invalid_arg "send"
else
wrap_syscall Write fd (fun () -> stub_send (unix_file_descr fd) buf pos len flags)
#endif
type io_vector = {
iov_buffer : t;
iov_offset : int;
iov_length : int;
}
let io_vector ~buffer ~offset ~length = {
iov_buffer = buffer;
iov_offset = offset;
iov_length = length;
}
let check_io_vectors func_name iovs =
List.iter
(fun iov ->
if iov.iov_offset < 0
|| iov.iov_length < 0
|| iov.iov_offset > length iov.iov_buffer - iov.iov_length then
invalid_arg func_name)
iovs
#if windows
let recv_msg ~socket ~io_vectors =
raise (Lwt_sys.Not_available "recv_msg")
#else
external stub_recv_msg : Unix.file_descr -> int -> io_vector list -> int * Unix.file_descr list = "lwt_unix_bytes_recv_msg"
let recv_msg ~socket ~io_vectors =
check_io_vectors "recv_msg" io_vectors;
let n_iovs = List.length io_vectors in
wrap_syscall Read socket
(fun () ->
stub_recv_msg (unix_file_descr socket) n_iovs io_vectors)
#endif
#if windows
let send_msg ~socket ~io_vectors ~fds =
raise (Lwt_sys.Not_available "send_msg")
#else
external stub_send_msg : Unix.file_descr -> int -> io_vector list -> int -> Unix.file_descr list -> int = "lwt_unix_bytes_send_msg"
let send_msg ~socket ~io_vectors ~fds =
check_io_vectors "send_msg" io_vectors;
let n_iovs = List.length io_vectors and n_fds = List.length fds in
wrap_syscall Write socket
(fun () ->
stub_send_msg (unix_file_descr socket) n_iovs io_vectors n_fds fds)
#endif
#if windows
let recvfrom fd buf pos len flags =
raise (Lwt_sys.Not_available "Lwt_bytes.recvfrom")
#else
external stub_recvfrom : Unix.file_descr -> t -> int -> int -> Unix.msg_flag list -> int * Unix.sockaddr = "lwt_unix_bytes_recvfrom"
let recvfrom fd buf pos len flags =
if pos < 0 || len < 0 || pos > length buf - len then
invalid_arg "Lwt_bytes.recvfrom"
else
wrap_syscall Read fd (fun () -> stub_recvfrom (unix_file_descr fd) buf pos len flags)
#endif
#if windows
let sendto fd buf pos len flags addr =
raise (Lwt_sys.Not_available "Lwt_bytes.sendto")
#else
external stub_sendto : Unix.file_descr -> t -> int -> int -> Unix.msg_flag list -> Unix.sockaddr -> int = "lwt_unix_bytes_sendto_byte" "lwt_unix_bytes_sendto"
let sendto fd buf pos len flags addr =
if pos < 0 || len < 0 || pos > length buf - len then
invalid_arg "Lwt_bytes.sendto"
else
wrap_syscall Write fd (fun () -> stub_sendto (unix_file_descr fd) buf pos len flags addr)
#endif
(* +-----------------------------------------------------------------+
| Memory mapped files |
+-----------------------------------------------------------------+ *)
let map_file ~fd ?pos ~shared ?(size=(-1)) () =
Array1.map_file fd ?pos char c_layout shared size
external mapped : t -> bool = "lwt_unix_mapped" "noalloc"
type advice =
| MADV_NORMAL
| MADV_RANDOM
| MADV_SEQUENTIAL
| MADV_WILLNEED
| MADV_DONTNEED
#if windows
let madvise buf pos len advice =
raise (Lwt_sys.Not_available "madvise")
#else
external stub_madvise : t -> int -> int -> advice -> unit = "lwt_unix_madvise"
let madvise buf pos len advice =
if pos < 0 || len < 0 || pos > length buf - len then
invalid_arg "Lwt_bytes.madvise"
else
stub_madvise buf pos len advice
#endif
external get_page_size : unit -> int = "lwt_unix_get_page_size"
let page_size = get_page_size ()
#if windows
let mincore buffer offset states =
raise (Lwt_sys.Not_available "mincore")
let wait_mincore buffer offset =
raise (Lwt_sys.Not_available "mincore")
#else
external stub_mincore : t -> int -> int -> bool array -> unit = "lwt_unix_mincore"
let mincore buffer offset states =
if (offset mod page_size <> 0
|| offset < 0
|| offset > length buffer - (Array.length states * page_size)) then
invalid_arg "Lwt_bytes.mincore"
else
stub_mincore buffer offset (Array.length states * page_size) states
external wait_mincore_job : t -> int -> unit job = "lwt_unix_wait_mincore_job"
let wait_mincore buffer offset =
if offset < 0 || offset >= length buffer then
invalid_arg "Lwt_bytes.wait_mincore"
else begin
let state = [|false|] in
mincore buffer (offset - (offset mod page_size)) state;
if state.(0) then
return ()
else
run_job (wait_mincore_job buffer offset)
end
#endif
| null | https://raw.githubusercontent.com/janestreet/lwt-async/c738e6202c1c7409e079e513c7bdf469f7f9984c/src/unix/lwt_bytes.ml | ocaml | +-----------------------------------------------------------------+
| Blitting |
+-----------------------------------------------------------------+
+-----------------------------------------------------------------+
| IOs |
+-----------------------------------------------------------------+
+-----------------------------------------------------------------+
| Memory mapped files |
+-----------------------------------------------------------------+ | Lightweight thread library for
* Module Lwt_unix
* Copyright ( C ) 2010
* 2010
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation , with linking exceptions ;
* either version 2.1 of the License , or ( at your option ) any later
* version . See COPYING file for details .
*
* This program is distributed in the hope that it will be useful , but
* WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU
* Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA
* 02111 - 1307 , USA .
*
* Module Lwt_unix
* Copyright (C) 2010 Jérémie Dimino
* 2010 Pierre Chambart
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, with linking exceptions;
* either version 2.1 of the License, or (at your option) any later
* version. See COPYING file for details.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*)
#include "src/unix/lwt_config.ml"
open Bigarray
open Lwt
type t = (char, int8_unsigned_elt, c_layout) Array1.t
let create size = Array1.create char c_layout size
let length bytes = Array1.dim bytes
external get : t -> int -> char = "%caml_ba_ref_1"
external set : t -> int -> char -> unit = "%caml_ba_set_1"
external unsafe_get : t -> int -> char = "%caml_ba_unsafe_ref_1"
external unsafe_set : t -> int -> char -> unit = "%caml_ba_unsafe_set_1"
external unsafe_fill : t -> int -> int -> char -> unit = "lwt_unix_fill_bytes" "noalloc"
let fill bytes ofs len ch =
if ofs < 0 || len < 0 || ofs > length bytes - len then
invalid_arg "Lwt_bytes.fill"
else
unsafe_fill bytes ofs len ch
external unsafe_blit_string_bytes : string -> int -> t -> int -> int -> unit = "lwt_unix_blit_string_bytes" "noalloc"
external unsafe_blit_bytes_string : t -> int -> string -> int -> int -> unit = "lwt_unix_blit_bytes_string" "noalloc"
external unsafe_blit : t -> int -> t -> int -> int -> unit = "lwt_unix_blit_bytes_bytes" "noalloc"
let blit_string_bytes src_buf src_ofs dst_buf dst_ofs len =
if (len < 0
|| src_ofs < 0 || src_ofs > String.length src_buf - len
|| dst_ofs < 0 || dst_ofs > length dst_buf - len) then
invalid_arg "String.blit"
else
unsafe_blit_string_bytes src_buf src_ofs dst_buf dst_ofs len
let blit_bytes_string src_buf src_ofs dst_buf dst_ofs len =
if (len < 0
|| src_ofs < 0 || src_ofs > length src_buf - len
|| dst_ofs < 0 || dst_ofs > String.length dst_buf - len) then
invalid_arg "String.blit"
else
unsafe_blit_bytes_string src_buf src_ofs dst_buf dst_ofs len
let blit src_buf src_ofs dst_buf dst_ofs len =
if (len < 0
|| src_ofs < 0 || src_ofs > length src_buf - len
|| dst_ofs < 0 || dst_ofs > length dst_buf - len) then
invalid_arg "String.blit"
else
unsafe_blit src_buf src_ofs dst_buf dst_ofs len
let of_string str =
let len = String.length str in
let bytes = create len in
unsafe_blit_string_bytes str 0 bytes 0 len;
bytes
let to_string bytes =
let len = length bytes in
let str = String.create len in
unsafe_blit_bytes_string bytes 0 str 0 len;
str
let proxy = Array1.sub
let extract buf ofs len =
if ofs < 0 || len < 0 || ofs > length buf - len then
invalid_arg "Lwt_bytes.extract"
else begin
let buf' = create len in
blit buf ofs buf' 0 len;
buf'
end
let copy buf =
let len = length buf in
let buf' = create len in
blit buf 0 buf' 0 len;
buf'
open Lwt_unix
external stub_read : Unix.file_descr -> t -> int -> int -> int = "lwt_unix_bytes_read"
external read_job : Unix.file_descr -> t -> int -> int -> int job = "lwt_unix_bytes_read_job"
let read fd buf pos len =
if pos < 0 || len < 0 || pos > length buf - len then
invalid_arg "Lwt_bytes.read"
else
blocking fd >>= function
| true ->
lwt () = wait_read fd in
run_job (read_job (unix_file_descr fd) buf pos len)
| false ->
wrap_syscall Read fd (fun () -> stub_read (unix_file_descr fd) buf pos len)
external stub_write : Unix.file_descr -> t -> int -> int -> int = "lwt_unix_bytes_write"
external write_job : Unix.file_descr -> t -> int -> int -> int job = "lwt_unix_bytes_write_job"
let write fd buf pos len =
if pos < 0 || len < 0 || pos > length buf - len then
invalid_arg "Lwt_bytes.write"
else
blocking fd >>= function
| true ->
lwt () = wait_write fd in
run_job (write_job (unix_file_descr fd) buf pos len)
| false ->
wrap_syscall Write fd (fun () -> stub_write (unix_file_descr fd) buf pos len)
#if windows
let recv fd buf pos len flags =
raise (Lwt_sys.Not_available "Lwt_bytes.recv")
#else
external stub_recv : Unix.file_descr -> t -> int -> int -> Unix.msg_flag list -> int = "lwt_unix_bytes_recv"
let recv fd buf pos len flags =
if pos < 0 || len < 0 || pos > length buf - len then
invalid_arg "recv"
else
wrap_syscall Read fd (fun () -> stub_recv (unix_file_descr fd) buf pos len flags)
#endif
#if windows
let send fd buf pos len flags =
raise (Lwt_sys.Not_available "Lwt_bytes.send")
#else
external stub_send : Unix.file_descr -> t -> int -> int -> Unix.msg_flag list -> int = "lwt_unix_bytes_send"
let send fd buf pos len flags =
if pos < 0 || len < 0 || pos > length buf - len then
invalid_arg "send"
else
wrap_syscall Write fd (fun () -> stub_send (unix_file_descr fd) buf pos len flags)
#endif
type io_vector = {
iov_buffer : t;
iov_offset : int;
iov_length : int;
}
let io_vector ~buffer ~offset ~length = {
iov_buffer = buffer;
iov_offset = offset;
iov_length = length;
}
let check_io_vectors func_name iovs =
List.iter
(fun iov ->
if iov.iov_offset < 0
|| iov.iov_length < 0
|| iov.iov_offset > length iov.iov_buffer - iov.iov_length then
invalid_arg func_name)
iovs
#if windows
let recv_msg ~socket ~io_vectors =
raise (Lwt_sys.Not_available "recv_msg")
#else
external stub_recv_msg : Unix.file_descr -> int -> io_vector list -> int * Unix.file_descr list = "lwt_unix_bytes_recv_msg"
let recv_msg ~socket ~io_vectors =
check_io_vectors "recv_msg" io_vectors;
let n_iovs = List.length io_vectors in
wrap_syscall Read socket
(fun () ->
stub_recv_msg (unix_file_descr socket) n_iovs io_vectors)
#endif
#if windows
let send_msg ~socket ~io_vectors ~fds =
raise (Lwt_sys.Not_available "send_msg")
#else
external stub_send_msg : Unix.file_descr -> int -> io_vector list -> int -> Unix.file_descr list -> int = "lwt_unix_bytes_send_msg"
let send_msg ~socket ~io_vectors ~fds =
check_io_vectors "send_msg" io_vectors;
let n_iovs = List.length io_vectors and n_fds = List.length fds in
wrap_syscall Write socket
(fun () ->
stub_send_msg (unix_file_descr socket) n_iovs io_vectors n_fds fds)
#endif
#if windows
let recvfrom fd buf pos len flags =
raise (Lwt_sys.Not_available "Lwt_bytes.recvfrom")
#else
external stub_recvfrom : Unix.file_descr -> t -> int -> int -> Unix.msg_flag list -> int * Unix.sockaddr = "lwt_unix_bytes_recvfrom"
let recvfrom fd buf pos len flags =
if pos < 0 || len < 0 || pos > length buf - len then
invalid_arg "Lwt_bytes.recvfrom"
else
wrap_syscall Read fd (fun () -> stub_recvfrom (unix_file_descr fd) buf pos len flags)
#endif
#if windows
let sendto fd buf pos len flags addr =
raise (Lwt_sys.Not_available "Lwt_bytes.sendto")
#else
external stub_sendto : Unix.file_descr -> t -> int -> int -> Unix.msg_flag list -> Unix.sockaddr -> int = "lwt_unix_bytes_sendto_byte" "lwt_unix_bytes_sendto"
let sendto fd buf pos len flags addr =
if pos < 0 || len < 0 || pos > length buf - len then
invalid_arg "Lwt_bytes.sendto"
else
wrap_syscall Write fd (fun () -> stub_sendto (unix_file_descr fd) buf pos len flags addr)
#endif
let map_file ~fd ?pos ~shared ?(size=(-1)) () =
Array1.map_file fd ?pos char c_layout shared size
external mapped : t -> bool = "lwt_unix_mapped" "noalloc"
type advice =
| MADV_NORMAL
| MADV_RANDOM
| MADV_SEQUENTIAL
| MADV_WILLNEED
| MADV_DONTNEED
#if windows
let madvise buf pos len advice =
raise (Lwt_sys.Not_available "madvise")
#else
external stub_madvise : t -> int -> int -> advice -> unit = "lwt_unix_madvise"
let madvise buf pos len advice =
if pos < 0 || len < 0 || pos > length buf - len then
invalid_arg "Lwt_bytes.madvise"
else
stub_madvise buf pos len advice
#endif
external get_page_size : unit -> int = "lwt_unix_get_page_size"
let page_size = get_page_size ()
#if windows
let mincore buffer offset states =
raise (Lwt_sys.Not_available "mincore")
let wait_mincore buffer offset =
raise (Lwt_sys.Not_available "mincore")
#else
external stub_mincore : t -> int -> int -> bool array -> unit = "lwt_unix_mincore"
let mincore buffer offset states =
if (offset mod page_size <> 0
|| offset < 0
|| offset > length buffer - (Array.length states * page_size)) then
invalid_arg "Lwt_bytes.mincore"
else
stub_mincore buffer offset (Array.length states * page_size) states
external wait_mincore_job : t -> int -> unit job = "lwt_unix_wait_mincore_job"
let wait_mincore buffer offset =
if offset < 0 || offset >= length buffer then
invalid_arg "Lwt_bytes.wait_mincore"
else begin
let state = [|false|] in
mincore buffer (offset - (offset mod page_size)) state;
if state.(0) then
return ()
else
run_job (wait_mincore_job buffer offset)
end
#endif
|
8d8a4bd2b579827e883128c8d8cf7cd380b73debb6188f4c9615ce7c2321167f | wdebeaum/step | ambiguous.lisp | ;;;;
;;;; w::ambiguous
;;;;
(define-words :pos W::adj
:templ CENTRAL-ADJ-TEMPL
:words (
(w::ambiguous
(senses
((lf-parent ont::ambiguous-val)
(example "he provided ambiguous instructions")
)
))
))
| null | https://raw.githubusercontent.com/wdebeaum/step/f38c07d9cd3a58d0e0183159d4445de9a0eafe26/src/LexiconManager/Data/new/ambiguous.lisp | lisp |
w::ambiguous
|
(define-words :pos W::adj
:templ CENTRAL-ADJ-TEMPL
:words (
(w::ambiguous
(senses
((lf-parent ont::ambiguous-val)
(example "he provided ambiguous instructions")
)
))
))
|
d50a954143ca92323a1c14acf71e81e93d45294349150d2d0e047bf12dc59797 | mwand/eopl3 | data-structures.scm | (module data-structures (lib "eopl.ss" "eopl")
data structures for LEXADDR language
(require "lang.scm") ; for expression?
(provide (all-defined-out)) ; too many things to list
;;;;;;;;;;;;;;;; expressed values ;;;;;;;;;;;;;;;;
;;; an expressed value is either a number, a boolean or a procval.
(define-datatype expval expval?
(num-val
(value number?))
(bool-val
(boolean boolean?))
(proc-val
(proc proc?)))
;;; extractors:
;; expval->num : ExpVal -> Int
(define expval->num
(lambda (v)
(cases expval v
(num-val (num) num)
(else (expval-extractor-error 'num v)))))
;; expval->bool : ExpVal -> Bool
(define expval->bool
(lambda (v)
(cases expval v
(bool-val (bool) bool)
(else (expval-extractor-error 'bool v)))))
;; expval->proc : ExpVal -> Proc
(define expval->proc
(lambda (v)
(cases expval v
(proc-val (proc) proc)
(else (expval-extractor-error 'proc v)))))
(define expval-extractor-error
(lambda (variant value)
(eopl:error 'expval-extractors "Looking for a ~s, found ~s"
variant value)))
;;;;;;;;;;;;;;;; procedures ;;;;;;;;;;;;;;;;
;; proc? : SchemeVal -> Bool
;; procedure : Exp * Nameless-env -> Proc
(define-datatype proc proc?
(procedure
in LEXADDR , bound variables are replaced by % nameless - vars , so
;; there is no need to declare bound variables.
;; (bvar symbol?)
(body expression?)
;; and the closure contains a nameless environment
(env nameless-environment?)))
;;;;;;;;;;;;;;;; environment constructors and observers ;;;;;;;;;;;;;;;;
;; nameless-environment? : SchemeVal -> Bool
Page : 99
(define nameless-environment?
(lambda (x)
((list-of expval?) x)))
;; empty-nameless-env : () -> Nameless-env
Page : 99
(define empty-nameless-env
(lambda ()
'()))
;; empty-nameless-env? : Nameless-env -> Bool
(define empty-nameless-env?
(lambda (x)
(null? x)))
;; extend-nameless-env : ExpVal * Nameless-env -> Nameless-env
Page : 99
(define extend-nameless-env
(lambda (val nameless-env)
(cons val nameless-env)))
apply - nameless - env : Nameless - env * Lexaddr - > ExpVal
Page : 99
(define apply-nameless-env
(lambda (nameless-env n)
(list-ref nameless-env n)))
)
| null | https://raw.githubusercontent.com/mwand/eopl3/b50e015be7f021d94c1af5f0e3a05d40dd2b0cbf/chapter3/lexaddr-lang/data-structures.scm | scheme | for expression?
too many things to list
expressed values ;;;;;;;;;;;;;;;;
an expressed value is either a number, a boolean or a procval.
extractors:
expval->num : ExpVal -> Int
expval->bool : ExpVal -> Bool
expval->proc : ExpVal -> Proc
procedures ;;;;;;;;;;;;;;;;
proc? : SchemeVal -> Bool
procedure : Exp * Nameless-env -> Proc
there is no need to declare bound variables.
(bvar symbol?)
and the closure contains a nameless environment
environment constructors and observers ;;;;;;;;;;;;;;;;
nameless-environment? : SchemeVal -> Bool
empty-nameless-env : () -> Nameless-env
empty-nameless-env? : Nameless-env -> Bool
extend-nameless-env : ExpVal * Nameless-env -> Nameless-env | (module data-structures (lib "eopl.ss" "eopl")
data structures for LEXADDR language
(define-datatype expval expval?
(num-val
(value number?))
(bool-val
(boolean boolean?))
(proc-val
(proc proc?)))
(define expval->num
(lambda (v)
(cases expval v
(num-val (num) num)
(else (expval-extractor-error 'num v)))))
(define expval->bool
(lambda (v)
(cases expval v
(bool-val (bool) bool)
(else (expval-extractor-error 'bool v)))))
(define expval->proc
(lambda (v)
(cases expval v
(proc-val (proc) proc)
(else (expval-extractor-error 'proc v)))))
(define expval-extractor-error
(lambda (variant value)
(eopl:error 'expval-extractors "Looking for a ~s, found ~s"
variant value)))
(define-datatype proc proc?
(procedure
in LEXADDR , bound variables are replaced by % nameless - vars , so
(body expression?)
(env nameless-environment?)))
Page : 99
(define nameless-environment?
(lambda (x)
((list-of expval?) x)))
Page : 99
(define empty-nameless-env
(lambda ()
'()))
(define empty-nameless-env?
(lambda (x)
(null? x)))
Page : 99
(define extend-nameless-env
(lambda (val nameless-env)
(cons val nameless-env)))
apply - nameless - env : Nameless - env * Lexaddr - > ExpVal
Page : 99
(define apply-nameless-env
(lambda (nameless-env n)
(list-ref nameless-env n)))
)
|
f311c1d5178ae0d0dcc5f7ae88e8e92286c201459de5588a65b26fbfc9575349 | schibsted/spid-tech-docs | wash_test.clj | (ns spid-docs.sample-responses.wash-test
(:require [spid-docs.sample-responses.wash :refer :all]
[midje.sweet :refer :all]))
(fact "It reduces lists of data to a manageable amount"
(wash-data [{:id 1} {:id 2} {:id 3}]) => [{:id 1}])
(fact "It reduces list-like maps to a manageable amount"
(wash-data {"id1" {:name "abc"}
"id2" {:name "def"}}) => {"id1" {:name "abc"}})
(fact "To be a list-like map, all maps have to have at least one key in common."
(wash-data {"id1" {:name "abc"}
"id2" {:title "def"}}) => {"id1" {:name "abc"}
"id2" {:title "def"}})
(fact "It chooses the entry in a list-like map with the most keys."
(wash-data {"id1" {:name "abc"}
"id2" {:name "def"
:title "ghi"}}) => (wash-data {"id2" {:name "def"
:title "ghi"}}))
(fact "It works on nested structures"
(wash-data {"accounts" {"id1" {:name "abc"}
"id2" {:name "def"}}}) => {"accounts" {"id1" {:name "abc"}}})
(fact "It works with empty maps"
(wash-data {"empty" {}}) => {"empty" {}})
(fact "It masks potentially sensitive data"
(let [data (-> {:clientId "666"
:merchantId "0123456"
:userId "0123456"
:email ""
:ip "80.65.52.213"
:emails [{:value ""} {:value ""}]
:addresses {:home {:country "NORGE"
:streetNumber "6"
:longitude ""
:floor ""
:locality "OSLO"
:formatted "VARGVEIEN 6, 0139 OSLO, NORGE"
:streetEntrance ""
:apartment ""
:postalCode "0139"
:latitude ""
:type "home"
:region ""
:streetAddress "VARGVEIEN"}
:office {:country "NORGE"
:streetNumber "32"
:longitude ""
:floor ""
:locality "OSLO"
:formatted "Annen gate 32, 0139 OSLO, NORGE"
:streetEntrance ""
:apartment ""
:postalCode "0139"
:latitude ""
:type "home"
:region ""
:streetAddress "VARGVEIEN"}}}
mask-sensitive-data)]
(:clientId data) => "[Your client ID]"
(:merchantId data) => "[Your merchant ID]"
(:userId data) => #"^\d{7}$"
(:email data) => ""
(:ip data) => "127.0.0.1"
(:emails data) => [{:value ""} {:value ""}]
(:addresses data) => {:home {:country "NORGE"
:streetNumber "1"
:longitude ""
:floor ""
:locality "OSLO"
:formatted "STREET 1, 0123 OSLO, NORGE"
:streetEntrance ""
:apartment ""
:postalCode "0123"
:latitude ""
:type "home"
:region ""
:streetAddress "STREET"}
:office {:country "NORGE"
:streetNumber "2"
:longitude ""
:floor ""
:locality "OSLO"
:formatted "STREET 2, 0123 OSLO, NORGE"
:streetEntrance ""
:apartment ""
:postalCode "0123"
:latitude ""
:type "home"
:region ""
:streetAddress "STREET"}}))
| null | https://raw.githubusercontent.com/schibsted/spid-tech-docs/ee6a4394e9732572e97fc3a55506b2d6b9a9fe2b/test/spid_docs/sample_responses/wash_test.clj | clojure | (ns spid-docs.sample-responses.wash-test
(:require [spid-docs.sample-responses.wash :refer :all]
[midje.sweet :refer :all]))
(fact "It reduces lists of data to a manageable amount"
(wash-data [{:id 1} {:id 2} {:id 3}]) => [{:id 1}])
(fact "It reduces list-like maps to a manageable amount"
(wash-data {"id1" {:name "abc"}
"id2" {:name "def"}}) => {"id1" {:name "abc"}})
(fact "To be a list-like map, all maps have to have at least one key in common."
(wash-data {"id1" {:name "abc"}
"id2" {:title "def"}}) => {"id1" {:name "abc"}
"id2" {:title "def"}})
(fact "It chooses the entry in a list-like map with the most keys."
(wash-data {"id1" {:name "abc"}
"id2" {:name "def"
:title "ghi"}}) => (wash-data {"id2" {:name "def"
:title "ghi"}}))
(fact "It works on nested structures"
(wash-data {"accounts" {"id1" {:name "abc"}
"id2" {:name "def"}}}) => {"accounts" {"id1" {:name "abc"}}})
(fact "It works with empty maps"
(wash-data {"empty" {}}) => {"empty" {}})
(fact "It masks potentially sensitive data"
(let [data (-> {:clientId "666"
:merchantId "0123456"
:userId "0123456"
:email ""
:ip "80.65.52.213"
:emails [{:value ""} {:value ""}]
:addresses {:home {:country "NORGE"
:streetNumber "6"
:longitude ""
:floor ""
:locality "OSLO"
:formatted "VARGVEIEN 6, 0139 OSLO, NORGE"
:streetEntrance ""
:apartment ""
:postalCode "0139"
:latitude ""
:type "home"
:region ""
:streetAddress "VARGVEIEN"}
:office {:country "NORGE"
:streetNumber "32"
:longitude ""
:floor ""
:locality "OSLO"
:formatted "Annen gate 32, 0139 OSLO, NORGE"
:streetEntrance ""
:apartment ""
:postalCode "0139"
:latitude ""
:type "home"
:region ""
:streetAddress "VARGVEIEN"}}}
mask-sensitive-data)]
(:clientId data) => "[Your client ID]"
(:merchantId data) => "[Your merchant ID]"
(:userId data) => #"^\d{7}$"
(:email data) => ""
(:ip data) => "127.0.0.1"
(:emails data) => [{:value ""} {:value ""}]
(:addresses data) => {:home {:country "NORGE"
:streetNumber "1"
:longitude ""
:floor ""
:locality "OSLO"
:formatted "STREET 1, 0123 OSLO, NORGE"
:streetEntrance ""
:apartment ""
:postalCode "0123"
:latitude ""
:type "home"
:region ""
:streetAddress "STREET"}
:office {:country "NORGE"
:streetNumber "2"
:longitude ""
:floor ""
:locality "OSLO"
:formatted "STREET 2, 0123 OSLO, NORGE"
:streetEntrance ""
:apartment ""
:postalCode "0123"
:latitude ""
:type "home"
:region ""
:streetAddress "STREET"}}))
| |
bf3ddc348cf6af7ed785fbe9393b0ca8613f12a9780d62bccafa0c6ada845aea | owlbarn/owl_ode | damped.ml | open Owl_ode
open Owl_ode.Types
open Owl_plplot
let damped_noforcing a (xs, ps) _ : Owl.Mat.mat =
Owl.Mat.((xs *$ -1.0) + (ps *$ (-1.0 *. a)))
let a = 1.0
let dt = 0.1
let plot_sol fname t sol1 sol2 sol3 =
let open Owl in
let h = Plot.create fname in
let open Plot in
set_foreground_color h 0 0 0;
set_background_color h 255 255 255;
set_title h fname;
plot ~h ~spec:[ RGB (0, 0, 255); LineStyle 1 ] t (Mat.col sol1 0);
plot ~h ~spec:[ RGB (0, 255, 0); LineStyle 1 ] t (Mat.col sol2 0);
plot ~h ~spec:[ RGB (255, 0, 0); LineStyle 1 ] t (Mat.col sol3 0);
(* XXX: I could not figure out how to make the legend black instead of red *)
legend_on h ~position:NorthEast [| "Leapfrog"; "Ruth3"; "Symplectic Euler" |];
output h
let () =
let x0 = Owl.Mat.of_array [| -0.25 |] 1 1 in
let p0 = Owl.Mat.of_array [| 0.75 |] 1 1 in
let t0, duration = 0.0, 15.0 in
let f = damped_noforcing a in
let tspec = T1 { t0; duration; dt } in
let t, sol1, _ = Ode.odeint (module Symplectic.D.Leapfrog) f (x0, p0) tspec () in
let _, sol2, _ = Ode.odeint Symplectic.D.ruth3 f (x0, p0) tspec () in
let _, sol3, _ =
Ode.odeint (module Symplectic.D.Symplectic_Euler) f (x0, p0) tspec ()
in
(* XXX: I'd prefer t to be already an Owl array as well *)
plot_sol "damped.png" t sol1 sol2 sol3
| null | https://raw.githubusercontent.com/owlbarn/owl_ode/5d934fbff87eea9f060d6c949bf78467024d8791/examples/damped.ml | ocaml | XXX: I could not figure out how to make the legend black instead of red
XXX: I'd prefer t to be already an Owl array as well | open Owl_ode
open Owl_ode.Types
open Owl_plplot
let damped_noforcing a (xs, ps) _ : Owl.Mat.mat =
Owl.Mat.((xs *$ -1.0) + (ps *$ (-1.0 *. a)))
let a = 1.0
let dt = 0.1
let plot_sol fname t sol1 sol2 sol3 =
let open Owl in
let h = Plot.create fname in
let open Plot in
set_foreground_color h 0 0 0;
set_background_color h 255 255 255;
set_title h fname;
plot ~h ~spec:[ RGB (0, 0, 255); LineStyle 1 ] t (Mat.col sol1 0);
plot ~h ~spec:[ RGB (0, 255, 0); LineStyle 1 ] t (Mat.col sol2 0);
plot ~h ~spec:[ RGB (255, 0, 0); LineStyle 1 ] t (Mat.col sol3 0);
legend_on h ~position:NorthEast [| "Leapfrog"; "Ruth3"; "Symplectic Euler" |];
output h
let () =
let x0 = Owl.Mat.of_array [| -0.25 |] 1 1 in
let p0 = Owl.Mat.of_array [| 0.75 |] 1 1 in
let t0, duration = 0.0, 15.0 in
let f = damped_noforcing a in
let tspec = T1 { t0; duration; dt } in
let t, sol1, _ = Ode.odeint (module Symplectic.D.Leapfrog) f (x0, p0) tspec () in
let _, sol2, _ = Ode.odeint Symplectic.D.ruth3 f (x0, p0) tspec () in
let _, sol3, _ =
Ode.odeint (module Symplectic.D.Symplectic_Euler) f (x0, p0) tspec ()
in
plot_sol "damped.png" t sol1 sol2 sol3
|
45abc58fea11e4c08a542835e4d607197c8ad3bf6b2e563d637ae4df0185c22e | basho/riak_test | replication2_ssl.erl | %% -------------------------------------------------------------------
%%
Copyright ( c ) 2012 - 2015 Basho Technologies , Inc.
%%
This file is provided to you under the Apache License ,
%% Version 2.0 (the "License"); you may not use this file
except in compliance with the License . You may obtain
%% a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
%% KIND, either express or implied. See the License for the
%% specific language governing permissions and limitations
%% under the License.
%%
%% -------------------------------------------------------------------
-module(replication2_ssl).
-behavior(riak_test).
-export([confirm/0]).
-include_lib("eunit/include/eunit.hrl").
%% Certificate Names
-define(DEF_DOM, ".basho.com").
-define(DOM_WC, "*" ++ ?DEF_DOM).
-define(BAD_WC, "*.bahso.com").
-define(CERTN(S), S ++ ?DEF_DOM).
-define(SITEN(N), ?CERTN("site" ++ ??N)).
-define(CERTP(S), filename:join(CertDir, S)).
%% Certificate Information
-record(ci, {
cn, %% common name of the certificate
rd = 0, %% required ssl_depth
wc = ?DOM_WC, %% acceptable *.domain wildcard
ssl %% options returned from ssl_paths
}).
%%
@doc Tests various TLS ( SSL ) connection scenarios for MDC .
The following configiration options are recognized :
%%
num_nodes [ default 6 ]
How many nodes to use to build two clusters .
%%
cluster_a_size [ default ( num_nodes div 2 ) ]
%% How many nodes to use in cluster "A". The remainder is used in cluster "B".
%%
%% conn_fail_time [default rt_max_wait_time]
%% A (presumably shortened) timout to use in tests where the connection is
%% expected to be rejected due to invalid TLS configurations. Something around
one minute is appropriate . Using the default ten - minute timeout , this
test will take more than an hour and a half to run successfully .
%%
confirm() ->
test requires allow_mult = false
rt:set_conf(all, [{"buckets.default.allow_mult", "false"}]),
NumNodes = rt_config:get(num_nodes, 6),
ClusterASize = rt_config:get(cluster_a_size, (NumNodes div 2)),
CertDir = rt_config:get(rt_scratch_dir) ++ "/certs",
%% make some CAs
make_certs:rootCA(CertDir, "CA_0"),
make_certs:intermediateCA(CertDir, "CA_1", "CA_0"),
make_certs:intermediateCA(CertDir, "CA_2", "CA_1"),
%% make a bunch of certificates and matching ci records
S1Name = ?SITEN(1),
S2Name = ?SITEN(2),
S3Name = ?SITEN(3),
S4Name = ?SITEN(4),
S5Name = ?SITEN(5),
S6Name = ?SITEN(6),
W1Name = ?CERTN("wildcard1"),
W2Name = ?CERTN("wildcard2"),
make_certs:endusers(CertDir, "CA_0", [S1Name, S2Name]),
CIdep0s1 = #ci{cn = S1Name, rd = 0, ssl = ssl_paths(?CERTP(S1Name))},
CIdep0s2 = #ci{cn = S2Name, rd = 0, ssl = ssl_paths(?CERTP(S2Name))},
make_certs:endusers(CertDir, "CA_1", [S3Name, S4Name]),
CIdep1s1 = #ci{cn = S3Name, rd = 1, ssl = ssl_paths(?CERTP(S3Name))},
CIdep1s2 = #ci{cn = S4Name, rd = 1, ssl = ssl_paths(?CERTP(S4Name))},
make_certs:endusers(CertDir, "CA_2", [S5Name, S6Name]),
CIdep2s1 = #ci{cn = S5Name, rd = 2, ssl = ssl_paths(?CERTP(S5Name))},
CIdep2s2 = #ci{cn = S6Name, rd = 2, ssl = ssl_paths(?CERTP(S6Name))},
make_certs:enduser(CertDir, "CA_1", ?DOM_WC, W1Name),
CIdep1wc = #ci{cn = ?DOM_WC, rd = 1, ssl = ssl_paths(?CERTP(W1Name))},
make_certs:enduser(CertDir, "CA_2", ?DOM_WC, W2Name),
CIdep2wc = #ci{cn = ?DOM_WC, rd = 2, ssl = ssl_paths(?CERTP(W2Name))},
% crufty old certs really need to be replaced
CIexpired = #ci{cn = "ny.cataclysm-software.net", rd = 0,
wc = "*.cataclysm-software.net", ssl = ssl_paths(
filename:join([rt:priv_dir(), "certs", "cacert.org"]),
"ny-cert-old.pem", "ny-key.pem", "ca")},
lager:info("Deploy ~p nodes", [NumNodes]),
ConfRepl = {riak_repl,
[{fullsync_on_connect, false}, {fullsync_interval, disabled}]},
ConfTcpBasic = [ConfRepl, {riak_core, [{ssl_enabled, false}]}],
%%
%% !!! IMPORTANT !!!
Properties added to node configurations currently be removed ,
only overwritten . As such , configurations that include ACLs MUST come
%% after ALL non-ACL configurations! This has been learned the hard way :(
%% The same applies to the ssl_depth option, though it's much easier to
%% contend with - make sure it works, then always use a valid depth.
%%
%%
%% Connection Test descriptors
%% Each is a tuple: {Description, Node1Config, Node2Config, Should Pass}
%%
SslConnTests = [
%%
%% basic tests
%%
{"non-SSL peer fails",
[ConfRepl, {riak_core, [{ssl_enabled, true}
] ++ CIdep0s1#ci.ssl }],
ConfTcpBasic,
false},
{"non-SSL local fails",
ConfTcpBasic,
[ConfRepl, {riak_core, [{ssl_enabled, true}
] ++ CIdep0s2#ci.ssl }],
false},
{"basic SSL connectivity",
[ConfRepl, {riak_core, [{ssl_enabled, true}
] ++ CIdep0s1#ci.ssl }],
[ConfRepl, {riak_core, [{ssl_enabled, true}
] ++ CIdep0s2#ci.ssl }],
true},
{"expired peer certificate fails",
[ConfRepl, {riak_core, [{ssl_enabled, true}
] ++ CIdep0s1#ci.ssl }],
[ConfRepl, {riak_core, [{ssl_enabled, true}
] ++ CIexpired#ci.ssl }],
false},
{"expired local certificate fails",
[ConfRepl, {riak_core, [{ssl_enabled, true}
] ++ CIexpired#ci.ssl }],
[ConfRepl, {riak_core, [{ssl_enabled, true}
] ++ CIdep0s2#ci.ssl }],
false},
{"identical certificate CN is disallowed",
[ConfRepl, {riak_core, [{ssl_enabled, true}
] ++ CIdep0s1#ci.ssl }],
[ConfRepl, {riak_core, [{ssl_enabled, true}
] ++ CIdep0s1#ci.ssl }],
false},
{"identical wildcard certificate CN is allowed",
[ConfRepl, {riak_core, [{ssl_enabled, true}
] ++ CIdep1wc#ci.ssl }],
[ConfRepl, {riak_core, [{ssl_enabled, true}
] ++ CIdep1wc#ci.ssl }],
true},
{"SSL connectivity with one intermediate CA is allowed by default",
[ConfRepl, {riak_core, [{ssl_enabled, true}
] ++ CIdep1s1#ci.ssl }],
[ConfRepl, {riak_core, [{ssl_enabled, true}
] ++ CIdep1s2#ci.ssl }],
true},
{"SSL connectivity with two intermediate CAs is disallowed by default",
[ConfRepl, {riak_core, [{ssl_enabled, true}
] ++ CIdep2s1#ci.ssl }],
[ConfRepl, {riak_core, [{ssl_enabled, true}
] ++ CIdep2s2#ci.ssl }],
false},
{"wildcard certificates on both ends",
[ConfRepl, {riak_core, [{ssl_enabled, true}
] ++ CIdep1wc#ci.ssl }],
[ConfRepl, {riak_core, [{ssl_enabled, true}
] ++ CIdep1wc#ci.ssl }],
true},
{"wildcard certificate on one end",
[ConfRepl, {riak_core, [{ssl_enabled, true}
] ++ CIdep1wc#ci.ssl }],
[ConfRepl, {riak_core, [{ssl_enabled, true}
] ++ CIdep0s1#ci.ssl }],
true},
%%
%% first use of ssl_depth, all subsequent tests must specify
%%
{"disallowing intermediate CA setting allows direct-signed certs",
[ConfRepl, {riak_core, [{ssl_enabled, true}
, {ssl_depth, 0}
] ++ CIdep0s1#ci.ssl }],
[ConfRepl, {riak_core, [{ssl_enabled, true}
, {ssl_depth, 0}
] ++ CIdep0s2#ci.ssl }],
true},
{"disallowing intermediate CA disallows intermediate-signed peer",
[ConfRepl, {riak_core, [{ssl_enabled, true}
, {ssl_depth, 0}
] ++ CIdep0s1#ci.ssl }],
[ConfRepl, {riak_core, [{ssl_enabled, true}
, {ssl_depth, CIdep0s1#ci.rd}
] ++ CIdep1s2#ci.ssl }],
false},
{"disallowing intermediate CA disallows intermediate-signed local",
[ConfRepl, {riak_core, [{ssl_enabled, true}
, {ssl_depth, CIdep0s2#ci.rd}
] ++ CIdep1s1#ci.ssl }],
[ConfRepl, {riak_core, [{ssl_enabled, true}
, {ssl_depth, 0}
] ++ CIdep0s2#ci.ssl }],
false},
{"allow arbitrary-depth intermediate CAs",
[ConfRepl, {riak_core, [{ssl_enabled, true}
, {ssl_depth, CIdep2s2#ci.rd}
] ++ CIdep2s1#ci.ssl }],
[ConfRepl, {riak_core, [{ssl_enabled, true}
, {ssl_depth, CIdep2s1#ci.rd}
] ++ CIdep2s2#ci.ssl }],
true},
%%
%% first use of peer_common_name_acl, all subsequent tests must specify
%%
{"wildcard certificate on one end with matching ACL",
[ConfRepl, {riak_core, [{ssl_enabled, true}
, {ssl_depth, CIdep1s1#ci.rd}
] ++ CIdep1wc#ci.ssl }],
[ConfRepl, {riak_core, [{ssl_enabled, true}
, {ssl_depth, CIdep1wc#ci.rd}
, {peer_common_name_acl, [?DOM_WC]}
] ++ CIdep1s1#ci.ssl }],
true},
{"wildcard certificate on one end with mismatched ACL",
[ConfRepl, {riak_core, [{ssl_enabled, true}
, {ssl_depth, CIdep1s1#ci.rd}
] ++ CIdep1wc#ci.ssl }],
[ConfRepl, {riak_core, [{ssl_enabled, true}
, {ssl_depth, CIdep1wc#ci.rd}
, {peer_common_name_acl, [?BAD_WC]}
] ++ CIdep1s1#ci.ssl }],
false},
{"one wildcard ACL and one strict ACL",
[ConfRepl, {riak_core, [{ssl_enabled, true}
, {ssl_depth, CIdep1s2#ci.rd}
, {peer_common_name_acl, [?DOM_WC]}
] ++ CIdep1s1#ci.ssl }],
[ConfRepl, {riak_core, [{ssl_enabled, true}
, {ssl_depth, CIdep1s1#ci.rd}
, {peer_common_name_acl, [CIdep1s1#ci.cn]}
] ++ CIdep1s2#ci.ssl }],
true},
{"wildcard certificates on both ends with ACLs",
[ConfRepl, {riak_core, [{ssl_enabled, true}
, {ssl_depth, CIdep2wc#ci.rd}
, {peer_common_name_acl, [CIdep2wc#ci.wc]}
] ++ CIdep1wc#ci.ssl }],
[ConfRepl, {riak_core, [{ssl_enabled, true}
, {ssl_depth, CIdep1wc#ci.rd}
, {peer_common_name_acl, [CIdep1wc#ci.wc]}
] ++ CIdep2wc#ci.ssl }],
true},
{"explicit certificates with strict ACLs",
[ConfRepl, {riak_core, [{ssl_enabled, true}
, {ssl_depth, CIdep2s2#ci.rd}
, {peer_common_name_acl, [CIdep2s2#ci.cn]}
] ++ CIdep1s1#ci.ssl }],
[ConfRepl, {riak_core, [{ssl_enabled, true}
, {ssl_depth, CIdep1s1#ci.rd}
, {peer_common_name_acl, [CIdep1s1#ci.cn]}
] ++ CIdep2s2#ci.ssl }],
true}
],
lager:info("Deploying 2 nodes for connectivity tests"),
[Node1, Node2] = rt:deploy_nodes(2, ConfTcpBasic, [riak_kv, riak_repl]),
repl_util:name_cluster(Node1, "A"),
repl_util:name_cluster(Node2, "B"),
%% we'll need to wait for cluster names before continuing
rt:wait_until_ring_converged([Node1]),
rt:wait_until_ring_converged([Node2]),
rt:wait_for_service(Node1, [riak_kv, riak_repl]),
rt:wait_for_service(Node2, [riak_kv, riak_repl]),
lager:info("=== Testing basic connectivity"),
rt:log_to_nodes([Node1, Node2], "Testing basic connectivity"),
{ok, {_IP, Port}} = rpc:call(Node2, application, get_env,
[riak_core, cluster_mgr]),
lager:info("connect cluster A:~p to B on port ~p", [Node1, Port]),
rt:log_to_nodes([Node1, Node2], "connect A to B"),
repl_util:connect_cluster(Node1, "127.0.0.1", Port),
lager:info("Waiting for connection to B"),
?assertEqual(ok, repl_util:wait_for_connection(Node1, "B")),
%% run each of the SSL connectivity tests
lists:foreach(fun({Desc, Conf1, Conf2, ShouldPass}) ->
test_connection(Desc, {Node1, Conf1}, {Node2, Conf2}, ShouldPass)
end, SslConnTests),
lager:info("Connectivity tests passed"),
repl_util:disconnect_cluster(Node1, "B"),
lager:info("Re-deploying 6 nodes"),
Nodes = rt:deploy_nodes(6, ConfTcpBasic, [riak_kv, riak_repl]),
[rt:wait_until_pingable(N) || N <- Nodes],
{ANodes, BNodes} = lists:split(ClusterASize, Nodes),
lager:info("Reconfiguring nodes with SSL options"),
ConfANodes = [ConfRepl, {riak_core, [{ssl_enabled, true}
, {ssl_depth, CIdep1s2#ci.rd}
, {peer_common_name_acl, [CIdep1s2#ci.cn]}
] ++ CIdep1s1#ci.ssl }],
ConfBNodes = [ConfRepl, {riak_core, [{ssl_enabled, true}
, {ssl_depth, CIdep1s1#ci.rd}
, {peer_common_name_acl, [CIdep1s1#ci.cn]}
] ++ CIdep1s2#ci.ssl }],
[rt:update_app_config(N, ConfANodes) || N <- ANodes],
[rt:update_app_config(N, ConfBNodes) || N <- BNodes],
[rt:wait_until_pingable(N) || N <- Nodes],
lager:info("Build cluster A"),
repl_util:make_cluster(ANodes),
lager:info("Build cluster B"),
repl_util:make_cluster(BNodes),
repl_util:disconnect_cluster(Node1, "B"),
replication2:replication(ANodes, BNodes, false),
pass.
test_connection(Desc, {N1, C1}, {N2, C2}, ShouldPass) ->
lager:info("=== Testing " ++ Desc),
rt:log_to_nodes([N1, N2], "Testing " ++ Desc),
test_connection({N1, C1}, {N2, C2}, ShouldPass).
test_connection(Left, Right, true) ->
?assertEqual(ok, test_connection(Left, Right)),
lager:info("Connection succeeded");
test_connection(Left, Right, false) ->
DefaultTimeout = rt_config:get(rt_max_wait_time),
ConnFailTimeout = rt_config:get(conn_fail_time, DefaultTimeout),
rt_config:set(rt_max_wait_time, ConnFailTimeout),
?assertMatch({fail, _}, test_connection(Left, Right)),
rt_config:set(rt_max_wait_time, DefaultTimeout),
lager:info("Connection rejected").
test_connection({Node1, Config1}, {Node2, Config2}) ->
repl_util:disconnect_cluster(Node1, "B"),
repl_util:wait_for_disconnect(Node1, "B"),
rt:update_app_config(Node2, Config2),
rt:wait_until_pingable(Node2),
rt:update_app_config(Node1, Config1),
rt:wait_until_pingable(Node1),
rt:wait_for_service(Node1, [riak_kv, riak_repl]),
rt:wait_for_service(Node2, [riak_kv, riak_repl]),
{ok, {_IP, Port}} = rpc:call(Node2, application, get_env,
[riak_core, cluster_mgr]),
lager:info("connect cluster A:~p to B on port ~p", [Node1, Port]),
rt:log_to_nodes([Node1, Node2], "connect A to B"),
repl_util:connect_cluster(Node1, "127.0.0.1", Port),
repl_util:wait_for_connection(Node1, "B").
ssl_paths(Dir) ->
ssl_paths(Dir, "cert.pem", "key.pem", "cacerts.pem").
ssl_paths(Dir, Cert, Key, CaCerts) ->
[{certfile, filename:join(Dir, Cert)}
,{keyfile, filename:join(Dir, Key)}
,{cacertdir, filename:join(Dir, CaCerts)}].
| null | https://raw.githubusercontent.com/basho/riak_test/8170137b283061ba94bc85bf42575021e26c929d/tests/replication2_ssl.erl | erlang | -------------------------------------------------------------------
Version 2.0 (the "License"); you may not use this file
a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing,
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-------------------------------------------------------------------
Certificate Names
Certificate Information
common name of the certificate
required ssl_depth
acceptable *.domain wildcard
options returned from ssl_paths
How many nodes to use in cluster "A". The remainder is used in cluster "B".
conn_fail_time [default rt_max_wait_time]
A (presumably shortened) timout to use in tests where the connection is
expected to be rejected due to invalid TLS configurations. Something around
make some CAs
make a bunch of certificates and matching ci records
crufty old certs really need to be replaced
!!! IMPORTANT !!!
after ALL non-ACL configurations! This has been learned the hard way :(
The same applies to the ssl_depth option, though it's much easier to
contend with - make sure it works, then always use a valid depth.
Connection Test descriptors
Each is a tuple: {Description, Node1Config, Node2Config, Should Pass}
basic tests
first use of ssl_depth, all subsequent tests must specify
first use of peer_common_name_acl, all subsequent tests must specify
we'll need to wait for cluster names before continuing
run each of the SSL connectivity tests | Copyright ( c ) 2012 - 2015 Basho Technologies , Inc.
This file is provided to you under the Apache License ,
except in compliance with the License . You may obtain
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
-module(replication2_ssl).
-behavior(riak_test).
-export([confirm/0]).
-include_lib("eunit/include/eunit.hrl").
-define(DEF_DOM, ".basho.com").
-define(DOM_WC, "*" ++ ?DEF_DOM).
-define(BAD_WC, "*.bahso.com").
-define(CERTN(S), S ++ ?DEF_DOM).
-define(SITEN(N), ?CERTN("site" ++ ??N)).
-define(CERTP(S), filename:join(CertDir, S)).
-record(ci, {
}).
@doc Tests various TLS ( SSL ) connection scenarios for MDC .
The following configiration options are recognized :
num_nodes [ default 6 ]
How many nodes to use to build two clusters .
cluster_a_size [ default ( num_nodes div 2 ) ]
one minute is appropriate . Using the default ten - minute timeout , this
test will take more than an hour and a half to run successfully .
confirm() ->
test requires allow_mult = false
rt:set_conf(all, [{"buckets.default.allow_mult", "false"}]),
NumNodes = rt_config:get(num_nodes, 6),
ClusterASize = rt_config:get(cluster_a_size, (NumNodes div 2)),
CertDir = rt_config:get(rt_scratch_dir) ++ "/certs",
make_certs:rootCA(CertDir, "CA_0"),
make_certs:intermediateCA(CertDir, "CA_1", "CA_0"),
make_certs:intermediateCA(CertDir, "CA_2", "CA_1"),
S1Name = ?SITEN(1),
S2Name = ?SITEN(2),
S3Name = ?SITEN(3),
S4Name = ?SITEN(4),
S5Name = ?SITEN(5),
S6Name = ?SITEN(6),
W1Name = ?CERTN("wildcard1"),
W2Name = ?CERTN("wildcard2"),
make_certs:endusers(CertDir, "CA_0", [S1Name, S2Name]),
CIdep0s1 = #ci{cn = S1Name, rd = 0, ssl = ssl_paths(?CERTP(S1Name))},
CIdep0s2 = #ci{cn = S2Name, rd = 0, ssl = ssl_paths(?CERTP(S2Name))},
make_certs:endusers(CertDir, "CA_1", [S3Name, S4Name]),
CIdep1s1 = #ci{cn = S3Name, rd = 1, ssl = ssl_paths(?CERTP(S3Name))},
CIdep1s2 = #ci{cn = S4Name, rd = 1, ssl = ssl_paths(?CERTP(S4Name))},
make_certs:endusers(CertDir, "CA_2", [S5Name, S6Name]),
CIdep2s1 = #ci{cn = S5Name, rd = 2, ssl = ssl_paths(?CERTP(S5Name))},
CIdep2s2 = #ci{cn = S6Name, rd = 2, ssl = ssl_paths(?CERTP(S6Name))},
make_certs:enduser(CertDir, "CA_1", ?DOM_WC, W1Name),
CIdep1wc = #ci{cn = ?DOM_WC, rd = 1, ssl = ssl_paths(?CERTP(W1Name))},
make_certs:enduser(CertDir, "CA_2", ?DOM_WC, W2Name),
CIdep2wc = #ci{cn = ?DOM_WC, rd = 2, ssl = ssl_paths(?CERTP(W2Name))},
CIexpired = #ci{cn = "ny.cataclysm-software.net", rd = 0,
wc = "*.cataclysm-software.net", ssl = ssl_paths(
filename:join([rt:priv_dir(), "certs", "cacert.org"]),
"ny-cert-old.pem", "ny-key.pem", "ca")},
lager:info("Deploy ~p nodes", [NumNodes]),
ConfRepl = {riak_repl,
[{fullsync_on_connect, false}, {fullsync_interval, disabled}]},
ConfTcpBasic = [ConfRepl, {riak_core, [{ssl_enabled, false}]}],
Properties added to node configurations currently be removed ,
only overwritten . As such , configurations that include ACLs MUST come
SslConnTests = [
{"non-SSL peer fails",
[ConfRepl, {riak_core, [{ssl_enabled, true}
] ++ CIdep0s1#ci.ssl }],
ConfTcpBasic,
false},
{"non-SSL local fails",
ConfTcpBasic,
[ConfRepl, {riak_core, [{ssl_enabled, true}
] ++ CIdep0s2#ci.ssl }],
false},
{"basic SSL connectivity",
[ConfRepl, {riak_core, [{ssl_enabled, true}
] ++ CIdep0s1#ci.ssl }],
[ConfRepl, {riak_core, [{ssl_enabled, true}
] ++ CIdep0s2#ci.ssl }],
true},
{"expired peer certificate fails",
[ConfRepl, {riak_core, [{ssl_enabled, true}
] ++ CIdep0s1#ci.ssl }],
[ConfRepl, {riak_core, [{ssl_enabled, true}
] ++ CIexpired#ci.ssl }],
false},
{"expired local certificate fails",
[ConfRepl, {riak_core, [{ssl_enabled, true}
] ++ CIexpired#ci.ssl }],
[ConfRepl, {riak_core, [{ssl_enabled, true}
] ++ CIdep0s2#ci.ssl }],
false},
{"identical certificate CN is disallowed",
[ConfRepl, {riak_core, [{ssl_enabled, true}
] ++ CIdep0s1#ci.ssl }],
[ConfRepl, {riak_core, [{ssl_enabled, true}
] ++ CIdep0s1#ci.ssl }],
false},
{"identical wildcard certificate CN is allowed",
[ConfRepl, {riak_core, [{ssl_enabled, true}
] ++ CIdep1wc#ci.ssl }],
[ConfRepl, {riak_core, [{ssl_enabled, true}
] ++ CIdep1wc#ci.ssl }],
true},
{"SSL connectivity with one intermediate CA is allowed by default",
[ConfRepl, {riak_core, [{ssl_enabled, true}
] ++ CIdep1s1#ci.ssl }],
[ConfRepl, {riak_core, [{ssl_enabled, true}
] ++ CIdep1s2#ci.ssl }],
true},
{"SSL connectivity with two intermediate CAs is disallowed by default",
[ConfRepl, {riak_core, [{ssl_enabled, true}
] ++ CIdep2s1#ci.ssl }],
[ConfRepl, {riak_core, [{ssl_enabled, true}
] ++ CIdep2s2#ci.ssl }],
false},
{"wildcard certificates on both ends",
[ConfRepl, {riak_core, [{ssl_enabled, true}
] ++ CIdep1wc#ci.ssl }],
[ConfRepl, {riak_core, [{ssl_enabled, true}
] ++ CIdep1wc#ci.ssl }],
true},
{"wildcard certificate on one end",
[ConfRepl, {riak_core, [{ssl_enabled, true}
] ++ CIdep1wc#ci.ssl }],
[ConfRepl, {riak_core, [{ssl_enabled, true}
] ++ CIdep0s1#ci.ssl }],
true},
{"disallowing intermediate CA setting allows direct-signed certs",
[ConfRepl, {riak_core, [{ssl_enabled, true}
, {ssl_depth, 0}
] ++ CIdep0s1#ci.ssl }],
[ConfRepl, {riak_core, [{ssl_enabled, true}
, {ssl_depth, 0}
] ++ CIdep0s2#ci.ssl }],
true},
{"disallowing intermediate CA disallows intermediate-signed peer",
[ConfRepl, {riak_core, [{ssl_enabled, true}
, {ssl_depth, 0}
] ++ CIdep0s1#ci.ssl }],
[ConfRepl, {riak_core, [{ssl_enabled, true}
, {ssl_depth, CIdep0s1#ci.rd}
] ++ CIdep1s2#ci.ssl }],
false},
{"disallowing intermediate CA disallows intermediate-signed local",
[ConfRepl, {riak_core, [{ssl_enabled, true}
, {ssl_depth, CIdep0s2#ci.rd}
] ++ CIdep1s1#ci.ssl }],
[ConfRepl, {riak_core, [{ssl_enabled, true}
, {ssl_depth, 0}
] ++ CIdep0s2#ci.ssl }],
false},
{"allow arbitrary-depth intermediate CAs",
[ConfRepl, {riak_core, [{ssl_enabled, true}
, {ssl_depth, CIdep2s2#ci.rd}
] ++ CIdep2s1#ci.ssl }],
[ConfRepl, {riak_core, [{ssl_enabled, true}
, {ssl_depth, CIdep2s1#ci.rd}
] ++ CIdep2s2#ci.ssl }],
true},
{"wildcard certificate on one end with matching ACL",
[ConfRepl, {riak_core, [{ssl_enabled, true}
, {ssl_depth, CIdep1s1#ci.rd}
] ++ CIdep1wc#ci.ssl }],
[ConfRepl, {riak_core, [{ssl_enabled, true}
, {ssl_depth, CIdep1wc#ci.rd}
, {peer_common_name_acl, [?DOM_WC]}
] ++ CIdep1s1#ci.ssl }],
true},
{"wildcard certificate on one end with mismatched ACL",
[ConfRepl, {riak_core, [{ssl_enabled, true}
, {ssl_depth, CIdep1s1#ci.rd}
] ++ CIdep1wc#ci.ssl }],
[ConfRepl, {riak_core, [{ssl_enabled, true}
, {ssl_depth, CIdep1wc#ci.rd}
, {peer_common_name_acl, [?BAD_WC]}
] ++ CIdep1s1#ci.ssl }],
false},
{"one wildcard ACL and one strict ACL",
[ConfRepl, {riak_core, [{ssl_enabled, true}
, {ssl_depth, CIdep1s2#ci.rd}
, {peer_common_name_acl, [?DOM_WC]}
] ++ CIdep1s1#ci.ssl }],
[ConfRepl, {riak_core, [{ssl_enabled, true}
, {ssl_depth, CIdep1s1#ci.rd}
, {peer_common_name_acl, [CIdep1s1#ci.cn]}
] ++ CIdep1s2#ci.ssl }],
true},
{"wildcard certificates on both ends with ACLs",
[ConfRepl, {riak_core, [{ssl_enabled, true}
, {ssl_depth, CIdep2wc#ci.rd}
, {peer_common_name_acl, [CIdep2wc#ci.wc]}
] ++ CIdep1wc#ci.ssl }],
[ConfRepl, {riak_core, [{ssl_enabled, true}
, {ssl_depth, CIdep1wc#ci.rd}
, {peer_common_name_acl, [CIdep1wc#ci.wc]}
] ++ CIdep2wc#ci.ssl }],
true},
{"explicit certificates with strict ACLs",
[ConfRepl, {riak_core, [{ssl_enabled, true}
, {ssl_depth, CIdep2s2#ci.rd}
, {peer_common_name_acl, [CIdep2s2#ci.cn]}
] ++ CIdep1s1#ci.ssl }],
[ConfRepl, {riak_core, [{ssl_enabled, true}
, {ssl_depth, CIdep1s1#ci.rd}
, {peer_common_name_acl, [CIdep1s1#ci.cn]}
] ++ CIdep2s2#ci.ssl }],
true}
],
lager:info("Deploying 2 nodes for connectivity tests"),
[Node1, Node2] = rt:deploy_nodes(2, ConfTcpBasic, [riak_kv, riak_repl]),
repl_util:name_cluster(Node1, "A"),
repl_util:name_cluster(Node2, "B"),
rt:wait_until_ring_converged([Node1]),
rt:wait_until_ring_converged([Node2]),
rt:wait_for_service(Node1, [riak_kv, riak_repl]),
rt:wait_for_service(Node2, [riak_kv, riak_repl]),
lager:info("=== Testing basic connectivity"),
rt:log_to_nodes([Node1, Node2], "Testing basic connectivity"),
{ok, {_IP, Port}} = rpc:call(Node2, application, get_env,
[riak_core, cluster_mgr]),
lager:info("connect cluster A:~p to B on port ~p", [Node1, Port]),
rt:log_to_nodes([Node1, Node2], "connect A to B"),
repl_util:connect_cluster(Node1, "127.0.0.1", Port),
lager:info("Waiting for connection to B"),
?assertEqual(ok, repl_util:wait_for_connection(Node1, "B")),
lists:foreach(fun({Desc, Conf1, Conf2, ShouldPass}) ->
test_connection(Desc, {Node1, Conf1}, {Node2, Conf2}, ShouldPass)
end, SslConnTests),
lager:info("Connectivity tests passed"),
repl_util:disconnect_cluster(Node1, "B"),
lager:info("Re-deploying 6 nodes"),
Nodes = rt:deploy_nodes(6, ConfTcpBasic, [riak_kv, riak_repl]),
[rt:wait_until_pingable(N) || N <- Nodes],
{ANodes, BNodes} = lists:split(ClusterASize, Nodes),
lager:info("Reconfiguring nodes with SSL options"),
ConfANodes = [ConfRepl, {riak_core, [{ssl_enabled, true}
, {ssl_depth, CIdep1s2#ci.rd}
, {peer_common_name_acl, [CIdep1s2#ci.cn]}
] ++ CIdep1s1#ci.ssl }],
ConfBNodes = [ConfRepl, {riak_core, [{ssl_enabled, true}
, {ssl_depth, CIdep1s1#ci.rd}
, {peer_common_name_acl, [CIdep1s1#ci.cn]}
] ++ CIdep1s2#ci.ssl }],
[rt:update_app_config(N, ConfANodes) || N <- ANodes],
[rt:update_app_config(N, ConfBNodes) || N <- BNodes],
[rt:wait_until_pingable(N) || N <- Nodes],
lager:info("Build cluster A"),
repl_util:make_cluster(ANodes),
lager:info("Build cluster B"),
repl_util:make_cluster(BNodes),
repl_util:disconnect_cluster(Node1, "B"),
replication2:replication(ANodes, BNodes, false),
pass.
test_connection(Desc, {N1, C1}, {N2, C2}, ShouldPass) ->
lager:info("=== Testing " ++ Desc),
rt:log_to_nodes([N1, N2], "Testing " ++ Desc),
test_connection({N1, C1}, {N2, C2}, ShouldPass).
test_connection(Left, Right, true) ->
?assertEqual(ok, test_connection(Left, Right)),
lager:info("Connection succeeded");
test_connection(Left, Right, false) ->
DefaultTimeout = rt_config:get(rt_max_wait_time),
ConnFailTimeout = rt_config:get(conn_fail_time, DefaultTimeout),
rt_config:set(rt_max_wait_time, ConnFailTimeout),
?assertMatch({fail, _}, test_connection(Left, Right)),
rt_config:set(rt_max_wait_time, DefaultTimeout),
lager:info("Connection rejected").
test_connection({Node1, Config1}, {Node2, Config2}) ->
repl_util:disconnect_cluster(Node1, "B"),
repl_util:wait_for_disconnect(Node1, "B"),
rt:update_app_config(Node2, Config2),
rt:wait_until_pingable(Node2),
rt:update_app_config(Node1, Config1),
rt:wait_until_pingable(Node1),
rt:wait_for_service(Node1, [riak_kv, riak_repl]),
rt:wait_for_service(Node2, [riak_kv, riak_repl]),
{ok, {_IP, Port}} = rpc:call(Node2, application, get_env,
[riak_core, cluster_mgr]),
lager:info("connect cluster A:~p to B on port ~p", [Node1, Port]),
rt:log_to_nodes([Node1, Node2], "connect A to B"),
repl_util:connect_cluster(Node1, "127.0.0.1", Port),
repl_util:wait_for_connection(Node1, "B").
ssl_paths(Dir) ->
ssl_paths(Dir, "cert.pem", "key.pem", "cacerts.pem").
ssl_paths(Dir, Cert, Key, CaCerts) ->
[{certfile, filename:join(Dir, Cert)}
,{keyfile, filename:join(Dir, Key)}
,{cacertdir, filename:join(Dir, CaCerts)}].
|
0acb43daf463fa2140a4790f101a9810b3b237a416c999bc08723b95d433c137 | haskell-opengl/OpenGLRaw | PixelTexture.hs | # LANGUAGE PatternSynonyms #
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.GL.SGIS.PixelTexture
Copyright : ( c ) 2019
-- License : BSD3
--
Maintainer : < >
-- Stability : stable
-- Portability : portable
--
--------------------------------------------------------------------------------
module Graphics.GL.SGIS.PixelTexture (
-- * Extension Support
glGetSGISPixelTexture,
gl_SGIS_pixel_texture,
-- * Enums
pattern GL_PIXEL_FRAGMENT_ALPHA_SOURCE_SGIS,
pattern GL_PIXEL_FRAGMENT_RGB_SOURCE_SGIS,
pattern GL_PIXEL_GROUP_COLOR_SGIS,
pattern GL_PIXEL_TEXTURE_SGIS,
-- * Functions
glGetPixelTexGenParameterfvSGIS,
glGetPixelTexGenParameterivSGIS,
glPixelTexGenParameterfSGIS,
glPixelTexGenParameterfvSGIS,
glPixelTexGenParameteriSGIS,
glPixelTexGenParameterivSGIS
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Tokens
import Graphics.GL.Functions
| null | https://raw.githubusercontent.com/haskell-opengl/OpenGLRaw/57e50c9d28dfa62d6a87ae9b561af28f64ce32a0/src/Graphics/GL/SGIS/PixelTexture.hs | haskell | ------------------------------------------------------------------------------
|
Module : Graphics.GL.SGIS.PixelTexture
License : BSD3
Stability : stable
Portability : portable
------------------------------------------------------------------------------
* Extension Support
* Enums
* Functions | # LANGUAGE PatternSynonyms #
Copyright : ( c ) 2019
Maintainer : < >
module Graphics.GL.SGIS.PixelTexture (
glGetSGISPixelTexture,
gl_SGIS_pixel_texture,
pattern GL_PIXEL_FRAGMENT_ALPHA_SOURCE_SGIS,
pattern GL_PIXEL_FRAGMENT_RGB_SOURCE_SGIS,
pattern GL_PIXEL_GROUP_COLOR_SGIS,
pattern GL_PIXEL_TEXTURE_SGIS,
glGetPixelTexGenParameterfvSGIS,
glGetPixelTexGenParameterivSGIS,
glPixelTexGenParameterfSGIS,
glPixelTexGenParameterfvSGIS,
glPixelTexGenParameteriSGIS,
glPixelTexGenParameterivSGIS
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Tokens
import Graphics.GL.Functions
|
0a08749d6e1baf8a5c383e6d8f14e4f7c5f492ed65d1c39706a6a5cff1d3d804 | dym/movitz | scratch.lisp | ------------------ - mode : t -*--------------------------
;;;;
Copyright ( C ) 2007 ,
;;;;
;;;; Filename: scratch.lisp
;;;; Description: Misc. testing code etc.
Author : < >
;;;; Distribution: See the accompanying file COPYING.
;;;;
$ I d : , v 1.3 2008/02/23 22:28:55 ffjeld Exp $
;;;;
;;;;------------------------------------------------------------------
(provide :scratch)
(in-package los0)
#+ignore
(defun set.2 ()
(let ((*var-used-in-set-tests* 'a)
(var '*var-used-in-set-tests*))
(declare (special *var-used-in-set-tests*))
(values
(let ((*var-used-in-set-tests* 'c))
(list (set var 'b) *var-used-in-set-tests* (symbol-value var)))
*var-used-in-set-tests*)))
;; (b c b)
;; b)
#+ignore
(defun test-lend-constant ()
(let ((symbols '(a b c d e f g h i j k l m n o p q r s t u v w x y z))
(table (make-hash-table :test #'eq)))
(loop for sym in symbols
for i from 1
do (setf (gethash sym table) i))
(let ((sum 0))
(values (maphash #'(lambda (k v)
(assert (eq (elt symbols (1- v)) k))
(incf sum v))
table)
sum))))
#+ignore
(defun test-aux (x y &aux (sum (+ x y)))
sum)
#+ignore
(defun mapc.error.3 ()
(mapc #'append))
#+ignore
(defun with-hash-table-iterator.12 ()
(block done
(let ((x :bad))
(declare (special x))
(let ((x :good))
(with-hash-table-iterator (m (return-from done x))
(declare (special x))))))
:good)
#+ignore
(defun string.15 ()
(when (> char-code-limit 65536)
(loop for i = (random char-code-limit)
for c = (code-char i)
for s = (and c (string c))
repeat 2000
when (and c
(or (not (stringp s))
(not (= (length s) 1))
(not (eql c (char s 0)))))
collect (list i c s)))
nil)
(defun x (bios32)
(warn "X: ~S" (memref-int bios32))
(warn "X: ~S" (= (memref-int bios32) #x5f32335f)))
(defun setfint (x o)
(setf (memref x o :type :unsigned-byte32) 0))
(defun fint (x)
(memref-int x :type :unsigned-byte32 :physicalp t))
(defun good ()
(with-inline-assembly (:returns :untagged-fixnum-ecx)
((:gs-override) :movl (#x1000000) :ecx)))
(defun (setf good) (x)
(with-inline-assembly (:returns :untagged-fixnum-ecx)
(:compile-form (:result-mode :untagged-fixnum-ecx) x)
((:gs-override) :movl :ecx (#x1000000))))
(defun test2 ()
(funcall
(compile
nil
'(lambda (a) (declare (notinline > *))
(declare (optimize (compilation-speed 0) (safety 2) (speed 2) (debug 0) (space 3)))
(catch 'ct1 (* a (throw 'ct1 (if (> 0) a 0))))))
5445205692802))
(defun test3 ()
(loop for x below 2 count (not (not (typep x t)))))
(defun test4 ()
(let ((aa 1)) (if (not (/= aa 0)) aa 0)))
(defun test-floppy ()
(muerte.x86-pc::fd-start-disk) ; to initialize the controller and spin the drive up.
to seek to track 70 .
(setf (muerte.x86-pc::fd-motor) nil)) ; to turn the drive and controller off.
(defun alist-get-expand (alist key)
(let (cons)
(tagbody
loop
(setq cons (car alist))
(cond ((eq alist nil) (go end))
((eq cons nil))
((eq key (car cons)) (go end)))
(setq alist (cdr alist))
(go loop)
end)
(cdr cons)))
;;;(defun test-irq ()
;;; (with-inline-assembly (:returns :multiple-values)
;;; (:compile-form (:result-mode :multiple-values) (values 0 1 2 3 4 5))
(: int 42 ) ) )
;;;
;;;(defun koo ()
( prog1 ( make - values )
;;; (format t "hello: ~S" (values 'a 'b 'c 'd))))
;;;
;;;(defun test-complement (&rest args)
;;; (declare (dynamic-extent args))
;;; (apply (complement #'symbolp) args))
;;;
;;;(defun test-constantly (&rest args)
;;; (declare (dynamic-extent args))
;;; (apply (constantly 'test-value) args))
(defun test-closure (x z)
(flet ((closure (y) (= x (1+ y))))
(declare (dynamic-extent (function closure)))
(closure z)
#+ignore (funcall (lambda (y) (= x (1+ y)))
z)))
(defun test-stack-cons (x y)
(muerte::with-dynamic-extent-scope (zap)
(let ((foo (muerte::with-dynamic-extent-allocation (zap)
(cons x (lambda () y)))))
(format t "~Z: ~S, ~S" foo foo (funcall (cdr foo))))))
(defun test-handler (x)
(let ((foo x))
(handler-bind
((error (lambda (c)
(format t "error: ~S ~S" c x))))
(error "This is an error. ~S" foo))))
(defun fooo (v w)
(tagbody
(print (block blurgh
(progv (list v) (list w)
(format t "Uh: ~S" (symbol-value v))
(if (symbol-value v)
(return-from blurgh 1)
(go zap)))))
zap)
t)
(defun test-break ()
(with-inline-assembly (:returns :multiple-values)
(:movl 10 :ecx)
(:movl :esi :eax) ; This function should return itself!
(:clc)
(:break)))
(defun test-upload (x)
;; (warn "Test-upload blab la bla!!")
(setf x (cdr x))
x)
( defun zzz ( x )
;;; (multiple-value-bind (symbol status)
;;; (values-list x)
( warn " sym : ~S , stat : ~S " symbol status ) ) )
;;;
#+ignore
(defun test-loop (x)
(format t "test-loop: ~S~%"
(loop for i from 0 to 10 collect x)))
#+ignore
(defun delay (time)
(dotimes (i time)
(with-inline-assembly (:returns :nothing)
(:nop)
(:nop))))
;;;
;;;(defun test-consp (x)
;;; (with-inline-assembly (:returns :boolean-cf=1)
;;; (:compile-form (:result-mode :ecx) x)
(: leal (: edi -4 ) : eax )
(: : cl : ) ) )
#+ignore
(defun test-block (x)
(block nil
(let ((*print-base* (if x (return 3) 8)))
(jumbo 2 2 (and x 2) (+ 3 3 (or x 4)) (if x 2 (return nil)))))
#+ignore (+ x 2))
#+ignore
(defun jumbo (a b c &rest x)
(declare (dynamic-extent x))
(print a) (print b) (print c)
(print x)
'jumbo)
(defun jumbo2 (a b &rest x)
(declare (dynamic-extent x))
(print a) (print b)
(print x)
'jumbo)
(defun jumbo3 (a &rest x)
(declare (dynamic-extent x))
(print a)
(print x)
'jumbo)
(defun jumbo4 (&rest x)
(declare (dynamic-extent x))
(print x)
'jumbo)
#+ignore
(defun tagbodyxx (x)
(tagbody
(print 'hello)
haha
(unwind-protect
(when x (go hoho))
(warn "unwind.."))
(print 'world)
hoho
(print 'blrugh)))
#+ignore
(defun tagbodyxx (x)
(tagbody
(print 'hello)
haha
(unwind-protect
(funcall (lambda ()
(when x (go hoho))))
(warn "unwind.."))
(print 'world)
hoho
(print 'blrugh)))
#+ignore
(defun kumbo (&key a b (c (jumbo 1 2 3)) d)
(print a)
(print b)
(print c)
(print d))
#+ignore
(defun lumbo (a &optional (b 'zap))
(print a)
(print b))
(defmacro do-check-esp (&body body)
`(let ((before (with-inline-assembly (:returns :eax) (:movl :esp :eax))))
(with-inline-assembly (:returns :nothing)
(:compile-form (:result-mode :multiple-values) (progn ,@body)))
(unless (eq before
(with-inline-assembly (:returns :eax) (:movl :esp :eax)))
(error "ESP before body: ~S, after: ~S"
(with-inline-assembly (:returns :eax) (:movl :esp :eax))))))
#+ignore
(defun test-m-v-call ()
(do-check-esp
(multiple-value-call #'format t "~@{ ~D~}~%"
'a (values) 'b (test-loop 1) (make-values)
'c 'd 'e (make-no-values) 'f)))
(defun test-m-v-call2 ()
(multiple-value-call #'format t "~@{ ~D~}~%"
'a 'b (values 1 2 3) 'c 'd 'e 'f))
(defun make-values ()
(values 0 1 2 3 4 5))
(defun xfuncall (&rest args)
(declare (dynamic-extent args))
(break "xfuncall:~{ ~S~^,~}" args)
(values))
(defun xfoo (f)
(do-check-esp
(multiple-value-bind (a b c d)
(multiple-value-prog1 (make-values)
(format t "hello world"))
(format t "~&a: ~S, b: ~S, c: ~S, d: ~S ~S" a b c d f))))
#+ignore
(defun make-no-values ()
(values))
#+ignore
(defun test-nth-values ()
(nth-value 2 (make-values)))
#+ignore
(defun test-values2 ()
(multiple-value-bind (a b c d e f g h)
(make-values)
(format t "test-values2: A: ~S, B: ~S, C: ~S, D: ~S, E: ~S, F: ~S G: ~S, H: ~S~%"
a b c d e f g h)))
#+ignore
(defun test-flet (zap)
(flet ((pingo (z y x)
(declare (ignore y z))
(format t "This is pingo: ~S with zap: ~W~%" x zap)))
;; (declare (dynamic-extent pingo))
(pingo 100 200 300)))
#+ignore
(defun test-flet2 (zap)
(flet ((pingo (z y x)
(declare (ignore y z))
(format t "This is pingo: ~S with zap: ~W~%" x zap)))
;; (declare (dynamic-extent pingo))
(lambda (x)
(pingo 100 200 300))))
(defun test-boo ()
(let ((real-cmuc #'test-flet2))
(let ((plongo (lambda (x)
(warn "~S real-cmuc: ~S" x real-cmuc)
(funcall real-cmuc x))))
(funcall plongo 'zooom))))
(defun test-labels ()
(labels ((pingo (x)
(format t "~&This is pingo: ~S~%" x)
(when (plusp x)
(pingo (1- x)))))
(pingo 5)))
#+ignore
(defun foo-type (length start1 sequence-1)
(do* ((i 0 #+ignore (+ start1 length -1) (1- i)))
((< i start1) sequence-1)
(declare (type muerte::index i length))
(setf (sequence-1-ref i)
'foo)))
#+ignore
(defun test-values ()
(multiple-value-bind (a b c d e f g h i j)
(multiple-value-prog1
(make-values)
;;; (format t "this is the resulting form.~%")
(format t "this is the first ignorable form.~%" 1 2 3)
(format t "this is the second ignorable form.~%"))
;;; (format t "test-values num: ~D~%" (capture-reg8 :cl))
(format t "test-values: A: ~Z, B: ~Z, C: ~Z, D: ~Z ~Z ~Z ~Z ~Z ~Z ~Z~%" a b c d e f g h i j)))
#+ignore
(defun test-keywords (&key a b (c 100) ((:d x) 5 x-p))
(format t "test-keywords: a: ~S, b: ~S, c: ~S, x: ~S, x-p: ~S~%"
a b c x x-p))
#+ignore
(defun test-k1 (a b &key x)
(declare (ignore a b))
(warn "x: ~S" x))
(defun test-funcall (&rest args)
(declare (dynamic-extent args))
(format t "~&test-funcall args: ~S~%" args))
#+ignore
(defun test-rest (&optional (a0 nil a0-p) a1 a3 &rest args)
(declare (dynamic-extent args))
(when a0-p
(format t "args: ~S, ~S, ~S: ~S~%" a0 a1 a3 args)))
(defun test-return ()
(print (block nil
(values 'x 'y (if (foo) (return 'foo) (return-from test-return 'not-foo)) 'bar)))
5)
#+ignore
(defun test-lexthrow (x)
(apply (lambda (a b)
(unwind-protect
(if (plusp a) 0 (return-from test-lexthrow (+ a b)))
(warn "To serve and protect!")))
x))
#+ignore
(defun test-lexgo (x)
(let ((*print-base* 2))
(return-from test-lexgo (print 123))))
#+ignore
(defun test-xgo (c x)
(tagbody
loop
(warn "c: ~S" c)
(apply (lambda (a)
(decf c)
(if (plusp a) (go exit) (go loop))
(warn "juhu, a or x: ~S, c: ~S" a c))
x)
exit
(warn "exited: ~S" c)))
(defun test-bignum ()
123456789123456)
(defun fe32 ()
#xfffffffe)
(defun fe64 ()
#xfffffffffffffffe)
(defun fe96 ()
#xfffffffffffffffffffffffe)
(defun one32 ()
#x100000000)
(defun z (op x y)
(let ((foo (cons 1 2))
(result (funcall op x y))
(bar (cons 3 4)))
(if (not (typep result 'pointer))
(warn "foo: ~Z result: ~Z, bar: ~Z, diff foo-bar: ~D."
foo result bar
(- (object-location bar) (object-location foo)))
(warn "foo: ~Z result: ~Z, bar: ~Z, diff: ~D, ~D."
foo result bar
(- (object-location result) (object-location foo))
(- (object-location bar) (object-location result))))
(values foo result bar)))
(defun modx (x)
(lambda ()
(print x)))
(defun mod30 (x)
(ldb (Byte 30 0) x))
(defun mod32-4 (x)
(ldb (byte 28 4) x))
(defun mod24-4 (x)
(ldb (Byte 24 4) x))
(defun zz (op x y)
(let ((foo (vector 1 2))
(result (funcall op x y))
(bar (vector 3 4)))
(if (not (typep result 'pointer))
(warn "foo: ~Z result: ~Z, bar: ~Z, diff foo-bar: ~D."
foo result bar
(- (object-location bar) (object-location foo)))
(warn "foo: ~Z result: ~Z, bar: ~Z, diff: ~D, ~D."
foo result bar
(- (object-location result) (object-location foo))
(- (object-location bar) (object-location result))))
(values foo result bar)))
(defun testb ()
#(1 2 3 4))
(defun gt5 (x)
(<= x 5))
(defun xplus (x)
(typep x '(integer 0 *)))
(defstruct (xxx :constructor (:constructor boa-make-xxx (x y z)))
x y (z 'init-z))
(defun test-struct ()
(format t "make-xxx: ~S~%" (let ((s (make-xxx))) s))
(format t "make-xxx: ~S~%" (xxx-z (make-xxx))))
(defun test-dynamic ()
#+ignore
(let ((x 100))
(let ((y x))
(let ((z y))
(format t "y: ~S, x: ~S, z: ~S~%" y x z))))
#+ignore
(format t "~D ~D ~D~%" 0 1
(let ((*x* 100))
(declare (special *x*))
(format t "*x*: ~S~%" *x*)
(symbol-value '*x*)))
#+ignore
(format t "~D ~D ~D~%" 0 1
(progv '(*x*) '(101)
(format t "*x*: ~S~%" (symbol-value '*x*))
(symbol-value '*x*)))
(let ((*x* 200))
(declare (special *x*))
(format t "*x*: ~S~%" *x*)
#+ignore
(let ((*x* 300))
(declare (special *x*))
(format t "*x*: ~S~%" *x*))
*x*))
#+ignore
(defun test-dynamic-formal (*print-base*)
(print *print-base*))
#+ignore
(defun verify-throw ()
"CLHS speaketh:
The following prints ``The inner catch returns :SECOND-THROW'' and then returns :outer-catch."
(catch 'foo
(format t "The inner catch returns ~s.~%"
(catch 'foo
(unwind-protect (throw 'foo :first-throw)
(throw 'foo :second-throw))))
:outer-catch))
#+ignore
(defun do-throw ()
(unwind-protect (print 'hello)
(throw 'foo :second-throw)))
#+ignore
(defun bloo (x)
#'bloo
(multiple-value-prog1
(sloo x (1+ x))
(print 'hello)))
#+ignore
(defun sloo (&rest x)
(declare (dynamic-extent x))
(let ((y (car x)))
(sloo y)))
#+ignore
(defun test-throw (tag)
(unwind-protect
(warn "throw: ~Z" (throw tag (values 'throw1 (make-values) 'throw2)))
(warn "Something happened: ~W" (make-values))
#+ignore (return-from test-throw 'interrupted-value))
(error "Huh?"))
#+ignore
(defun test-catch (x)
(catch 'test-tag
(test-throw x 'test-tag)
(format t "Hello world")))
(defun test-throw (x tag)
(when x
(warn "Throwing ~S.." tag)
(throw tag (values-list x))))
#+ignore
(defun test-up-catch ()
(catch 'test-tag
(test-up 'test-tag)
(format t "Hello world")))
#+ignore
(defun test-up (tag)
(unwind-protect
(test-throw tag)
(print 'hello-cleanup)))
(defun test-cons (x)
(let ((cc (cons x x)))
(cdr cc)))
(defun xx (x)
(eql nil x))
(defun test-fixed (x y z)
(warn "x: ~W, y: ~W, z: ~W" x y z))
(defun test-let-closure ()
(tagbody
(let ((*print-base* 10)
(x (go zz))
(*print-radix* nil))
(warn "lending x: ~W" x)
(values (lambda ()
(warn "borrowed x: ~W" x)
(* x 2))
#+ignore
(lambda (y)
(setf x y))))
zz
(warn "zz")))
(defun test-not (x)
(if (not x) 0 100))
(defun test-pingo (z)
(block zzz
(warn "hello world")
(let ((zingo (+ z 23)))
(return-from zzz
(let ((x (* z zingo)))
(print (* x 2)))))
(warn "not this")))
(defun display-hash (x)
(loop for k being the hash-keys of x using (hash-value v)
do (format t "~&~S => ~S" k v))
(values))
;;;(defclass test-class ()
;;; (s1 s2))
;;;
(defun show-hash (x)
(loop for y being the hash-keys of x
do (format t "~&key: ~W [~W]" y (symbol-package y)))
(values))
;;;
;;;
;;;(defclass c () (s1 s2))
;;;
( ( x ) )
;;;(defmethod m ((x c))
;;; (declare (ignore x))
;;; (warn "more m's: ~{~W~}" (when (next-method-p)
;;; (list (call-next-method))))
;;; #'call-next-method)
;;;
;;;(defmethod m ((x standard-object))
;;; (declare (ignore x))
;;; 'this-is-m-on-standard-object)
;;;
;;;(defmethod m ((x fixnum))
;;; (declare (ignore x))
;;; 'this-is-m-on-fixnum)
(defun test-nested-extent ()
;; Check that the compiler doesn't suffer from the let nested-extent problem.
;; identity is used so the compiler won't shortcut the bindings.
(let ((foo (identity 'foo-value))
(bar (let ((zot (identity 'test-nested-extent)))
(setq zot 'zot-value)
(identity zot))))
(if (eq foo 'foo-value)
(format t "~&Success: foo is ~W, bar is ~W" foo bar)
(format t "~&Failure! foo is ~W, bar is ~W" foo bar))))
(defun bar (x)
(multiple-value-prog1
(values 0 1 2)
(format t "blungolo: ~S" x)))
#+ignore
(defun test-ncase (x y z)
(numargs-case
(1 (x) (values x 'one))
(2 (x y) (values (+ x y) 'one 'two))
(3 (x y z) (values (+ x y z) 'one 'two 'three))
(t (args) (declare (ignore args)) 27)))
#+ignore
(defun xbar ()
(print-dynamic-context :terse t)
(block handler-case-block
(let (handler-case-var)
(tagbody
(handler-bind
((error (lambda (handler-case-temp-var)
(setq handler-case-var handler-case-temp-var)
(go handler-case-clause-tag))))
(print-dynamic-context :terse t)
(return-from handler-case-block
(signal "hello world")))
handler-case-clause-tag
(return-from handler-case-block
(let ((|c| handler-case-var))
(format t "got an error: ~s" |c|))))))
(print-dynamic-context :terse t))
#+ignore
(defun plingu (&optional v)
(let ((x (1+ *print-base*)))
(print "foo")
(print "foo")
(print x)
(print v)))
#+ignore
(defun (setf dingu) (x y)
(when (> x y)
(return-from dingu 'fooob))
(+ x y))
(defun foo (&edx edx x &optional (y nil yp))
(format t "~@{ ~A~}" x y yp edx))
(defun wefwe (&rest args)
(declare (dynamic-extent args))
(do ((p args (cdr p)))
((endp p))
(let ((x (car p)))
(print x))))
(defun mubmo ()
(let ((x (muerte::copy-funobj #'format))
(y (cons 1 2)))
(warn "x: ~Z, y: ~Z" x y)))
;;;;;
(defclass food () ())
(defgeneric cook (food))
( defmethod cook : before ( ( f food ) )
;;; (declare (ignore f))
;;; (print "A food is about to be cooked."))
;;;
( defmethod cook : after ( ( f food ) )
;;; (declare (ignore f))
;;; (print "A food has been cooked."))
(defmethod cook :after ((f food))
(declare (ignore f))
(print "Cooking some food."))
(defun test-pie (n pie)
(dotimes (i n)
(pie-filling pie)))
(defun test-inc (n)
(dotimes (i n)
(warn "foo: ~S" (lambda ()
(setf i 5)))))
(defun test-id (n x)
(dotimes (i n)
(identity x)))
(defun test-inc2 (x)
(print (prog1 x (incf x)))
(print x))
(defclass pie (food)
((filling :accessor pie-filling
:initarg :filling
:initform 'apple))
#+ignore (:default-initargs :filling (if (foo) 'apple 'banana)))
(defclass pie2 (food)
((filling :accessor pie-filling
:initarg :filling
)))
(defmethod cook ((p (eql 'pie)))
(warn "Won't really cook a symbolic pie!")
(values))
(defmethod cook ((p (eql 'pudding)))
'cooked-pudding)
(defmethod slot-value-using-class :after (class (pie pie2) slot)
(warn "HEy, don't poke inside my pie2!"))
(defmethod cook :after ((p symbol))
(warn "A symbol may or may not have been cooked."))
(defmethod cook ((p pie))
(cond
((eq 'banana (pie-filling p))
(print "Won't cook a banana-pie, trying next.")
(call-next-method))
(t (print "Cooking a pie.")
(setf (pie-filling p) (list 'cooked (pie-filling p))))))
(defmethod cook :before ((p pie))
(declare (ignore p))
(print "A pie is about to be cooked."))
(defmethod cook :after ((p pie))
(declare (ignore p))
(print "A pie has been cooked."))
(defun xwrite (object)
(with-inline-assembly (:returns :nothing)
(:locally (:movl (:edi (:edi-offset muerte::dynamic-env)) :eax))
(:movl :eax (#x1000000))
(:movl :ebp (#x1000004))
(:movl :esi (#x1000008)))
(block handler-case-block-1431896
(let (handler-case-var-1431897)
(tagbody
(handler-bind
((serious-condition
(lambda (handler-case-temp-var-1431898)
(setq handler-case-var-1431897 handler-case-temp-var-1431898)
(go handler-case-clause-tag-1431899))))
(return-from handler-case-block-1431896
(muerte::internal-write object)))
handler-case-clause-tag-1431899
(return-from handler-case-block-1431896
(let ((c handler-case-var-1431897))
(print-unreadable-object (c *standard-output* :type t :identity t)
(format t " while printing ~z" object))))))))
(defun ub (x)
`(hello world ,x or . what))
(define-primitive-function test-irq-pf ()
""
(with-inline-assembly (:returns :nothing)
(:int 113)
(:ret)))
(defun test-irq (&optional eax ebx ecx edx)
(multiple-value-bind (p1 p2)
(with-inline-assembly (:returns :multiple-values)
(:load-lexical (:lexical-binding eax) :eax)
(:load-lexical (:lexical-binding ebx) :ebx)
(:load-lexical (:lexical-binding ecx) :ecx)
(:load-lexical (:lexical-binding edx) :edx)
(:pushl :eax)
(:pushl :ebx)
(:jecxz 'dont-call)
(:globally (:call (:edi (:edi-offset values) 80)))
dont-call
(:store-lexical (:lexical-binding eax) :eax :type t)
(:store-lexical (:lexical-binding ebx) :ebx :type t)
(:store-lexical (:lexical-binding ecx) :ecx :type t)
(:store-lexical (:lexical-binding edx) :edx :type t)
(:popl :ebx)
(:popl :eax)
(:movl 2 :ecx)
(:stc))
(values eax ebx ecx edx p1 p2)))
(defun null-primitive-function (x)
"This function is just like identity, except it also calls a null primitive function.
Can be used to measure the overhead of primitive function."
(with-inline-assembly (:returns :eax)
(:load-lexical (:lexical-binding x) :eax)
(:% :bytes 8 #xff #x97) ; (:call-local-pf ret-trampoline)
(:% :bytes 32 #.(bt:slot-offset 'movitz::movitz-run-time-context 'movitz::ret-trampoline))))
(defun my-test-labels (x)
(labels (#+ignore (p () (print x))
(q (y) (list x y)))
(declare (ignore q))
(1+ x)))
(defparameter *timer-stack* nil)
(defparameter *timer-prevstack* nil)
(defparameter *timer-esi* nil)
(defparameter *timer-frame* #100(nil))
(defparameter *timer-base* 2)
(defparameter *timer-variation* 1000)
(defun test-format (&optional timeout (x #xab))
(let ((fasit (format nil "~2,'0X" x)))
(test-timer timeout)
(format t "~&Fasit: ~S" fasit)
(loop
(let ((x (format nil "~2,'0X" x)))
(assert (string= fasit x) ()
"Failed tesT. Fasit: ~S, X: ~S" fasit x)))))
(defun test-clc (&optional (timeout #xfffe) no-timer)
(unless no-timer
(test-timer timeout))
(loop
(funcall (find-symbol (string :test-clc) :clc))))
(defun test-timer (function
&key (base *timer-base*)
(variation *timer-variation*)
(timeout (+ base (random variation))))
(setf (exception-handler 32)
(lambda (exception-vector exception-frame)
(declare (ignore exception-vector exception-frame))
;;; (loop with f = *timer-frame*
for o from 20 downto -36 by 4 as i upfrom 0
do ( setf ( aref f i ) ( memref exception - frame o 0 : lisp ) ) )
;;; (let ((ts *timer-stack*))
( setf ( fill - pointer ts ) 0 )
;;; (loop for stack-frame = exception-frame then (stack-frame-uplink stack-frame)
;;; while (plusp stack-frame)
do ( multiple - value - bind ( offset code - vector funobj )
;;; (stack-frame-call-site stack-frame)
( vector - push funobj ts )
;;; (vector-push offset ts)
;;; (vector-push code-vector ts))))
( )
(when (eql #\esc (muerte.x86-pc.keyboard:poll-char))
(break "Test-timer keyboard break."))
(with-inline-assembly (:returns :nothing)
(:compile-form (:result-mode :ecx) muerte.x86-pc::*screen*)
(:shrl 2 :ecx)
((:gs-override) :addb 1 (:ecx 158))
((:gs-override) :movb #x40 (:ecx 159)))
(do ((frame (muerte::stack-frame-uplink nil (muerte::current-stack-frame))
(muerte::stack-frame-uplink nil frame)))
((plusp frame))
(when (eq (with-inline-assembly (:returns :eax) (:movl :esi :eax))
(muerte::stack-frame-funobj nil frame))
(error "Double interrupt.")))
( dolist ( range muerte::%memory - map - roots% )
;;; (map-header-vals (lambda (x type)
;;; (declare (ignore type))
;;; x)
;;; (car range) (cdr range)))
(map-stack-vector #'muerte::identity* nil (muerte::current-stack-frame))
(with-inline-assembly (:returns :nothing)
(:compile-form (:result-mode :ecx) muerte.x86-pc::*screen*)
(:shrl 2 :ecx)
((:gs-override) :movb #x20 (:ecx 159)))
#+ignore (setf *timer-prevstack* *timer-stack*
*timer-stack* (muerte::copy-current-control-stack))
(pic8259-end-of-interrupt 0)
(setf (pit8253-timer-mode 0) +pit8253-mode-single-timeout+
(pit8253-timer-count 0) (or timeout (+ base (random variation))))
;;; (muerte::sti)
))
(with-inline-assembly (:returns :nothing)
(:compile-form (:result-mode :ecx) muerte.x86-pc::*screen*)
(:shrl 2 :ecx)
((:gs-override) :movw #x4646 (:ecx 158)))
(setf (pit8253-timer-mode 0) +pit8253-mode-single-timeout+
(pit8253-timer-count 0) (or timeout (+ base (random variation))))
(setf (pic8259-irq-mask) #xfffe)
(pic8259-end-of-interrupt 0)
(with-inline-assembly (:returns :nothing) (:sti))
(unwind-protect
(when function
(funcall function))
(muerte::cli)
(setf (pic8259-irq-mask) #xffff)))
(defun wetweg (x)
(memref-int (memref x 2 :type :unsigned-byte32) :physicalp nil :type :unsigned-byte8))
(defun test-throwing (&optional (x #xffff))
(when x
(test-timer x))
(loop
(catch 'foo
(unwind-protect
(funcall (lambda ()
(unwind-protect
(progn
( unless ( logbitp 9 ( ) )
;;; (break "Someone switched off interrupts!"))
( incf ( memref - int muerte.x86 - pc::*screen * : type : unsigned - byte16 ) )
(throw 'foo 'inner-peace))
(incf (memref-int muerte.x86-pc::*screen* :index 80 :type :unsigned-byte16)))))
(incf (memref-int muerte.x86-pc::*screen* :index 160 :type :unsigned-byte16))))))
#+ignore
(defun fvf-textmode-screendump ()
(muerte.ip4::ip4-init)
(let* ((w muerte.x86-pc::*screen-width*)
(h muerte.x86-pc::*screen-height*)
(data (make-array (* w h)
:element-type 'character
:fill-pointer 0)))
(loop for y below h
do (loop for x below w
do (vector-push (code-char
(ldb (byte 8 0)
(memref-int muerte.x86-pc::*screen*
:index (+ x (* y muerte.x86-pc::*screen-stride*))
:type :unsigned-byte16)))
data)))
(muerte.ip4:tftp/ethernet-write :129.242.19.132 "movitz-screendump.txt" data
:quiet t
:mac (muerte.ip4::polling-arp
muerte.ip4::*ip4-router*
(lambda ()
(eql #\escape (muerte.x86-pc.keyboard:poll-char)))))))
(defun memdump (start length)
(loop for addr upfrom start repeat length
collect (memref-int addr :type :unsigned-byte8)))
(defun plus (a b)
(+ (muerte::check-the fixnum a)
(muerte::check-the fixnum b)))
(defun vector-non-dups (vector)
"Count the number of unique elements in vector."
(loop for i from 1 to (length vector)
for x across vector
count (not (find x vector :start i))))
(defun blit (buffer)
(loop for i from 0 below 16000
do (setf (memref-int #xa0000 :index i :type :unsigned-byte32)
(memref buffer 2 :index i :type :unsigned-byte32))))
#+ignore
(defun ztstring (physical-address)
(let ((s (make-string (loop for i upfrom 0
until (= 0 (memref-int physical-address :index i :type :unsigned-byte8))
finally (return i)))))
(loop for i from 0 below (length s)
do (setf (char s i)
(code-char (memref-int physical-address :index i :type :unsigned-byte8))))
s))
(defmacro do-default ((var &rest error-spec) &body init-forms)
`(or (and (boundp ',var)
(symbol-value ',var))
(setf (symbol-value ',var)
(progn ,@init-forms))
,(when error-spec
`(error ,@error-spec))))
#+ignore
(defun bridge (&optional (inside (do-default (*inside* "No inside NIC.")
(muerte.x86-pc.ne2k:ne2k-probe #x300)))
(outside (do-default (*outside* "No outside NIC.")
(muerte.x86-pc.ne2k:ne2k-probe #x280))))
(let ((buffer (make-array +max-ethernet-frame-size+
:element-type '(unsigned-byte 8)
:fill-pointer t)))
(loop
(ignore-errors
(reset-device inside)
(reset-device outside)
(setf (promiscuous-p inside) t
(promiscuous-p outside) t)
(loop
(when (receive inside buffer)
(transmit outside buffer))
(when (receive outside buffer)
(transmit inside buffer))
(case (muerte.x86-pc.keyboard:poll-char)
(#\escape (break "Under the bridge."))
(#\e (error "this is an error!"))))))))
(defparameter *write-barrier* nil)
(defun show-writes ()
(loop with num = (length *write-barrier*)
for i from 0 below num by 4
initially (format t "~&Number of writes: ~D" (truncate num 4))
do (format t "~&~D ~S: [~Z] Write to ~S: ~S."
i (aref *write-barrier* (+ i 3))
(aref *write-barrier* i)
(aref *write-barrier* i) (aref *write-barrier* (+ i 2))))
(values))
(defun es-test (&optional (barrier-size 1000))
(setf *write-barrier* (or *write-barrier*
(make-array (* 4 barrier-size) :fill-pointer 0))
(fill-pointer *write-barrier*) 0
(exception-handler 13) #'general-protection-handler
(segment-register :es) 0)
(values))
(defun general-protection-handler (vector dit-frame)
(assert (= vector 13))
(let ((eip (dit-frame-ref nil dit-frame :eip :unsigned-byte32)))
(assert (= #x26 (memref-int eip :offset 0 :type :unsigned-byte8 :physicalp nil))) ; ES override prefix?
(let ((opcode (memref-int eip :offset 1 :type :unsigned-byte8 :physicalp nil))
(mod/rm (memref-int eip :offset 2 :type :unsigned-byte8 :physicalp nil)))
(if (not (= #x89 opcode))
(interrupt-default-handler vector dit-frame)
(let ((value (ecase (ldb (byte 3 3) mod/rm)
(0 (dit-frame-ref nil dit-frame :eax :lisp))
(3 (dit-frame-ref nil dit-frame :ebx :lisp)))))
If we return , do n't execute with the ES override prefix :
(setf (dit-frame-ref nil dit-frame :eip :unsigned-byte32) (1+ eip))
;; If value isn't a pointer, we don't care..
(when (typep value 'pointer)
(multiple-value-bind (object offset)
(case (logand mod/rm #xc7)
(: < value > (: eax < disp8 > ) )
(values (dit-frame-ref nil dit-frame :eax)
(memref-int eip :offset 3 :type :signed-byte8 :physicalp nil)))
(: < value > (: ebx < > ) )
(values (dit-frame-ref nil dit-frame :ebx)
(memref-int eip :offset 3 :type :signed-byte8 :physicalp nil)))
the / SIB case
(let ((sib (memref-int eip :offset 3 :type :unsigned-byte8 :physicalp nil)))
(case sib
((#x19 #x0b)
(values (dit-frame-ref nil dit-frame :ebx)
(+ (dit-frame-ref nil dit-frame :ecx :unsigned-byte8)
(memref-int eip :offset 4 :type :signed-byte8 :physicalp nil))))
((#x1a)
(values (dit-frame-ref nil dit-frame :ebx)
(+ (dit-frame-ref nil dit-frame :edx :unsigned-byte8)
(memref-int eip :offset 4 :type :signed-byte8 :physicalp nil))))))))
(when (not object)
(setf (segment-register :es) (segment-register :ds))
(break "[~S] With value ~S, unknown movl at ~S: ~S ~S ~S ~S"
dit-frame value eip
(memref-int eip :offset 1 :type :unsigned-byte8 :physicalp nil)
(memref-int eip :offset 2 :type :unsigned-byte8 :physicalp nil)
(memref-int eip :offset 3 :type :unsigned-byte8 :physicalp nil)
(memref-int eip :offset 4 :type :unsigned-byte8 :physicalp nil)))
(check-type object pointer)
(check-type offset fixnum)
(let ((write-barrier *write-barrier*)
(location (object-location object)))
(assert (not (location-in-object-p
(los0::space-other (%run-time-context-slot nil 'nursery-space))
location)) ()
"Write ~S to old-space at ~S." value location)
(unless (or (eq object write-barrier)
#+ignore
(location-in-object-p (%run-time-context-slot nil 'nursery-space)
location)
(location-in-object-p (%run-time-context-slot nil 'stack-vector)
location))
(if (location-in-object-p (%run-time-context-slot nil 'nursery-space)
location)
(vector-push 'stack-actually write-barrier)
(vector-push object write-barrier))
(vector-push offset write-barrier)
(vector-push value write-barrier)
(unless (vector-push eip write-barrier)
(setf (segment-register :es) (segment-register :ds))
(break "Write-barrier is full: ~D" (length write-barrier))))))))))))
| null | https://raw.githubusercontent.com/dym/movitz/56176e1ebe3eabc15c768df92eca7df3c197cb3d/losp/scratch.lisp | lisp |
Filename: scratch.lisp
Description: Misc. testing code etc.
Distribution: See the accompanying file COPYING.
------------------------------------------------------------------
(b c b)
b)
to initialize the controller and spin the drive up.
to turn the drive and controller off.
(defun test-irq ()
(with-inline-assembly (:returns :multiple-values)
(:compile-form (:result-mode :multiple-values) (values 0 1 2 3 4 5))
(defun koo ()
(format t "hello: ~S" (values 'a 'b 'c 'd))))
(defun test-complement (&rest args)
(declare (dynamic-extent args))
(apply (complement #'symbolp) args))
(defun test-constantly (&rest args)
(declare (dynamic-extent args))
(apply (constantly 'test-value) args))
This function should return itself!
(warn "Test-upload blab la bla!!")
(multiple-value-bind (symbol status)
(values-list x)
(defun test-consp (x)
(with-inline-assembly (:returns :boolean-cf=1)
(:compile-form (:result-mode :ecx) x)
(declare (dynamic-extent pingo))
(declare (dynamic-extent pingo))
(format t "this is the resulting form.~%")
(format t "test-values num: ~D~%" (capture-reg8 :cl))
(defclass test-class ()
(s1 s2))
(defclass c () (s1 s2))
(defmethod m ((x c))
(declare (ignore x))
(warn "more m's: ~{~W~}" (when (next-method-p)
(list (call-next-method))))
#'call-next-method)
(defmethod m ((x standard-object))
(declare (ignore x))
'this-is-m-on-standard-object)
(defmethod m ((x fixnum))
(declare (ignore x))
'this-is-m-on-fixnum)
Check that the compiler doesn't suffer from the let nested-extent problem.
identity is used so the compiler won't shortcut the bindings.
(declare (ignore f))
(print "A food is about to be cooked."))
(declare (ignore f))
(print "A food has been cooked."))
(:call-local-pf ret-trampoline)
(loop with f = *timer-frame*
(let ((ts *timer-stack*))
(loop for stack-frame = exception-frame then (stack-frame-uplink stack-frame)
while (plusp stack-frame)
(stack-frame-call-site stack-frame)
(vector-push offset ts)
(vector-push code-vector ts))))
(map-header-vals (lambda (x type)
(declare (ignore type))
x)
(car range) (cdr range)))
(muerte::sti)
(break "Someone switched off interrupts!"))
ES override prefix?
If value isn't a pointer, we don't care.. | ------------------ - mode : t -*--------------------------
Copyright ( C ) 2007 ,
Author : < >
$ I d : , v 1.3 2008/02/23 22:28:55 ffjeld Exp $
(provide :scratch)
(in-package los0)
#+ignore
(defun set.2 ()
(let ((*var-used-in-set-tests* 'a)
(var '*var-used-in-set-tests*))
(declare (special *var-used-in-set-tests*))
(values
(let ((*var-used-in-set-tests* 'c))
(list (set var 'b) *var-used-in-set-tests* (symbol-value var)))
*var-used-in-set-tests*)))
#+ignore
(defun test-lend-constant ()
(let ((symbols '(a b c d e f g h i j k l m n o p q r s t u v w x y z))
(table (make-hash-table :test #'eq)))
(loop for sym in symbols
for i from 1
do (setf (gethash sym table) i))
(let ((sum 0))
(values (maphash #'(lambda (k v)
(assert (eq (elt symbols (1- v)) k))
(incf sum v))
table)
sum))))
#+ignore
(defun test-aux (x y &aux (sum (+ x y)))
sum)
#+ignore
(defun mapc.error.3 ()
(mapc #'append))
#+ignore
(defun with-hash-table-iterator.12 ()
(block done
(let ((x :bad))
(declare (special x))
(let ((x :good))
(with-hash-table-iterator (m (return-from done x))
(declare (special x))))))
:good)
#+ignore
(defun string.15 ()
(when (> char-code-limit 65536)
(loop for i = (random char-code-limit)
for c = (code-char i)
for s = (and c (string c))
repeat 2000
when (and c
(or (not (stringp s))
(not (= (length s) 1))
(not (eql c (char s 0)))))
collect (list i c s)))
nil)
(defun x (bios32)
(warn "X: ~S" (memref-int bios32))
(warn "X: ~S" (= (memref-int bios32) #x5f32335f)))
(defun setfint (x o)
(setf (memref x o :type :unsigned-byte32) 0))
(defun fint (x)
(memref-int x :type :unsigned-byte32 :physicalp t))
(defun good ()
(with-inline-assembly (:returns :untagged-fixnum-ecx)
((:gs-override) :movl (#x1000000) :ecx)))
(defun (setf good) (x)
(with-inline-assembly (:returns :untagged-fixnum-ecx)
(:compile-form (:result-mode :untagged-fixnum-ecx) x)
((:gs-override) :movl :ecx (#x1000000))))
(defun test2 ()
(funcall
(compile
nil
'(lambda (a) (declare (notinline > *))
(declare (optimize (compilation-speed 0) (safety 2) (speed 2) (debug 0) (space 3)))
(catch 'ct1 (* a (throw 'ct1 (if (> 0) a 0))))))
5445205692802))
(defun test3 ()
(loop for x below 2 count (not (not (typep x t)))))
(defun test4 ()
(let ((aa 1)) (if (not (/= aa 0)) aa 0)))
(defun test-floppy ()
to seek to track 70 .
(defun alist-get-expand (alist key)
(let (cons)
(tagbody
loop
(setq cons (car alist))
(cond ((eq alist nil) (go end))
((eq cons nil))
((eq key (car cons)) (go end)))
(setq alist (cdr alist))
(go loop)
end)
(cdr cons)))
(: int 42 ) ) )
( prog1 ( make - values )
(defun test-closure (x z)
(flet ((closure (y) (= x (1+ y))))
(declare (dynamic-extent (function closure)))
(closure z)
#+ignore (funcall (lambda (y) (= x (1+ y)))
z)))
(defun test-stack-cons (x y)
(muerte::with-dynamic-extent-scope (zap)
(let ((foo (muerte::with-dynamic-extent-allocation (zap)
(cons x (lambda () y)))))
(format t "~Z: ~S, ~S" foo foo (funcall (cdr foo))))))
(defun test-handler (x)
(let ((foo x))
(handler-bind
((error (lambda (c)
(format t "error: ~S ~S" c x))))
(error "This is an error. ~S" foo))))
(defun fooo (v w)
(tagbody
(print (block blurgh
(progv (list v) (list w)
(format t "Uh: ~S" (symbol-value v))
(if (symbol-value v)
(return-from blurgh 1)
(go zap)))))
zap)
t)
(defun test-break ()
(with-inline-assembly (:returns :multiple-values)
(:movl 10 :ecx)
(:clc)
(:break)))
(defun test-upload (x)
(setf x (cdr x))
x)
( defun zzz ( x )
( warn " sym : ~S , stat : ~S " symbol status ) ) )
#+ignore
(defun test-loop (x)
(format t "test-loop: ~S~%"
(loop for i from 0 to 10 collect x)))
#+ignore
(defun delay (time)
(dotimes (i time)
(with-inline-assembly (:returns :nothing)
(:nop)
(:nop))))
(: leal (: edi -4 ) : eax )
(: : cl : ) ) )
#+ignore
(defun test-block (x)
(block nil
(let ((*print-base* (if x (return 3) 8)))
(jumbo 2 2 (and x 2) (+ 3 3 (or x 4)) (if x 2 (return nil)))))
#+ignore (+ x 2))
#+ignore
(defun jumbo (a b c &rest x)
(declare (dynamic-extent x))
(print a) (print b) (print c)
(print x)
'jumbo)
(defun jumbo2 (a b &rest x)
(declare (dynamic-extent x))
(print a) (print b)
(print x)
'jumbo)
(defun jumbo3 (a &rest x)
(declare (dynamic-extent x))
(print a)
(print x)
'jumbo)
(defun jumbo4 (&rest x)
(declare (dynamic-extent x))
(print x)
'jumbo)
#+ignore
(defun tagbodyxx (x)
(tagbody
(print 'hello)
haha
(unwind-protect
(when x (go hoho))
(warn "unwind.."))
(print 'world)
hoho
(print 'blrugh)))
#+ignore
(defun tagbodyxx (x)
(tagbody
(print 'hello)
haha
(unwind-protect
(funcall (lambda ()
(when x (go hoho))))
(warn "unwind.."))
(print 'world)
hoho
(print 'blrugh)))
#+ignore
(defun kumbo (&key a b (c (jumbo 1 2 3)) d)
(print a)
(print b)
(print c)
(print d))
#+ignore
(defun lumbo (a &optional (b 'zap))
(print a)
(print b))
(defmacro do-check-esp (&body body)
`(let ((before (with-inline-assembly (:returns :eax) (:movl :esp :eax))))
(with-inline-assembly (:returns :nothing)
(:compile-form (:result-mode :multiple-values) (progn ,@body)))
(unless (eq before
(with-inline-assembly (:returns :eax) (:movl :esp :eax)))
(error "ESP before body: ~S, after: ~S"
(with-inline-assembly (:returns :eax) (:movl :esp :eax))))))
#+ignore
(defun test-m-v-call ()
(do-check-esp
(multiple-value-call #'format t "~@{ ~D~}~%"
'a (values) 'b (test-loop 1) (make-values)
'c 'd 'e (make-no-values) 'f)))
(defun test-m-v-call2 ()
(multiple-value-call #'format t "~@{ ~D~}~%"
'a 'b (values 1 2 3) 'c 'd 'e 'f))
(defun make-values ()
(values 0 1 2 3 4 5))
(defun xfuncall (&rest args)
(declare (dynamic-extent args))
(break "xfuncall:~{ ~S~^,~}" args)
(values))
(defun xfoo (f)
(do-check-esp
(multiple-value-bind (a b c d)
(multiple-value-prog1 (make-values)
(format t "hello world"))
(format t "~&a: ~S, b: ~S, c: ~S, d: ~S ~S" a b c d f))))
#+ignore
(defun make-no-values ()
(values))
#+ignore
(defun test-nth-values ()
(nth-value 2 (make-values)))
#+ignore
(defun test-values2 ()
(multiple-value-bind (a b c d e f g h)
(make-values)
(format t "test-values2: A: ~S, B: ~S, C: ~S, D: ~S, E: ~S, F: ~S G: ~S, H: ~S~%"
a b c d e f g h)))
#+ignore
(defun test-flet (zap)
(flet ((pingo (z y x)
(declare (ignore y z))
(format t "This is pingo: ~S with zap: ~W~%" x zap)))
(pingo 100 200 300)))
#+ignore
(defun test-flet2 (zap)
(flet ((pingo (z y x)
(declare (ignore y z))
(format t "This is pingo: ~S with zap: ~W~%" x zap)))
(lambda (x)
(pingo 100 200 300))))
(defun test-boo ()
(let ((real-cmuc #'test-flet2))
(let ((plongo (lambda (x)
(warn "~S real-cmuc: ~S" x real-cmuc)
(funcall real-cmuc x))))
(funcall plongo 'zooom))))
(defun test-labels ()
(labels ((pingo (x)
(format t "~&This is pingo: ~S~%" x)
(when (plusp x)
(pingo (1- x)))))
(pingo 5)))
#+ignore
(defun foo-type (length start1 sequence-1)
(do* ((i 0 #+ignore (+ start1 length -1) (1- i)))
((< i start1) sequence-1)
(declare (type muerte::index i length))
(setf (sequence-1-ref i)
'foo)))
#+ignore
(defun test-values ()
(multiple-value-bind (a b c d e f g h i j)
(multiple-value-prog1
(make-values)
(format t "this is the first ignorable form.~%" 1 2 3)
(format t "this is the second ignorable form.~%"))
(format t "test-values: A: ~Z, B: ~Z, C: ~Z, D: ~Z ~Z ~Z ~Z ~Z ~Z ~Z~%" a b c d e f g h i j)))
#+ignore
(defun test-keywords (&key a b (c 100) ((:d x) 5 x-p))
(format t "test-keywords: a: ~S, b: ~S, c: ~S, x: ~S, x-p: ~S~%"
a b c x x-p))
#+ignore
(defun test-k1 (a b &key x)
(declare (ignore a b))
(warn "x: ~S" x))
(defun test-funcall (&rest args)
(declare (dynamic-extent args))
(format t "~&test-funcall args: ~S~%" args))
#+ignore
(defun test-rest (&optional (a0 nil a0-p) a1 a3 &rest args)
(declare (dynamic-extent args))
(when a0-p
(format t "args: ~S, ~S, ~S: ~S~%" a0 a1 a3 args)))
(defun test-return ()
(print (block nil
(values 'x 'y (if (foo) (return 'foo) (return-from test-return 'not-foo)) 'bar)))
5)
#+ignore
(defun test-lexthrow (x)
(apply (lambda (a b)
(unwind-protect
(if (plusp a) 0 (return-from test-lexthrow (+ a b)))
(warn "To serve and protect!")))
x))
#+ignore
(defun test-lexgo (x)
(let ((*print-base* 2))
(return-from test-lexgo (print 123))))
#+ignore
(defun test-xgo (c x)
(tagbody
loop
(warn "c: ~S" c)
(apply (lambda (a)
(decf c)
(if (plusp a) (go exit) (go loop))
(warn "juhu, a or x: ~S, c: ~S" a c))
x)
exit
(warn "exited: ~S" c)))
(defun test-bignum ()
123456789123456)
(defun fe32 ()
#xfffffffe)
(defun fe64 ()
#xfffffffffffffffe)
(defun fe96 ()
#xfffffffffffffffffffffffe)
(defun one32 ()
#x100000000)
(defun z (op x y)
(let ((foo (cons 1 2))
(result (funcall op x y))
(bar (cons 3 4)))
(if (not (typep result 'pointer))
(warn "foo: ~Z result: ~Z, bar: ~Z, diff foo-bar: ~D."
foo result bar
(- (object-location bar) (object-location foo)))
(warn "foo: ~Z result: ~Z, bar: ~Z, diff: ~D, ~D."
foo result bar
(- (object-location result) (object-location foo))
(- (object-location bar) (object-location result))))
(values foo result bar)))
(defun modx (x)
(lambda ()
(print x)))
(defun mod30 (x)
(ldb (Byte 30 0) x))
(defun mod32-4 (x)
(ldb (byte 28 4) x))
(defun mod24-4 (x)
(ldb (Byte 24 4) x))
(defun zz (op x y)
(let ((foo (vector 1 2))
(result (funcall op x y))
(bar (vector 3 4)))
(if (not (typep result 'pointer))
(warn "foo: ~Z result: ~Z, bar: ~Z, diff foo-bar: ~D."
foo result bar
(- (object-location bar) (object-location foo)))
(warn "foo: ~Z result: ~Z, bar: ~Z, diff: ~D, ~D."
foo result bar
(- (object-location result) (object-location foo))
(- (object-location bar) (object-location result))))
(values foo result bar)))
(defun testb ()
#(1 2 3 4))
(defun gt5 (x)
(<= x 5))
(defun xplus (x)
(typep x '(integer 0 *)))
(defstruct (xxx :constructor (:constructor boa-make-xxx (x y z)))
x y (z 'init-z))
(defun test-struct ()
(format t "make-xxx: ~S~%" (let ((s (make-xxx))) s))
(format t "make-xxx: ~S~%" (xxx-z (make-xxx))))
(defun test-dynamic ()
#+ignore
(let ((x 100))
(let ((y x))
(let ((z y))
(format t "y: ~S, x: ~S, z: ~S~%" y x z))))
#+ignore
(format t "~D ~D ~D~%" 0 1
(let ((*x* 100))
(declare (special *x*))
(format t "*x*: ~S~%" *x*)
(symbol-value '*x*)))
#+ignore
(format t "~D ~D ~D~%" 0 1
(progv '(*x*) '(101)
(format t "*x*: ~S~%" (symbol-value '*x*))
(symbol-value '*x*)))
(let ((*x* 200))
(declare (special *x*))
(format t "*x*: ~S~%" *x*)
#+ignore
(let ((*x* 300))
(declare (special *x*))
(format t "*x*: ~S~%" *x*))
*x*))
#+ignore
(defun test-dynamic-formal (*print-base*)
(print *print-base*))
#+ignore
(defun verify-throw ()
"CLHS speaketh:
The following prints ``The inner catch returns :SECOND-THROW'' and then returns :outer-catch."
(catch 'foo
(format t "The inner catch returns ~s.~%"
(catch 'foo
(unwind-protect (throw 'foo :first-throw)
(throw 'foo :second-throw))))
:outer-catch))
#+ignore
(defun do-throw ()
(unwind-protect (print 'hello)
(throw 'foo :second-throw)))
#+ignore
(defun bloo (x)
#'bloo
(multiple-value-prog1
(sloo x (1+ x))
(print 'hello)))
#+ignore
(defun sloo (&rest x)
(declare (dynamic-extent x))
(let ((y (car x)))
(sloo y)))
#+ignore
(defun test-throw (tag)
(unwind-protect
(warn "throw: ~Z" (throw tag (values 'throw1 (make-values) 'throw2)))
(warn "Something happened: ~W" (make-values))
#+ignore (return-from test-throw 'interrupted-value))
(error "Huh?"))
#+ignore
(defun test-catch (x)
(catch 'test-tag
(test-throw x 'test-tag)
(format t "Hello world")))
(defun test-throw (x tag)
(when x
(warn "Throwing ~S.." tag)
(throw tag (values-list x))))
#+ignore
(defun test-up-catch ()
(catch 'test-tag
(test-up 'test-tag)
(format t "Hello world")))
#+ignore
(defun test-up (tag)
(unwind-protect
(test-throw tag)
(print 'hello-cleanup)))
(defun test-cons (x)
(let ((cc (cons x x)))
(cdr cc)))
(defun xx (x)
(eql nil x))
(defun test-fixed (x y z)
(warn "x: ~W, y: ~W, z: ~W" x y z))
(defun test-let-closure ()
(tagbody
(let ((*print-base* 10)
(x (go zz))
(*print-radix* nil))
(warn "lending x: ~W" x)
(values (lambda ()
(warn "borrowed x: ~W" x)
(* x 2))
#+ignore
(lambda (y)
(setf x y))))
zz
(warn "zz")))
(defun test-not (x)
(if (not x) 0 100))
(defun test-pingo (z)
(block zzz
(warn "hello world")
(let ((zingo (+ z 23)))
(return-from zzz
(let ((x (* z zingo)))
(print (* x 2)))))
(warn "not this")))
(defun display-hash (x)
(loop for k being the hash-keys of x using (hash-value v)
do (format t "~&~S => ~S" k v))
(values))
(defun show-hash (x)
(loop for y being the hash-keys of x
do (format t "~&key: ~W [~W]" y (symbol-package y)))
(values))
( ( x ) )
(defun test-nested-extent ()
(let ((foo (identity 'foo-value))
(bar (let ((zot (identity 'test-nested-extent)))
(setq zot 'zot-value)
(identity zot))))
(if (eq foo 'foo-value)
(format t "~&Success: foo is ~W, bar is ~W" foo bar)
(format t "~&Failure! foo is ~W, bar is ~W" foo bar))))
(defun bar (x)
(multiple-value-prog1
(values 0 1 2)
(format t "blungolo: ~S" x)))
#+ignore
(defun test-ncase (x y z)
(numargs-case
(1 (x) (values x 'one))
(2 (x y) (values (+ x y) 'one 'two))
(3 (x y z) (values (+ x y z) 'one 'two 'three))
(t (args) (declare (ignore args)) 27)))
#+ignore
(defun xbar ()
(print-dynamic-context :terse t)
(block handler-case-block
(let (handler-case-var)
(tagbody
(handler-bind
((error (lambda (handler-case-temp-var)
(setq handler-case-var handler-case-temp-var)
(go handler-case-clause-tag))))
(print-dynamic-context :terse t)
(return-from handler-case-block
(signal "hello world")))
handler-case-clause-tag
(return-from handler-case-block
(let ((|c| handler-case-var))
(format t "got an error: ~s" |c|))))))
(print-dynamic-context :terse t))
#+ignore
(defun plingu (&optional v)
(let ((x (1+ *print-base*)))
(print "foo")
(print "foo")
(print x)
(print v)))
#+ignore
(defun (setf dingu) (x y)
(when (> x y)
(return-from dingu 'fooob))
(+ x y))
(defun foo (&edx edx x &optional (y nil yp))
(format t "~@{ ~A~}" x y yp edx))
(defun wefwe (&rest args)
(declare (dynamic-extent args))
(do ((p args (cdr p)))
((endp p))
(let ((x (car p)))
(print x))))
(defun mubmo ()
(let ((x (muerte::copy-funobj #'format))
(y (cons 1 2)))
(warn "x: ~Z, y: ~Z" x y)))
(defclass food () ())
(defgeneric cook (food))
( defmethod cook : before ( ( f food ) )
( defmethod cook : after ( ( f food ) )
(defmethod cook :after ((f food))
(declare (ignore f))
(print "Cooking some food."))
(defun test-pie (n pie)
(dotimes (i n)
(pie-filling pie)))
(defun test-inc (n)
(dotimes (i n)
(warn "foo: ~S" (lambda ()
(setf i 5)))))
(defun test-id (n x)
(dotimes (i n)
(identity x)))
(defun test-inc2 (x)
(print (prog1 x (incf x)))
(print x))
(defclass pie (food)
((filling :accessor pie-filling
:initarg :filling
:initform 'apple))
#+ignore (:default-initargs :filling (if (foo) 'apple 'banana)))
(defclass pie2 (food)
((filling :accessor pie-filling
:initarg :filling
)))
(defmethod cook ((p (eql 'pie)))
(warn "Won't really cook a symbolic pie!")
(values))
(defmethod cook ((p (eql 'pudding)))
'cooked-pudding)
(defmethod slot-value-using-class :after (class (pie pie2) slot)
(warn "HEy, don't poke inside my pie2!"))
(defmethod cook :after ((p symbol))
(warn "A symbol may or may not have been cooked."))
(defmethod cook ((p pie))
(cond
((eq 'banana (pie-filling p))
(print "Won't cook a banana-pie, trying next.")
(call-next-method))
(t (print "Cooking a pie.")
(setf (pie-filling p) (list 'cooked (pie-filling p))))))
(defmethod cook :before ((p pie))
(declare (ignore p))
(print "A pie is about to be cooked."))
(defmethod cook :after ((p pie))
(declare (ignore p))
(print "A pie has been cooked."))
(defun xwrite (object)
(with-inline-assembly (:returns :nothing)
(:locally (:movl (:edi (:edi-offset muerte::dynamic-env)) :eax))
(:movl :eax (#x1000000))
(:movl :ebp (#x1000004))
(:movl :esi (#x1000008)))
(block handler-case-block-1431896
(let (handler-case-var-1431897)
(tagbody
(handler-bind
((serious-condition
(lambda (handler-case-temp-var-1431898)
(setq handler-case-var-1431897 handler-case-temp-var-1431898)
(go handler-case-clause-tag-1431899))))
(return-from handler-case-block-1431896
(muerte::internal-write object)))
handler-case-clause-tag-1431899
(return-from handler-case-block-1431896
(let ((c handler-case-var-1431897))
(print-unreadable-object (c *standard-output* :type t :identity t)
(format t " while printing ~z" object))))))))
(defun ub (x)
`(hello world ,x or . what))
(define-primitive-function test-irq-pf ()
""
(with-inline-assembly (:returns :nothing)
(:int 113)
(:ret)))
(defun test-irq (&optional eax ebx ecx edx)
(multiple-value-bind (p1 p2)
(with-inline-assembly (:returns :multiple-values)
(:load-lexical (:lexical-binding eax) :eax)
(:load-lexical (:lexical-binding ebx) :ebx)
(:load-lexical (:lexical-binding ecx) :ecx)
(:load-lexical (:lexical-binding edx) :edx)
(:pushl :eax)
(:pushl :ebx)
(:jecxz 'dont-call)
(:globally (:call (:edi (:edi-offset values) 80)))
dont-call
(:store-lexical (:lexical-binding eax) :eax :type t)
(:store-lexical (:lexical-binding ebx) :ebx :type t)
(:store-lexical (:lexical-binding ecx) :ecx :type t)
(:store-lexical (:lexical-binding edx) :edx :type t)
(:popl :ebx)
(:popl :eax)
(:movl 2 :ecx)
(:stc))
(values eax ebx ecx edx p1 p2)))
(defun null-primitive-function (x)
"This function is just like identity, except it also calls a null primitive function.
Can be used to measure the overhead of primitive function."
(with-inline-assembly (:returns :eax)
(:load-lexical (:lexical-binding x) :eax)
(:% :bytes 32 #.(bt:slot-offset 'movitz::movitz-run-time-context 'movitz::ret-trampoline))))
(defun my-test-labels (x)
(labels (#+ignore (p () (print x))
(q (y) (list x y)))
(declare (ignore q))
(1+ x)))
(defparameter *timer-stack* nil)
(defparameter *timer-prevstack* nil)
(defparameter *timer-esi* nil)
(defparameter *timer-frame* #100(nil))
(defparameter *timer-base* 2)
(defparameter *timer-variation* 1000)
(defun test-format (&optional timeout (x #xab))
(let ((fasit (format nil "~2,'0X" x)))
(test-timer timeout)
(format t "~&Fasit: ~S" fasit)
(loop
(let ((x (format nil "~2,'0X" x)))
(assert (string= fasit x) ()
"Failed tesT. Fasit: ~S, X: ~S" fasit x)))))
(defun test-clc (&optional (timeout #xfffe) no-timer)
(unless no-timer
(test-timer timeout))
(loop
(funcall (find-symbol (string :test-clc) :clc))))
(defun test-timer (function
&key (base *timer-base*)
(variation *timer-variation*)
(timeout (+ base (random variation))))
(setf (exception-handler 32)
(lambda (exception-vector exception-frame)
(declare (ignore exception-vector exception-frame))
for o from 20 downto -36 by 4 as i upfrom 0
do ( setf ( aref f i ) ( memref exception - frame o 0 : lisp ) ) )
( setf ( fill - pointer ts ) 0 )
do ( multiple - value - bind ( offset code - vector funobj )
( vector - push funobj ts )
( )
(when (eql #\esc (muerte.x86-pc.keyboard:poll-char))
(break "Test-timer keyboard break."))
(with-inline-assembly (:returns :nothing)
(:compile-form (:result-mode :ecx) muerte.x86-pc::*screen*)
(:shrl 2 :ecx)
((:gs-override) :addb 1 (:ecx 158))
((:gs-override) :movb #x40 (:ecx 159)))
(do ((frame (muerte::stack-frame-uplink nil (muerte::current-stack-frame))
(muerte::stack-frame-uplink nil frame)))
((plusp frame))
(when (eq (with-inline-assembly (:returns :eax) (:movl :esi :eax))
(muerte::stack-frame-funobj nil frame))
(error "Double interrupt.")))
( dolist ( range muerte::%memory - map - roots% )
(map-stack-vector #'muerte::identity* nil (muerte::current-stack-frame))
(with-inline-assembly (:returns :nothing)
(:compile-form (:result-mode :ecx) muerte.x86-pc::*screen*)
(:shrl 2 :ecx)
((:gs-override) :movb #x20 (:ecx 159)))
#+ignore (setf *timer-prevstack* *timer-stack*
*timer-stack* (muerte::copy-current-control-stack))
(pic8259-end-of-interrupt 0)
(setf (pit8253-timer-mode 0) +pit8253-mode-single-timeout+
(pit8253-timer-count 0) (or timeout (+ base (random variation))))
))
(with-inline-assembly (:returns :nothing)
(:compile-form (:result-mode :ecx) muerte.x86-pc::*screen*)
(:shrl 2 :ecx)
((:gs-override) :movw #x4646 (:ecx 158)))
(setf (pit8253-timer-mode 0) +pit8253-mode-single-timeout+
(pit8253-timer-count 0) (or timeout (+ base (random variation))))
(setf (pic8259-irq-mask) #xfffe)
(pic8259-end-of-interrupt 0)
(with-inline-assembly (:returns :nothing) (:sti))
(unwind-protect
(when function
(funcall function))
(muerte::cli)
(setf (pic8259-irq-mask) #xffff)))
(defun wetweg (x)
(memref-int (memref x 2 :type :unsigned-byte32) :physicalp nil :type :unsigned-byte8))
(defun test-throwing (&optional (x #xffff))
(when x
(test-timer x))
(loop
(catch 'foo
(unwind-protect
(funcall (lambda ()
(unwind-protect
(progn
( unless ( logbitp 9 ( ) )
( incf ( memref - int muerte.x86 - pc::*screen * : type : unsigned - byte16 ) )
(throw 'foo 'inner-peace))
(incf (memref-int muerte.x86-pc::*screen* :index 80 :type :unsigned-byte16)))))
(incf (memref-int muerte.x86-pc::*screen* :index 160 :type :unsigned-byte16))))))
#+ignore
(defun fvf-textmode-screendump ()
(muerte.ip4::ip4-init)
(let* ((w muerte.x86-pc::*screen-width*)
(h muerte.x86-pc::*screen-height*)
(data (make-array (* w h)
:element-type 'character
:fill-pointer 0)))
(loop for y below h
do (loop for x below w
do (vector-push (code-char
(ldb (byte 8 0)
(memref-int muerte.x86-pc::*screen*
:index (+ x (* y muerte.x86-pc::*screen-stride*))
:type :unsigned-byte16)))
data)))
(muerte.ip4:tftp/ethernet-write :129.242.19.132 "movitz-screendump.txt" data
:quiet t
:mac (muerte.ip4::polling-arp
muerte.ip4::*ip4-router*
(lambda ()
(eql #\escape (muerte.x86-pc.keyboard:poll-char)))))))
(defun memdump (start length)
(loop for addr upfrom start repeat length
collect (memref-int addr :type :unsigned-byte8)))
(defun plus (a b)
(+ (muerte::check-the fixnum a)
(muerte::check-the fixnum b)))
(defun vector-non-dups (vector)
"Count the number of unique elements in vector."
(loop for i from 1 to (length vector)
for x across vector
count (not (find x vector :start i))))
(defun blit (buffer)
(loop for i from 0 below 16000
do (setf (memref-int #xa0000 :index i :type :unsigned-byte32)
(memref buffer 2 :index i :type :unsigned-byte32))))
#+ignore
(defun ztstring (physical-address)
(let ((s (make-string (loop for i upfrom 0
until (= 0 (memref-int physical-address :index i :type :unsigned-byte8))
finally (return i)))))
(loop for i from 0 below (length s)
do (setf (char s i)
(code-char (memref-int physical-address :index i :type :unsigned-byte8))))
s))
(defmacro do-default ((var &rest error-spec) &body init-forms)
`(or (and (boundp ',var)
(symbol-value ',var))
(setf (symbol-value ',var)
(progn ,@init-forms))
,(when error-spec
`(error ,@error-spec))))
#+ignore
(defun bridge (&optional (inside (do-default (*inside* "No inside NIC.")
(muerte.x86-pc.ne2k:ne2k-probe #x300)))
(outside (do-default (*outside* "No outside NIC.")
(muerte.x86-pc.ne2k:ne2k-probe #x280))))
(let ((buffer (make-array +max-ethernet-frame-size+
:element-type '(unsigned-byte 8)
:fill-pointer t)))
(loop
(ignore-errors
(reset-device inside)
(reset-device outside)
(setf (promiscuous-p inside) t
(promiscuous-p outside) t)
(loop
(when (receive inside buffer)
(transmit outside buffer))
(when (receive outside buffer)
(transmit inside buffer))
(case (muerte.x86-pc.keyboard:poll-char)
(#\escape (break "Under the bridge."))
(#\e (error "this is an error!"))))))))
(defparameter *write-barrier* nil)
(defun show-writes ()
(loop with num = (length *write-barrier*)
for i from 0 below num by 4
initially (format t "~&Number of writes: ~D" (truncate num 4))
do (format t "~&~D ~S: [~Z] Write to ~S: ~S."
i (aref *write-barrier* (+ i 3))
(aref *write-barrier* i)
(aref *write-barrier* i) (aref *write-barrier* (+ i 2))))
(values))
(defun es-test (&optional (barrier-size 1000))
(setf *write-barrier* (or *write-barrier*
(make-array (* 4 barrier-size) :fill-pointer 0))
(fill-pointer *write-barrier*) 0
(exception-handler 13) #'general-protection-handler
(segment-register :es) 0)
(values))
(defun general-protection-handler (vector dit-frame)
(assert (= vector 13))
(let ((eip (dit-frame-ref nil dit-frame :eip :unsigned-byte32)))
(let ((opcode (memref-int eip :offset 1 :type :unsigned-byte8 :physicalp nil))
(mod/rm (memref-int eip :offset 2 :type :unsigned-byte8 :physicalp nil)))
(if (not (= #x89 opcode))
(interrupt-default-handler vector dit-frame)
(let ((value (ecase (ldb (byte 3 3) mod/rm)
(0 (dit-frame-ref nil dit-frame :eax :lisp))
(3 (dit-frame-ref nil dit-frame :ebx :lisp)))))
If we return , do n't execute with the ES override prefix :
(setf (dit-frame-ref nil dit-frame :eip :unsigned-byte32) (1+ eip))
(when (typep value 'pointer)
(multiple-value-bind (object offset)
(case (logand mod/rm #xc7)
(: < value > (: eax < disp8 > ) )
(values (dit-frame-ref nil dit-frame :eax)
(memref-int eip :offset 3 :type :signed-byte8 :physicalp nil)))
(: < value > (: ebx < > ) )
(values (dit-frame-ref nil dit-frame :ebx)
(memref-int eip :offset 3 :type :signed-byte8 :physicalp nil)))
the / SIB case
(let ((sib (memref-int eip :offset 3 :type :unsigned-byte8 :physicalp nil)))
(case sib
((#x19 #x0b)
(values (dit-frame-ref nil dit-frame :ebx)
(+ (dit-frame-ref nil dit-frame :ecx :unsigned-byte8)
(memref-int eip :offset 4 :type :signed-byte8 :physicalp nil))))
((#x1a)
(values (dit-frame-ref nil dit-frame :ebx)
(+ (dit-frame-ref nil dit-frame :edx :unsigned-byte8)
(memref-int eip :offset 4 :type :signed-byte8 :physicalp nil))))))))
(when (not object)
(setf (segment-register :es) (segment-register :ds))
(break "[~S] With value ~S, unknown movl at ~S: ~S ~S ~S ~S"
dit-frame value eip
(memref-int eip :offset 1 :type :unsigned-byte8 :physicalp nil)
(memref-int eip :offset 2 :type :unsigned-byte8 :physicalp nil)
(memref-int eip :offset 3 :type :unsigned-byte8 :physicalp nil)
(memref-int eip :offset 4 :type :unsigned-byte8 :physicalp nil)))
(check-type object pointer)
(check-type offset fixnum)
(let ((write-barrier *write-barrier*)
(location (object-location object)))
(assert (not (location-in-object-p
(los0::space-other (%run-time-context-slot nil 'nursery-space))
location)) ()
"Write ~S to old-space at ~S." value location)
(unless (or (eq object write-barrier)
#+ignore
(location-in-object-p (%run-time-context-slot nil 'nursery-space)
location)
(location-in-object-p (%run-time-context-slot nil 'stack-vector)
location))
(if (location-in-object-p (%run-time-context-slot nil 'nursery-space)
location)
(vector-push 'stack-actually write-barrier)
(vector-push object write-barrier))
(vector-push offset write-barrier)
(vector-push value write-barrier)
(unless (vector-push eip write-barrier)
(setf (segment-register :es) (segment-register :ds))
(break "Write-barrier is full: ~D" (length write-barrier))))))))))))
|
d5ff5198f42381b6dfce73eb34d495b0ddd9f63957850705655a1819a9ccfa83 | mu-chaco/ReWire | Annotate.hs | # LANGUAGE ScopedTypeVariables #
{-# LANGUAGE Safe #-}
module ReWire.Crust.Annotate
( annotate
, Annote
) where
import ReWire.Annotation (Annote (..), toSrcSpanInfo)
import ReWire.SYB
import ReWire.HaskellSyntaxOrphans ()
import Control.Monad.Identity (Identity (..))
import Data.Data (Data (..), cast)
import Data.Maybe (fromJust)
import Language.Haskell.Exts.SrcLoc (SrcSpanInfo)
import Language.Haskell.Exts.Syntax
annotate :: (Data (ast Annote), Functor ast, Monad m) => ast SrcSpanInfo -> m (ast Annote)
annotate m = return $ runIdentity $ runPureT nodes $ LocAnnote <$> m
type SF a = a Annote -> Identity (a Annote)
nodes :: Transform Identity
nodes = (s :: SF Module)
||> (s :: SF ModuleHead)
||> (s :: SF ExportSpecList)
||> (s :: SF ExportSpec)
||> (s :: SF ImportDecl)
||> (s :: SF ImportSpecList)
||> (s :: SF ImportSpec)
||> (s :: SF Assoc)
||> (s :: SF Decl)
||> (s :: SF DeclHead)
||> (s :: SF InstRule)
||> (s :: SF InstHead)
||> (s :: SF IPBind)
||> (s :: SF ClassDecl)
||> (s :: SF InstDecl)
||> (s :: SF Deriving)
||> (s :: SF DataOrNew)
||> (s :: SF ConDecl)
||> (s :: SF FieldDecl)
||> (s :: SF QualConDecl)
||> (s :: SF GadtDecl)
||> (s :: SF BangType)
||> (s :: SF Match)
||> (s :: SF Rhs)
||> (s :: SF GuardedRhs)
||> (s :: SF Context)
||> (s :: SF FunDep)
||> (s :: SF Asst)
||> (s :: SF Type)
||> (s :: SF Kind)
||> (s :: SF TyVarBind)
||> (s :: SF Exp)
||> (s :: SF Stmt)
||> (s :: SF QualStmt)
||> (s :: SF FieldUpdate)
||> (s :: SF Alt)
||> (s :: SF XAttr)
||> (s :: SF Pat)
||> (s :: SF PatField)
||> (s :: SF PXAttr)
||> (s :: SF RPat)
||> (s :: SF RPatOp)
||> (s :: SF Literal)
||> (s :: SF ModuleName)
||> (s :: SF QName)
||> (s :: SF Name)
||> (s :: SF QOp)
||> (s :: SF Op)
||> (s :: SF CName)
||> (s :: SF IPName)
||> (s :: SF XName)
||> (s :: SF Bracket)
||> (s :: SF Splice)
||> (s :: SF Safety)
||> (s :: SF CallConv)
||> (s :: SF ModulePragma)
||> (s :: SF Rule)
||> (s :: SF RuleVar)
||> (s :: SF Activation)
||> (s :: SF Annotation)
||> TId
where s n = return $ gmapT (\ t -> case cast t :: Maybe Annote of
Just _ -> fromJust $ cast $ AstAnnote (toSrcSpanInfo <$> n)
Nothing -> t) n
| null | https://raw.githubusercontent.com/mu-chaco/ReWire/b04686a4cd6cb36ca9976a4b6c42bc195ce69462/src/ReWire/Crust/Annotate.hs | haskell | # LANGUAGE Safe # | # LANGUAGE ScopedTypeVariables #
module ReWire.Crust.Annotate
( annotate
, Annote
) where
import ReWire.Annotation (Annote (..), toSrcSpanInfo)
import ReWire.SYB
import ReWire.HaskellSyntaxOrphans ()
import Control.Monad.Identity (Identity (..))
import Data.Data (Data (..), cast)
import Data.Maybe (fromJust)
import Language.Haskell.Exts.SrcLoc (SrcSpanInfo)
import Language.Haskell.Exts.Syntax
annotate :: (Data (ast Annote), Functor ast, Monad m) => ast SrcSpanInfo -> m (ast Annote)
annotate m = return $ runIdentity $ runPureT nodes $ LocAnnote <$> m
type SF a = a Annote -> Identity (a Annote)
nodes :: Transform Identity
nodes = (s :: SF Module)
||> (s :: SF ModuleHead)
||> (s :: SF ExportSpecList)
||> (s :: SF ExportSpec)
||> (s :: SF ImportDecl)
||> (s :: SF ImportSpecList)
||> (s :: SF ImportSpec)
||> (s :: SF Assoc)
||> (s :: SF Decl)
||> (s :: SF DeclHead)
||> (s :: SF InstRule)
||> (s :: SF InstHead)
||> (s :: SF IPBind)
||> (s :: SF ClassDecl)
||> (s :: SF InstDecl)
||> (s :: SF Deriving)
||> (s :: SF DataOrNew)
||> (s :: SF ConDecl)
||> (s :: SF FieldDecl)
||> (s :: SF QualConDecl)
||> (s :: SF GadtDecl)
||> (s :: SF BangType)
||> (s :: SF Match)
||> (s :: SF Rhs)
||> (s :: SF GuardedRhs)
||> (s :: SF Context)
||> (s :: SF FunDep)
||> (s :: SF Asst)
||> (s :: SF Type)
||> (s :: SF Kind)
||> (s :: SF TyVarBind)
||> (s :: SF Exp)
||> (s :: SF Stmt)
||> (s :: SF QualStmt)
||> (s :: SF FieldUpdate)
||> (s :: SF Alt)
||> (s :: SF XAttr)
||> (s :: SF Pat)
||> (s :: SF PatField)
||> (s :: SF PXAttr)
||> (s :: SF RPat)
||> (s :: SF RPatOp)
||> (s :: SF Literal)
||> (s :: SF ModuleName)
||> (s :: SF QName)
||> (s :: SF Name)
||> (s :: SF QOp)
||> (s :: SF Op)
||> (s :: SF CName)
||> (s :: SF IPName)
||> (s :: SF XName)
||> (s :: SF Bracket)
||> (s :: SF Splice)
||> (s :: SF Safety)
||> (s :: SF CallConv)
||> (s :: SF ModulePragma)
||> (s :: SF Rule)
||> (s :: SF RuleVar)
||> (s :: SF Activation)
||> (s :: SF Annotation)
||> TId
where s n = return $ gmapT (\ t -> case cast t :: Maybe Annote of
Just _ -> fromJust $ cast $ AstAnnote (toSrcSpanInfo <$> n)
Nothing -> t) n
|
228a99fb5f127db5d7b4e2ede5d973503a3bc5c09608d446706f52edfe44e8ad | FlowForwarding/lincx | linc_logic.erl | %%------------------------------------------------------------------------------
Copyright 2012 FlowForwarding.org
%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%-----------------------------------------------------------------------------
@author Erlang Solutions Ltd. < >
2012 FlowForwarding.org
%% @doc OpenFlow Logical Switch logic.
-module(linc_logic).
-behaviour(gen_server).
%% API
-export([send_to_controllers/2,
gen_datapath_id/1,
%% Backend general
get_datapath_id/1,
set_datapath_id/2,
get_backend_flow_tables/1,
get_backend_capabilities/1,
%% Backend ports
get_backend_ports/1,
get_port_config/2,
set_port_config/3,
get_port_features/2,
set_port_features/3,
is_port_valid/2,
%% Backend queues
get_backend_queues/1,
get_queue_min_rate/3,
set_queue_min_rate/4,
get_queue_max_rate/3,
set_queue_max_rate/4,
is_queue_valid/3,
%% Controllers
open_controller/5
]).
%% Internal API
-export([start_link/4]).
%% gen_server callbacks
-export([init/1,
handle_call/3,
handle_cast/2,
handle_info/2,
terminate/2,
code_change/3]).
-include_lib("of_protocol/include/of_protocol.hrl").
-include_lib("of_config/include/of_config.hrl").
-include("linc_logger.hrl").
-record(state, {
xid = 1 :: integer(),
backend_mod :: atom(),
ofconfig_backend_mod :: atom(),
backend_state :: term(),
switch_id :: integer(),
datapath_id :: string(),
config :: term(),
version :: integer()
}).
%%------------------------------------------------------------------------------
%% API functions
%%------------------------------------------------------------------------------
%% @doc Send message out to controllers.
-spec send_to_controllers(integer(), ofp_message()) -> any().
send_to_controllers(SwitchId, Message) ->
gen_server:cast(linc:lookup(SwitchId, linc_logic),
{send_to_controllers, Message}).
-spec get_datapath_id(integer()) -> string().
get_datapath_id(SwitchId) ->
gen_server:call(linc:lookup(SwitchId, linc_logic), get_datapath_id).
-spec set_datapath_id(integer(), string()) -> ok.
set_datapath_id(SwitchId, DatapathId) ->
gen_server:cast(linc:lookup(SwitchId, linc_logic),
{set_datapath_id, DatapathId}).
-spec get_backend_flow_tables(integer()) -> list(#flow_table{}).
get_backend_flow_tables(SwitchId) ->
gen_server:call(linc:lookup(SwitchId, linc_logic), get_backend_flow_tables).
-spec get_backend_capabilities(integer()) -> #capabilities{}.
get_backend_capabilities(SwitchId) ->
gen_server:call(linc:lookup(SwitchId, linc_logic), get_backend_capabilities).
-spec get_backend_ports(integer()) -> list(#port{}).
get_backend_ports(SwitchId) ->
gen_server:call(linc:lookup(SwitchId, linc_logic), get_backend_ports).
-spec get_port_config(integer(), integer()) -> #port_configuration{}.
get_port_config(SwitchId, PortNo) ->
gen_server:call(linc:lookup(SwitchId, linc_logic), {get_port_config,
PortNo}).
-spec set_port_config(integer(), integer(), #port_configuration{}) -> ok.
set_port_config(SwitchId, PortNo, PortConfig) ->
gen_server:cast(linc:lookup(SwitchId, linc_logic), {set_port_config,
PortNo, PortConfig}).
-spec get_port_features(integer(), integer()) -> #port_features{}.
get_port_features(SwitchId, PortNo) ->
gen_server:call(linc:lookup(SwitchId, linc_logic), {get_port_features,
PortNo}).
-spec set_port_features(integer(), integer(), #port_features{}) -> ok.
set_port_features(SwitchId, PortNo, PortFeatures) ->
gen_server:cast(linc:lookup(SwitchId, linc_logic), {set_port_features,
PortNo, PortFeatures}).
-spec is_port_valid(integer(), integer()) -> boolean().
is_port_valid(SwitchId, PortNo) ->
gen_server:call(linc:lookup(SwitchId, linc_logic), {is_port_valid, PortNo}).
-spec get_backend_queues(integer()) -> list(#queue{}).
get_backend_queues(SwitchId) ->
gen_server:call(linc:lookup(SwitchId, linc_logic), get_backend_queues).
-spec get_queue_min_rate(integer(), integer(), integer()) -> integer().
get_queue_min_rate(SwitchId, PortNo, QueueId) ->
gen_server:call(linc:lookup(SwitchId, linc_logic), {get_queue_min_rate,
PortNo, QueueId}).
-spec set_queue_min_rate(integer(), integer(), integer(), integer()) -> ok.
set_queue_min_rate(SwitchId, PortNo, QueueId, Rate) ->
gen_server:cast(linc:lookup(SwitchId, linc_logic), {set_queue_min_rate,
PortNo, QueueId, Rate}).
-spec get_queue_max_rate(integer(), integer(), integer()) -> integer().
get_queue_max_rate(SwitchId, PortNo, QueueId) ->
gen_server:call(linc:lookup(SwitchId, linc_logic), {get_queue_max_rate,
PortNo, QueueId}).
-spec set_queue_max_rate(integer(), integer(), integer(), integer()) -> ok.
set_queue_max_rate(SwitchId, PortNo, QueueId, Rate) ->
gen_server:cast(linc:lookup(SwitchId, linc_logic), {set_queue_max_rate,
PortNo, QueueId, Rate}).
-spec is_queue_valid(integer(), integer(), integer()) -> boolean().
is_queue_valid(SwitchId, PortNo, QueueId) ->
gen_server:call(linc:lookup(SwitchId, linc_logic), {is_queue_valid,
PortNo, QueueId}).
open_controller(SwitchId, Id, Host, Port, Proto) ->
gen_server:cast(linc:lookup(SwitchId, linc_logic), {open_controller, Id,
Host, Port, Proto}).
%% @doc Start the OF Switch logic.
-spec start_link(integer(), atom(), term(), term()) -> {ok, pid()} |
{error, any()}.
start_link(SwitchId, BackendMod, BackendOpts, Config) ->
gen_server:start_link(?MODULE, [SwitchId, BackendMod,
BackendOpts, Config], []).
%%------------------------------------------------------------------------------
%% gen_server callbacks
%%------------------------------------------------------------------------------
init([SwitchId, BackendMod, BackendOpts, Config]) ->
%% We trap exit signals here to handle shutdown initiated by the supervisor
%% and run terminate function which invokes terminate in callback modules
process_flag(trap_exit, true),
linc:register(SwitchId, linc_logic, self()),
OFConfigBackendMod = list_to_atom(atom_to_list(BackendMod) ++ "_ofconfig"),
%% Timeout 0 will send a timeout message to the gen_server to handle
%% backend initialization before any other message.
{ok, #state{backend_mod = BackendMod,
ofconfig_backend_mod = OFConfigBackendMod,
backend_state = BackendOpts,
switch_id = SwitchId,
config = Config}, 0}.
handle_call(get_datapath_id, _From, #state{datapath_id = DatapathId} = State) ->
{reply, DatapathId, State};
handle_call(get_backend_flow_tables, _From,
#state{ofconfig_backend_mod = OFConfigBackendMod,
datapath_id = DatapathId,
switch_id = SwitchId} = State) ->
FlowTables = OFConfigBackendMod:get_flow_tables(SwitchId, DatapathId),
{reply, FlowTables, State};
handle_call(get_backend_capabilities, _From,
#state{ofconfig_backend_mod = OFConfigBackendMod} = State) ->
Capabilities = OFConfigBackendMod:get_capabilities(),
{reply, Capabilities, State};
handle_call(get_backend_ports, _From,
#state{ofconfig_backend_mod = OFConfigBackendMod,
switch_id = SwitchId} = State) ->
Ports = OFConfigBackendMod:get_ports(SwitchId),
{reply, Ports, State};
handle_call({get_port_config, PortNo}, _From,
#state{ofconfig_backend_mod = OFConfigBackendMod,
switch_id = SwitchId} = State) ->
PortConfig = OFConfigBackendMod:get_port_config(SwitchId, PortNo),
{reply, PortConfig, State};
handle_call({get_port_features, PortNo}, _From,
#state{ofconfig_backend_mod = OFConfigBackendMod,
switch_id = SwitchId} = State) ->
PortFeatures = OFConfigBackendMod:get_port_features(SwitchId, PortNo),
{reply, PortFeatures, State};
handle_call(get_backend_queues, _From,
#state{ofconfig_backend_mod = OFConfigBackendMod,
switch_id = SwitchId} = State) ->
BackendQueues = OFConfigBackendMod:get_queues(SwitchId),
RealQueues = lists:filter(fun(#queue{id = default}) ->
false;
(#queue{})->
true
end, BackendQueues),
{reply, RealQueues, State};
handle_call(get_queue_min_rate, _From,
#state{ofconfig_backend_mod = OFConfigBackendMod,
switch_id = SwitchId} = State) ->
BackendQueues = OFConfigBackendMod:get_queue_min_rate(SwitchId),
{reply, BackendQueues, State};
handle_call(get_queue_max_rate, _From,
#state{ofconfig_backend_mod = OFConfigBackendMod,
switch_id = SwitchId} = State) ->
BackendQueues = OFConfigBackendMod:get_queue_max_rate(SwitchId),
{reply, BackendQueues, State};
handle_call({is_port_valid, PortNo}, _From,
#state{backend_mod = BackendMod,
switch_id = SwitchId} = State) ->
Validity = BackendMod:is_port_valid(SwitchId, PortNo),
{reply, Validity, State};
handle_call({is_queue_valid, PortNo, QueueId}, _From,
#state{backend_mod = BackendMod,
switch_id = SwitchId} = State) ->
Validity = BackendMod:is_queue_valid(SwitchId, PortNo, QueueId),
{reply, Validity, State};
handle_call(_Message, _From, State) ->
{reply, ok, State}.
handle_cast({send_to_controllers, Message},
#state{xid = Xid,
switch_id = SwitchId,
backend_mod = Backend} = State) ->
ofp_channel_send(SwitchId, Backend, Message#ofp_message{xid = Xid}),
{noreply, State#state{xid = Xid + 1}};
handle_cast({set_datapath_id, DatapathId},
#state{backend_mod = Backend,
backend_state = BackendState} = State) ->
BackendState2 = Backend:set_datapath_mac(BackendState,
extract_mac(DatapathId)),
{noreply, State#state{backend_state = BackendState2,
datapath_id = DatapathId}};
handle_cast({set_port_config, PortNo, PortConfig},
#state{ofconfig_backend_mod = OFConfigBackendMod,
switch_id = SwitchId} = State) ->
OFConfigBackendMod:set_port_config(SwitchId, PortNo, PortConfig),
{noreply, State};
handle_cast({set_port_features, PortNo, PortFeatures},
#state{ofconfig_backend_mod = OFConfigBackendMod,
switch_id = SwitchId} = State) ->
OFConfigBackendMod:set_port_features(SwitchId, PortNo, PortFeatures),
{noreply, State};
handle_cast({set_queue_min_rate, PortNo, QueueId, Rate},
#state{ofconfig_backend_mod = OFConfigBackendMod,
switch_id = SwitchId} = State) ->
OFConfigBackendMod:set_queue_min_rate(SwitchId, PortNo, QueueId, Rate),
{noreply, State};
handle_cast({set_queue_max_rate, PortNo, QueueId, Rate},
#state{ofconfig_backend_mod = OFConfigBackendMod,
switch_id = SwitchId} = State) ->
OFConfigBackendMod:set_queue_max_rate(SwitchId, PortNo, QueueId, Rate),
{noreply, State};
handle_cast({open_controller, ControllerId, Host, Port, Proto},
#state{version = Version,
switch_id = SwitchId} = State) ->
ChannelSup = linc:lookup(SwitchId, channel_sup),
Opts = [{controlling_process, self()}, {version, Version}],
ofp_channel:open(
ChannelSup, ControllerId, {remote_peer, Host, Port, Proto}, Opts),
{noreply, State};
handle_cast(_Message, State) ->
{noreply, State}.
handle_info(timeout, #state{backend_mod = BackendMod,
backend_state = BackendState,
switch_id = SwitchId,
config = Config} = State) ->
%% Starting the backend and opening connections to the controllers as a
%% first thing after the logic and the main supervisor started.
DatapathId = gen_datapath_id(SwitchId),
BackendOpts = lists:keystore(switch_id, 1, BackendState,
{switch_id, SwitchId}),
BackendOpts2 = lists:keystore(datapath_mac, 1, BackendOpts,
{datapath_mac, extract_mac(DatapathId)}),
BackendOpts3 = lists:keystore(config, 1, BackendOpts2,
{config, Config}),
case BackendMod:start(BackendOpts3) of
{ok, Version, BackendState2} ->
start_and_register_ofp_channels_sup(SwitchId),
Opts = [{controlling_process, self()}, {version, Version}],
open_ofp_channels(Opts, State),
start_and_register_controllers_listener(Opts, State),
{noreply, State#state{version = Version,
backend_state = BackendState2,
datapath_id = DatapathId}};
{error, Reason} ->
{stop, {backend_failed, Reason}, State}
end;
handle_info({ofp_message, Pid, #ofp_message{body = MessageBody} = Message},
#state{backend_mod = Backend,
backend_state = BackendState} = State) ->
?DEBUG("Received message from the controller: ~p", [Message]),
NewBState = case Backend:handle_message(MessageBody, BackendState) of
{noreply, NewState} ->
NewState;
{reply, ReplyBody, NewState} ->
ofp_channel_send(Pid,
Backend,
Message#ofp_message{body = ReplyBody}),
NewState
end,
{noreply, State#state{backend_state = NewBState}};
handle_info({ofp_connected, _Pid, {Host, Port, Id, Version}}, State) ->
?INFO("Connected to controller ~s:~p/~p using OFP v~p",
[Host, Port, Id, Version]),
{noreply, State};
handle_info({ofp_closed, _Pid, {Host, Port, Id, Reason}}, State) ->
?INFO("Connection to controller ~s:~p/~p closed because of ~p",
[Host, Port, Id, Reason]),
{noreply, State};
handle_info(_Info, State) ->
{noreply, State}.
terminate(Reason, #state{switch_id = SwitchId, backend_mod = BackendMod,
backend_state = BackendState}) ->
case Reason of
{backend_failed, DeatiledReason} ->
?ERROR("Backend module ~p failed to start because: ~p",
[BackendMod, DeatiledReason]),
supervisor:terminate_child(linc:lookup(SwitchId, linc_sup),
linc_logic);
_ ->
ok
end,
BackendMod:stop(BackendState).
code_change(_OldVersion, State, _Extra) ->
{ok, State}.
%%%-----------------------------------------------------------------------------
%%% Helpers
%%%-----------------------------------------------------------------------------
start_and_register_ofp_channels_sup(SwitchId) ->
%% This needs to be temporary, since it is explicitly started as a
%% child of linc_sup by linc_logic, and thus should _not_ be
%% automatically restarted by the supervisor.
ChannelSup = {ofp_channel_sup, {ofp_channel_sup, start_link, [SwitchId]},
temporary, 5000, supervisor, [ofp_channel_sup]},
{ok, ChannelSupPid} = supervisor:start_child(linc:lookup(SwitchId,
linc_sup),
ChannelSup),
linc:register(SwitchId, channel_sup, ChannelSupPid).
open_ofp_channels(Opts, #state{switch_id = SwitchId, config = Config}) ->
CtrlsConfig = controllers_config(Opts, linc:controllers_for_switch(SwitchId,
Config)),
ChannelSupPid = linc:lookup(SwitchId, channel_sup),
[ofp_channel:open(
ChannelSupPid, Id, {remote_peer, Host, Port, Protocol}, Opt)
|| {Id, Host, Port, Protocol, Opt} <- CtrlsConfig].
controllers_config(Opts, Controllers) ->
[case Ctrl of
{Id, Host, Port, Protocol} ->
{Id, Host, Port, Protocol, Opts};
{Id, Host, Port, Protocol, SysOpts} ->
{Id, Host, Port, Protocol, Opts ++ SysOpts}
end || Ctrl <- Controllers].
start_and_register_controllers_listener(Opts, #state{switch_id = SwitchId,
config = Config}) ->
case linc:controllers_listener_for_switch(SwitchId, Config) of
disabled ->
ok;
ConnListenerConfig ->
CtrlsListenerArgs = controllers_listener_args(SwitchId,
ConnListenerConfig,
Opts),
ConnListenerSupPid = start_controllers_listener(
CtrlsListenerArgs,
linc:lookup(SwitchId, linc_sup)),
linc:register(SwitchId, conn_listener_sup, ConnListenerSupPid)
end.
controllers_listener_args(SwitchId, {Address, Port, tcp}, Opts) ->
{ok, ParsedAddress} = inet_parse:address(Address),
[ParsedAddress, Port, linc:lookup(SwitchId, channel_sup), Opts].
start_controllers_listener(ConnListenerArgs, LincSupPid) ->
%% This needs to be temporary, since it is explicitly started as a
%% child of linc_sup by linc_logic, and thus should _not_ be
%% automatically restarted by the supervisor.
ConnListenerSupSpec =
{ofp_conn_listener_sup, {ofp_conn_listener_sup, start_link,
ConnListenerArgs},
temporary, infinity, supervisor, [ofp_conn_listener_sup]},
{ok, ConnListenerSupPid} = supervisor:start_child(LincSupPid,
ConnListenerSupSpec),
ConnListenerSupPid.
get_datapath_mac() ->
{ok, Ifs} = inet:getifaddrs(),
MACs = [element(2, lists:keyfind(hwaddr, 1, Ps))
|| {_IF, Ps} <- Ifs, lists:keymember(hwaddr, 1, Ps)],
Make sure MAC /= 0
[MAC | _] = [M || M <- MACs, M /= [0,0,0,0,0,0]],
to_hex(list_to_binary(MAC), []).
to_hex(<<>>, Hex) ->
lists:flatten(lists:reverse(Hex));
to_hex(<<B1:4, B2:4, Binary/binary>>, Hex) ->
I1 = integer_to_list(B1, 16),
I2 = integer_to_list(B2, 16),
to_hex(Binary, [":", I2, I1 | Hex]).
gen_datapath_id(SwitchId) when SwitchId < 10 ->
get_datapath_mac() ++ "00:0" ++ integer_to_list(SwitchId);
gen_datapath_id(SwitchId) when SwitchId < 100 ->
get_datapath_mac() ++ "00:" ++ integer_to_list(SwitchId);
gen_datapath_id(SwitchId) when SwitchId < 1000 ->
get_datapath_mac() ++ "0" ++ integer_to_list(SwitchId div 100) ++
":" ++ integer_to_list(SwitchId rem 100);
gen_datapath_id(SwitchId) when SwitchId < 10000 ->
get_datapath_mac() ++ integer_to_list(SwitchId div 100) ++
":" ++ integer_to_list(SwitchId rem 100).
extract_mac(DatapathId) ->
Str = re:replace(string:substr(DatapathId, 1, 17), ":", "",
[global, {return, list}]),
extract_mac(Str, <<>>).
extract_mac([], Mac) ->
Mac;
extract_mac([N1, N2 | Rest], Mac) ->
B1 = list_to_integer([N1], 16),
B2 = list_to_integer([N2], 16),
extract_mac(Rest, <<Mac/binary, B1:4, B2:4>>).
ofp_channel_send(Id, Backend, Message) ->
%% ofp_channel:send() can generate an exception, workaround this
SendRes =
try
ofp_channel:send(Id, Message)
catch
exit:{noproc,_} ->
{error, noproc}
end,
case SendRes of
ok ->
Backend:log_message_sent(Message),
ok;
{ok, filtered} ->
log_message_filtered(Message, Id);
{error, not_connected} = Error ->
%% Don't log not_connected errors, as they pollute debug output.
%% This error occurs each time when packet is received by
%% the switch but switch didn't connect to the controller yet.
Error;
{error, Reason} = Error ->
log_channel_send_error(Message, Id, Reason),
Error;
L when is_list(L) ->
lists:map(fun(ok) ->
ok;
({ok, filtered}) ->
log_message_filtered(Message, Id);
({error, not_connected} = Error) ->
%% Same as previous comment
Error;
({error, Reason} = Error) ->
log_channel_send_error(Message, Id, Reason),
Error
end, L)
end.
log_channel_send_error(Message, Id, Reason) ->
?ERROR("~nMessage: ~p~n"
"Channel id: ~p~n"
"Message cannot be sent through OFP Channel because:~n"
"~p~n", [Message, Id, Reason]).
log_message_filtered(Message, Id) ->
?DEBUG("Message: ~p~n"
"filtered and not sent through the channel with id: ~p~n",
[Message, Id]).
| null | https://raw.githubusercontent.com/FlowForwarding/lincx/7795923b51fa1e680511669f4a27404b2ed1f1dc/apps/linc/src/linc_logic.erl | erlang | ------------------------------------------------------------------------------
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-----------------------------------------------------------------------------
@doc OpenFlow Logical Switch logic.
API
Backend general
Backend ports
Backend queues
Controllers
Internal API
gen_server callbacks
------------------------------------------------------------------------------
API functions
------------------------------------------------------------------------------
@doc Send message out to controllers.
@doc Start the OF Switch logic.
------------------------------------------------------------------------------
gen_server callbacks
------------------------------------------------------------------------------
We trap exit signals here to handle shutdown initiated by the supervisor
and run terminate function which invokes terminate in callback modules
Timeout 0 will send a timeout message to the gen_server to handle
backend initialization before any other message.
Starting the backend and opening connections to the controllers as a
first thing after the logic and the main supervisor started.
-----------------------------------------------------------------------------
Helpers
-----------------------------------------------------------------------------
This needs to be temporary, since it is explicitly started as a
child of linc_sup by linc_logic, and thus should _not_ be
automatically restarted by the supervisor.
This needs to be temporary, since it is explicitly started as a
child of linc_sup by linc_logic, and thus should _not_ be
automatically restarted by the supervisor.
ofp_channel:send() can generate an exception, workaround this
Don't log not_connected errors, as they pollute debug output.
This error occurs each time when packet is received by
the switch but switch didn't connect to the controller yet.
Same as previous comment | Copyright 2012 FlowForwarding.org
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
@author Erlang Solutions Ltd. < >
2012 FlowForwarding.org
-module(linc_logic).
-behaviour(gen_server).
-export([send_to_controllers/2,
gen_datapath_id/1,
get_datapath_id/1,
set_datapath_id/2,
get_backend_flow_tables/1,
get_backend_capabilities/1,
get_backend_ports/1,
get_port_config/2,
set_port_config/3,
get_port_features/2,
set_port_features/3,
is_port_valid/2,
get_backend_queues/1,
get_queue_min_rate/3,
set_queue_min_rate/4,
get_queue_max_rate/3,
set_queue_max_rate/4,
is_queue_valid/3,
open_controller/5
]).
-export([start_link/4]).
-export([init/1,
handle_call/3,
handle_cast/2,
handle_info/2,
terminate/2,
code_change/3]).
-include_lib("of_protocol/include/of_protocol.hrl").
-include_lib("of_config/include/of_config.hrl").
-include("linc_logger.hrl").
-record(state, {
xid = 1 :: integer(),
backend_mod :: atom(),
ofconfig_backend_mod :: atom(),
backend_state :: term(),
switch_id :: integer(),
datapath_id :: string(),
config :: term(),
version :: integer()
}).
-spec send_to_controllers(integer(), ofp_message()) -> any().
send_to_controllers(SwitchId, Message) ->
gen_server:cast(linc:lookup(SwitchId, linc_logic),
{send_to_controllers, Message}).
-spec get_datapath_id(integer()) -> string().
get_datapath_id(SwitchId) ->
gen_server:call(linc:lookup(SwitchId, linc_logic), get_datapath_id).
-spec set_datapath_id(integer(), string()) -> ok.
set_datapath_id(SwitchId, DatapathId) ->
gen_server:cast(linc:lookup(SwitchId, linc_logic),
{set_datapath_id, DatapathId}).
-spec get_backend_flow_tables(integer()) -> list(#flow_table{}).
get_backend_flow_tables(SwitchId) ->
gen_server:call(linc:lookup(SwitchId, linc_logic), get_backend_flow_tables).
-spec get_backend_capabilities(integer()) -> #capabilities{}.
get_backend_capabilities(SwitchId) ->
gen_server:call(linc:lookup(SwitchId, linc_logic), get_backend_capabilities).
-spec get_backend_ports(integer()) -> list(#port{}).
get_backend_ports(SwitchId) ->
gen_server:call(linc:lookup(SwitchId, linc_logic), get_backend_ports).
-spec get_port_config(integer(), integer()) -> #port_configuration{}.
get_port_config(SwitchId, PortNo) ->
gen_server:call(linc:lookup(SwitchId, linc_logic), {get_port_config,
PortNo}).
-spec set_port_config(integer(), integer(), #port_configuration{}) -> ok.
set_port_config(SwitchId, PortNo, PortConfig) ->
gen_server:cast(linc:lookup(SwitchId, linc_logic), {set_port_config,
PortNo, PortConfig}).
-spec get_port_features(integer(), integer()) -> #port_features{}.
get_port_features(SwitchId, PortNo) ->
gen_server:call(linc:lookup(SwitchId, linc_logic), {get_port_features,
PortNo}).
-spec set_port_features(integer(), integer(), #port_features{}) -> ok.
set_port_features(SwitchId, PortNo, PortFeatures) ->
gen_server:cast(linc:lookup(SwitchId, linc_logic), {set_port_features,
PortNo, PortFeatures}).
-spec is_port_valid(integer(), integer()) -> boolean().
is_port_valid(SwitchId, PortNo) ->
gen_server:call(linc:lookup(SwitchId, linc_logic), {is_port_valid, PortNo}).
-spec get_backend_queues(integer()) -> list(#queue{}).
get_backend_queues(SwitchId) ->
gen_server:call(linc:lookup(SwitchId, linc_logic), get_backend_queues).
-spec get_queue_min_rate(integer(), integer(), integer()) -> integer().
get_queue_min_rate(SwitchId, PortNo, QueueId) ->
gen_server:call(linc:lookup(SwitchId, linc_logic), {get_queue_min_rate,
PortNo, QueueId}).
-spec set_queue_min_rate(integer(), integer(), integer(), integer()) -> ok.
set_queue_min_rate(SwitchId, PortNo, QueueId, Rate) ->
gen_server:cast(linc:lookup(SwitchId, linc_logic), {set_queue_min_rate,
PortNo, QueueId, Rate}).
-spec get_queue_max_rate(integer(), integer(), integer()) -> integer().
get_queue_max_rate(SwitchId, PortNo, QueueId) ->
gen_server:call(linc:lookup(SwitchId, linc_logic), {get_queue_max_rate,
PortNo, QueueId}).
-spec set_queue_max_rate(integer(), integer(), integer(), integer()) -> ok.
set_queue_max_rate(SwitchId, PortNo, QueueId, Rate) ->
gen_server:cast(linc:lookup(SwitchId, linc_logic), {set_queue_max_rate,
PortNo, QueueId, Rate}).
-spec is_queue_valid(integer(), integer(), integer()) -> boolean().
is_queue_valid(SwitchId, PortNo, QueueId) ->
gen_server:call(linc:lookup(SwitchId, linc_logic), {is_queue_valid,
PortNo, QueueId}).
open_controller(SwitchId, Id, Host, Port, Proto) ->
gen_server:cast(linc:lookup(SwitchId, linc_logic), {open_controller, Id,
Host, Port, Proto}).
-spec start_link(integer(), atom(), term(), term()) -> {ok, pid()} |
{error, any()}.
start_link(SwitchId, BackendMod, BackendOpts, Config) ->
gen_server:start_link(?MODULE, [SwitchId, BackendMod,
BackendOpts, Config], []).
init([SwitchId, BackendMod, BackendOpts, Config]) ->
process_flag(trap_exit, true),
linc:register(SwitchId, linc_logic, self()),
OFConfigBackendMod = list_to_atom(atom_to_list(BackendMod) ++ "_ofconfig"),
{ok, #state{backend_mod = BackendMod,
ofconfig_backend_mod = OFConfigBackendMod,
backend_state = BackendOpts,
switch_id = SwitchId,
config = Config}, 0}.
handle_call(get_datapath_id, _From, #state{datapath_id = DatapathId} = State) ->
{reply, DatapathId, State};
handle_call(get_backend_flow_tables, _From,
#state{ofconfig_backend_mod = OFConfigBackendMod,
datapath_id = DatapathId,
switch_id = SwitchId} = State) ->
FlowTables = OFConfigBackendMod:get_flow_tables(SwitchId, DatapathId),
{reply, FlowTables, State};
handle_call(get_backend_capabilities, _From,
#state{ofconfig_backend_mod = OFConfigBackendMod} = State) ->
Capabilities = OFConfigBackendMod:get_capabilities(),
{reply, Capabilities, State};
handle_call(get_backend_ports, _From,
#state{ofconfig_backend_mod = OFConfigBackendMod,
switch_id = SwitchId} = State) ->
Ports = OFConfigBackendMod:get_ports(SwitchId),
{reply, Ports, State};
handle_call({get_port_config, PortNo}, _From,
#state{ofconfig_backend_mod = OFConfigBackendMod,
switch_id = SwitchId} = State) ->
PortConfig = OFConfigBackendMod:get_port_config(SwitchId, PortNo),
{reply, PortConfig, State};
handle_call({get_port_features, PortNo}, _From,
#state{ofconfig_backend_mod = OFConfigBackendMod,
switch_id = SwitchId} = State) ->
PortFeatures = OFConfigBackendMod:get_port_features(SwitchId, PortNo),
{reply, PortFeatures, State};
handle_call(get_backend_queues, _From,
#state{ofconfig_backend_mod = OFConfigBackendMod,
switch_id = SwitchId} = State) ->
BackendQueues = OFConfigBackendMod:get_queues(SwitchId),
RealQueues = lists:filter(fun(#queue{id = default}) ->
false;
(#queue{})->
true
end, BackendQueues),
{reply, RealQueues, State};
handle_call(get_queue_min_rate, _From,
#state{ofconfig_backend_mod = OFConfigBackendMod,
switch_id = SwitchId} = State) ->
BackendQueues = OFConfigBackendMod:get_queue_min_rate(SwitchId),
{reply, BackendQueues, State};
handle_call(get_queue_max_rate, _From,
#state{ofconfig_backend_mod = OFConfigBackendMod,
switch_id = SwitchId} = State) ->
BackendQueues = OFConfigBackendMod:get_queue_max_rate(SwitchId),
{reply, BackendQueues, State};
handle_call({is_port_valid, PortNo}, _From,
#state{backend_mod = BackendMod,
switch_id = SwitchId} = State) ->
Validity = BackendMod:is_port_valid(SwitchId, PortNo),
{reply, Validity, State};
handle_call({is_queue_valid, PortNo, QueueId}, _From,
#state{backend_mod = BackendMod,
switch_id = SwitchId} = State) ->
Validity = BackendMod:is_queue_valid(SwitchId, PortNo, QueueId),
{reply, Validity, State};
handle_call(_Message, _From, State) ->
{reply, ok, State}.
handle_cast({send_to_controllers, Message},
#state{xid = Xid,
switch_id = SwitchId,
backend_mod = Backend} = State) ->
ofp_channel_send(SwitchId, Backend, Message#ofp_message{xid = Xid}),
{noreply, State#state{xid = Xid + 1}};
handle_cast({set_datapath_id, DatapathId},
#state{backend_mod = Backend,
backend_state = BackendState} = State) ->
BackendState2 = Backend:set_datapath_mac(BackendState,
extract_mac(DatapathId)),
{noreply, State#state{backend_state = BackendState2,
datapath_id = DatapathId}};
handle_cast({set_port_config, PortNo, PortConfig},
#state{ofconfig_backend_mod = OFConfigBackendMod,
switch_id = SwitchId} = State) ->
OFConfigBackendMod:set_port_config(SwitchId, PortNo, PortConfig),
{noreply, State};
handle_cast({set_port_features, PortNo, PortFeatures},
#state{ofconfig_backend_mod = OFConfigBackendMod,
switch_id = SwitchId} = State) ->
OFConfigBackendMod:set_port_features(SwitchId, PortNo, PortFeatures),
{noreply, State};
handle_cast({set_queue_min_rate, PortNo, QueueId, Rate},
#state{ofconfig_backend_mod = OFConfigBackendMod,
switch_id = SwitchId} = State) ->
OFConfigBackendMod:set_queue_min_rate(SwitchId, PortNo, QueueId, Rate),
{noreply, State};
handle_cast({set_queue_max_rate, PortNo, QueueId, Rate},
#state{ofconfig_backend_mod = OFConfigBackendMod,
switch_id = SwitchId} = State) ->
OFConfigBackendMod:set_queue_max_rate(SwitchId, PortNo, QueueId, Rate),
{noreply, State};
handle_cast({open_controller, ControllerId, Host, Port, Proto},
#state{version = Version,
switch_id = SwitchId} = State) ->
ChannelSup = linc:lookup(SwitchId, channel_sup),
Opts = [{controlling_process, self()}, {version, Version}],
ofp_channel:open(
ChannelSup, ControllerId, {remote_peer, Host, Port, Proto}, Opts),
{noreply, State};
handle_cast(_Message, State) ->
{noreply, State}.
handle_info(timeout, #state{backend_mod = BackendMod,
backend_state = BackendState,
switch_id = SwitchId,
config = Config} = State) ->
DatapathId = gen_datapath_id(SwitchId),
BackendOpts = lists:keystore(switch_id, 1, BackendState,
{switch_id, SwitchId}),
BackendOpts2 = lists:keystore(datapath_mac, 1, BackendOpts,
{datapath_mac, extract_mac(DatapathId)}),
BackendOpts3 = lists:keystore(config, 1, BackendOpts2,
{config, Config}),
case BackendMod:start(BackendOpts3) of
{ok, Version, BackendState2} ->
start_and_register_ofp_channels_sup(SwitchId),
Opts = [{controlling_process, self()}, {version, Version}],
open_ofp_channels(Opts, State),
start_and_register_controllers_listener(Opts, State),
{noreply, State#state{version = Version,
backend_state = BackendState2,
datapath_id = DatapathId}};
{error, Reason} ->
{stop, {backend_failed, Reason}, State}
end;
handle_info({ofp_message, Pid, #ofp_message{body = MessageBody} = Message},
#state{backend_mod = Backend,
backend_state = BackendState} = State) ->
?DEBUG("Received message from the controller: ~p", [Message]),
NewBState = case Backend:handle_message(MessageBody, BackendState) of
{noreply, NewState} ->
NewState;
{reply, ReplyBody, NewState} ->
ofp_channel_send(Pid,
Backend,
Message#ofp_message{body = ReplyBody}),
NewState
end,
{noreply, State#state{backend_state = NewBState}};
handle_info({ofp_connected, _Pid, {Host, Port, Id, Version}}, State) ->
?INFO("Connected to controller ~s:~p/~p using OFP v~p",
[Host, Port, Id, Version]),
{noreply, State};
handle_info({ofp_closed, _Pid, {Host, Port, Id, Reason}}, State) ->
?INFO("Connection to controller ~s:~p/~p closed because of ~p",
[Host, Port, Id, Reason]),
{noreply, State};
handle_info(_Info, State) ->
{noreply, State}.
terminate(Reason, #state{switch_id = SwitchId, backend_mod = BackendMod,
backend_state = BackendState}) ->
case Reason of
{backend_failed, DeatiledReason} ->
?ERROR("Backend module ~p failed to start because: ~p",
[BackendMod, DeatiledReason]),
supervisor:terminate_child(linc:lookup(SwitchId, linc_sup),
linc_logic);
_ ->
ok
end,
BackendMod:stop(BackendState).
code_change(_OldVersion, State, _Extra) ->
{ok, State}.
start_and_register_ofp_channels_sup(SwitchId) ->
ChannelSup = {ofp_channel_sup, {ofp_channel_sup, start_link, [SwitchId]},
temporary, 5000, supervisor, [ofp_channel_sup]},
{ok, ChannelSupPid} = supervisor:start_child(linc:lookup(SwitchId,
linc_sup),
ChannelSup),
linc:register(SwitchId, channel_sup, ChannelSupPid).
open_ofp_channels(Opts, #state{switch_id = SwitchId, config = Config}) ->
CtrlsConfig = controllers_config(Opts, linc:controllers_for_switch(SwitchId,
Config)),
ChannelSupPid = linc:lookup(SwitchId, channel_sup),
[ofp_channel:open(
ChannelSupPid, Id, {remote_peer, Host, Port, Protocol}, Opt)
|| {Id, Host, Port, Protocol, Opt} <- CtrlsConfig].
controllers_config(Opts, Controllers) ->
[case Ctrl of
{Id, Host, Port, Protocol} ->
{Id, Host, Port, Protocol, Opts};
{Id, Host, Port, Protocol, SysOpts} ->
{Id, Host, Port, Protocol, Opts ++ SysOpts}
end || Ctrl <- Controllers].
start_and_register_controllers_listener(Opts, #state{switch_id = SwitchId,
config = Config}) ->
case linc:controllers_listener_for_switch(SwitchId, Config) of
disabled ->
ok;
ConnListenerConfig ->
CtrlsListenerArgs = controllers_listener_args(SwitchId,
ConnListenerConfig,
Opts),
ConnListenerSupPid = start_controllers_listener(
CtrlsListenerArgs,
linc:lookup(SwitchId, linc_sup)),
linc:register(SwitchId, conn_listener_sup, ConnListenerSupPid)
end.
controllers_listener_args(SwitchId, {Address, Port, tcp}, Opts) ->
{ok, ParsedAddress} = inet_parse:address(Address),
[ParsedAddress, Port, linc:lookup(SwitchId, channel_sup), Opts].
start_controllers_listener(ConnListenerArgs, LincSupPid) ->
ConnListenerSupSpec =
{ofp_conn_listener_sup, {ofp_conn_listener_sup, start_link,
ConnListenerArgs},
temporary, infinity, supervisor, [ofp_conn_listener_sup]},
{ok, ConnListenerSupPid} = supervisor:start_child(LincSupPid,
ConnListenerSupSpec),
ConnListenerSupPid.
get_datapath_mac() ->
{ok, Ifs} = inet:getifaddrs(),
MACs = [element(2, lists:keyfind(hwaddr, 1, Ps))
|| {_IF, Ps} <- Ifs, lists:keymember(hwaddr, 1, Ps)],
Make sure MAC /= 0
[MAC | _] = [M || M <- MACs, M /= [0,0,0,0,0,0]],
to_hex(list_to_binary(MAC), []).
to_hex(<<>>, Hex) ->
lists:flatten(lists:reverse(Hex));
to_hex(<<B1:4, B2:4, Binary/binary>>, Hex) ->
I1 = integer_to_list(B1, 16),
I2 = integer_to_list(B2, 16),
to_hex(Binary, [":", I2, I1 | Hex]).
gen_datapath_id(SwitchId) when SwitchId < 10 ->
get_datapath_mac() ++ "00:0" ++ integer_to_list(SwitchId);
gen_datapath_id(SwitchId) when SwitchId < 100 ->
get_datapath_mac() ++ "00:" ++ integer_to_list(SwitchId);
gen_datapath_id(SwitchId) when SwitchId < 1000 ->
get_datapath_mac() ++ "0" ++ integer_to_list(SwitchId div 100) ++
":" ++ integer_to_list(SwitchId rem 100);
gen_datapath_id(SwitchId) when SwitchId < 10000 ->
get_datapath_mac() ++ integer_to_list(SwitchId div 100) ++
":" ++ integer_to_list(SwitchId rem 100).
extract_mac(DatapathId) ->
Str = re:replace(string:substr(DatapathId, 1, 17), ":", "",
[global, {return, list}]),
extract_mac(Str, <<>>).
extract_mac([], Mac) ->
Mac;
extract_mac([N1, N2 | Rest], Mac) ->
B1 = list_to_integer([N1], 16),
B2 = list_to_integer([N2], 16),
extract_mac(Rest, <<Mac/binary, B1:4, B2:4>>).
ofp_channel_send(Id, Backend, Message) ->
SendRes =
try
ofp_channel:send(Id, Message)
catch
exit:{noproc,_} ->
{error, noproc}
end,
case SendRes of
ok ->
Backend:log_message_sent(Message),
ok;
{ok, filtered} ->
log_message_filtered(Message, Id);
{error, not_connected} = Error ->
Error;
{error, Reason} = Error ->
log_channel_send_error(Message, Id, Reason),
Error;
L when is_list(L) ->
lists:map(fun(ok) ->
ok;
({ok, filtered}) ->
log_message_filtered(Message, Id);
({error, not_connected} = Error) ->
Error;
({error, Reason} = Error) ->
log_channel_send_error(Message, Id, Reason),
Error
end, L)
end.
log_channel_send_error(Message, Id, Reason) ->
?ERROR("~nMessage: ~p~n"
"Channel id: ~p~n"
"Message cannot be sent through OFP Channel because:~n"
"~p~n", [Message, Id, Reason]).
log_message_filtered(Message, Id) ->
?DEBUG("Message: ~p~n"
"filtered and not sent through the channel with id: ~p~n",
[Message, Id]).
|
957ba14d8f246c58f4b71a216e6d5d635061b8e734751a277819166a5383f037 | OCamlPro/alt-ergo | myDynlink.mli | (******************************************************************************)
(* *)
Alt - Ergo : The SMT Solver For Software Verification
Copyright ( C ) 2013 - 2018
(* *)
(* This file is distributed under the terms of the license indicated *)
(* in the file 'License.OCamlPro'. If 'License.OCamlPro' is not *)
(* present, please contact us to clarify licensing. *)
(* *)
(******************************************************************************)
* Dynlink wrapper
A wrapper of the Dynlink module : we use Dynlink except when we want to
generate a static ( native ) binary *
A wrapper of the Dynlink module: we use Dynlink except when we want to
generate a static (native) binary **)
type error
(** Type error, as in {!Dynlink.error} *)
exception Error of error
(** Error exception, as in {!Dynlink.Error} *)
val error_message : error -> string
(** Error messages as strings, as in {!Dynlink.error_message} *)
val loadfile : string -> unit
(** Load a compiled file, as in {!Dynlink.loadfile}. *)
val load : bool -> string -> string -> unit
* Same as loadfile but try to load plugins dir if loadfile raise an Error
@raise Errors . Error if the plugin failed to be loaded
@raise Errors.Error if the plugin failed to be loaded *)
| null | https://raw.githubusercontent.com/OCamlPro/alt-ergo/291523151417f4cd112744d740b58ab1e8a630b4/src/lib/util/myDynlink.mli | ocaml | ****************************************************************************
This file is distributed under the terms of the license indicated
in the file 'License.OCamlPro'. If 'License.OCamlPro' is not
present, please contact us to clarify licensing.
****************************************************************************
* Type error, as in {!Dynlink.error}
* Error exception, as in {!Dynlink.Error}
* Error messages as strings, as in {!Dynlink.error_message}
* Load a compiled file, as in {!Dynlink.loadfile}. | Alt - Ergo : The SMT Solver For Software Verification
Copyright ( C ) 2013 - 2018
* Dynlink wrapper
A wrapper of the Dynlink module : we use Dynlink except when we want to
generate a static ( native ) binary *
A wrapper of the Dynlink module: we use Dynlink except when we want to
generate a static (native) binary **)
type error
exception Error of error
val error_message : error -> string
val loadfile : string -> unit
val load : bool -> string -> string -> unit
* Same as loadfile but try to load plugins dir if loadfile raise an Error
@raise Errors . Error if the plugin failed to be loaded
@raise Errors.Error if the plugin failed to be loaded *)
|
6de1dee530c5d4a6cc63924d8b88c8c203909754bbe70c8a2ec11e4a7f20cd4b | Oblosys/proxima | Code.hs |
UUAGC 0.9.10 ( Code.ag )
module Code where
import Pretty
import Patterns
import Data.List(partition)
import Data.Set(Set)
import qualified Data.Set as Set
import Data.Map(Map)
import qualified Data.Map as Map
-- Unboxed tuples
-- unbox Whether unboxed tuples are wanted or not
-- inh The inherited attributes.
-- If there are none, no unboxing can take place,
-- because in that case the semantic function (a top-level identifier) would have an unboxed type.
Of course we ca n't have an unboxed 1 - tuple
mkTupleExpr :: Bool -> Bool -> Exprs -> Expr
mkTupleExpr unbox noInh exprs | not unbox || noInh || length exprs == 1 = TupleExpr exprs
| otherwise = UnboxedTupleExpr exprs
mkTupleType :: Bool -> Bool -> Types -> Type
mkTupleType unbox noInh tps | not unbox || noInh || length tps == 1 = TupleType tps
| otherwise = UnboxedTupleType tps
mkTupleLhs :: Bool -> Bool -> [String] -> Lhs
mkTupleLhs unbox noInh comps | not unbox || noInh || length comps == 1 = TupleLhs comps
| otherwise = UnboxedTupleLhs comps
CaseAlt -----------------------------------------------------
alternatives :
alternative CaseAlt :
child left :
child expr : Expr
alternatives:
alternative CaseAlt:
child left : Lhs
child expr : Expr
-}
data CaseAlt = CaseAlt (Lhs) (Expr)
CaseAlts ----------------------------------------------------
alternatives :
alternative Cons :
child hd : CaseAlt
child tl : CaseAlts
alternative :
alternatives:
alternative Cons:
child hd : CaseAlt
child tl : CaseAlts
alternative Nil:
-}
type CaseAlts = [(CaseAlt)]
-- Chunk -------------------------------------------------------
alternatives :
alternative :
child name : { String }
child comment : Decl
child info : Decls
child dataDef : Decls
child cataFun : Decls
child semDom : Decls
child semWrapper : Decls
child semFunctions : Decls
child : { [ String ] }
alternatives:
alternative Chunk:
child name : {String}
child comment : Decl
child info : Decls
child dataDef : Decls
child cataFun : Decls
child semDom : Decls
child semWrapper : Decls
child semFunctions : Decls
child semNames : {[String]}
-}
data Chunk = Chunk (String) (Decl) (Decls) (Decls) (Decls) (Decls) (Decls) (Decls) ([String])
Chunks ------------------------------------------------------
alternatives :
alternative Cons :
child hd : Chunk
child tl : Chunks
alternative :
alternatives:
alternative Cons:
child hd : Chunk
child tl : Chunks
alternative Nil:
-}
type Chunks = [(Chunk)]
DataAlt -----------------------------------------------------
alternatives :
alternative DataAlt :
child name : { String }
child args : { [ String ] }
alternative Record :
child name : { String }
child args : { [ ( String , String ) ] }
alternatives:
alternative DataAlt:
child name : {String}
child args : {[String]}
alternative Record:
child name : {String}
child args : {[(String,String)]}
-}
data DataAlt = DataAlt (String) ([String])
| Record (String) ([(String,String)])
-- DataAlts ----------------------------------------------------
alternatives :
alternative Cons :
child hd : DataAlt
child tl : DataAlts
alternative :
alternatives:
alternative Cons:
child hd : DataAlt
child tl : DataAlts
alternative Nil:
-}
type DataAlts = [(DataAlt)]
-- Decl --------------------------------------------------------
alternatives :
alternative Comment :
child txt : { String }
alternative Data :
child name : { String }
child params : { [ String ] }
child alts : DataAlts
child strict :
child derivings : { [ String ] }
alternative :
child left :
child rhs : Expr
child binds : { Set String }
child uses : { Set String }
alternative NewType :
child name : { String }
child params : { [ String ] }
child con : { String }
child tp : Type
alternative PragmaDecl :
child txt : { String }
alternative :
child name : { String }
child tp : Type
alternative Type :
child name : { String }
child params : { [ String ] }
child tp : Type
alternatives:
alternative Comment:
child txt : {String}
alternative Data:
child name : {String}
child params : {[String]}
child alts : DataAlts
child strict : {Bool}
child derivings : {[String]}
alternative Decl:
child left : Lhs
child rhs : Expr
child binds : {Set String}
child uses : {Set String}
alternative NewType:
child name : {String}
child params : {[String]}
child con : {String}
child tp : Type
alternative PragmaDecl:
child txt : {String}
alternative TSig:
child name : {String}
child tp : Type
alternative Type:
child name : {String}
child params : {[String]}
child tp : Type
-}
data Decl = Comment (String)
| Data (String) ([String]) (DataAlts) (Bool) ([String])
| Decl (Lhs) (Expr) (Set String) (Set String)
| NewType (String) ([String]) (String) (Type)
| PragmaDecl (String)
| TSig (String) (Type)
| Type (String) ([String]) (Type)
-- Decls -------------------------------------------------------
alternatives :
alternative Cons :
child hd : Decl
child tl : Decls
alternative :
alternatives:
alternative Cons:
child hd : Decl
child tl : Decls
alternative Nil:
-}
type Decls = [(Decl)]
-- Expr --------------------------------------------------------
alternatives :
alternative App :
child name : { String }
child args : Exprs
alternative Case :
child expr :
child alts : CaseAlts
alternative Lambda :
child args : Exprs
child body :
alternative Let :
child decls : Decls
child body :
alternative LineExpr :
child expr :
alternative PragmaExpr :
child onLeftSide : { Bool }
child onNewLine :
child txt : { String }
child expr :
alternative SimpleExpr :
child txt : { String }
alternative :
child lns : { [ String ] }
alternative Trace :
child txt : { String }
child expr :
alternative TupleExpr :
child exprs : Exprs
alternative TypedExpr :
child expr :
child tp : Type
alternative UnboxedTupleExpr :
child exprs : Exprs
alternatives:
alternative App:
child name : {String}
child args : Exprs
alternative Case:
child expr : Expr
child alts : CaseAlts
alternative Lambda:
child args : Exprs
child body : Expr
alternative Let:
child decls : Decls
child body : Expr
alternative LineExpr:
child expr : Expr
alternative PragmaExpr:
child onLeftSide : {Bool}
child onNewLine : {Bool}
child txt : {String}
child expr : Expr
alternative SimpleExpr:
child txt : {String}
alternative TextExpr:
child lns : {[String]}
alternative Trace:
child txt : {String}
child expr : Expr
alternative TupleExpr:
child exprs : Exprs
alternative TypedExpr:
child expr : Expr
child tp : Type
alternative UnboxedTupleExpr:
child exprs : Exprs
-}
data Expr = App (String) (Exprs)
| Case (Expr) (CaseAlts)
| Lambda (Exprs) (Expr)
| Let (Decls) (Expr)
| LineExpr (Expr)
| PragmaExpr (Bool) (Bool) (String) (Expr)
| SimpleExpr (String)
| TextExpr ([String])
| Trace (String) (Expr)
| TupleExpr (Exprs)
| TypedExpr (Expr) (Type)
| UnboxedTupleExpr (Exprs)
-- Exprs -------------------------------------------------------
alternatives :
alternative Cons :
child hd :
child tl : Exprs
alternative :
alternatives:
alternative Cons:
child hd : Expr
child tl : Exprs
alternative Nil:
-}
type Exprs = [(Expr)]
-- Lhs ---------------------------------------------------------
alternatives :
alternative Fun :
child name : { String }
child args : Exprs
alternative :
child pat3 : { Pattern }
alternative :
child pat3 : { Pattern }
alternative :
child comps : { [ String ] }
alternative UnboxedTupleLhs :
child comps : { [ String ] }
alternatives:
alternative Fun:
child name : {String}
child args : Exprs
alternative Pattern3:
child pat3 : {Pattern}
alternative Pattern3SM:
child pat3 : {Pattern}
alternative TupleLhs:
child comps : {[String]}
alternative UnboxedTupleLhs:
child comps : {[String]}
-}
data Lhs = Fun (String) (Exprs)
| Pattern3 (Pattern)
| Pattern3SM (Pattern)
| TupleLhs ([String])
| UnboxedTupleLhs ([String])
Program -----------------------------------------------------
alternatives :
alternative Program :
child chunks : Chunks
alternatives:
alternative Program:
child chunks : Chunks
-}
data Program = Program (Chunks)
-- Type --------------------------------------------------------
alternatives :
alternative :
child left : Type
child right : Type
alternative :
child left : { [ ( String , [ String ] ) ] }
child right : Type
alternative List :
child tp : Type
alternative SimpleType :
child txt : { String }
alternative TupleType :
child tps : Types
alternative TypeApp :
child func : Type
child args : Types
alternative UnboxedTupleType :
child tps : Types
alternatives:
alternative Arr:
child left : Type
child right : Type
alternative CtxApp:
child left : {[(String, [String])]}
child right : Type
alternative List:
child tp : Type
alternative SimpleType:
child txt : {String}
alternative TupleType:
child tps : Types
alternative TypeApp:
child func : Type
child args : Types
alternative UnboxedTupleType:
child tps : Types
-}
data Type = Arr (Type) (Type)
| CtxApp ([(String, [String])]) (Type)
| List (Type)
| SimpleType (String)
| TupleType (Types)
| TypeApp (Type) (Types)
| UnboxedTupleType (Types)
deriving ( Show)
-- Types -------------------------------------------------------
alternatives :
alternative Cons :
child hd : Type
child tl : Types
alternative :
alternatives:
alternative Cons:
child hd : Type
child tl : Types
alternative Nil:
-}
type Types = [(Type)] | null | https://raw.githubusercontent.com/Oblosys/proxima/f154dff2ccb8afe00eeb325d9d06f5e2a5ee7589/uuagc/src-derived/Code.hs | haskell | Unboxed tuples
unbox Whether unboxed tuples are wanted or not
inh The inherited attributes.
If there are none, no unboxing can take place,
because in that case the semantic function (a top-level identifier) would have an unboxed type.
---------------------------------------------------
--------------------------------------------------
Chunk -------------------------------------------------------
----------------------------------------------------
---------------------------------------------------
DataAlts ----------------------------------------------------
Decl --------------------------------------------------------
Decls -------------------------------------------------------
Expr --------------------------------------------------------
Exprs -------------------------------------------------------
Lhs ---------------------------------------------------------
---------------------------------------------------
Type --------------------------------------------------------
Types ------------------------------------------------------- |
UUAGC 0.9.10 ( Code.ag )
module Code where
import Pretty
import Patterns
import Data.List(partition)
import Data.Set(Set)
import qualified Data.Set as Set
import Data.Map(Map)
import qualified Data.Map as Map
Of course we ca n't have an unboxed 1 - tuple
mkTupleExpr :: Bool -> Bool -> Exprs -> Expr
mkTupleExpr unbox noInh exprs | not unbox || noInh || length exprs == 1 = TupleExpr exprs
| otherwise = UnboxedTupleExpr exprs
mkTupleType :: Bool -> Bool -> Types -> Type
mkTupleType unbox noInh tps | not unbox || noInh || length tps == 1 = TupleType tps
| otherwise = UnboxedTupleType tps
mkTupleLhs :: Bool -> Bool -> [String] -> Lhs
mkTupleLhs unbox noInh comps | not unbox || noInh || length comps == 1 = TupleLhs comps
| otherwise = UnboxedTupleLhs comps
alternatives :
alternative CaseAlt :
child left :
child expr : Expr
alternatives:
alternative CaseAlt:
child left : Lhs
child expr : Expr
-}
data CaseAlt = CaseAlt (Lhs) (Expr)
alternatives :
alternative Cons :
child hd : CaseAlt
child tl : CaseAlts
alternative :
alternatives:
alternative Cons:
child hd : CaseAlt
child tl : CaseAlts
alternative Nil:
-}
type CaseAlts = [(CaseAlt)]
alternatives :
alternative :
child name : { String }
child comment : Decl
child info : Decls
child dataDef : Decls
child cataFun : Decls
child semDom : Decls
child semWrapper : Decls
child semFunctions : Decls
child : { [ String ] }
alternatives:
alternative Chunk:
child name : {String}
child comment : Decl
child info : Decls
child dataDef : Decls
child cataFun : Decls
child semDom : Decls
child semWrapper : Decls
child semFunctions : Decls
child semNames : {[String]}
-}
data Chunk = Chunk (String) (Decl) (Decls) (Decls) (Decls) (Decls) (Decls) (Decls) ([String])
alternatives :
alternative Cons :
child hd : Chunk
child tl : Chunks
alternative :
alternatives:
alternative Cons:
child hd : Chunk
child tl : Chunks
alternative Nil:
-}
type Chunks = [(Chunk)]
alternatives :
alternative DataAlt :
child name : { String }
child args : { [ String ] }
alternative Record :
child name : { String }
child args : { [ ( String , String ) ] }
alternatives:
alternative DataAlt:
child name : {String}
child args : {[String]}
alternative Record:
child name : {String}
child args : {[(String,String)]}
-}
data DataAlt = DataAlt (String) ([String])
| Record (String) ([(String,String)])
alternatives :
alternative Cons :
child hd : DataAlt
child tl : DataAlts
alternative :
alternatives:
alternative Cons:
child hd : DataAlt
child tl : DataAlts
alternative Nil:
-}
type DataAlts = [(DataAlt)]
alternatives :
alternative Comment :
child txt : { String }
alternative Data :
child name : { String }
child params : { [ String ] }
child alts : DataAlts
child strict :
child derivings : { [ String ] }
alternative :
child left :
child rhs : Expr
child binds : { Set String }
child uses : { Set String }
alternative NewType :
child name : { String }
child params : { [ String ] }
child con : { String }
child tp : Type
alternative PragmaDecl :
child txt : { String }
alternative :
child name : { String }
child tp : Type
alternative Type :
child name : { String }
child params : { [ String ] }
child tp : Type
alternatives:
alternative Comment:
child txt : {String}
alternative Data:
child name : {String}
child params : {[String]}
child alts : DataAlts
child strict : {Bool}
child derivings : {[String]}
alternative Decl:
child left : Lhs
child rhs : Expr
child binds : {Set String}
child uses : {Set String}
alternative NewType:
child name : {String}
child params : {[String]}
child con : {String}
child tp : Type
alternative PragmaDecl:
child txt : {String}
alternative TSig:
child name : {String}
child tp : Type
alternative Type:
child name : {String}
child params : {[String]}
child tp : Type
-}
data Decl = Comment (String)
| Data (String) ([String]) (DataAlts) (Bool) ([String])
| Decl (Lhs) (Expr) (Set String) (Set String)
| NewType (String) ([String]) (String) (Type)
| PragmaDecl (String)
| TSig (String) (Type)
| Type (String) ([String]) (Type)
alternatives :
alternative Cons :
child hd : Decl
child tl : Decls
alternative :
alternatives:
alternative Cons:
child hd : Decl
child tl : Decls
alternative Nil:
-}
type Decls = [(Decl)]
alternatives :
alternative App :
child name : { String }
child args : Exprs
alternative Case :
child expr :
child alts : CaseAlts
alternative Lambda :
child args : Exprs
child body :
alternative Let :
child decls : Decls
child body :
alternative LineExpr :
child expr :
alternative PragmaExpr :
child onLeftSide : { Bool }
child onNewLine :
child txt : { String }
child expr :
alternative SimpleExpr :
child txt : { String }
alternative :
child lns : { [ String ] }
alternative Trace :
child txt : { String }
child expr :
alternative TupleExpr :
child exprs : Exprs
alternative TypedExpr :
child expr :
child tp : Type
alternative UnboxedTupleExpr :
child exprs : Exprs
alternatives:
alternative App:
child name : {String}
child args : Exprs
alternative Case:
child expr : Expr
child alts : CaseAlts
alternative Lambda:
child args : Exprs
child body : Expr
alternative Let:
child decls : Decls
child body : Expr
alternative LineExpr:
child expr : Expr
alternative PragmaExpr:
child onLeftSide : {Bool}
child onNewLine : {Bool}
child txt : {String}
child expr : Expr
alternative SimpleExpr:
child txt : {String}
alternative TextExpr:
child lns : {[String]}
alternative Trace:
child txt : {String}
child expr : Expr
alternative TupleExpr:
child exprs : Exprs
alternative TypedExpr:
child expr : Expr
child tp : Type
alternative UnboxedTupleExpr:
child exprs : Exprs
-}
data Expr = App (String) (Exprs)
| Case (Expr) (CaseAlts)
| Lambda (Exprs) (Expr)
| Let (Decls) (Expr)
| LineExpr (Expr)
| PragmaExpr (Bool) (Bool) (String) (Expr)
| SimpleExpr (String)
| TextExpr ([String])
| Trace (String) (Expr)
| TupleExpr (Exprs)
| TypedExpr (Expr) (Type)
| UnboxedTupleExpr (Exprs)
alternatives :
alternative Cons :
child hd :
child tl : Exprs
alternative :
alternatives:
alternative Cons:
child hd : Expr
child tl : Exprs
alternative Nil:
-}
type Exprs = [(Expr)]
alternatives :
alternative Fun :
child name : { String }
child args : Exprs
alternative :
child pat3 : { Pattern }
alternative :
child pat3 : { Pattern }
alternative :
child comps : { [ String ] }
alternative UnboxedTupleLhs :
child comps : { [ String ] }
alternatives:
alternative Fun:
child name : {String}
child args : Exprs
alternative Pattern3:
child pat3 : {Pattern}
alternative Pattern3SM:
child pat3 : {Pattern}
alternative TupleLhs:
child comps : {[String]}
alternative UnboxedTupleLhs:
child comps : {[String]}
-}
data Lhs = Fun (String) (Exprs)
| Pattern3 (Pattern)
| Pattern3SM (Pattern)
| TupleLhs ([String])
| UnboxedTupleLhs ([String])
alternatives :
alternative Program :
child chunks : Chunks
alternatives:
alternative Program:
child chunks : Chunks
-}
data Program = Program (Chunks)
alternatives :
alternative :
child left : Type
child right : Type
alternative :
child left : { [ ( String , [ String ] ) ] }
child right : Type
alternative List :
child tp : Type
alternative SimpleType :
child txt : { String }
alternative TupleType :
child tps : Types
alternative TypeApp :
child func : Type
child args : Types
alternative UnboxedTupleType :
child tps : Types
alternatives:
alternative Arr:
child left : Type
child right : Type
alternative CtxApp:
child left : {[(String, [String])]}
child right : Type
alternative List:
child tp : Type
alternative SimpleType:
child txt : {String}
alternative TupleType:
child tps : Types
alternative TypeApp:
child func : Type
child args : Types
alternative UnboxedTupleType:
child tps : Types
-}
data Type = Arr (Type) (Type)
| CtxApp ([(String, [String])]) (Type)
| List (Type)
| SimpleType (String)
| TupleType (Types)
| TypeApp (Type) (Types)
| UnboxedTupleType (Types)
deriving ( Show)
alternatives :
alternative Cons :
child hd : Type
child tl : Types
alternative :
alternatives:
alternative Cons:
child hd : Type
child tl : Types
alternative Nil:
-}
type Types = [(Type)] |
5a294bb57be0b6abbba50d9b252bdd7958d04e096543b7f2ed21495bd1794ba5 | haskell-suite/haskell-src-exts | Unicode2.hs | # LANGUAGE UnicodeSyntax #
lengthOP n (⊜) = 0 ⊜ n
| null | https://raw.githubusercontent.com/haskell-suite/haskell-src-exts/84a4930e0e5c051b7d9efd20ef7c822d5fc1c33b/tests/examples/Unicode2.hs | haskell | # LANGUAGE UnicodeSyntax #
lengthOP n (⊜) = 0 ⊜ n
| |
e306b2b8796b5a3e10cd50298b52e0b0e06b8935a42ccfd585a3b53c1ea0bfb3 | ryanpbrewster/haskell | P102.hs | module TestData.P102 (txt) where
txt :: [[Int]]
txt =
[ [ -340,495,-153,-910,835,-947]
, [ -175,41,-421,-714,574,-645]
, [ -547,712,-352,579,951,-786]
, [ 419,-864,-83,650,-399,171]
, [ -429,-89,-357,-930,296,-29]
, [ -734,-702,823,-745,-684,-62]
, [ -971,762,925,-776,-663,-157]
, [ 162,570,628,485,-807,-896]
, [ 641,91,-65,700,887,759]
, [ 215,-496,46,-931,422,-30]
, [ -119,359,668,-609,-358,-494]
, [ 440,929,968,214,760,-857]
, [ -700,785,838,29,-216,411]
, [ -770,-458,-325,-53,-505,633]
, [ -752,-805,349,776,-799,687]
, [ 323,5,561,-36,919,-560]
, [ -907,358,264,320,204,274]
, [ -728,-466,350,969,292,-345]
, [ 940,836,272,-533,748,185]
, [ 411,998,813,520,316,-949]
, [ -152,326,658,-762,148,-651]
, [ 330,507,-9,-628,101,174]
, [ 551,-496,772,-541,-702,-45]
, [ -164,-489,-90,322,631,-59]
, [ 673,366,-4,-143,-606,-704]
, [ 428,-609,801,-449,740,-269]
, [ 453,-924,-785,-346,-853,111]
, [ -738,555,-181,467,-426,-20]
, [ 958,-692,784,-343,505,-569]
, [ 620,27,263,54,-439,-726]
, [ 804,87,998,859,871,-78]
, [ -119,-453,-709,-292,-115,-56]
, [ -626,138,-940,-476,-177,-274]
, [ -11,160,142,588,446,158]
, [ 538,727,550,787,330,810]
, [ 420,-689,854,-546,337,516]
, [ 872,-998,-607,748,473,-192]
, [ 653,440,-516,-985,808,-857]
, [ 374,-158,331,-940,-338,-641]
, [ 137,-925,-179,771,734,-715]
, [ -314,198,-115,29,-641,-39]
, [ 759,-574,-385,355,590,-603]
, [ -189,-63,-168,204,289,305]
, [ -182,-524,-715,-621,911,-255]
, [ 331,-816,-833,471,168,126]
, [ -514,581,-855,-220,-731,-507]
, [ 129,169,576,651,-87,-458]
, [ 783,-444,-881,658,-266,298]
, [ 603,-430,-598,585,368,899]
, [ 43,-724,962,-376,851,409]
, [ -610,-646,-883,-261,-482,-881]
, [ -117,-237,978,641,101,-747]
, [ 579,125,-715,-712,208,534]
, [ 672,-214,-762,372,874,533]
, [ -564,965,38,715,367,242]
, [ 500,951,-700,-981,-61,-178]
, [ -382,-224,-959,903,-282,-60]
, [ -355,295,426,-331,-591,655]
, [ 892,128,958,-271,-993,274]
, [ -454,-619,302,138,-790,-874]
, [ -642,601,-574,159,-290,-318]
, [ 266,-109,257,-686,54,975]
, [ 162,628,-478,840,264,-266]
, [ 466,-280,982,1,904,-810]
, [ 721,839,730,-807,777,981]
, [ -129,-430,748,263,943,96]
, [ 434,-94,410,-990,249,-704]
, [ 237,42,122,-732,44,-51]
, [ 909,-116,-229,545,292,717]
, [ 824,-768,-807,-370,-262,30]
, [ 675,58,332,-890,-651,791]
, [ 363,825,-717,254,684,240]
, [ 405,-715,900,166,-589,422]
, [ -476,686,-830,-319,634,-807]
, [ 633,837,-971,917,-764,207]
, [ -116,-44,-193,-70,908,809]
, [ -26,-252,998,408,70,-713]
, [ -601,645,-462,842,-644,-591]
, [ -160,653,274,113,-138,687]
, [ 369,-273,-181,925,-167,-693]
, [ -338,135,480,-967,-13,-840]
, [ -90,-270,-564,695,161,907]
, [ 607,-430,869,-713,461,-469]
, [ 919,-165,-776,522,606,-708]
, [ -203,465,288,207,-339,-458]
, [ -453,-534,-715,975,838,-677]
, [ -973,310,-350,934,546,-805]
, [ -835,385,708,-337,-594,-772]
, [ -14,914,900,-495,-627,594]
, [ 833,-713,-213,578,-296,699]
, [ -27,-748,484,455,915,291]
, [ 270,889,739,-57,442,-516]
, [ 119,811,-679,905,184,130]
, [ -678,-469,925,553,612,482]
, [ 101,-571,-732,-842,644,588]
, [ -71,-737,566,616,957,-663]
, [ -634,-356,90,-207,936,622]
, [ 598,443,964,-895,-58,529]
, [ 847,-467,929,-742,91,10]
, [ -633,829,-780,-408,222,-30]
, [ -818,57,275,-38,-746,198]
, [ -722,-825,-549,597,-391,99]
, [ -570,908,430,873,-103,-360]
, [ 342,-681,512,434,542,-528]
, [ 297,850,479,609,543,-357]
, [ 9,784,212,548,56,859]
, [ -152,560,-240,-969,-18,713]
, [ 140,-133,34,-635,250,-163]
, [ -272,-22,-169,-662,989,-604]
, [ 471,-765,355,633,-742,-118]
, [ -118,146,942,663,547,-376]
, [ 583,16,162,264,715,-33]
, [ -230,-446,997,-838,561,555]
, [ 372,397,-729,-318,-276,649]
, [ 92,982,-970,-390,-922,922]
, [ -981,713,-951,-337,-669,670]
, [ -999,846,-831,-504,7,-128]
, [ 455,-954,-370,682,-510,45]
, [ 822,-960,-892,-385,-662,314]
, [ -668,-686,-367,-246,530,-341]
, [ -723,-720,-926,-836,-142,757]
, [ -509,-134,384,-221,-873,-639]
, [ -803,-52,-706,-669,373,-339]
, [ 933,578,631,-616,770,555]
, [ 741,-564,-33,-605,-576,275]
, [ -715,445,-233,-730,734,-704]
, [ 120,-10,-266,-685,-490,-17]
, [ -232,-326,-457,-946,-457,-116]
, [ 811,52,639,826,-200,147]
, [ -329,279,293,612,943,955]
, [ -721,-894,-393,-969,-642,453]
, [ -688,-826,-352,-75,371,79]
, [ -809,-979,407,497,858,-248]
, [ -485,-232,-242,-582,-81,849]
, [ 141,-106,123,-152,806,-596]
, [ -428,57,-992,811,-192,478]
, [ 864,393,122,858,255,-876]
, [ -284,-780,240,457,354,-107]
, [ 956,605,-477,44,26,-678]
, [ 86,710,-533,-815,439,327]
, [ -906,-626,-834,763,426,-48]
, [ 201,-150,-904,652,475,412]
, [ -247,149,81,-199,-531,-148]
, [ 923,-76,-353,175,-121,-223]
, [ 427,-674,453,472,-410,585]
, [ 931,776,-33,85,-962,-865]
, [ -655,-908,-902,208,869,792]
, [ -316,-102,-45,-436,-222,885]
, [ -309,768,-574,653,745,-975]
, [ 896,27,-226,993,332,198]
, [ 323,655,-89,260,240,-902]
, [ 501,-763,-424,793,813,616]
, [ 993,375,-938,-621,672,-70]
, [ -880,-466,-283,770,-824,143]
, [ 63,-283,886,-142,879,-116]
, [ -964,-50,-521,-42,-306,-161]
, [ 724,-22,866,-871,933,-383]
, [ -344,135,282,966,-80,917]
, [ -281,-189,420,810,362,-582]
, [ -515,455,-588,814,162,332]
, [ 555,-436,-123,-210,869,-943]
, [ 589,577,232,286,-554,876]
, [ -773,127,-58,-171,-452,125]
, [ -428,575,906,-232,-10,-224]
, [ 437,276,-335,-348,605,878]
, [ -964,511,-386,-407,168,-220]
, [ 307,513,912,-463,-423,-416]
, [ -445,539,273,886,-18,760]
, [ -396,-585,-670,414,47,364]
, [ 143,-506,754,906,-971,-203]
, [ -544,472,-180,-541,869,-465]
, [ -779,-15,-396,890,972,-220]
, [ -430,-564,503,182,-119,456]
, [ 89,-10,-739,399,506,499]
, [ 954,162,-810,-973,127,870]
, [ 890,952,-225,158,828,237]
, [ -868,952,349,465,574,750]
, [ -915,369,-975,-596,-395,-134]
, [ -135,-601,575,582,-667,640]
, [ 413,890,-560,-276,-555,-562]
, [ -633,-269,561,-820,-624,499]
, [ 371,-92,-784,-593,864,-717]
, [ -971,655,-439,367,754,-951]
, [ 172,-347,36,279,-247,-402]
, [ 633,-301,364,-349,-683,-387]
, [ -780,-211,-713,-948,-648,543]
, [ 72,58,762,-465,-66,462]
, [ 78,502,781,-832,713,836]
, [ -431,-64,-484,-392,208,-343]
, [ -64,101,-29,-860,-329,844]
, [ 398,391,828,-858,700,395]
, [ 578,-896,-326,-604,314,180]
, [ 97,-321,-695,185,-357,852]
, [ 854,839,283,-375,951,-209]
, [ 194,96,-564,-847,162,524]
, [ -354,532,494,621,580,560]
, [ 419,-678,-450,926,-5,-924]
, [ -661,905,519,621,-143,394]
, [ -573,268,296,-562,-291,-319]
, [ -211,266,-196,158,564,-183]
, [ 18,-585,-398,777,-581,864]
, [ 790,-894,-745,-604,-418,70]
, [ 848,-339,150,773,11,851]
, [ -954,-809,-53,-20,-648,-304]
, [ 658,-336,-658,-905,853,407]
, [ -365,-844,350,-625,852,-358]
, [ 986,-315,-230,-159,21,180]
, [ -15,599,45,-286,-941,847]
, [ -613,-68,184,639,-987,550]
, [ 334,675,-56,-861,923,340]
, [ -848,-596,960,231,-28,-34]
, [ 707,-811,-994,-356,-167,-171]
, [ -470,-764,72,576,-600,-204]
, [ 379,189,-542,-576,585,800]
, [ 440,540,-445,-563,379,-334]
, [ -155,64,514,-288,853,106]
, [ -304,751,481,-520,-708,-694]
, [ -709,132,594,126,-844,63]
, [ 723,471,421,-138,-962,892]
, [ -440,-263,39,513,-672,-954]
, [ 775,809,-581,330,752,-107]
, [ -376,-158,335,-708,-514,578]
, [ -343,-769,456,-187,25,413]
, [ 548,-877,-172,300,-500,928]
, [ 938,-102,423,-488,-378,-969]
, [ -36,564,-55,131,958,-800]
, [ -322,511,-413,503,700,-847]
, [ -966,547,-88,-17,-359,-67]
, [ 637,-341,-437,-181,527,-153]
, [ -74,449,-28,3,485,189]
, [ -997,658,-224,-948,702,-807]
, [ -224,736,-896,127,-945,-850]
, [ -395,-106,439,-553,-128,124]
, [ -841,-445,-758,-572,-489,212]
, [ 633,-327,13,-512,952,771]
, [ -940,-171,-6,-46,-923,-425]
, [ -142,-442,-817,-998,843,-695]
, [ 340,847,-137,-920,-988,-658]
, [ -653,217,-679,-257,651,-719]
, [ -294,365,-41,342,74,-892]
, [ 690,-236,-541,494,408,-516]
, [ 180,-807,225,790,494,59]
, [ 707,605,-246,656,284,271]
, [ 65,294,152,824,442,-442]
, [ -321,781,-540,341,316,415]
, [ 420,371,-2,545,995,248]
, [ 56,-191,-604,971,615,449]
, [ -981,-31,510,592,-390,-362]
, [ -317,-968,913,365,97,508]
, [ 832,63,-864,-510,86,202]
, [ -483,456,-636,340,-310,676]
, [ 981,-847,751,-508,-962,-31]
, [ -157,99,73,797,63,-172]
, [ 220,858,872,924,866,-381]
, [ 996,-169,805,321,-164,971]
, [ 896,11,-625,-973,-782,76]
, [ 578,-280,730,-729,307,-905]
, [ -580,-749,719,-698,967,603]
, [ -821,874,-103,-623,662,-491]
, [ -763,117,661,-644,672,-607]
, [ 592,787,-798,-169,-298,690]
, [ 296,644,-526,-762,-447,665]
, [ 534,-818,852,-120,57,-379]
, [ -986,-549,-329,294,954,258]
, [ -133,352,-660,-77,904,-356]
, [ 748,343,215,500,317,-277]
, [ 311,7,910,-896,-809,795]
, [ 763,-602,-753,313,-352,917]
, [ 668,619,-474,-597,-650,650]
, [ -297,563,-701,-987,486,-902]
, [ -461,-740,-657,233,-482,-328]
, [ -446,-250,-986,-458,-629,520]
, [ 542,-49,-327,-469,257,-947]
, [ 121,-575,-634,-143,-184,521]
, [ 30,504,455,-645,-229,-945]
, [ -12,-295,377,764,771,125]
, [ -686,-133,225,-25,-376,-143]
, [ -6,-46,338,270,-405,-872]
, [ -623,-37,582,467,963,898]
, [ -804,869,-477,420,-475,-303]
, [ 94,41,-842,-193,-768,720]
, [ -656,-918,415,645,-357,460]
, [ -47,-486,-911,468,-608,-686]
, [ -158,251,419,-394,-655,-895]
, [ 272,-695,979,508,-358,959]
, [ -776,650,-918,-467,-690,-534]
, [ -85,-309,-626,167,-366,-429]
, [ -880,-732,-186,-924,970,-875]
, [ 517,645,-274,962,-804,544]
, [ 721,402,104,640,478,-499]
, [ 198,684,-134,-723,-452,-905]
, [ -245,745,239,238,-826,441]
, [ -217,206,-32,462,-981,-895]
, [ -51,989,526,-173,560,-676]
, [ -480,-659,-976,-580,-727,466]
, [ -996,-90,-995,158,-239,642]
, [ 302,288,-194,-294,17,924]
, [ -943,969,-326,114,-500,103]
, [ -619,163,339,-880,230,421]
, [ -344,-601,-795,557,565,-779]
, [ 590,345,-129,-202,-125,-58]
, [ -777,-195,159,674,775,411]
, [ -939,312,-665,810,121,855]
, [ -971,254,712,815,452,581]
, [ 442,-9,327,-750,61,757]
, [ -342,869,869,-160,390,-772]
, [ 620,601,565,-169,-69,-183]
, [ -25,924,-817,964,321,-970]
, [ -64,-6,-133,978,825,-379]
, [ 601,436,-24,98,-115,940]
, [ -97,502,614,-574,922,513]
, [ -125,262,-946,695,99,-220]
, [ 429,-721,719,-694,197,-558]
, [ 326,689,-70,-908,-673,338]
, [ -468,-856,-902,-254,-358,305]
, [ -358,530,542,355,-253,-47]
, [ -438,-74,-362,963,988,788]
, [ 137,717,467,622,319,-380]
, [ -86,310,-336,851,918,-288]
, [ 721,395,646,-53,255,-425]
, [ 255,175,912,84,-209,878]
, [ -632,-485,-400,-357,991,-608]
, [ 235,-559,992,-297,857,-591]
, [ 87,-71,148,130,647,578]
, [ -290,-584,-639,-788,-21,592]
, [ 386,984,625,-731,-993,-336]
, [ -538,634,-209,-828,-150,-774]
, [ -754,-387,607,-781,976,-199]
, [ 412,-798,-664,295,709,-537]
, [ -412,932,-880,-232,561,852]
, [ -656,-358,-198,-964,-433,-848]
, [ -762,-668,-632,186,-673,-11]
, [ -876,237,-282,-312,-83,682]
, [ 403,73,-57,-436,-622,781]
, [ -587,873,798,976,-39,329]
, [ -369,-622,553,-341,817,794]
, [ -108,-616,920,-849,-679,96]
, [ 290,-974,234,239,-284,-321]
, [ -22,394,-417,-419,264,58]
, [ -473,-551,69,923,591,-228]
, [ -956,662,-113,851,-581,-794]
, [ -258,-681,413,-471,-637,-817]
, [ -866,926,992,-653,-7,794]
, [ 556,-350,602,917,831,-610]
, [ 188,245,-906,361,492,174]
, [ -720,384,-818,329,638,-666]
, [ -246,846,890,-325,-59,-850]
, [ -118,-509,620,-762,-256,15]
, [ -787,-536,-452,-338,-399,813]
, [ 458,560,525,-311,-608,-419]
, [ 494,-811,-825,-127,-812,894]
, [ -801,890,-629,-860,574,925]
, [ -709,-193,-213,138,-410,-403]
, [ 861,91,708,-187,5,-222]
, [ 789,646,777,154,90,-49]
, [ -267,-830,-114,531,591,-698]
, [ -126,-82,881,-418,82,652]
, [ -894,130,-726,-935,393,-815]
, [ -142,563,654,638,-712,-597]
, [ -759,60,-23,977,100,-765]
, [ -305,595,-570,-809,482,762]
, [ -161,-267,53,963,998,-529]
, [ -300,-57,798,353,703,486]
, [ -990,696,-764,699,-565,719]
, [ -232,-205,566,571,977,369]
, [ 740,865,151,-817,-204,-293]
, [ 94,445,-768,229,537,-406]
, [ 861,620,37,-424,-36,656]
, [ 390,-369,952,733,-464,569]
, [ -482,-604,959,554,-705,-626]
, [ -396,-615,-991,108,272,-723]
, [ 143,780,535,142,-917,-147]
, [ 138,-629,-217,-908,905,115]
, [ 915,103,-852,64,-468,-642]
, [ 570,734,-785,-268,-326,-759]
, [ 738,531,-332,586,-779,24]
, [ 870,440,-217,473,-383,415]
, [ -296,-333,-330,-142,-924,950]
, [ 118,120,-35,-245,-211,-652]
, [ 61,634,153,-243,838,789]
, [ 726,-582,210,105,983,537]
, [ -313,-323,758,234,29,848]
, [ -847,-172,-593,733,-56,617]
, [ 54,255,-512,156,-575,675]
, [ -873,-956,-148,623,95,200]
, [ 700,-370,926,649,-978,157]
, [ -639,-202,719,130,747,222]
, [ 194,-33,955,943,505,114]
, [ -226,-790,28,-930,827,783]
, [ -392,-74,-28,714,218,-612]
, [ 209,626,-888,-683,-912,495]
, [ 487,751,614,933,631,445]
, [ -348,-34,-411,-106,835,321]
, [ -689,872,-29,-800,312,-542]
, [ -52,566,827,570,-862,-77]
, [ 471,992,309,-402,389,912]
, [ 24,520,-83,-51,555,503]
, [ -265,-317,283,-970,-472,690]
, [ 606,526,137,71,-651,150]
, [ 217,-518,663,66,-605,-331]
, [ -562,232,-76,-503,205,-323]
, [ 842,-521,546,285,625,-186]
, [ 997,-927,344,909,-546,974]
, [ -677,419,81,121,-705,771]
, [ 719,-379,-944,-797,784,-155]
, [ -378,286,-317,-797,-111,964]
, [ -288,-573,784,80,-532,-646]
, [ -77,407,-248,-797,769,-816]
, [ -24,-637,287,-858,-927,-333]
, [ -902,37,894,-823,141,684]
, [ 125,467,-177,-516,686,399]
, [ -321,-542,641,-590,527,-224]
, [ -400,-712,-876,-208,632,-543]
, [ -676,-429,664,-242,-269,922]
, [ -608,-273,-141,930,687,380]
, [ 786,-12,498,494,310,326]
, [ -739,-617,606,-960,804,188]
, [ 384,-368,-243,-350,-459,31]
, [ -550,397,320,-868,328,-279]
, [ 969,-179,853,864,-110,514]
, [ 910,793,302,-822,-285,488]
, [ -605,-128,218,-283,-17,-227]
, [ 16,324,667,708,750,3]
, [ 485,-813,19,585,71,930]
, [ -218,816,-687,-97,-732,-360]
, [ -497,-151,376,-23,3,315]
, [ -412,-989,-610,-813,372,964]
, [ -878,-280,87,381,-311,69]
, [ -609,-90,-731,-679,150,585]
, [ 889,27,-162,605,75,-770]
, [ 448,617,-988,0,-103,-504]
, [ -800,-537,-69,627,608,-668]
, [ 534,686,-664,942,830,920]
, [ -238,775,495,932,-793,497]
, [ -343,958,-914,-514,-691,651]
, [ 568,-136,208,359,728,28]
, [ 286,912,-794,683,556,-102]
, [ -638,-629,-484,445,-64,-497]
, [ 58,505,-801,-110,872,632]
, [ -390,777,353,267,976,369]
, [ -993,515,105,-133,358,-572]
, [ 964,996,355,-212,-667,38]
, [ -725,-614,-35,365,132,-196]
, [ 237,-536,-416,-302,312,477]
, [ -664,574,-210,224,48,-925]
, [ 869,-261,-256,-240,-3,-698]
, [ 712,385,32,-34,916,-315]
, [ 895,-409,-100,-346,728,-624]
, [ -806,327,-450,889,-781,-939]
, [ -586,-403,698,318,-939,899]
, [ 557,-57,-920,659,333,-51]
, [ -441,232,-918,-205,246,1]
, [ 783,167,-797,-595,245,-736]
, [ -36,-531,-486,-426,-813,-160]
, [ 777,-843,817,313,-228,-572]
, [ 735,866,-309,-564,-81,190]
, [ -413,645,101,719,-719,218]
, [ -83,164,767,796,-430,-459]
, [ 122,779,-15,-295,-96,-892]
, [ 462,379,70,548,834,-312]
, [ -630,-534,124,187,-737,114]
, [ -299,-604,318,-591,936,826]
, [ -879,218,-642,-483,-318,-866]
, [ -691,62,-658,761,-895,-854]
, [ -822,493,687,569,910,-202]
, [ -223,784,304,-5,541,925]
, [ -914,541,737,-662,-662,-195]
, [ -622,615,414,358,881,-878]
, [ 339,745,-268,-968,-280,-227]
, [ -364,855,148,-709,-827,472]
, [ -890,-532,-41,664,-612,577]
, [ -702,-859,971,-722,-660,-920]
, [ -539,-605,737,149,973,-802]
, [ 800,42,-448,-811,152,511]
, [ -933,377,-110,-105,-374,-937]
, [ -766,152,482,120,-308,390]
, [ -568,775,-292,899,732,890]
, [ -177,-317,-502,-259,328,-511]
, [ 612,-696,-574,-660,132,31]
, [ -119,563,-805,-864,179,-672]
, [ 425,-627,183,-331,839,318]
, [ -711,-976,-749,152,-916,261]
, [ 181,-63,497,211,262,406]
, [ -537,700,-859,-765,-928,77]
, [ 892,832,231,-749,-82,613]
, [ 816,216,-642,-216,-669,-912]
, [ -6,624,-937,-370,-344,268]
, [ 737,-710,-869,983,-324,-274]
, [ 565,952,-547,-158,374,-444]
, [ 51,-683,645,-845,515,636]
, [ -953,-631,114,-377,-764,-144]
, [ -8,470,-242,-399,-675,-730]
, [ -540,689,-20,47,-607,590]
, [ -329,-710,-779,942,-388,979]
, [ 123,829,674,122,203,563]
, [ 46,782,396,-33,386,610]
, [ 872,-846,-523,-122,-55,-190]
, [ 388,-994,-525,974,127,596]
, [ 781,-680,796,-34,-959,-62]
, [ -749,173,200,-384,-745,-446]
, [ 379,618,136,-250,-224,970]
, [ -58,240,-921,-760,-901,-626]
, [ 366,-185,565,-100,515,688]
, [ 489,999,-893,-263,-637,816]
, [ 838,-496,-316,-513,419,479]
, [ 107,676,-15,882,98,-397]
, [ -999,941,-903,-424,670,-325]
, [ 171,-979,835,178,169,-984]
, [ -609,-607,378,-681,184,402]
, [ -316,903,-575,-800,224,983]
, [ 591,-18,-460,551,-167,918]
, [ -756,405,-117,441,163,-320]
, [ 456,24,6,881,-836,-539]
, [ -489,-585,915,651,-892,-382]
, [ -177,-122,73,-711,-386,591]
, [ 181,724,530,686,-131,241]
, [ 737,288,886,216,233,33]
, [ -548,-386,-749,-153,-85,-982]
, [ -835,227,904,160,-99,25]
, [ -9,-42,-162,728,840,-963]
, [ 217,-763,870,771,47,-846]
, [ -595,808,-491,556,337,-900]
, [ -134,281,-724,441,-134,708]
, [ -789,-508,651,-962,661,315]
, [ -839,-923,339,402,41,-487]
, [ 300,-790,48,703,-398,-811]
, [ 955,-51,462,-685,960,-717]
, [ 910,-880,592,-255,-51,-776]
, [ -885,169,-793,368,-565,458]
, [ -905,940,-492,-630,-535,-988]
, [ 245,797,763,869,-82,550]
, [ -310,38,-933,-367,-650,824]
, [ -95,32,-83,337,226,990]
, [ -218,-975,-191,-208,-785,-293]
, [ -672,-953,517,-901,-247,465]
, [ 681,-148,261,-857,544,-923]
, [ 640,341,446,-618,195,769]
, [ 384,398,-846,365,671,815]
, [ 578,576,-911,907,762,-859]
, [ 548,-428,144,-630,-759,-146]
, [ 710,-73,-700,983,-97,-889]
, [ -46,898,-973,-362,-817,-717]
, [ 151,-81,-125,-900,-478,-154]
, [ 483,615,-537,-932,181,-68]
, [ 786,-223,518,25,-306,-12]
, [ -422,268,-809,-683,635,468]
, [ 983,-734,-694,-608,-110,4]
, [ -786,-196,749,-354,137,-8]
, [ -181,36,668,-200,691,-973]
, [ -629,-838,692,-736,437,-871]
, [ -208,-536,-159,-596,8,197]
, [ -3,370,-686,170,913,-376]
, [ 44,-998,-149,-993,-200,512]
, [ -519,136,859,497,536,434]
, [ 77,-985,972,-340,-705,-837]
, [ -381,947,250,360,344,322]
, [ -26,131,699,750,707,384]
, [ -914,655,299,193,406,955]
, [ -883,-921,220,595,-546,794]
, [ -599,577,-569,-404,-704,489]
, [ -594,-963,-624,-460,880,-760]
, [ -603,88,-99,681,55,-328]
, [ 976,472,139,-453,-531,-860]
, [ 192,-290,513,-89,666,432]
, [ 417,487,575,293,567,-668]
, [ 655,711,-162,449,-980,972]
, [ -505,664,-685,-239,603,-592]
, [ -625,-802,-67,996,384,-636]
, [ 365,-593,522,-666,-200,-431]
, [ -868,708,560,-860,-630,-355]
, [ -702,785,-637,-611,-597,960]
, [ -137,-696,-93,-803,408,406]
, [ 891,-123,-26,-609,-610,518]
, [ 133,-832,-198,555,708,-110]
, [ 791,617,-69,487,696,315]
, [ -900,694,-565,517,-269,-416]
, [ 914,135,-781,600,-71,-600]
, [ 991,-915,-422,-351,-837,313]
, [ -840,-398,-302,21,590,146]
, [ 62,-558,-702,-384,-625,831]
, [ -363,-426,-924,-496,792,-908]
, [ 73,361,-817,-466,400,922]
, [ -626,-164,-626,860,-524,286]
, [ 255,26,-944,809,-606,986]
, [ -457,-256,-103,50,-867,-871]
, [ -223,803,196,480,612,136]
, [ -820,-928,700,780,-977,721]
, [ 717,332,53,-933,-128,793]
, [ -602,-648,562,593,890,702]
, [ -469,-875,-527,911,-475,-222]
, [ 110,-281,-552,-536,-816,596]
, [ -981,654,413,-981,-75,-95]
, [ -754,-742,-515,894,-220,-344]
, [ 795,-52,156,408,-603,76]
, [ 474,-157,423,-499,-807,-791]
, [ 260,688,40,-52,702,-122]
, [ -584,-517,-390,-881,302,-504]
, [ 61,797,665,708,14,668]
, [ 366,166,458,-614,564,-983]
, [ 72,539,-378,796,381,-824]
, [ -485,201,-588,842,736,379]
, [ -149,-894,-298,705,-303,-406]
, [ 660,-935,-580,521,93,633]
, [ -382,-282,-375,-841,-828,171]
, [ -567,743,-100,43,144,122]
, [ -281,-786,-749,-551,296,304]
, [ 11,-426,-792,212,857,-175]
, [ 594,143,-699,289,315,137]
, [ 341,596,-390,107,-631,-804]
, [ -751,-636,-424,-854,193,651]
, [ -145,384,749,675,-786,517]
, [ 224,-865,-323,96,-916,258]
, [ -309,403,-388,826,35,-270]
, [ -942,709,222,158,-699,-103]
, [ -589,842,-997,29,-195,-210]
, [ 264,426,566,145,-217,623]
, [ 217,965,507,-601,-453,507]
, [ -206,307,-982,4,64,-292]
, [ 676,-49,-38,-701,550,883]
, [ 5,-850,-438,659,745,-773]
, [ 933,238,-574,-570,91,-33]
, [ -866,121,-928,358,459,-843]
, [ -568,-631,-352,-580,-349,189]
, [ -737,849,-963,-486,-662,970]
, [ 135,334,-967,-71,-365,-792]
, [ 789,21,-227,51,990,-275]
, [ 240,412,-886,230,591,256]
, [ -609,472,-853,-754,959,661]
, [ 401,521,521,314,929,982]
, [ -499,784,-208,71,-302,296]
, [ -557,-948,-553,-526,-864,793]
, [ 270,-626,828,44,37,14]
, [ -412,224,617,-593,502,699]
, [ 41,-908,81,562,-849,163]
, [ 165,917,761,-197,331,-341]
, [ -687,314,799,755,-969,648]
, [ -164,25,578,439,-334,-576]
, [ 213,535,874,-177,-551,24]
, [ -689,291,-795,-225,-496,-125]
, [ 465,461,558,-118,-568,-909]
, [ 567,660,-810,46,-485,878]
, [ -147,606,685,-690,-774,984]
, [ 568,-886,-43,854,-738,616]
, [ -800,386,-614,585,764,-226]
, [ -518,23,-225,-732,-79,440]
, [ -173,-291,-689,636,642,-447]
, [ -598,-16,227,410,496,211]
, [ -474,-930,-656,-321,-420,36]
, [ -435,165,-819,555,540,144]
, [ -969,149,828,568,394,648]
, [ 65,-848,257,720,-625,-851]
, [ 981,899,275,635,465,-877]
, [ 80,290,792,760,-191,-321]
, [ -605,-858,594,33,706,593]
, [ 585,-472,318,-35,354,-927]
, [ -365,664,803,581,-965,-814]
, [ -427,-238,-480,146,-55,-606]
, [ 879,-193,250,-890,336,117]
, [ -226,-322,-286,-765,-836,-218]
, [ -913,564,-667,-698,937,283]
, [ 872,-901,810,-623,-52,-709]
, [ 473,171,717,38,-429,-644]
, [ 225,824,-219,-475,-180,234]
, [ -530,-797,-948,238,851,-623]
, [ 85,975,-363,529,598,28]
, [ -799,166,-804,210,-769,851]
, [ -687,-158,885,736,-381,-461]
, [ 447,592,928,-514,-515,-661]
, [ -399,-777,-493,80,-544,-78]
, [ -884,631,171,-825,-333,551]
, [ 191,268,-577,676,137,-33]
, [ 212,-853,709,798,583,-56]
, [ -908,-172,-540,-84,-135,-56]
, [ 303,311,406,-360,-240,811]
, [ 798,-708,824,59,234,-57]
, [ 491,693,-74,585,-85,877]
, [ 509,-65,-936,329,-51,722]
, [ -122,858,-52,467,-77,-609]
, [ 850,760,547,-495,-953,-952]
, [ -460,-541,890,910,286,724]
, [ -914,843,-579,-983,-387,-460]
, [ 989,-171,-877,-326,-899,458]
, [ 846,175,-915,540,-1000,-982]
, [ -852,-920,-306,496,530,-18]
, [ 338,-991,160,85,-455,-661]
, [ -186,-311,-460,-563,-231,-414]
, [ -932,-302,959,597,793,748]
, [ -366,-402,-788,-279,514,53]
, [ -940,-956,447,-956,211,-285]
, [ 564,806,-911,-914,934,754]
, [ 575,-858,-277,15,409,-714]
, [ 848,462,100,-381,135,242]
, [ 330,718,-24,-190,860,-78]
, [ 479,458,941,108,-866,-653]
, [ 212,980,962,-962,115,841]
, [ -827,-474,-206,881,323,765]
, [ 506,-45,-30,-293,524,-133]
, [ 832,-173,547,-852,-561,-842]
, [ -397,-661,-708,819,-545,-228]
, [ 521,51,-489,852,36,-258]
, [ 227,-164,189,465,-987,-882]
, [ -73,-997,641,-995,449,-615]
, [ 151,-995,-638,415,257,-400]
, [ -663,-297,-748,537,-734,198]
, [ -585,-401,-81,-782,-80,-105]
, [ 99,-21,238,-365,-704,-368]
, [ 45,416,849,-211,-371,-1]
, [ -404,-443,795,-406,36,-933]
, [ 272,-363,981,-491,-380,77]
, [ 713,-342,-366,-849,643,911]
, [ -748,671,-537,813,961,-200]
, [ -194,-909,703,-662,-601,188]
, [ 281,500,724,286,267,197]
, [ -832,847,-595,820,-316,637]
, [ 520,521,-54,261,923,-10]
, [ 4,-808,-682,-258,441,-695]
, [ -793,-107,-969,905,798,446]
, [ -108,-739,-590,69,-855,-365]
, [ 380,-623,-930,817,468,713]
, [ 759,-849,-236,433,-723,-931]
, [ 95,-320,-686,124,-69,-329]
, [ -655,518,-210,-523,284,-866]
, [ 144,303,639,70,-171,269]
, [ 173,-333,947,-304,55,40]
, [ 274,878,-482,-888,-835,375]
, [ -982,-854,-36,-218,-114,-230]
, [ 905,-979,488,-485,-479,114]
, [ 877,-157,553,-530,-47,-321]
, [ 350,664,-881,442,-220,-284]
, [ 434,-423,-365,878,-726,584]
, [ 535,909,-517,-447,-660,-141]
, [ -966,191,50,353,182,-642]
, [ -785,-634,123,-907,-162,511]
, [ 146,-850,-214,814,-704,25]
, [ 692,1,521,492,-637,274]
, [ -662,-372,-313,597,983,-647]
, [ -962,-526,68,-549,-819,231]
, [ 740,-890,-318,797,-666,948]
, [ -190,-12,-468,-455,948,284]
, [ 16,478,-506,-888,628,-154]
, [ 272,630,-976,308,433,3]
, [ -169,-391,-132,189,302,-388]
, [ 109,-784,474,-167,-265,-31]
, [ -177,-532,283,464,421,-73]
, [ 650,635,592,-138,1,-387]
, [ -932,703,-827,-492,-355,686]
, [ 586,-311,340,-618,645,-434]
, [ -951,736,647,-127,-303,590]
, [ 188,444,903,718,-931,500]
, [ -872,-642,-296,-571,337,241]
, [ 23,65,152,125,880,470]
, [ 512,823,-42,217,823,-263]
, [ 180,-831,-380,886,607,762]
, [ 722,443,-149,-216,-115,759]
, [ -19,660,-36,901,923,231]
, [ 562,-322,-626,-968,194,-825]
, [ 204,-920,938,784,362,150]
, [ -410,-266,-715,559,-672,124]
, [ -198,446,-140,454,-461,-447]
, [ 83,-346,830,-493,-759,-382]
, [ -881,601,581,234,-134,-925]
, [ -494,914,-42,899,235,629]
, [ -390,50,956,437,774,-700]
, [ -514,514,44,-512,-576,-313]
, [ 63,-688,808,-534,-570,-399]
, [ -726,572,-896,102,-294,-28]
, [ -688,757,401,406,955,-511]
, [ -283,423,-485,480,-767,908]
, [ -541,952,-594,116,-854,451]
, [ -273,-796,236,625,-626,257]
, [ -407,-493,373,826,-309,297]
, [ -750,955,-476,641,-809,713]
, [ 8,415,695,226,-111,2]
, [ 733,209,152,-920,401,995]
, [ 921,-103,-919,66,871,-947]
, [ -907,89,-869,-214,851,-559]
, [ -307,748,524,-755,314,-711]
, [ 188,897,-72,-763,482,103]
, [ 545,-821,-232,-596,-334,-754]
, [ -217,-788,-820,388,-200,-662]
, [ 779,160,-723,-975,-142,-998]
, [ -978,-519,-78,-981,842,904]
, [ -504,-736,-295,21,-472,-482]
, [ 391,115,-705,574,652,-446]
, [ 813,-988,865,830,-263,487]
, [ 194,80,774,-493,-761,-872]
, [ -415,-284,-803,7,-810,670]
, [ -484,-4,881,-872,55,-852]
, [ -379,822,-266,324,-48,748]
, [ -304,-278,406,-60,959,-89]
, [ 404,756,577,-643,-332,658]
, [ 291,460,125,491,-312,83]
, [ 311,-734,-141,582,282,-557]
, [ -450,-661,-981,710,-177,794]
, [ 328,264,-787,971,-743,-407]
, [ -622,518,993,-241,-738,229]
, [ 273,-826,-254,-917,-710,-111]
, [ 809,770,96,368,-818,725]
, [ -488,773,502,-342,534,745]
, [ -28,-414,236,-315,-484,363]
, [ 179,-466,-566,713,-683,56]
, [ 560,-240,-597,619,916,-940]
, [ 893,473,872,-868,-642,-461]
, [ 799,489,383,-321,-776,-833]
, [ 980,490,-508,764,-512,-426]
, [ 917,961,-16,-675,440,559]
, [ -812,212,784,-987,-132,554]
, [ -886,454,747,806,190,231]
, [ 910,341,21,-66,708,725]
, [ 29,929,-831,-494,-303,389]
, [ -103,492,-271,-174,-515,529]
, [ -292,119,419,788,247,-951]
, [ 483,543,-347,-673,664,-549]
, [ -926,-871,-437,337,162,-877]
, [ 299,472,-771,5,-88,-643]
, [ -103,525,-725,-998,264,22]
, [ -505,708,550,-545,823,347]
, [ -738,931,59,147,-156,-259]
, [ 456,968,-162,889,132,-911]
, [ 535,120,968,-517,-864,-541]
, [ 24,-395,-593,-766,-565,-332]
, [ 834,611,825,-576,280,629]
, [ 211,-548,140,-278,-592,929]
, [ -999,-240,-63,-78,793,573]
, [ -573,160,450,987,529,322]
, [ 63,353,315,-187,-461,577]
, [ 189,-950,-247,656,289,241]
, [ 209,-297,397,664,-805,484]
, [ -655,452,435,-556,917,874]
, [ 253,-756,262,-888,-778,-214]
, [ 793,-451,323,-251,-401,-458]
, [ -396,619,-651,-287,-668,-781]
, [ 698,720,-349,742,-807,546]
, [ 738,280,680,279,-540,858]
, [ -789,387,530,-36,-551,-491]
, [ 162,579,-427,-272,228,710]
, [ 689,356,917,-580,729,217]
, [ -115,-638,866,424,-82,-194]
, [ 411,-338,-917,172,227,-29]
, [ -612,63,630,-976,-64,-204]
, [ -200,911,583,-571,682,-579]
, [ 91,298,396,-183,788,-955]
, [ 141,-873,-277,149,-396,916]
, [ 321,958,-136,573,541,-777]
, [ 797,-909,-469,-877,988,-653]
, [ 784,-198,129,883,-203,399]
, [ -68,-810,223,-423,-467,-512]
, [ 531,-445,-603,-997,-841,641]
, [ -274,-242,174,261,-636,-158]
, [ -574,494,-796,-798,-798,99]
, [ 95,-82,-613,-954,-753,986]
, [ -883,-448,-864,-401,938,-392]
, [ 913,930,-542,-988,310,410]
, [ 506,-99,43,512,790,-222]
, [ 724,31,49,-950,260,-134]
, [ -287,-947,-234,-700,56,588]
, [ -33,782,-144,948,105,-791]
, [ 548,-546,-652,-293,881,-520]
, [ 691,-91,76,991,-631,742]
, [ -520,-429,-244,-296,724,-48]
, [ 778,646,377,50,-188,56]
, [ -895,-507,-898,-165,-674,652]
, [ 654,584,-634,177,-349,-620]
, [ 114,-980,355,62,182,975]
, [ 516,9,-442,-298,274,-579]
, [ -238,262,-431,-896,506,-850]
, [ 47,748,846,821,-537,-293]
, [ 839,726,593,285,-297,840]
, [ 634,-486,468,-304,-887,-567]
, [ -864,914,296,-124,335,233]
, [ 88,-253,-523,-956,-554,803]
, [ -587,417,281,-62,-409,-363]
, [ -136,-39,-292,-768,-264,876]
, [ -127,506,-891,-331,-744,-430]
, [ 778,584,-750,-129,-479,-94]
, [ -876,-771,-987,-757,180,-641]
, [ -777,-694,411,-87,329,190]
, [ -347,-999,-882,158,-754,232]
, [ -105,918,188,237,-110,-591]
, [ -209,703,-838,77,838,909]
, [ -995,-339,-762,750,860,472]
, [ 185,271,-289,173,811,-300]
, [ 2,65,-656,-22,36,-139]
, [ 765,-210,883,974,961,-905]
, [ -212,295,-615,-840,77,474]
, [ 211,-910,-440,703,-11,859]
, [ -559,-4,-196,841,-277,969]
, [ -73,-159,-887,126,978,-371]
, [ -569,633,-423,-33,512,-393]
, [ 503,143,-383,-109,-649,-998]
, [ -663,339,-317,-523,-2,596]
, [ 690,-380,570,378,-652,132]
, [ 72,-744,-930,399,-525,935]
, [ 865,-983,115,37,995,826]
, [ 594,-621,-872,443,188,-241]
, [ -1000,291,754,234,-435,-869]
, [ -868,901,654,-907,59,181]
, [ -868,-793,-431,596,-446,-564]
, [ 900,-944,-680,-796,902,-366]
, [ 331,430,943,853,-851,-942]
, [ 315,-538,-354,-909,139,721]
, [ 170,-884,-225,-818,-808,-657]
, [ -279,-34,-533,-871,-972,552]
, [ 691,-986,-800,-950,654,-747]
, [ 603,988,899,841,-630,591]
, [ 876,-949,809,562,602,-536]
, [ -693,363,-189,495,738,-1000]
, [ -383,431,-633,297,665,959]
, [ -740,686,-207,-803,188,-520]
, [ -820,226,31,-339,10,121]
, [ -312,-844,624,-516,483,621]
, [ -822,-529,69,-278,800,328]
, [ 834,-82,-759,420,811,-264]
, [ -960,-240,-921,561,173,46]
, [ -324,909,-790,-814,-2,-785]
, [ 976,334,-290,-891,704,-581]
, [ 150,-798,689,-823,237,-639]
, [ -551,-320,876,-502,-622,-628]
, [ -136,845,904,595,-702,-261]
, [ -857,-377,-522,-101,-943,-805]
, [ -682,-787,-888,-459,-752,-985]
, [ -571,-81,623,-133,447,643]
, [ -375,-158,72,-387,-324,-696]
, [ -660,-650,340,188,569,526]
, [ 727,-218,16,-7,-595,-988]
, [ -966,-684,802,-783,-272,-194]
, [ 115,-566,-888,47,712,180]
, [ -237,-69,45,-272,981,-812]
, [ 48,897,439,417,50,325]
, [ 348,616,180,254,104,-784]
, [ -730,811,-548,612,-736,790]
, [ 138,-810,123,930,65,865]
, [ -768,-299,-49,-895,-692,-418]
, [ 487,-531,802,-159,-12,634]
, [ 808,-179,552,-73,470,717]
, [ 720,-644,886,-141,625,144]
, [ -485,-505,-347,-244,-916,66]
, [ 600,-565,995,-5,324,227]
, [ -771,-35,904,-482,753,-303]
, [ -701,65,426,-763,-504,-479]
, [ 409,733,-823,475,64,718]
, [ 865,975,368,893,-413,-433]
, [ 812,-597,-970,819,813,624]
, [ 193,-642,-381,-560,545,398]
, [ 711,28,-316,771,717,-865]
, [ -509,462,809,-136,786,635]
, [ 618,-49,484,169,635,547]
, [ -747,685,-882,-496,-332,82]
, [ -501,-851,870,563,290,570]
, [ -279,-829,-509,397,457,816]
, [ -508,80,850,-188,483,-326]
, [ 860,-100,360,119,-205,787]
, [ -870,21,-39,-827,-185,932]
, [ 826,284,-136,-866,-330,-97]
, [ -944,-82,745,899,-97,365]
, [ 929,262,564,632,-115,632]
, [ 244,-276,713,330,-897,-214]
, [ -890,-109,664,876,-974,-907]
, [ 716,249,816,489,723,141]
, [ -96,-560,-272,45,-70,645]
, [ 762,-503,414,-828,-254,-646]
, [ 909,-13,903,-422,-344,-10]
, [ 658,-486,743,545,50,674]
, [ -241,507,-367,18,-48,-241]
, [ 886,-268,884,-762,120,-486]
, [ -412,-528,879,-647,223,-393]
, [ 851,810,234,937,-726,797]
, [ -999,942,839,-134,-996,-189]
, [ 100,979,-527,-521,378,800]
, [ 544,-844,-832,-530,-77,-641]
, [ 43,889,31,442,-934,-503]
, [ -330,-370,-309,-439,173,547]
, [ 169,945,62,-753,-542,-597]
, [ 208,751,-372,-647,-520,70]
, [ 765,-840,907,-257,379,918]
, [ 334,-135,-689,730,-427,618]
, [ 137,-508,66,-695,78,169]
, [ -962,-123,400,-417,151,969]
, [ 328,689,666,427,-555,-642]
, [ -907,343,605,-341,-647,582]
, [ -667,-363,-571,818,-265,-399]
, [ 525,-938,904,898,725,692]
, [ -176,-802,-858,-9,780,275]
, [ 580,170,-740,287,691,-97]
, [ 365,557,-375,361,-288,859]
, [ 193,737,842,-808,520,282]
, [ -871,65,-799,836,179,-720]
, [ 958,-144,744,-789,797,-48]
, [ 122,582,662,912,68,757]
, [ 595,241,-801,513,388,186]
, [ -103,-677,-259,-731,-281,-857]
, [ 921,319,-696,683,-88,-997]
, [ 775,200,78,858,648,768]
, [ 316,821,-763,68,-290,-741]
, [ 564,664,691,504,760,787]
, [ 694,-119,973,-385,309,-760]
, [ 777,-947,-57,990,74,19]
, [ 971,626,-496,-781,-602,-239]
, [ -651,433,11,-339,939,294]
, [ -965,-728,560,569,-708,-247]
]
| null | https://raw.githubusercontent.com/ryanpbrewster/haskell/6edd0afe234008a48b4871032dedfd143ca6e412/project-euler/tests/TestData/P102.hs | haskell | module TestData.P102 (txt) where
txt :: [[Int]]
txt =
[ [ -340,495,-153,-910,835,-947]
, [ -175,41,-421,-714,574,-645]
, [ -547,712,-352,579,951,-786]
, [ 419,-864,-83,650,-399,171]
, [ -429,-89,-357,-930,296,-29]
, [ -734,-702,823,-745,-684,-62]
, [ -971,762,925,-776,-663,-157]
, [ 162,570,628,485,-807,-896]
, [ 641,91,-65,700,887,759]
, [ 215,-496,46,-931,422,-30]
, [ -119,359,668,-609,-358,-494]
, [ 440,929,968,214,760,-857]
, [ -700,785,838,29,-216,411]
, [ -770,-458,-325,-53,-505,633]
, [ -752,-805,349,776,-799,687]
, [ 323,5,561,-36,919,-560]
, [ -907,358,264,320,204,274]
, [ -728,-466,350,969,292,-345]
, [ 940,836,272,-533,748,185]
, [ 411,998,813,520,316,-949]
, [ -152,326,658,-762,148,-651]
, [ 330,507,-9,-628,101,174]
, [ 551,-496,772,-541,-702,-45]
, [ -164,-489,-90,322,631,-59]
, [ 673,366,-4,-143,-606,-704]
, [ 428,-609,801,-449,740,-269]
, [ 453,-924,-785,-346,-853,111]
, [ -738,555,-181,467,-426,-20]
, [ 958,-692,784,-343,505,-569]
, [ 620,27,263,54,-439,-726]
, [ 804,87,998,859,871,-78]
, [ -119,-453,-709,-292,-115,-56]
, [ -626,138,-940,-476,-177,-274]
, [ -11,160,142,588,446,158]
, [ 538,727,550,787,330,810]
, [ 420,-689,854,-546,337,516]
, [ 872,-998,-607,748,473,-192]
, [ 653,440,-516,-985,808,-857]
, [ 374,-158,331,-940,-338,-641]
, [ 137,-925,-179,771,734,-715]
, [ -314,198,-115,29,-641,-39]
, [ 759,-574,-385,355,590,-603]
, [ -189,-63,-168,204,289,305]
, [ -182,-524,-715,-621,911,-255]
, [ 331,-816,-833,471,168,126]
, [ -514,581,-855,-220,-731,-507]
, [ 129,169,576,651,-87,-458]
, [ 783,-444,-881,658,-266,298]
, [ 603,-430,-598,585,368,899]
, [ 43,-724,962,-376,851,409]
, [ -610,-646,-883,-261,-482,-881]
, [ -117,-237,978,641,101,-747]
, [ 579,125,-715,-712,208,534]
, [ 672,-214,-762,372,874,533]
, [ -564,965,38,715,367,242]
, [ 500,951,-700,-981,-61,-178]
, [ -382,-224,-959,903,-282,-60]
, [ -355,295,426,-331,-591,655]
, [ 892,128,958,-271,-993,274]
, [ -454,-619,302,138,-790,-874]
, [ -642,601,-574,159,-290,-318]
, [ 266,-109,257,-686,54,975]
, [ 162,628,-478,840,264,-266]
, [ 466,-280,982,1,904,-810]
, [ 721,839,730,-807,777,981]
, [ -129,-430,748,263,943,96]
, [ 434,-94,410,-990,249,-704]
, [ 237,42,122,-732,44,-51]
, [ 909,-116,-229,545,292,717]
, [ 824,-768,-807,-370,-262,30]
, [ 675,58,332,-890,-651,791]
, [ 363,825,-717,254,684,240]
, [ 405,-715,900,166,-589,422]
, [ -476,686,-830,-319,634,-807]
, [ 633,837,-971,917,-764,207]
, [ -116,-44,-193,-70,908,809]
, [ -26,-252,998,408,70,-713]
, [ -601,645,-462,842,-644,-591]
, [ -160,653,274,113,-138,687]
, [ 369,-273,-181,925,-167,-693]
, [ -338,135,480,-967,-13,-840]
, [ -90,-270,-564,695,161,907]
, [ 607,-430,869,-713,461,-469]
, [ 919,-165,-776,522,606,-708]
, [ -203,465,288,207,-339,-458]
, [ -453,-534,-715,975,838,-677]
, [ -973,310,-350,934,546,-805]
, [ -835,385,708,-337,-594,-772]
, [ -14,914,900,-495,-627,594]
, [ 833,-713,-213,578,-296,699]
, [ -27,-748,484,455,915,291]
, [ 270,889,739,-57,442,-516]
, [ 119,811,-679,905,184,130]
, [ -678,-469,925,553,612,482]
, [ 101,-571,-732,-842,644,588]
, [ -71,-737,566,616,957,-663]
, [ -634,-356,90,-207,936,622]
, [ 598,443,964,-895,-58,529]
, [ 847,-467,929,-742,91,10]
, [ -633,829,-780,-408,222,-30]
, [ -818,57,275,-38,-746,198]
, [ -722,-825,-549,597,-391,99]
, [ -570,908,430,873,-103,-360]
, [ 342,-681,512,434,542,-528]
, [ 297,850,479,609,543,-357]
, [ 9,784,212,548,56,859]
, [ -152,560,-240,-969,-18,713]
, [ 140,-133,34,-635,250,-163]
, [ -272,-22,-169,-662,989,-604]
, [ 471,-765,355,633,-742,-118]
, [ -118,146,942,663,547,-376]
, [ 583,16,162,264,715,-33]
, [ -230,-446,997,-838,561,555]
, [ 372,397,-729,-318,-276,649]
, [ 92,982,-970,-390,-922,922]
, [ -981,713,-951,-337,-669,670]
, [ -999,846,-831,-504,7,-128]
, [ 455,-954,-370,682,-510,45]
, [ 822,-960,-892,-385,-662,314]
, [ -668,-686,-367,-246,530,-341]
, [ -723,-720,-926,-836,-142,757]
, [ -509,-134,384,-221,-873,-639]
, [ -803,-52,-706,-669,373,-339]
, [ 933,578,631,-616,770,555]
, [ 741,-564,-33,-605,-576,275]
, [ -715,445,-233,-730,734,-704]
, [ 120,-10,-266,-685,-490,-17]
, [ -232,-326,-457,-946,-457,-116]
, [ 811,52,639,826,-200,147]
, [ -329,279,293,612,943,955]
, [ -721,-894,-393,-969,-642,453]
, [ -688,-826,-352,-75,371,79]
, [ -809,-979,407,497,858,-248]
, [ -485,-232,-242,-582,-81,849]
, [ 141,-106,123,-152,806,-596]
, [ -428,57,-992,811,-192,478]
, [ 864,393,122,858,255,-876]
, [ -284,-780,240,457,354,-107]
, [ 956,605,-477,44,26,-678]
, [ 86,710,-533,-815,439,327]
, [ -906,-626,-834,763,426,-48]
, [ 201,-150,-904,652,475,412]
, [ -247,149,81,-199,-531,-148]
, [ 923,-76,-353,175,-121,-223]
, [ 427,-674,453,472,-410,585]
, [ 931,776,-33,85,-962,-865]
, [ -655,-908,-902,208,869,792]
, [ -316,-102,-45,-436,-222,885]
, [ -309,768,-574,653,745,-975]
, [ 896,27,-226,993,332,198]
, [ 323,655,-89,260,240,-902]
, [ 501,-763,-424,793,813,616]
, [ 993,375,-938,-621,672,-70]
, [ -880,-466,-283,770,-824,143]
, [ 63,-283,886,-142,879,-116]
, [ -964,-50,-521,-42,-306,-161]
, [ 724,-22,866,-871,933,-383]
, [ -344,135,282,966,-80,917]
, [ -281,-189,420,810,362,-582]
, [ -515,455,-588,814,162,332]
, [ 555,-436,-123,-210,869,-943]
, [ 589,577,232,286,-554,876]
, [ -773,127,-58,-171,-452,125]
, [ -428,575,906,-232,-10,-224]
, [ 437,276,-335,-348,605,878]
, [ -964,511,-386,-407,168,-220]
, [ 307,513,912,-463,-423,-416]
, [ -445,539,273,886,-18,760]
, [ -396,-585,-670,414,47,364]
, [ 143,-506,754,906,-971,-203]
, [ -544,472,-180,-541,869,-465]
, [ -779,-15,-396,890,972,-220]
, [ -430,-564,503,182,-119,456]
, [ 89,-10,-739,399,506,499]
, [ 954,162,-810,-973,127,870]
, [ 890,952,-225,158,828,237]
, [ -868,952,349,465,574,750]
, [ -915,369,-975,-596,-395,-134]
, [ -135,-601,575,582,-667,640]
, [ 413,890,-560,-276,-555,-562]
, [ -633,-269,561,-820,-624,499]
, [ 371,-92,-784,-593,864,-717]
, [ -971,655,-439,367,754,-951]
, [ 172,-347,36,279,-247,-402]
, [ 633,-301,364,-349,-683,-387]
, [ -780,-211,-713,-948,-648,543]
, [ 72,58,762,-465,-66,462]
, [ 78,502,781,-832,713,836]
, [ -431,-64,-484,-392,208,-343]
, [ -64,101,-29,-860,-329,844]
, [ 398,391,828,-858,700,395]
, [ 578,-896,-326,-604,314,180]
, [ 97,-321,-695,185,-357,852]
, [ 854,839,283,-375,951,-209]
, [ 194,96,-564,-847,162,524]
, [ -354,532,494,621,580,560]
, [ 419,-678,-450,926,-5,-924]
, [ -661,905,519,621,-143,394]
, [ -573,268,296,-562,-291,-319]
, [ -211,266,-196,158,564,-183]
, [ 18,-585,-398,777,-581,864]
, [ 790,-894,-745,-604,-418,70]
, [ 848,-339,150,773,11,851]
, [ -954,-809,-53,-20,-648,-304]
, [ 658,-336,-658,-905,853,407]
, [ -365,-844,350,-625,852,-358]
, [ 986,-315,-230,-159,21,180]
, [ -15,599,45,-286,-941,847]
, [ -613,-68,184,639,-987,550]
, [ 334,675,-56,-861,923,340]
, [ -848,-596,960,231,-28,-34]
, [ 707,-811,-994,-356,-167,-171]
, [ -470,-764,72,576,-600,-204]
, [ 379,189,-542,-576,585,800]
, [ 440,540,-445,-563,379,-334]
, [ -155,64,514,-288,853,106]
, [ -304,751,481,-520,-708,-694]
, [ -709,132,594,126,-844,63]
, [ 723,471,421,-138,-962,892]
, [ -440,-263,39,513,-672,-954]
, [ 775,809,-581,330,752,-107]
, [ -376,-158,335,-708,-514,578]
, [ -343,-769,456,-187,25,413]
, [ 548,-877,-172,300,-500,928]
, [ 938,-102,423,-488,-378,-969]
, [ -36,564,-55,131,958,-800]
, [ -322,511,-413,503,700,-847]
, [ -966,547,-88,-17,-359,-67]
, [ 637,-341,-437,-181,527,-153]
, [ -74,449,-28,3,485,189]
, [ -997,658,-224,-948,702,-807]
, [ -224,736,-896,127,-945,-850]
, [ -395,-106,439,-553,-128,124]
, [ -841,-445,-758,-572,-489,212]
, [ 633,-327,13,-512,952,771]
, [ -940,-171,-6,-46,-923,-425]
, [ -142,-442,-817,-998,843,-695]
, [ 340,847,-137,-920,-988,-658]
, [ -653,217,-679,-257,651,-719]
, [ -294,365,-41,342,74,-892]
, [ 690,-236,-541,494,408,-516]
, [ 180,-807,225,790,494,59]
, [ 707,605,-246,656,284,271]
, [ 65,294,152,824,442,-442]
, [ -321,781,-540,341,316,415]
, [ 420,371,-2,545,995,248]
, [ 56,-191,-604,971,615,449]
, [ -981,-31,510,592,-390,-362]
, [ -317,-968,913,365,97,508]
, [ 832,63,-864,-510,86,202]
, [ -483,456,-636,340,-310,676]
, [ 981,-847,751,-508,-962,-31]
, [ -157,99,73,797,63,-172]
, [ 220,858,872,924,866,-381]
, [ 996,-169,805,321,-164,971]
, [ 896,11,-625,-973,-782,76]
, [ 578,-280,730,-729,307,-905]
, [ -580,-749,719,-698,967,603]
, [ -821,874,-103,-623,662,-491]
, [ -763,117,661,-644,672,-607]
, [ 592,787,-798,-169,-298,690]
, [ 296,644,-526,-762,-447,665]
, [ 534,-818,852,-120,57,-379]
, [ -986,-549,-329,294,954,258]
, [ -133,352,-660,-77,904,-356]
, [ 748,343,215,500,317,-277]
, [ 311,7,910,-896,-809,795]
, [ 763,-602,-753,313,-352,917]
, [ 668,619,-474,-597,-650,650]
, [ -297,563,-701,-987,486,-902]
, [ -461,-740,-657,233,-482,-328]
, [ -446,-250,-986,-458,-629,520]
, [ 542,-49,-327,-469,257,-947]
, [ 121,-575,-634,-143,-184,521]
, [ 30,504,455,-645,-229,-945]
, [ -12,-295,377,764,771,125]
, [ -686,-133,225,-25,-376,-143]
, [ -6,-46,338,270,-405,-872]
, [ -623,-37,582,467,963,898]
, [ -804,869,-477,420,-475,-303]
, [ 94,41,-842,-193,-768,720]
, [ -656,-918,415,645,-357,460]
, [ -47,-486,-911,468,-608,-686]
, [ -158,251,419,-394,-655,-895]
, [ 272,-695,979,508,-358,959]
, [ -776,650,-918,-467,-690,-534]
, [ -85,-309,-626,167,-366,-429]
, [ -880,-732,-186,-924,970,-875]
, [ 517,645,-274,962,-804,544]
, [ 721,402,104,640,478,-499]
, [ 198,684,-134,-723,-452,-905]
, [ -245,745,239,238,-826,441]
, [ -217,206,-32,462,-981,-895]
, [ -51,989,526,-173,560,-676]
, [ -480,-659,-976,-580,-727,466]
, [ -996,-90,-995,158,-239,642]
, [ 302,288,-194,-294,17,924]
, [ -943,969,-326,114,-500,103]
, [ -619,163,339,-880,230,421]
, [ -344,-601,-795,557,565,-779]
, [ 590,345,-129,-202,-125,-58]
, [ -777,-195,159,674,775,411]
, [ -939,312,-665,810,121,855]
, [ -971,254,712,815,452,581]
, [ 442,-9,327,-750,61,757]
, [ -342,869,869,-160,390,-772]
, [ 620,601,565,-169,-69,-183]
, [ -25,924,-817,964,321,-970]
, [ -64,-6,-133,978,825,-379]
, [ 601,436,-24,98,-115,940]
, [ -97,502,614,-574,922,513]
, [ -125,262,-946,695,99,-220]
, [ 429,-721,719,-694,197,-558]
, [ 326,689,-70,-908,-673,338]
, [ -468,-856,-902,-254,-358,305]
, [ -358,530,542,355,-253,-47]
, [ -438,-74,-362,963,988,788]
, [ 137,717,467,622,319,-380]
, [ -86,310,-336,851,918,-288]
, [ 721,395,646,-53,255,-425]
, [ 255,175,912,84,-209,878]
, [ -632,-485,-400,-357,991,-608]
, [ 235,-559,992,-297,857,-591]
, [ 87,-71,148,130,647,578]
, [ -290,-584,-639,-788,-21,592]
, [ 386,984,625,-731,-993,-336]
, [ -538,634,-209,-828,-150,-774]
, [ -754,-387,607,-781,976,-199]
, [ 412,-798,-664,295,709,-537]
, [ -412,932,-880,-232,561,852]
, [ -656,-358,-198,-964,-433,-848]
, [ -762,-668,-632,186,-673,-11]
, [ -876,237,-282,-312,-83,682]
, [ 403,73,-57,-436,-622,781]
, [ -587,873,798,976,-39,329]
, [ -369,-622,553,-341,817,794]
, [ -108,-616,920,-849,-679,96]
, [ 290,-974,234,239,-284,-321]
, [ -22,394,-417,-419,264,58]
, [ -473,-551,69,923,591,-228]
, [ -956,662,-113,851,-581,-794]
, [ -258,-681,413,-471,-637,-817]
, [ -866,926,992,-653,-7,794]
, [ 556,-350,602,917,831,-610]
, [ 188,245,-906,361,492,174]
, [ -720,384,-818,329,638,-666]
, [ -246,846,890,-325,-59,-850]
, [ -118,-509,620,-762,-256,15]
, [ -787,-536,-452,-338,-399,813]
, [ 458,560,525,-311,-608,-419]
, [ 494,-811,-825,-127,-812,894]
, [ -801,890,-629,-860,574,925]
, [ -709,-193,-213,138,-410,-403]
, [ 861,91,708,-187,5,-222]
, [ 789,646,777,154,90,-49]
, [ -267,-830,-114,531,591,-698]
, [ -126,-82,881,-418,82,652]
, [ -894,130,-726,-935,393,-815]
, [ -142,563,654,638,-712,-597]
, [ -759,60,-23,977,100,-765]
, [ -305,595,-570,-809,482,762]
, [ -161,-267,53,963,998,-529]
, [ -300,-57,798,353,703,486]
, [ -990,696,-764,699,-565,719]
, [ -232,-205,566,571,977,369]
, [ 740,865,151,-817,-204,-293]
, [ 94,445,-768,229,537,-406]
, [ 861,620,37,-424,-36,656]
, [ 390,-369,952,733,-464,569]
, [ -482,-604,959,554,-705,-626]
, [ -396,-615,-991,108,272,-723]
, [ 143,780,535,142,-917,-147]
, [ 138,-629,-217,-908,905,115]
, [ 915,103,-852,64,-468,-642]
, [ 570,734,-785,-268,-326,-759]
, [ 738,531,-332,586,-779,24]
, [ 870,440,-217,473,-383,415]
, [ -296,-333,-330,-142,-924,950]
, [ 118,120,-35,-245,-211,-652]
, [ 61,634,153,-243,838,789]
, [ 726,-582,210,105,983,537]
, [ -313,-323,758,234,29,848]
, [ -847,-172,-593,733,-56,617]
, [ 54,255,-512,156,-575,675]
, [ -873,-956,-148,623,95,200]
, [ 700,-370,926,649,-978,157]
, [ -639,-202,719,130,747,222]
, [ 194,-33,955,943,505,114]
, [ -226,-790,28,-930,827,783]
, [ -392,-74,-28,714,218,-612]
, [ 209,626,-888,-683,-912,495]
, [ 487,751,614,933,631,445]
, [ -348,-34,-411,-106,835,321]
, [ -689,872,-29,-800,312,-542]
, [ -52,566,827,570,-862,-77]
, [ 471,992,309,-402,389,912]
, [ 24,520,-83,-51,555,503]
, [ -265,-317,283,-970,-472,690]
, [ 606,526,137,71,-651,150]
, [ 217,-518,663,66,-605,-331]
, [ -562,232,-76,-503,205,-323]
, [ 842,-521,546,285,625,-186]
, [ 997,-927,344,909,-546,974]
, [ -677,419,81,121,-705,771]
, [ 719,-379,-944,-797,784,-155]
, [ -378,286,-317,-797,-111,964]
, [ -288,-573,784,80,-532,-646]
, [ -77,407,-248,-797,769,-816]
, [ -24,-637,287,-858,-927,-333]
, [ -902,37,894,-823,141,684]
, [ 125,467,-177,-516,686,399]
, [ -321,-542,641,-590,527,-224]
, [ -400,-712,-876,-208,632,-543]
, [ -676,-429,664,-242,-269,922]
, [ -608,-273,-141,930,687,380]
, [ 786,-12,498,494,310,326]
, [ -739,-617,606,-960,804,188]
, [ 384,-368,-243,-350,-459,31]
, [ -550,397,320,-868,328,-279]
, [ 969,-179,853,864,-110,514]
, [ 910,793,302,-822,-285,488]
, [ -605,-128,218,-283,-17,-227]
, [ 16,324,667,708,750,3]
, [ 485,-813,19,585,71,930]
, [ -218,816,-687,-97,-732,-360]
, [ -497,-151,376,-23,3,315]
, [ -412,-989,-610,-813,372,964]
, [ -878,-280,87,381,-311,69]
, [ -609,-90,-731,-679,150,585]
, [ 889,27,-162,605,75,-770]
, [ 448,617,-988,0,-103,-504]
, [ -800,-537,-69,627,608,-668]
, [ 534,686,-664,942,830,920]
, [ -238,775,495,932,-793,497]
, [ -343,958,-914,-514,-691,651]
, [ 568,-136,208,359,728,28]
, [ 286,912,-794,683,556,-102]
, [ -638,-629,-484,445,-64,-497]
, [ 58,505,-801,-110,872,632]
, [ -390,777,353,267,976,369]
, [ -993,515,105,-133,358,-572]
, [ 964,996,355,-212,-667,38]
, [ -725,-614,-35,365,132,-196]
, [ 237,-536,-416,-302,312,477]
, [ -664,574,-210,224,48,-925]
, [ 869,-261,-256,-240,-3,-698]
, [ 712,385,32,-34,916,-315]
, [ 895,-409,-100,-346,728,-624]
, [ -806,327,-450,889,-781,-939]
, [ -586,-403,698,318,-939,899]
, [ 557,-57,-920,659,333,-51]
, [ -441,232,-918,-205,246,1]
, [ 783,167,-797,-595,245,-736]
, [ -36,-531,-486,-426,-813,-160]
, [ 777,-843,817,313,-228,-572]
, [ 735,866,-309,-564,-81,190]
, [ -413,645,101,719,-719,218]
, [ -83,164,767,796,-430,-459]
, [ 122,779,-15,-295,-96,-892]
, [ 462,379,70,548,834,-312]
, [ -630,-534,124,187,-737,114]
, [ -299,-604,318,-591,936,826]
, [ -879,218,-642,-483,-318,-866]
, [ -691,62,-658,761,-895,-854]
, [ -822,493,687,569,910,-202]
, [ -223,784,304,-5,541,925]
, [ -914,541,737,-662,-662,-195]
, [ -622,615,414,358,881,-878]
, [ 339,745,-268,-968,-280,-227]
, [ -364,855,148,-709,-827,472]
, [ -890,-532,-41,664,-612,577]
, [ -702,-859,971,-722,-660,-920]
, [ -539,-605,737,149,973,-802]
, [ 800,42,-448,-811,152,511]
, [ -933,377,-110,-105,-374,-937]
, [ -766,152,482,120,-308,390]
, [ -568,775,-292,899,732,890]
, [ -177,-317,-502,-259,328,-511]
, [ 612,-696,-574,-660,132,31]
, [ -119,563,-805,-864,179,-672]
, [ 425,-627,183,-331,839,318]
, [ -711,-976,-749,152,-916,261]
, [ 181,-63,497,211,262,406]
, [ -537,700,-859,-765,-928,77]
, [ 892,832,231,-749,-82,613]
, [ 816,216,-642,-216,-669,-912]
, [ -6,624,-937,-370,-344,268]
, [ 737,-710,-869,983,-324,-274]
, [ 565,952,-547,-158,374,-444]
, [ 51,-683,645,-845,515,636]
, [ -953,-631,114,-377,-764,-144]
, [ -8,470,-242,-399,-675,-730]
, [ -540,689,-20,47,-607,590]
, [ -329,-710,-779,942,-388,979]
, [ 123,829,674,122,203,563]
, [ 46,782,396,-33,386,610]
, [ 872,-846,-523,-122,-55,-190]
, [ 388,-994,-525,974,127,596]
, [ 781,-680,796,-34,-959,-62]
, [ -749,173,200,-384,-745,-446]
, [ 379,618,136,-250,-224,970]
, [ -58,240,-921,-760,-901,-626]
, [ 366,-185,565,-100,515,688]
, [ 489,999,-893,-263,-637,816]
, [ 838,-496,-316,-513,419,479]
, [ 107,676,-15,882,98,-397]
, [ -999,941,-903,-424,670,-325]
, [ 171,-979,835,178,169,-984]
, [ -609,-607,378,-681,184,402]
, [ -316,903,-575,-800,224,983]
, [ 591,-18,-460,551,-167,918]
, [ -756,405,-117,441,163,-320]
, [ 456,24,6,881,-836,-539]
, [ -489,-585,915,651,-892,-382]
, [ -177,-122,73,-711,-386,591]
, [ 181,724,530,686,-131,241]
, [ 737,288,886,216,233,33]
, [ -548,-386,-749,-153,-85,-982]
, [ -835,227,904,160,-99,25]
, [ -9,-42,-162,728,840,-963]
, [ 217,-763,870,771,47,-846]
, [ -595,808,-491,556,337,-900]
, [ -134,281,-724,441,-134,708]
, [ -789,-508,651,-962,661,315]
, [ -839,-923,339,402,41,-487]
, [ 300,-790,48,703,-398,-811]
, [ 955,-51,462,-685,960,-717]
, [ 910,-880,592,-255,-51,-776]
, [ -885,169,-793,368,-565,458]
, [ -905,940,-492,-630,-535,-988]
, [ 245,797,763,869,-82,550]
, [ -310,38,-933,-367,-650,824]
, [ -95,32,-83,337,226,990]
, [ -218,-975,-191,-208,-785,-293]
, [ -672,-953,517,-901,-247,465]
, [ 681,-148,261,-857,544,-923]
, [ 640,341,446,-618,195,769]
, [ 384,398,-846,365,671,815]
, [ 578,576,-911,907,762,-859]
, [ 548,-428,144,-630,-759,-146]
, [ 710,-73,-700,983,-97,-889]
, [ -46,898,-973,-362,-817,-717]
, [ 151,-81,-125,-900,-478,-154]
, [ 483,615,-537,-932,181,-68]
, [ 786,-223,518,25,-306,-12]
, [ -422,268,-809,-683,635,468]
, [ 983,-734,-694,-608,-110,4]
, [ -786,-196,749,-354,137,-8]
, [ -181,36,668,-200,691,-973]
, [ -629,-838,692,-736,437,-871]
, [ -208,-536,-159,-596,8,197]
, [ -3,370,-686,170,913,-376]
, [ 44,-998,-149,-993,-200,512]
, [ -519,136,859,497,536,434]
, [ 77,-985,972,-340,-705,-837]
, [ -381,947,250,360,344,322]
, [ -26,131,699,750,707,384]
, [ -914,655,299,193,406,955]
, [ -883,-921,220,595,-546,794]
, [ -599,577,-569,-404,-704,489]
, [ -594,-963,-624,-460,880,-760]
, [ -603,88,-99,681,55,-328]
, [ 976,472,139,-453,-531,-860]
, [ 192,-290,513,-89,666,432]
, [ 417,487,575,293,567,-668]
, [ 655,711,-162,449,-980,972]
, [ -505,664,-685,-239,603,-592]
, [ -625,-802,-67,996,384,-636]
, [ 365,-593,522,-666,-200,-431]
, [ -868,708,560,-860,-630,-355]
, [ -702,785,-637,-611,-597,960]
, [ -137,-696,-93,-803,408,406]
, [ 891,-123,-26,-609,-610,518]
, [ 133,-832,-198,555,708,-110]
, [ 791,617,-69,487,696,315]
, [ -900,694,-565,517,-269,-416]
, [ 914,135,-781,600,-71,-600]
, [ 991,-915,-422,-351,-837,313]
, [ -840,-398,-302,21,590,146]
, [ 62,-558,-702,-384,-625,831]
, [ -363,-426,-924,-496,792,-908]
, [ 73,361,-817,-466,400,922]
, [ -626,-164,-626,860,-524,286]
, [ 255,26,-944,809,-606,986]
, [ -457,-256,-103,50,-867,-871]
, [ -223,803,196,480,612,136]
, [ -820,-928,700,780,-977,721]
, [ 717,332,53,-933,-128,793]
, [ -602,-648,562,593,890,702]
, [ -469,-875,-527,911,-475,-222]
, [ 110,-281,-552,-536,-816,596]
, [ -981,654,413,-981,-75,-95]
, [ -754,-742,-515,894,-220,-344]
, [ 795,-52,156,408,-603,76]
, [ 474,-157,423,-499,-807,-791]
, [ 260,688,40,-52,702,-122]
, [ -584,-517,-390,-881,302,-504]
, [ 61,797,665,708,14,668]
, [ 366,166,458,-614,564,-983]
, [ 72,539,-378,796,381,-824]
, [ -485,201,-588,842,736,379]
, [ -149,-894,-298,705,-303,-406]
, [ 660,-935,-580,521,93,633]
, [ -382,-282,-375,-841,-828,171]
, [ -567,743,-100,43,144,122]
, [ -281,-786,-749,-551,296,304]
, [ 11,-426,-792,212,857,-175]
, [ 594,143,-699,289,315,137]
, [ 341,596,-390,107,-631,-804]
, [ -751,-636,-424,-854,193,651]
, [ -145,384,749,675,-786,517]
, [ 224,-865,-323,96,-916,258]
, [ -309,403,-388,826,35,-270]
, [ -942,709,222,158,-699,-103]
, [ -589,842,-997,29,-195,-210]
, [ 264,426,566,145,-217,623]
, [ 217,965,507,-601,-453,507]
, [ -206,307,-982,4,64,-292]
, [ 676,-49,-38,-701,550,883]
, [ 5,-850,-438,659,745,-773]
, [ 933,238,-574,-570,91,-33]
, [ -866,121,-928,358,459,-843]
, [ -568,-631,-352,-580,-349,189]
, [ -737,849,-963,-486,-662,970]
, [ 135,334,-967,-71,-365,-792]
, [ 789,21,-227,51,990,-275]
, [ 240,412,-886,230,591,256]
, [ -609,472,-853,-754,959,661]
, [ 401,521,521,314,929,982]
, [ -499,784,-208,71,-302,296]
, [ -557,-948,-553,-526,-864,793]
, [ 270,-626,828,44,37,14]
, [ -412,224,617,-593,502,699]
, [ 41,-908,81,562,-849,163]
, [ 165,917,761,-197,331,-341]
, [ -687,314,799,755,-969,648]
, [ -164,25,578,439,-334,-576]
, [ 213,535,874,-177,-551,24]
, [ -689,291,-795,-225,-496,-125]
, [ 465,461,558,-118,-568,-909]
, [ 567,660,-810,46,-485,878]
, [ -147,606,685,-690,-774,984]
, [ 568,-886,-43,854,-738,616]
, [ -800,386,-614,585,764,-226]
, [ -518,23,-225,-732,-79,440]
, [ -173,-291,-689,636,642,-447]
, [ -598,-16,227,410,496,211]
, [ -474,-930,-656,-321,-420,36]
, [ -435,165,-819,555,540,144]
, [ -969,149,828,568,394,648]
, [ 65,-848,257,720,-625,-851]
, [ 981,899,275,635,465,-877]
, [ 80,290,792,760,-191,-321]
, [ -605,-858,594,33,706,593]
, [ 585,-472,318,-35,354,-927]
, [ -365,664,803,581,-965,-814]
, [ -427,-238,-480,146,-55,-606]
, [ 879,-193,250,-890,336,117]
, [ -226,-322,-286,-765,-836,-218]
, [ -913,564,-667,-698,937,283]
, [ 872,-901,810,-623,-52,-709]
, [ 473,171,717,38,-429,-644]
, [ 225,824,-219,-475,-180,234]
, [ -530,-797,-948,238,851,-623]
, [ 85,975,-363,529,598,28]
, [ -799,166,-804,210,-769,851]
, [ -687,-158,885,736,-381,-461]
, [ 447,592,928,-514,-515,-661]
, [ -399,-777,-493,80,-544,-78]
, [ -884,631,171,-825,-333,551]
, [ 191,268,-577,676,137,-33]
, [ 212,-853,709,798,583,-56]
, [ -908,-172,-540,-84,-135,-56]
, [ 303,311,406,-360,-240,811]
, [ 798,-708,824,59,234,-57]
, [ 491,693,-74,585,-85,877]
, [ 509,-65,-936,329,-51,722]
, [ -122,858,-52,467,-77,-609]
, [ 850,760,547,-495,-953,-952]
, [ -460,-541,890,910,286,724]
, [ -914,843,-579,-983,-387,-460]
, [ 989,-171,-877,-326,-899,458]
, [ 846,175,-915,540,-1000,-982]
, [ -852,-920,-306,496,530,-18]
, [ 338,-991,160,85,-455,-661]
, [ -186,-311,-460,-563,-231,-414]
, [ -932,-302,959,597,793,748]
, [ -366,-402,-788,-279,514,53]
, [ -940,-956,447,-956,211,-285]
, [ 564,806,-911,-914,934,754]
, [ 575,-858,-277,15,409,-714]
, [ 848,462,100,-381,135,242]
, [ 330,718,-24,-190,860,-78]
, [ 479,458,941,108,-866,-653]
, [ 212,980,962,-962,115,841]
, [ -827,-474,-206,881,323,765]
, [ 506,-45,-30,-293,524,-133]
, [ 832,-173,547,-852,-561,-842]
, [ -397,-661,-708,819,-545,-228]
, [ 521,51,-489,852,36,-258]
, [ 227,-164,189,465,-987,-882]
, [ -73,-997,641,-995,449,-615]
, [ 151,-995,-638,415,257,-400]
, [ -663,-297,-748,537,-734,198]
, [ -585,-401,-81,-782,-80,-105]
, [ 99,-21,238,-365,-704,-368]
, [ 45,416,849,-211,-371,-1]
, [ -404,-443,795,-406,36,-933]
, [ 272,-363,981,-491,-380,77]
, [ 713,-342,-366,-849,643,911]
, [ -748,671,-537,813,961,-200]
, [ -194,-909,703,-662,-601,188]
, [ 281,500,724,286,267,197]
, [ -832,847,-595,820,-316,637]
, [ 520,521,-54,261,923,-10]
, [ 4,-808,-682,-258,441,-695]
, [ -793,-107,-969,905,798,446]
, [ -108,-739,-590,69,-855,-365]
, [ 380,-623,-930,817,468,713]
, [ 759,-849,-236,433,-723,-931]
, [ 95,-320,-686,124,-69,-329]
, [ -655,518,-210,-523,284,-866]
, [ 144,303,639,70,-171,269]
, [ 173,-333,947,-304,55,40]
, [ 274,878,-482,-888,-835,375]
, [ -982,-854,-36,-218,-114,-230]
, [ 905,-979,488,-485,-479,114]
, [ 877,-157,553,-530,-47,-321]
, [ 350,664,-881,442,-220,-284]
, [ 434,-423,-365,878,-726,584]
, [ 535,909,-517,-447,-660,-141]
, [ -966,191,50,353,182,-642]
, [ -785,-634,123,-907,-162,511]
, [ 146,-850,-214,814,-704,25]
, [ 692,1,521,492,-637,274]
, [ -662,-372,-313,597,983,-647]
, [ -962,-526,68,-549,-819,231]
, [ 740,-890,-318,797,-666,948]
, [ -190,-12,-468,-455,948,284]
, [ 16,478,-506,-888,628,-154]
, [ 272,630,-976,308,433,3]
, [ -169,-391,-132,189,302,-388]
, [ 109,-784,474,-167,-265,-31]
, [ -177,-532,283,464,421,-73]
, [ 650,635,592,-138,1,-387]
, [ -932,703,-827,-492,-355,686]
, [ 586,-311,340,-618,645,-434]
, [ -951,736,647,-127,-303,590]
, [ 188,444,903,718,-931,500]
, [ -872,-642,-296,-571,337,241]
, [ 23,65,152,125,880,470]
, [ 512,823,-42,217,823,-263]
, [ 180,-831,-380,886,607,762]
, [ 722,443,-149,-216,-115,759]
, [ -19,660,-36,901,923,231]
, [ 562,-322,-626,-968,194,-825]
, [ 204,-920,938,784,362,150]
, [ -410,-266,-715,559,-672,124]
, [ -198,446,-140,454,-461,-447]
, [ 83,-346,830,-493,-759,-382]
, [ -881,601,581,234,-134,-925]
, [ -494,914,-42,899,235,629]
, [ -390,50,956,437,774,-700]
, [ -514,514,44,-512,-576,-313]
, [ 63,-688,808,-534,-570,-399]
, [ -726,572,-896,102,-294,-28]
, [ -688,757,401,406,955,-511]
, [ -283,423,-485,480,-767,908]
, [ -541,952,-594,116,-854,451]
, [ -273,-796,236,625,-626,257]
, [ -407,-493,373,826,-309,297]
, [ -750,955,-476,641,-809,713]
, [ 8,415,695,226,-111,2]
, [ 733,209,152,-920,401,995]
, [ 921,-103,-919,66,871,-947]
, [ -907,89,-869,-214,851,-559]
, [ -307,748,524,-755,314,-711]
, [ 188,897,-72,-763,482,103]
, [ 545,-821,-232,-596,-334,-754]
, [ -217,-788,-820,388,-200,-662]
, [ 779,160,-723,-975,-142,-998]
, [ -978,-519,-78,-981,842,904]
, [ -504,-736,-295,21,-472,-482]
, [ 391,115,-705,574,652,-446]
, [ 813,-988,865,830,-263,487]
, [ 194,80,774,-493,-761,-872]
, [ -415,-284,-803,7,-810,670]
, [ -484,-4,881,-872,55,-852]
, [ -379,822,-266,324,-48,748]
, [ -304,-278,406,-60,959,-89]
, [ 404,756,577,-643,-332,658]
, [ 291,460,125,491,-312,83]
, [ 311,-734,-141,582,282,-557]
, [ -450,-661,-981,710,-177,794]
, [ 328,264,-787,971,-743,-407]
, [ -622,518,993,-241,-738,229]
, [ 273,-826,-254,-917,-710,-111]
, [ 809,770,96,368,-818,725]
, [ -488,773,502,-342,534,745]
, [ -28,-414,236,-315,-484,363]
, [ 179,-466,-566,713,-683,56]
, [ 560,-240,-597,619,916,-940]
, [ 893,473,872,-868,-642,-461]
, [ 799,489,383,-321,-776,-833]
, [ 980,490,-508,764,-512,-426]
, [ 917,961,-16,-675,440,559]
, [ -812,212,784,-987,-132,554]
, [ -886,454,747,806,190,231]
, [ 910,341,21,-66,708,725]
, [ 29,929,-831,-494,-303,389]
, [ -103,492,-271,-174,-515,529]
, [ -292,119,419,788,247,-951]
, [ 483,543,-347,-673,664,-549]
, [ -926,-871,-437,337,162,-877]
, [ 299,472,-771,5,-88,-643]
, [ -103,525,-725,-998,264,22]
, [ -505,708,550,-545,823,347]
, [ -738,931,59,147,-156,-259]
, [ 456,968,-162,889,132,-911]
, [ 535,120,968,-517,-864,-541]
, [ 24,-395,-593,-766,-565,-332]
, [ 834,611,825,-576,280,629]
, [ 211,-548,140,-278,-592,929]
, [ -999,-240,-63,-78,793,573]
, [ -573,160,450,987,529,322]
, [ 63,353,315,-187,-461,577]
, [ 189,-950,-247,656,289,241]
, [ 209,-297,397,664,-805,484]
, [ -655,452,435,-556,917,874]
, [ 253,-756,262,-888,-778,-214]
, [ 793,-451,323,-251,-401,-458]
, [ -396,619,-651,-287,-668,-781]
, [ 698,720,-349,742,-807,546]
, [ 738,280,680,279,-540,858]
, [ -789,387,530,-36,-551,-491]
, [ 162,579,-427,-272,228,710]
, [ 689,356,917,-580,729,217]
, [ -115,-638,866,424,-82,-194]
, [ 411,-338,-917,172,227,-29]
, [ -612,63,630,-976,-64,-204]
, [ -200,911,583,-571,682,-579]
, [ 91,298,396,-183,788,-955]
, [ 141,-873,-277,149,-396,916]
, [ 321,958,-136,573,541,-777]
, [ 797,-909,-469,-877,988,-653]
, [ 784,-198,129,883,-203,399]
, [ -68,-810,223,-423,-467,-512]
, [ 531,-445,-603,-997,-841,641]
, [ -274,-242,174,261,-636,-158]
, [ -574,494,-796,-798,-798,99]
, [ 95,-82,-613,-954,-753,986]
, [ -883,-448,-864,-401,938,-392]
, [ 913,930,-542,-988,310,410]
, [ 506,-99,43,512,790,-222]
, [ 724,31,49,-950,260,-134]
, [ -287,-947,-234,-700,56,588]
, [ -33,782,-144,948,105,-791]
, [ 548,-546,-652,-293,881,-520]
, [ 691,-91,76,991,-631,742]
, [ -520,-429,-244,-296,724,-48]
, [ 778,646,377,50,-188,56]
, [ -895,-507,-898,-165,-674,652]
, [ 654,584,-634,177,-349,-620]
, [ 114,-980,355,62,182,975]
, [ 516,9,-442,-298,274,-579]
, [ -238,262,-431,-896,506,-850]
, [ 47,748,846,821,-537,-293]
, [ 839,726,593,285,-297,840]
, [ 634,-486,468,-304,-887,-567]
, [ -864,914,296,-124,335,233]
, [ 88,-253,-523,-956,-554,803]
, [ -587,417,281,-62,-409,-363]
, [ -136,-39,-292,-768,-264,876]
, [ -127,506,-891,-331,-744,-430]
, [ 778,584,-750,-129,-479,-94]
, [ -876,-771,-987,-757,180,-641]
, [ -777,-694,411,-87,329,190]
, [ -347,-999,-882,158,-754,232]
, [ -105,918,188,237,-110,-591]
, [ -209,703,-838,77,838,909]
, [ -995,-339,-762,750,860,472]
, [ 185,271,-289,173,811,-300]
, [ 2,65,-656,-22,36,-139]
, [ 765,-210,883,974,961,-905]
, [ -212,295,-615,-840,77,474]
, [ 211,-910,-440,703,-11,859]
, [ -559,-4,-196,841,-277,969]
, [ -73,-159,-887,126,978,-371]
, [ -569,633,-423,-33,512,-393]
, [ 503,143,-383,-109,-649,-998]
, [ -663,339,-317,-523,-2,596]
, [ 690,-380,570,378,-652,132]
, [ 72,-744,-930,399,-525,935]
, [ 865,-983,115,37,995,826]
, [ 594,-621,-872,443,188,-241]
, [ -1000,291,754,234,-435,-869]
, [ -868,901,654,-907,59,181]
, [ -868,-793,-431,596,-446,-564]
, [ 900,-944,-680,-796,902,-366]
, [ 331,430,943,853,-851,-942]
, [ 315,-538,-354,-909,139,721]
, [ 170,-884,-225,-818,-808,-657]
, [ -279,-34,-533,-871,-972,552]
, [ 691,-986,-800,-950,654,-747]
, [ 603,988,899,841,-630,591]
, [ 876,-949,809,562,602,-536]
, [ -693,363,-189,495,738,-1000]
, [ -383,431,-633,297,665,959]
, [ -740,686,-207,-803,188,-520]
, [ -820,226,31,-339,10,121]
, [ -312,-844,624,-516,483,621]
, [ -822,-529,69,-278,800,328]
, [ 834,-82,-759,420,811,-264]
, [ -960,-240,-921,561,173,46]
, [ -324,909,-790,-814,-2,-785]
, [ 976,334,-290,-891,704,-581]
, [ 150,-798,689,-823,237,-639]
, [ -551,-320,876,-502,-622,-628]
, [ -136,845,904,595,-702,-261]
, [ -857,-377,-522,-101,-943,-805]
, [ -682,-787,-888,-459,-752,-985]
, [ -571,-81,623,-133,447,643]
, [ -375,-158,72,-387,-324,-696]
, [ -660,-650,340,188,569,526]
, [ 727,-218,16,-7,-595,-988]
, [ -966,-684,802,-783,-272,-194]
, [ 115,-566,-888,47,712,180]
, [ -237,-69,45,-272,981,-812]
, [ 48,897,439,417,50,325]
, [ 348,616,180,254,104,-784]
, [ -730,811,-548,612,-736,790]
, [ 138,-810,123,930,65,865]
, [ -768,-299,-49,-895,-692,-418]
, [ 487,-531,802,-159,-12,634]
, [ 808,-179,552,-73,470,717]
, [ 720,-644,886,-141,625,144]
, [ -485,-505,-347,-244,-916,66]
, [ 600,-565,995,-5,324,227]
, [ -771,-35,904,-482,753,-303]
, [ -701,65,426,-763,-504,-479]
, [ 409,733,-823,475,64,718]
, [ 865,975,368,893,-413,-433]
, [ 812,-597,-970,819,813,624]
, [ 193,-642,-381,-560,545,398]
, [ 711,28,-316,771,717,-865]
, [ -509,462,809,-136,786,635]
, [ 618,-49,484,169,635,547]
, [ -747,685,-882,-496,-332,82]
, [ -501,-851,870,563,290,570]
, [ -279,-829,-509,397,457,816]
, [ -508,80,850,-188,483,-326]
, [ 860,-100,360,119,-205,787]
, [ -870,21,-39,-827,-185,932]
, [ 826,284,-136,-866,-330,-97]
, [ -944,-82,745,899,-97,365]
, [ 929,262,564,632,-115,632]
, [ 244,-276,713,330,-897,-214]
, [ -890,-109,664,876,-974,-907]
, [ 716,249,816,489,723,141]
, [ -96,-560,-272,45,-70,645]
, [ 762,-503,414,-828,-254,-646]
, [ 909,-13,903,-422,-344,-10]
, [ 658,-486,743,545,50,674]
, [ -241,507,-367,18,-48,-241]
, [ 886,-268,884,-762,120,-486]
, [ -412,-528,879,-647,223,-393]
, [ 851,810,234,937,-726,797]
, [ -999,942,839,-134,-996,-189]
, [ 100,979,-527,-521,378,800]
, [ 544,-844,-832,-530,-77,-641]
, [ 43,889,31,442,-934,-503]
, [ -330,-370,-309,-439,173,547]
, [ 169,945,62,-753,-542,-597]
, [ 208,751,-372,-647,-520,70]
, [ 765,-840,907,-257,379,918]
, [ 334,-135,-689,730,-427,618]
, [ 137,-508,66,-695,78,169]
, [ -962,-123,400,-417,151,969]
, [ 328,689,666,427,-555,-642]
, [ -907,343,605,-341,-647,582]
, [ -667,-363,-571,818,-265,-399]
, [ 525,-938,904,898,725,692]
, [ -176,-802,-858,-9,780,275]
, [ 580,170,-740,287,691,-97]
, [ 365,557,-375,361,-288,859]
, [ 193,737,842,-808,520,282]
, [ -871,65,-799,836,179,-720]
, [ 958,-144,744,-789,797,-48]
, [ 122,582,662,912,68,757]
, [ 595,241,-801,513,388,186]
, [ -103,-677,-259,-731,-281,-857]
, [ 921,319,-696,683,-88,-997]
, [ 775,200,78,858,648,768]
, [ 316,821,-763,68,-290,-741]
, [ 564,664,691,504,760,787]
, [ 694,-119,973,-385,309,-760]
, [ 777,-947,-57,990,74,19]
, [ 971,626,-496,-781,-602,-239]
, [ -651,433,11,-339,939,294]
, [ -965,-728,560,569,-708,-247]
]
| |
38cccd6a43f4b09bb3cf68d0b32015c33aece38739de3d4a5494a6981ff11b95 | 8c6794b6/haskell-sc-scratch | Nameplate.hs | {-# LANGUAGE DeriveDataTypeable #-}
# LANGUAGE TypeOperators #
# LANGUAGE MultiParamTypeClasses #
------------------------------------------------------------------------------
-- |
-- Module : $Header$
-- License : BSD3
Maintainer :
-- Stability : unstable
-- Portability : non-portable
--
module Pearl.Nameplate where
import Control.Monad.State
import Data.Data
import Data.Generics.Uniplate.Data
data Name = Name String (Maybe Int)
deriving (Eq, Show)
class Nom a where
(==@) :: a -> a -> Bool
data a :\\ b = a :\\ b
instance (Eq a, Eq b) => Eq (a :\\ b) where
(a :\\ b) == (c :\\ d) = undefined
class Monad m => FreshM m where
renameFM :: Name -> m Name
class Subst t u where
(|->) :: FreshM m => Name -> t -> m u
class FreeVars t u where
fvars :: t -> u -> [Name]
data Tree = Leaf Nid
| Branch Nid [Tree]
deriving (Eq, Show, Data, Typeable)
data Nid = Known Int
| Anon
deriving (Eq, Show, Data, Typeable)
t1 :: Tree
t1 = Branch (Known 0)
[ Leaf Anon
, Branch (Known 2)
[ Leaf Anon
, Branch Anon
[Leaf Anon
,Leaf Anon]
, Branch Anon []
, Leaf (Known 22)]
, Leaf (Known 3)]
fillIds :: Tree -> Int -> Tree
fillIds t n = fillIt (maximum (n:ids)) t where
ids = [n | Leaf (Known n) <- universe t] ++
[n | Branch (Known n) _ <- universe t]
fillIt :: Int -> Tree -> Tree
fillIt n (Leaf Anon) = Leaf (Known (n+1))
fillIt n (Leaf x) = Leaf x
fillIt n (Branch Anon ts) = Branch (Known (n+1)) (map (fillIt (n+1)) ts)
fillIt n (Branch x ts) = Branch x (map (fillIt (n+1)) ts)
| null | https://raw.githubusercontent.com/8c6794b6/haskell-sc-scratch/22de2199359fa56f256b544609cd6513b5e40f43/Scratch/Pearl/Nameplate.hs | haskell | # LANGUAGE DeriveDataTypeable #
----------------------------------------------------------------------------
|
Module : $Header$
License : BSD3
Stability : unstable
Portability : non-portable
| # LANGUAGE TypeOperators #
# LANGUAGE MultiParamTypeClasses #
Maintainer :
module Pearl.Nameplate where
import Control.Monad.State
import Data.Data
import Data.Generics.Uniplate.Data
data Name = Name String (Maybe Int)
deriving (Eq, Show)
class Nom a where
(==@) :: a -> a -> Bool
data a :\\ b = a :\\ b
instance (Eq a, Eq b) => Eq (a :\\ b) where
(a :\\ b) == (c :\\ d) = undefined
class Monad m => FreshM m where
renameFM :: Name -> m Name
class Subst t u where
(|->) :: FreshM m => Name -> t -> m u
class FreeVars t u where
fvars :: t -> u -> [Name]
data Tree = Leaf Nid
| Branch Nid [Tree]
deriving (Eq, Show, Data, Typeable)
data Nid = Known Int
| Anon
deriving (Eq, Show, Data, Typeable)
t1 :: Tree
t1 = Branch (Known 0)
[ Leaf Anon
, Branch (Known 2)
[ Leaf Anon
, Branch Anon
[Leaf Anon
,Leaf Anon]
, Branch Anon []
, Leaf (Known 22)]
, Leaf (Known 3)]
fillIds :: Tree -> Int -> Tree
fillIds t n = fillIt (maximum (n:ids)) t where
ids = [n | Leaf (Known n) <- universe t] ++
[n | Branch (Known n) _ <- universe t]
fillIt :: Int -> Tree -> Tree
fillIt n (Leaf Anon) = Leaf (Known (n+1))
fillIt n (Leaf x) = Leaf x
fillIt n (Branch Anon ts) = Branch (Known (n+1)) (map (fillIt (n+1)) ts)
fillIt n (Branch x ts) = Branch x (map (fillIt (n+1)) ts)
|
6d8a927a4deed77b712ecac6e160be70dadec009b37496ccb5a16e55174e959b | sellout/haskerwaul | ColaxDistributive.hs | module Haskerwaul.Category.Rig.ColaxDistributive
( module Haskerwaul.Category.Rig.ColaxDistributive
-- * extended modules
, module Haskerwaul.Category.Rig.ColaxDistributive.Left
, module Haskerwaul.Category.Rig.ColaxDistributive.Right
) where
import Haskerwaul.Category.Rig.ColaxDistributive.Left
import Haskerwaul.Category.Rig.ColaxDistributive.Right
-- |
-- = references
--
-- - [nLab](-distributive+rig+category)
type ColaxDistributiveRigCategory c p s =
(LeftColaxDistributiveRigCategory c p s, RightColaxDistributiveRigCategory c p s)
| null | https://raw.githubusercontent.com/sellout/haskerwaul/cf54bd7ce5bf4f3d1fd0d9d991dc733785b66a73/src/Haskerwaul/Category/Rig/ColaxDistributive.hs | haskell | * extended modules
|
= references
- [nLab](-distributive+rig+category) | module Haskerwaul.Category.Rig.ColaxDistributive
( module Haskerwaul.Category.Rig.ColaxDistributive
, module Haskerwaul.Category.Rig.ColaxDistributive.Left
, module Haskerwaul.Category.Rig.ColaxDistributive.Right
) where
import Haskerwaul.Category.Rig.ColaxDistributive.Left
import Haskerwaul.Category.Rig.ColaxDistributive.Right
type ColaxDistributiveRigCategory c p s =
(LeftColaxDistributiveRigCategory c p s, RightColaxDistributiveRigCategory c p s)
|
8bc1b3849d6670fdd816190c50be87d74eb47ab93cbd3fec3e08399d71e77169 | kmi/irs | arthritis.lisp | ;;; FILE: arthritis-ontology.lisp
;;; **************************************************************************
Based on : , , Complete Family Health Encyclopedia
and CYC ontology
;;;
Author :
Date : 2.2002
(in-package ocml)
(in-ontology arthritis)
(def-class medical-condition ()
((has-technical-name :type string)
(has-short-name :type string)
(has-alternative-name :type string)
(susceptible-groups :type population-specification)
(caused-by :type medical-condition-causing-agent) ;; virus/bacterium etc.
(reported-symptoms :type medical-symptom)
(has-site :type site)
(onset :type onset-index) ;;e.g. gradual
(has-periodicity :type periodicity-index)
(has-severity :type severity-index)
(has-rarity :type rarity-index) ;;rare-common
(physical-examination-result :type examination-result)
(test-result :type test-result)
(can-be-treated-by :type treatment)
(sequelae :type medical-condition)
(sequela-of :type medical-condition)
(associated-with :type medical-condition)
(part-of-syndrome :type syndrome)
(possible-confusibles :type medical-condition)
(discriminators :type medical-symptom)
(prognosis :value prognosis)
)
)
(def-domain-class disorder (medical-condition)
((caused-by :type disorder-causing-agent) ;; injury/wear-and-tear etc.
)
)
(def-domain-class disease (medical-condition)
((caused-by :type disease-causing-agent) ;; virus/bacterium etc.
(spread-by :type transmission-medium) ;;aerosol, touch, etc.
(incubation-period :type integer) ;;; days
)
)
(def-domain-class autoimmune-disorder (disorder)
)
(def-domain-class heart-disease (disease)
((site :value heart)
)
)
(def-domain-class skin-disease (disease)
((site :value skin) ;;
)
)
;;;;;;;;; Arthritis ;;;;;;;;;;
(def-domain-class joint-disease (disease)
)
(def-domain-class joint-disorder (disorder)
)
(def-domain-class rheumatic-fever (joint-disease heart-disease)
)
(def-domain-class arthritis (joint-disease)
)
;;;;;;;;; osteoarthritis ;;;;;;
(def-domain-class osteoarthritis (arthritis)
((disease-alternative-name :value degenerative-arthritis
:value osteoarthrosis)
(caused-by :value joint-wear-and-tear
:value joint-injury
:value joint-deformity
:value inflammation-from-disease)
(susceptible-groups :value older-people
:value sufferers-joint-injury)
(reported-symptoms :value joint-pain
:value joint-swelling
:value joint-stiffness
:value joint-creaking)
(site :value hips
:value knees
:value spine)
(physical-examination-result :value joint-tenderness
:value swelling
:value pain-on-movement)
(test-result :value (x-ray loss-of-cartilage positive)
:value (x-ray formation-osteophytes positive))
(can-be-treated-by :default-value (analgesic-drugs pain)
:default-value (nonsteroidal-anti-inflammatories inflammation)
:default-value (corticosteroid painful-joint)
:default-value (physiotherapy general-symptoms)
)
(discriminators :value none)
)
)
(def-domain-class severe-osteoarthritis (osteoarthritis)
((reported-symptoms :value severe-joint-pain
:value severe-swelling
:value severe-joint-stiffness)
(test-result :value (x-ray extensive-loss-of-cartilage positive)
:value (x-ray extensive-formation-osteophytes positive)) ;;outgrowths new bone
(can-be-treated-by :value (arthroplasty relieve-symptoms) ;; joint replacement *********
;;;;;:value (arthrodesis relieve-symptoms) ;; joint immobilization
)
)
)
;;;;;;;;; Rheumatoid arthritis ;;;;;;
(def-domain-class rheumatoid-arthritis (arthritis autoimmune-disorder)
((disease-alternative-name :value none)
(caused-by :value joint-wear-and-tear
:value joint-injury
:value joint-deformity
:value inflammation-from-disease)
(susceptible-groups :value young-adults
:value middle-aged
:value older-people)
(reported-symptoms :value joint-pain
:value joint-stiffness
:value joint-swelling
:value joint-reddening
:value joint-deformity
:value mild-fever
:value generalised-aches-and-pains)
(site :value fingers
:value wrists
:value toes
:value joints)
(onset gradual) ;;???
(has-periodcity recurrent-attacks)
(severity moderate)
1 - 2 % population
(physical-examination-result :value weakness-tendons
:value weakness-ligaments
:value weakness-muscles
:value weak-grip
:value raynauds-phenomenon
:value carpal-tunnel-syndrome
:value tenosynovitis
:value soft-nodules-beneath-skin
:value bursitis
:value bakers-cyst-behind-knee
:value fatigue
)
(test-result :value (x-ray joint-deformities positive)
:value (blood-test anaemia positive)
:value (blood-test rheumatoid-factor positive)
)
(can-be-treated-by :value (antirheumatic-drugs slow-progress)
:value (nonsteroidal-anti-inflammatories relieve-joint-pain-stiffness)
:value (corticosteroid relieve-painful-joint)
:value (immuno-suppressant-drugs suppress-immune-system)
:value (physiotherapy general-symptoms)
:value (splints relieve-hand-wrist-pain)
:value (occupational-therapy general-symptoms)
:value (diet relieve-general-symptoms)
:value (acupuncture relieve-pain)
)
(discriminators :value none)
(sequelae :value pericarditis
:value poor-circulation
:value foot-ulcers
:value hand-ulcers
:value pleural-effusion
:value pulmonary-fibrosis
:value sjogrens-syndrome
:value enlarged-lymph-nodes
:value hypersplenism-feltys-syndrome
)
)
)
(def-domain-class severe-rheumatoid-arthritis (arthritis)
((disease-name :value severe-rheumatoid-arthritis)
(reported-symptoms :value severe-joint-pain
:value severe-joint-stiffness
:value severe-joint-swelling
:value severe-joint-deformity)
(site :value hip
:value knee)
(has-periodcity frequent-attacks)
(severity severe)
(test-result :value (x-ray severe-joint-deformities positive)
)
(can-be-treated-by :value (arthroplasty relieve-symptoms) ;; **************
)
)
)
(def-domain-class juvenile-rheumatoid-arthritis (arthritis)
((susceptible-groups :value children-2-4-years
:value children-around-puberty)
(rarity rare)
months ? ?
(possible-confusibles :value viral-bacterial-infection
:value rheumatic-fever
:value crohns-disease
:value ulcerative-colitis
:value haemophilia
:value sickle-cell-anaemia
:value leukaemia)
(prognosis :value condition-disappears-after-several-years
:value may-leave-deformity)
)
)
(def-domain-class stills-disease (juvenile-rheumatoid-arthritis)
((disease-alternative-name :value systemic-onset-juvenile-arthritis)
(reported-symptoms :value fever
:value rash
:value enlarged-lymph-nodes
:value abdominal-pain
:value weight-loss)
(onset illness-followed-by-joint-symptoms)
)
)
(def-domain-class polyarticular-juvenile-arthritis (juvenile-rheumatoid-arthritis)
((site :value many-joints)
)
)
(def-domain-class pauciarticular-juvenile-artritis (juvenile-rheumatoid-arthritis)
((site :value four-or-fewer-joints)
)
)
;;; no rheumatoid factor
(def-domain-class seronegative-rheumatoid-arthritis (arthritis)
((test-result :value (blood-test rheumatoid-factor negative)
)
)
)
;;;;;;;;; Ankylosing Spondylitis ;;;;;;
(def-domain-class ankylosing-spondylitis (arthritis)
((disease-alternative-name :value none)
(caused-by :value unknown)
(susceptible-groups :value 20-40-year-olds)
(reported-symptoms :value pain-lower-back-and-hips
:value stiffness-lower-back-and-hips
:value worse-in-morning
:value chest-pain
:value loss-appetite
20 - 40 = range / worse - in - morning = qualification
(site :value joints-between-spine-and-pelvis
:value hips
:value knees
:value ankles
:value tissues-heel)
(onset :value preceded-by-colitis
:value preceded-by-psoriasis)
1 % population
(physical-examination-result :value iritis
:value inflammation-tissues-heel
)
(test-result :value (blood-test HLA-B27 positive);; histocompatibility complex found 'more' often
:value (x-ray increase-bone-density-around-sacriliac-joints positive)
:value (x-ray loss-of-spacebetween-joints-and-bony-outgrowths positive)
)
(can-be-treated-by :value (heat relieve-general-symptoms)
:value (massage relieve-general-symptoms)
:value (exercise relieve-general-symptoms)
:value (immuno-suppressant-drugs suppress-immune-system)
:value (anti-inflammatory-drugs reduce-pain-and-stiffness)
)
(discriminators :value none)
(sequelae :value ankylosis
:value kyphosis
) ;;ankylosis = permanent stiffness loss of movement / kyphosis = curvature- of spine
)
)
;;;;;;;;; Gout ;;;;;;
(def-domain-class gout (arthritis)
((disease-alternative-name :value none)
(caused-by :value hyperuricaemia-leads-to-uric-acid-crystals-in-joints)
10:1 men : women
(reported-symptoms :value severe-pain
:value affects-single-joint)
(site :value joints-base-big-toe
:value wrist
:value knees
:value ankles
:value foot
:value small-joints-of-hand)
(has-periodicity
:value acute-attacks
:value (peaking-at 24-to-36-hours )
:value last-few-days
:value affects-single-joint
:value subsequent-attack-6-24-months
:value subsequent-attack-more-joints
:value subsequent-attack-constant-pain)
(physical-examination-result :value swollen-joint
:value red-joint
:value swelling-spreads
:value redness-spreads
:value tender-joint
)
(test-result :value (blood-test high-level-uric-acid positive)
:value (aspirated-fluid-joint uric-acid-crystals positive)
)
(can-be-treated-by :value (nonsteroidal-anti-inflammatories relieve-joint-pain-inflammation)
:value (colchicine relieve-joint-pain-inflammation)
:value (corticosteriod-drugs relieve-joint-pain-inflammation)
:value (allopurinal inhibit-formation-uric-acid)
:value (uricosuric-drugs increase-kidney-excretion-uric-acid)
)
(possible-confusibles :value cellulitis);; redness/swelling
(discriminators :value affects-single-joint)
(associated-with :value kidney-stones) ;;? sequela?
(sequelae :value hypertension
)
)
)
Infective Arthritis ; ; ; ; ; ;
(def-domain-class infective-arthritis (arthritis)
((disease-alternative-name :value septic-arthritis
:value pyogenic-arthritis)
(caused-by :value bacterial-invasion-of-joint-from-bacteraemia
:value bacterial-invasion-of-joint-from-infected-wound
:value tubercle-bacilli-invasion-of-joint)
(reported-symptoms :value joint-pain
:value joint-swelling)
(site :value joints)
(physical-examination-result :value swollen-joint
:value red-joint
:value swelling-spreads
:value redness-spreads
:value tender-joint
)
(sequela-of :value chickenpox
:value rubella
:value mumps
:value rheumatic-fever
:value non-specific-urethritis
)
(part-of-syndrome reiters-sundrome ) ;;with-NSU
)
)
;;;;;;;;; Lupus ;;;;;;
(def-domain-class lupus (skin-disease joint-disorder autoimmune-disorder)
"causes inflammation of connective tissue - CHEP p. 650"
(
(caused-by :value autoimmune-disorder
:value inherited
:value hormonal-factors)
(triggered-by :value viral-infection
:value sunlight
:value drugs)
(susceptible-groups :value women-child-bearing-age
9:1 women : men / Chinese People of colour
(rarity :value 0.4);; 1:250
(has-periodicity :value symptoms-subside-and-recur)
(severity :value variable)
(test-result :value (blood-test antibodies-attack-bodys-tissues positive)
:value (biopsy antibodies-attack-bodys-tissues positive)
)
(can-be-treated-by :value (anti-malarial-drugs skin-rash)
:value (nonsteroidal-anti-inflammatories relieve-joint-pain-stiffness)
:value (corticosteroid relieve-fever)
:value (corticosteroid relieve-pleurisy)
:value (corticosteroid relieve-neurological-symptoms)
:value (immuno-suppressant-drugs relieve-severe-neurological-symptoms)
:value (immuno-suppressant-drugs relieve-kidney-damage)
)))
(def-domain-class discoid-lupus-erythematosus (lupus)
((disease-alternative-name :value DLE)
(reported-symptoms :value rash
:value red-circular-areas-skin
:value scarring
:value hair-loss)
(site :value face
:value behind-ears
:value scalp)
(physical-examination-result :value red-circular-areas-skin
:value scarring
:value hair-loss
)
)
)
(def-domain-class systemic-lupus-erythematosus (lupus)
((disease-alternative-name :value SLE)
(prognosis :value possibly-fatal
:value prologed-survival-if-diagnosed-early
:value prologed-survival-if-kidney-problems-treated)
(reported-symptoms :value rash
:value illness
:value fatigue
:value loss-of-appetite
:value nausea
:value joint-pain
:value weight-loss)
(site :value skin
:value joints
:value kidneys)
(physical-examination-result :value red-blotchy-butterfly-shaped-rash-nose-cheeks
:value no-scarring
)
(test-result :value (blood-test anaemia positive)
:value (neuro-test neurological-problems positive)
:value (psych-test psychological-problems positive)
:value (test kidney-failure positive)
:value (test pleurisy positive)
:value (test arthritis positive)
:value (test pericarditis positive)
)
(can-be-treated-by :value (nonsteroidal-anti-inflammatories relieve-joint-pain-stiffness)
:value (corticosteroid relieve-fever)
:value (corticosteroid relieve-pleurisy)
:value (corticosteroid relieve-neurological-symptoms)
:value (immuno-suppressant-drugs relieve-severe-neurological-symptoms)
:value (immuno-suppressant-drugs relieve-kidney-damage)
:value (physiotherapy general-symptoms)
:value (splints relieve-hand-wrist-pain)
:value (occupational-therapy general-symptoms)
:value (diet relieve-general-symptoms)
:value (acupuncture relieve-pain)
)
(discriminators :value red-blotchy-butterfly-shaped-rash)
)
)
;;;;;;;;; END Arthritis ;;;;;
;;;;;;;;; RTDs ;;;;;;;;;;;;;;
(def-domain-class respiratory-tract-disease (disease)
((disease-short-name :default-value "RTD")
)
)
(def-domain-class upper-respiratory-tract-disease (respiratory-tract-disease)
((disease-short-name :default-value "URTD")
)
)
(def-domain-class lower-respiratory-tract-disease (respiratory-tract-disease)
((disease-short-name :default-value "LRTD")
)
)
;;;;;;;;; URTDs ;;;;;;;;;;;
(def-domain-class influenza (upper-respiratory-tract-disease)
((disease-short-name :value flu)
(caused-by :value virus)
(spread-by :value droplet-infection)
(incubation-period :value 2) ;;; days
(reported-symptoms :value fever11
:value shivering
:value headache
:value aches-and-pains
:value nasal-congestion
:value sore-throat
:value cough)
(physical-examination-result :value high-temperature)
(test-result :value none)
(can-be-treated-by :value (salicylates discomfort)
:value (codeine-linctus cough)
:value (warm-environment rest)
:value (steam-inhalers laryngitis)
)
(discriminators :value sore-throat-with-persistent-dry-cough)
)
)
;;;;;;;;; LRTDs ;;;;;;;;;;;
(def-domain-class pneumonia (lower-respiratory-tract-disease)
)
(def-domain-class bacterial-pneumonia (pneumonia)
((reported-symptoms :value productive-cough
:value systemic-upset
:value purulent-sputum
:value mucoid-sputum)
(susceptible-groups :value ageing
:value sufferers-chronic-respiratory-disease
:value sufferers-heart-failure
:value patients-prone-to-aspiration)
(environmental-factors :value winter
:value polluted-air)
)
)
(def-domain-class pneumococcal-pneumonia (bacterial-pneumonia)
((disease-alternative-name :value acute-lobar-pneumonia)
(spread-by :value droplet-infection)
(reported-symptoms :value sudden-onset-fever
:value shivering
:value tachypnoea
:value cold-sores
:value generalized-pain
:value pleuritic-chest-pain
:value painful-dry-cough-becoming-productive-of-blood)
(physical-examination-result :value high-temperature
:value diminished-chest-movements
:value signs-of-consolidation
:value pleural-rub
:value crepitations)
(test-result :value (peripheral-blood-film polymorphonuclear-leucocytosis)
:value (blood-culture pneumococcus-growth)
:value (sputum-culture pneumococcus-growth)
:value (gram-staining diplococci-presence))
(can-be-treated-by :value (benzyl-penicillin 600);; mg
:value (amoxycillin 250)
:value (erythromycin)
)
(sequelae :value pulmonary-fibrosis
:value bronchiectasis
:value abscess
:value empyema
:value meningism
artefact of disease/ secondary result
(possible-confusibles :value pulmonary-infarction
:value haemoptysis)
(discriminators :value sore-throat-with-persistent-dry-cough)
)
)
(def-domain-class staphylococcal-pneumonia (bacterial-pneumonia)
)
(def-domain-class gram-negative-pneumonia (bacterial-pneumonia)
)
;;; test instances
(def-domain-instance influenza1 influenza
)
(def-domain-instance pneum1 pneumococcal-pneumonia
)
(def-domain-instance arthritis1 stills-disease
)
(def-domain-instance arthritis1 stills-disease
)
(def-domain-instance seveer1 severe-rheumatoid-arthritis
)
;;;;;; Treatments ;;;;;;;;;
(def-domain-class treatment ()
)
(def-domain-class drug-treatment (treatment)
)
(def-domain-class surgical-treatment (treatment)
)
(def-domain-class body-part-replacement (surgical-treatment)
)
(def-domain-class body-part-fusion (surgical-treatment)
)
(def-domain-class arthroplasty (body-part-replacement)
"replacement joint/part by metal or plastic components"
(
(site
:value hip
:value knees
:value finger
:value shoulder
:value elbow
)))
(def-domain-class arthrodesis (body-part-fusion)
((comment :value "two boness in diseased joint fused to prevent joint movement")
(needed-if :value all-other-options-fail)
(prognosis :value fusion-within-6-months
:value no-need-for-maintenance
)
)
)
1 . Classes for symptoms , tests , treatments , onset ? etc . prognosis ?
2 . Patients
3 . Diagnoses
4 . Rules patient history , tests , symptoms etc -- > disorders
;;;;;;;;;;;;
;; Patient class + rel from patient to possible transportedted patients
;; e.g. general health, age, fear of flying etc.
;(def-class topic-type () ?x
; :iff-def (or (= ?x topic) (subclass-of ?x topic)))
(def-relation query1 (?x ?disease)
:sufficient (and
(susceptible-groups ?x ?disease)
(susceptible-groups ?x ?disease)))
(def-relation query2 (?x ?disease)
:sufficient (susceptible-groups ?x ?disease))
(def-relation query3 (?x ?c)
:sufficient (and
(can-be-treated-by ?x (arthroplasty ?rest))
(disease-name ?x ?c)))
;(= ?x topic) (subclass-of ?x topic))) | null | https://raw.githubusercontent.com/kmi/irs/e1b8d696f61c6b6878c0e92d993ed549fee6e7dd/ontologies/domains/arthritis/arthritis.lisp | lisp | FILE: arthritis-ontology.lisp
**************************************************************************
virus/bacterium etc.
e.g. gradual
rare-common
injury/wear-and-tear etc.
virus/bacterium etc.
aerosol, touch, etc.
days
Arthritis ;;;;;;;;;;
osteoarthritis ;;;;;;
outgrowths new bone
joint replacement *********
:value (arthrodesis relieve-symptoms) ;; joint immobilization
Rheumatoid arthritis ;;;;;;
???
**************
no rheumatoid factor
Ankylosing Spondylitis ;;;;;;
histocompatibility complex found 'more' often
ankylosis = permanent stiffness loss of movement / kyphosis = curvature- of spine
Gout ;;;;;;
redness/swelling
? sequela?
; ; ; ; ;
with-NSU
Lupus ;;;;;;
1:250
END Arthritis ;;;;;
RTDs ;;;;;;;;;;;;;;
URTDs ;;;;;;;;;;;
days
LRTDs ;;;;;;;;;;;
mg
test instances
Treatments ;;;;;;;;;
Patient class + rel from patient to possible transportedted patients
e.g. general health, age, fear of flying etc.
(def-class topic-type () ?x
:iff-def (or (= ?x topic) (subclass-of ?x topic)))
(= ?x topic) (subclass-of ?x topic))) | Based on : , , Complete Family Health Encyclopedia
and CYC ontology
Author :
Date : 2.2002
(in-package ocml)
(in-ontology arthritis)
(def-class medical-condition ()
((has-technical-name :type string)
(has-short-name :type string)
(has-alternative-name :type string)
(susceptible-groups :type population-specification)
(reported-symptoms :type medical-symptom)
(has-site :type site)
(has-periodicity :type periodicity-index)
(has-severity :type severity-index)
(physical-examination-result :type examination-result)
(test-result :type test-result)
(can-be-treated-by :type treatment)
(sequelae :type medical-condition)
(sequela-of :type medical-condition)
(associated-with :type medical-condition)
(part-of-syndrome :type syndrome)
(possible-confusibles :type medical-condition)
(discriminators :type medical-symptom)
(prognosis :value prognosis)
)
)
(def-domain-class disorder (medical-condition)
)
)
(def-domain-class disease (medical-condition)
)
)
(def-domain-class autoimmune-disorder (disorder)
)
(def-domain-class heart-disease (disease)
((site :value heart)
)
)
(def-domain-class skin-disease (disease)
)
)
(def-domain-class joint-disease (disease)
)
(def-domain-class joint-disorder (disorder)
)
(def-domain-class rheumatic-fever (joint-disease heart-disease)
)
(def-domain-class arthritis (joint-disease)
)
(def-domain-class osteoarthritis (arthritis)
((disease-alternative-name :value degenerative-arthritis
:value osteoarthrosis)
(caused-by :value joint-wear-and-tear
:value joint-injury
:value joint-deformity
:value inflammation-from-disease)
(susceptible-groups :value older-people
:value sufferers-joint-injury)
(reported-symptoms :value joint-pain
:value joint-swelling
:value joint-stiffness
:value joint-creaking)
(site :value hips
:value knees
:value spine)
(physical-examination-result :value joint-tenderness
:value swelling
:value pain-on-movement)
(test-result :value (x-ray loss-of-cartilage positive)
:value (x-ray formation-osteophytes positive))
(can-be-treated-by :default-value (analgesic-drugs pain)
:default-value (nonsteroidal-anti-inflammatories inflammation)
:default-value (corticosteroid painful-joint)
:default-value (physiotherapy general-symptoms)
)
(discriminators :value none)
)
)
(def-domain-class severe-osteoarthritis (osteoarthritis)
((reported-symptoms :value severe-joint-pain
:value severe-swelling
:value severe-joint-stiffness)
(test-result :value (x-ray extensive-loss-of-cartilage positive)
)
)
)
(def-domain-class rheumatoid-arthritis (arthritis autoimmune-disorder)
((disease-alternative-name :value none)
(caused-by :value joint-wear-and-tear
:value joint-injury
:value joint-deformity
:value inflammation-from-disease)
(susceptible-groups :value young-adults
:value middle-aged
:value older-people)
(reported-symptoms :value joint-pain
:value joint-stiffness
:value joint-swelling
:value joint-reddening
:value joint-deformity
:value mild-fever
:value generalised-aches-and-pains)
(site :value fingers
:value wrists
:value toes
:value joints)
(has-periodcity recurrent-attacks)
(severity moderate)
1 - 2 % population
(physical-examination-result :value weakness-tendons
:value weakness-ligaments
:value weakness-muscles
:value weak-grip
:value raynauds-phenomenon
:value carpal-tunnel-syndrome
:value tenosynovitis
:value soft-nodules-beneath-skin
:value bursitis
:value bakers-cyst-behind-knee
:value fatigue
)
(test-result :value (x-ray joint-deformities positive)
:value (blood-test anaemia positive)
:value (blood-test rheumatoid-factor positive)
)
(can-be-treated-by :value (antirheumatic-drugs slow-progress)
:value (nonsteroidal-anti-inflammatories relieve-joint-pain-stiffness)
:value (corticosteroid relieve-painful-joint)
:value (immuno-suppressant-drugs suppress-immune-system)
:value (physiotherapy general-symptoms)
:value (splints relieve-hand-wrist-pain)
:value (occupational-therapy general-symptoms)
:value (diet relieve-general-symptoms)
:value (acupuncture relieve-pain)
)
(discriminators :value none)
(sequelae :value pericarditis
:value poor-circulation
:value foot-ulcers
:value hand-ulcers
:value pleural-effusion
:value pulmonary-fibrosis
:value sjogrens-syndrome
:value enlarged-lymph-nodes
:value hypersplenism-feltys-syndrome
)
)
)
(def-domain-class severe-rheumatoid-arthritis (arthritis)
((disease-name :value severe-rheumatoid-arthritis)
(reported-symptoms :value severe-joint-pain
:value severe-joint-stiffness
:value severe-joint-swelling
:value severe-joint-deformity)
(site :value hip
:value knee)
(has-periodcity frequent-attacks)
(severity severe)
(test-result :value (x-ray severe-joint-deformities positive)
)
)
)
)
(def-domain-class juvenile-rheumatoid-arthritis (arthritis)
((susceptible-groups :value children-2-4-years
:value children-around-puberty)
(rarity rare)
months ? ?
(possible-confusibles :value viral-bacterial-infection
:value rheumatic-fever
:value crohns-disease
:value ulcerative-colitis
:value haemophilia
:value sickle-cell-anaemia
:value leukaemia)
(prognosis :value condition-disappears-after-several-years
:value may-leave-deformity)
)
)
(def-domain-class stills-disease (juvenile-rheumatoid-arthritis)
((disease-alternative-name :value systemic-onset-juvenile-arthritis)
(reported-symptoms :value fever
:value rash
:value enlarged-lymph-nodes
:value abdominal-pain
:value weight-loss)
(onset illness-followed-by-joint-symptoms)
)
)
(def-domain-class polyarticular-juvenile-arthritis (juvenile-rheumatoid-arthritis)
((site :value many-joints)
)
)
(def-domain-class pauciarticular-juvenile-artritis (juvenile-rheumatoid-arthritis)
((site :value four-or-fewer-joints)
)
)
(def-domain-class seronegative-rheumatoid-arthritis (arthritis)
((test-result :value (blood-test rheumatoid-factor negative)
)
)
)
(def-domain-class ankylosing-spondylitis (arthritis)
((disease-alternative-name :value none)
(caused-by :value unknown)
(susceptible-groups :value 20-40-year-olds)
(reported-symptoms :value pain-lower-back-and-hips
:value stiffness-lower-back-and-hips
:value worse-in-morning
:value chest-pain
:value loss-appetite
20 - 40 = range / worse - in - morning = qualification
(site :value joints-between-spine-and-pelvis
:value hips
:value knees
:value ankles
:value tissues-heel)
(onset :value preceded-by-colitis
:value preceded-by-psoriasis)
1 % population
(physical-examination-result :value iritis
:value inflammation-tissues-heel
)
:value (x-ray increase-bone-density-around-sacriliac-joints positive)
:value (x-ray loss-of-spacebetween-joints-and-bony-outgrowths positive)
)
(can-be-treated-by :value (heat relieve-general-symptoms)
:value (massage relieve-general-symptoms)
:value (exercise relieve-general-symptoms)
:value (immuno-suppressant-drugs suppress-immune-system)
:value (anti-inflammatory-drugs reduce-pain-and-stiffness)
)
(discriminators :value none)
(sequelae :value ankylosis
:value kyphosis
)
)
(def-domain-class gout (arthritis)
((disease-alternative-name :value none)
(caused-by :value hyperuricaemia-leads-to-uric-acid-crystals-in-joints)
10:1 men : women
(reported-symptoms :value severe-pain
:value affects-single-joint)
(site :value joints-base-big-toe
:value wrist
:value knees
:value ankles
:value foot
:value small-joints-of-hand)
(has-periodicity
:value acute-attacks
:value (peaking-at 24-to-36-hours )
:value last-few-days
:value affects-single-joint
:value subsequent-attack-6-24-months
:value subsequent-attack-more-joints
:value subsequent-attack-constant-pain)
(physical-examination-result :value swollen-joint
:value red-joint
:value swelling-spreads
:value redness-spreads
:value tender-joint
)
(test-result :value (blood-test high-level-uric-acid positive)
:value (aspirated-fluid-joint uric-acid-crystals positive)
)
(can-be-treated-by :value (nonsteroidal-anti-inflammatories relieve-joint-pain-inflammation)
:value (colchicine relieve-joint-pain-inflammation)
:value (corticosteriod-drugs relieve-joint-pain-inflammation)
:value (allopurinal inhibit-formation-uric-acid)
:value (uricosuric-drugs increase-kidney-excretion-uric-acid)
)
(discriminators :value affects-single-joint)
(sequelae :value hypertension
)
)
)
(def-domain-class infective-arthritis (arthritis)
((disease-alternative-name :value septic-arthritis
:value pyogenic-arthritis)
(caused-by :value bacterial-invasion-of-joint-from-bacteraemia
:value bacterial-invasion-of-joint-from-infected-wound
:value tubercle-bacilli-invasion-of-joint)
(reported-symptoms :value joint-pain
:value joint-swelling)
(site :value joints)
(physical-examination-result :value swollen-joint
:value red-joint
:value swelling-spreads
:value redness-spreads
:value tender-joint
)
(sequela-of :value chickenpox
:value rubella
:value mumps
:value rheumatic-fever
:value non-specific-urethritis
)
)
)
(def-domain-class lupus (skin-disease joint-disorder autoimmune-disorder)
"causes inflammation of connective tissue - CHEP p. 650"
(
(caused-by :value autoimmune-disorder
:value inherited
:value hormonal-factors)
(triggered-by :value viral-infection
:value sunlight
:value drugs)
(susceptible-groups :value women-child-bearing-age
9:1 women : men / Chinese People of colour
(has-periodicity :value symptoms-subside-and-recur)
(severity :value variable)
(test-result :value (blood-test antibodies-attack-bodys-tissues positive)
:value (biopsy antibodies-attack-bodys-tissues positive)
)
(can-be-treated-by :value (anti-malarial-drugs skin-rash)
:value (nonsteroidal-anti-inflammatories relieve-joint-pain-stiffness)
:value (corticosteroid relieve-fever)
:value (corticosteroid relieve-pleurisy)
:value (corticosteroid relieve-neurological-symptoms)
:value (immuno-suppressant-drugs relieve-severe-neurological-symptoms)
:value (immuno-suppressant-drugs relieve-kidney-damage)
)))
(def-domain-class discoid-lupus-erythematosus (lupus)
((disease-alternative-name :value DLE)
(reported-symptoms :value rash
:value red-circular-areas-skin
:value scarring
:value hair-loss)
(site :value face
:value behind-ears
:value scalp)
(physical-examination-result :value red-circular-areas-skin
:value scarring
:value hair-loss
)
)
)
(def-domain-class systemic-lupus-erythematosus (lupus)
((disease-alternative-name :value SLE)
(prognosis :value possibly-fatal
:value prologed-survival-if-diagnosed-early
:value prologed-survival-if-kidney-problems-treated)
(reported-symptoms :value rash
:value illness
:value fatigue
:value loss-of-appetite
:value nausea
:value joint-pain
:value weight-loss)
(site :value skin
:value joints
:value kidneys)
(physical-examination-result :value red-blotchy-butterfly-shaped-rash-nose-cheeks
:value no-scarring
)
(test-result :value (blood-test anaemia positive)
:value (neuro-test neurological-problems positive)
:value (psych-test psychological-problems positive)
:value (test kidney-failure positive)
:value (test pleurisy positive)
:value (test arthritis positive)
:value (test pericarditis positive)
)
(can-be-treated-by :value (nonsteroidal-anti-inflammatories relieve-joint-pain-stiffness)
:value (corticosteroid relieve-fever)
:value (corticosteroid relieve-pleurisy)
:value (corticosteroid relieve-neurological-symptoms)
:value (immuno-suppressant-drugs relieve-severe-neurological-symptoms)
:value (immuno-suppressant-drugs relieve-kidney-damage)
:value (physiotherapy general-symptoms)
:value (splints relieve-hand-wrist-pain)
:value (occupational-therapy general-symptoms)
:value (diet relieve-general-symptoms)
:value (acupuncture relieve-pain)
)
(discriminators :value red-blotchy-butterfly-shaped-rash)
)
)
(def-domain-class respiratory-tract-disease (disease)
((disease-short-name :default-value "RTD")
)
)
(def-domain-class upper-respiratory-tract-disease (respiratory-tract-disease)
((disease-short-name :default-value "URTD")
)
)
(def-domain-class lower-respiratory-tract-disease (respiratory-tract-disease)
((disease-short-name :default-value "LRTD")
)
)
(def-domain-class influenza (upper-respiratory-tract-disease)
((disease-short-name :value flu)
(caused-by :value virus)
(spread-by :value droplet-infection)
(reported-symptoms :value fever11
:value shivering
:value headache
:value aches-and-pains
:value nasal-congestion
:value sore-throat
:value cough)
(physical-examination-result :value high-temperature)
(test-result :value none)
(can-be-treated-by :value (salicylates discomfort)
:value (codeine-linctus cough)
:value (warm-environment rest)
:value (steam-inhalers laryngitis)
)
(discriminators :value sore-throat-with-persistent-dry-cough)
)
)
(def-domain-class pneumonia (lower-respiratory-tract-disease)
)
(def-domain-class bacterial-pneumonia (pneumonia)
((reported-symptoms :value productive-cough
:value systemic-upset
:value purulent-sputum
:value mucoid-sputum)
(susceptible-groups :value ageing
:value sufferers-chronic-respiratory-disease
:value sufferers-heart-failure
:value patients-prone-to-aspiration)
(environmental-factors :value winter
:value polluted-air)
)
)
(def-domain-class pneumococcal-pneumonia (bacterial-pneumonia)
((disease-alternative-name :value acute-lobar-pneumonia)
(spread-by :value droplet-infection)
(reported-symptoms :value sudden-onset-fever
:value shivering
:value tachypnoea
:value cold-sores
:value generalized-pain
:value pleuritic-chest-pain
:value painful-dry-cough-becoming-productive-of-blood)
(physical-examination-result :value high-temperature
:value diminished-chest-movements
:value signs-of-consolidation
:value pleural-rub
:value crepitations)
(test-result :value (peripheral-blood-film polymorphonuclear-leucocytosis)
:value (blood-culture pneumococcus-growth)
:value (sputum-culture pneumococcus-growth)
:value (gram-staining diplococci-presence))
:value (amoxycillin 250)
:value (erythromycin)
)
(sequelae :value pulmonary-fibrosis
:value bronchiectasis
:value abscess
:value empyema
:value meningism
artefact of disease/ secondary result
(possible-confusibles :value pulmonary-infarction
:value haemoptysis)
(discriminators :value sore-throat-with-persistent-dry-cough)
)
)
(def-domain-class staphylococcal-pneumonia (bacterial-pneumonia)
)
(def-domain-class gram-negative-pneumonia (bacterial-pneumonia)
)
(def-domain-instance influenza1 influenza
)
(def-domain-instance pneum1 pneumococcal-pneumonia
)
(def-domain-instance arthritis1 stills-disease
)
(def-domain-instance arthritis1 stills-disease
)
(def-domain-instance seveer1 severe-rheumatoid-arthritis
)
(def-domain-class treatment ()
)
(def-domain-class drug-treatment (treatment)
)
(def-domain-class surgical-treatment (treatment)
)
(def-domain-class body-part-replacement (surgical-treatment)
)
(def-domain-class body-part-fusion (surgical-treatment)
)
(def-domain-class arthroplasty (body-part-replacement)
"replacement joint/part by metal or plastic components"
(
(site
:value hip
:value knees
:value finger
:value shoulder
:value elbow
)))
(def-domain-class arthrodesis (body-part-fusion)
((comment :value "two boness in diseased joint fused to prevent joint movement")
(needed-if :value all-other-options-fail)
(prognosis :value fusion-within-6-months
:value no-need-for-maintenance
)
)
)
1 . Classes for symptoms , tests , treatments , onset ? etc . prognosis ?
2 . Patients
3 . Diagnoses
4 . Rules patient history , tests , symptoms etc -- > disorders
(def-relation query1 (?x ?disease)
:sufficient (and
(susceptible-groups ?x ?disease)
(susceptible-groups ?x ?disease)))
(def-relation query2 (?x ?disease)
:sufficient (susceptible-groups ?x ?disease))
(def-relation query3 (?x ?c)
:sufficient (and
(can-be-treated-by ?x (arthroplasty ?rest))
(disease-name ?x ?c)))
|
2a513618b4b20637b02c00fdd235fd70f1c69cdfd8223cc0b67ce84e6b50a8bc | liquidz/build.edn | version.clj | (ns build-edn.version
(:require
[clojure.string :as str]
[malli.core :as m]
[malli.experimental :as mx]))
(def ^:private ?parsed-version
[:map {:closed true}
[:version/major 'string?]
[:version/minor 'string?]
[:version/patch 'string?]
[:version/snapshot? 'boolean?]])
(def ^:private ?version-type
[:enum
:major
:minor
:patch])
(mx/defn parse-semantic-version
:- [:maybe ?parsed-version]
[s]
(when (string? s)
(let [snapshot? (str/ends-with? s "-SNAPSHOT")
[_ major minor patch] (->> (str/replace s #"-SNAPSHOT$" "")
(re-seq #"^([^.]+)\.([^.]+)\.([^.]+)$")
(first))
parsed {:version/major major
:version/minor minor
:version/patch patch
:version/snapshot? snapshot?}]
(when (m/validate ?parsed-version parsed)
parsed))))
(mx/defn to-semantic-version
:- 'string?
[{:version/keys [major minor patch snapshot?]} :- ?parsed-version]
(cond-> (format "%s.%s.%s" major minor patch)
snapshot? (str "-SNAPSHOT")))
(mx/defn bump-version
:- [:maybe ?parsed-version]
([parsed-version]
(bump-version parsed-version :patch))
([parsed-version :- ?parsed-version
version-type :- ?version-type]
(let [target-key (keyword "version" (name version-type))]
(when-let [new-version (some-> (get parsed-version target-key)
parse-long inc str)]
(assoc parsed-version target-key new-version)))))
(mx/defn add-snapshot
:- ?parsed-version
[parsed-version :- ?parsed-version]
(assoc parsed-version :version/snapshot? true))
(mx/defn remove-snapshot
:- ?parsed-version
[parsed-version :- ?parsed-version]
(assoc parsed-version :version/snapshot? false))
| null | https://raw.githubusercontent.com/liquidz/build.edn/206383012a36f8009d6dc7b1b677c9ff67f8d521/src/build_edn/version.clj | clojure | (ns build-edn.version
(:require
[clojure.string :as str]
[malli.core :as m]
[malli.experimental :as mx]))
(def ^:private ?parsed-version
[:map {:closed true}
[:version/major 'string?]
[:version/minor 'string?]
[:version/patch 'string?]
[:version/snapshot? 'boolean?]])
(def ^:private ?version-type
[:enum
:major
:minor
:patch])
(mx/defn parse-semantic-version
:- [:maybe ?parsed-version]
[s]
(when (string? s)
(let [snapshot? (str/ends-with? s "-SNAPSHOT")
[_ major minor patch] (->> (str/replace s #"-SNAPSHOT$" "")
(re-seq #"^([^.]+)\.([^.]+)\.([^.]+)$")
(first))
parsed {:version/major major
:version/minor minor
:version/patch patch
:version/snapshot? snapshot?}]
(when (m/validate ?parsed-version parsed)
parsed))))
(mx/defn to-semantic-version
:- 'string?
[{:version/keys [major minor patch snapshot?]} :- ?parsed-version]
(cond-> (format "%s.%s.%s" major minor patch)
snapshot? (str "-SNAPSHOT")))
(mx/defn bump-version
:- [:maybe ?parsed-version]
([parsed-version]
(bump-version parsed-version :patch))
([parsed-version :- ?parsed-version
version-type :- ?version-type]
(let [target-key (keyword "version" (name version-type))]
(when-let [new-version (some-> (get parsed-version target-key)
parse-long inc str)]
(assoc parsed-version target-key new-version)))))
(mx/defn add-snapshot
:- ?parsed-version
[parsed-version :- ?parsed-version]
(assoc parsed-version :version/snapshot? true))
(mx/defn remove-snapshot
:- ?parsed-version
[parsed-version :- ?parsed-version]
(assoc parsed-version :version/snapshot? false))
| |
969869d4e887661bef642ce1a784e444fe7059164607966c72c0eeadc500cb4c | ocaml/odoc | markup.mli | * examples .
* The OCaml manual gives a
{ { : #ss:ocamldoc-placement}comprehensive example }
of comment placement . This has been replicated in the module below to
show how this is rendered by [ odoc ] .
{{:#ss:ocamldoc-placement}comprehensive example}
of comment placement. This has been replicated in the module Foo below to
show how this is rendered by [odoc]. *)
module type Foo = sig
* The first special comment of the file is the comment associated
with the whole module .
with the whole module.*)
(** Special comments can be placed between elements and are kept
by the OCamldoc tool, but are not associated to any element.
[@]-tags in these comments are ignored.*)
(*******************************************************************)
* Comments like the one above , with more than two asterisks ,
are ignored .
are ignored. *)
(** The comment for function f. *)
val f : int -> int -> int
(** The continuation of the comment for function f. *)
(* Hello, I'm a simple comment :-) *)
exception My_exception of (int -> int) * int
(** Comment for exception My_exception, even with a simple comment
between the special comment and the exception.*)
(** Comment for type weather *)
type weather =
| Rain of int (** The comment for constructor Rain *)
* The comment for constructor
* Comment for type weather2
type weather2 =
| Rain of int (** The comment for constructor Rain *)
* The comment for constructor
(** I can continue the comment for type weather2 here
because there is already a comment associated to the last constructor.*)
* The comment for type my_record
type my_record = {
foo : int; (** Comment for field foo *)
bar : string; (** Comment for field bar *)
}
* Continuation of comment for type my_record
(** Comment for foo *)
val foo : string
(** This comment is associated to foo and not to bar. *)
val bar : string
(** This comment is associated to bar. *)
class cl :
object
(** Interesting information about cl *)
end
* The comment for class my_class
class my_class :
object
inherit cl
(** A comment to describe inheritance from cl *)
val mutable tutu : string
(** The comment for attribute tutu *)
val toto : int
(** The comment for attribute toto. *)
(** This comment is not attached to titi since
there is a blank line before titi, but is kept
as a comment in the class. *)
val titi : string
method toto : string
(** Comment for method toto *)
method m : float -> int
(** Comment for method m *)
end
(** The comment for the class type my_class_type *)
class type my_class_type =
object
val mutable x : int
(** The comment for variable x. *)
method m : int -> int
(** The comment for method m. *)
end
* The comment for module
module Foo : sig
val x : int
(** The comment for x *)
(** A special comment that is kept but not associated to any element *)
end
(** The comment for module type my_module_type. *)
module type my_module_type = sig
val x : int
(** The comment for value x. *)
(** The comment for module M. *)
module M : sig
val y : int
(** The comment for value y. *)
(* ... *)
end
end
end
module Stop : sig
(** This module demonstrates the use of stop comments ([(**/**)]) *)
class type foo =
object
method m : string
(** comment for method m *)
(**/**)
method bar : int
(** This method won't appear in the documentation *)
end
val foo : string
(** This value appears in the documentation, since the Stop special comment
in the class does not affect the parent module of the class.*)
(**/**)
val bar : string
(** The value bar does not appear in the documentation.*)
(**/**)
type t = string
(** The type t appears since in the documentation since the previous stop comment
toggled off the "no documentation mode". *)
end
* { 2 Scoping rules }
module Scope : sig
(** In this floating comment I can refer to type {!t} and value {!v}
declared later in the signature *)
type t
val v : t
val x : int
val y : int
module A : sig
(** In this module I can refer to val {!x} declared above as well as
type {!u} declared later in the parent module. Elements declared
in this signature take priority, so {!y} refers to {!A.y} as
opposed to the [y] declared in the parent signature.
@see 'markup.mli' for a good time *)
val y : string
end
type u
end
module Preamble_examples : sig
(** This module demonstrates the various ways that preambles are calculated *)
* This is the comment attached to the declaration of Hidden__Module
module Hidden__Module : sig
* This is the top comment declared in the module Hidden__module .
This is the second paragraph in the module Hidden__module .
@canonical Odoc_examples . . Module
This is the second paragraph in the module Hidden__module.
@canonical Odoc_examples.Markup.Module *)
type t
(** This is a comment on type t *)
end
module Module = Hidden__Module
* This comment is on the declaration of Module as an alias of Hidden__Module
* This is the comment attached to the declaration of module Hidden__Module2
module Hidden__Module2 : sig
* This is the top comment declared in the module Hidden__module2 .
This is the second paragraph in the module Hidden__module2 .
@canonical Odoc_examples . .
This is the second paragraph in the module Hidden__module2.
@canonical Odoc_examples.Markup.Module2 *)
type t
(** This is a comment on type t *)
end
module Module2 = Hidden__Module2
module Nonhidden_module : sig
* This is the top comment declared in the module Hidden__module2 .
This is the second paragraph in the module Hidden__module2 .
This is the second paragraph in the module Hidden__module2.
*)
end
module Module3 = Nonhidden_module
* This comment is on the declaration of Module3 as an alias of Nonhidden_module
module Nonhidden_module2 : sig
* This is the top comment declared in the module Hidden__module2 .
This is the second paragraph in the module Hidden__module2 .
This is the second paragraph in the module Hidden__module2.
*)
end
module Module4 = Nonhidden_module2
(** The [modules] special reference can be used to refer to a list of modules.
It uses the synopsis from the modules *)
end
| null | https://raw.githubusercontent.com/ocaml/odoc/37196b0066c0382619676cecd335d332b8cc9022/doc/examples/markup.mli | ocaml | * Special comments can be placed between elements and are kept
by the OCamldoc tool, but are not associated to any element.
[@]-tags in these comments are ignored.
*****************************************************************
* The comment for function f.
* The continuation of the comment for function f.
Hello, I'm a simple comment :-)
* Comment for exception My_exception, even with a simple comment
between the special comment and the exception.
* Comment for type weather
* The comment for constructor Rain
* The comment for constructor Rain
* I can continue the comment for type weather2 here
because there is already a comment associated to the last constructor.
* Comment for field foo
* Comment for field bar
* Comment for foo
* This comment is associated to foo and not to bar.
* This comment is associated to bar.
* Interesting information about cl
* A comment to describe inheritance from cl
* The comment for attribute tutu
* The comment for attribute toto.
* This comment is not attached to titi since
there is a blank line before titi, but is kept
as a comment in the class.
* Comment for method toto
* Comment for method m
* The comment for the class type my_class_type
* The comment for variable x.
* The comment for method m.
* The comment for x
* A special comment that is kept but not associated to any element
* The comment for module type my_module_type.
* The comment for value x.
* The comment for module M.
* The comment for value y.
...
* This module demonstrates the use of stop comments ([(**/*
* comment for method m
*/*
* This method won't appear in the documentation
* This value appears in the documentation, since the Stop special comment
in the class does not affect the parent module of the class.
*/*
* The value bar does not appear in the documentation.
*/*
* The type t appears since in the documentation since the previous stop comment
toggled off the "no documentation mode".
* In this floating comment I can refer to type {!t} and value {!v}
declared later in the signature
* In this module I can refer to val {!x} declared above as well as
type {!u} declared later in the parent module. Elements declared
in this signature take priority, so {!y} refers to {!A.y} as
opposed to the [y] declared in the parent signature.
@see 'markup.mli' for a good time
* This module demonstrates the various ways that preambles are calculated
* This is a comment on type t
* This is a comment on type t
* The [modules] special reference can be used to refer to a list of modules.
It uses the synopsis from the modules | * examples .
* The OCaml manual gives a
{ { : #ss:ocamldoc-placement}comprehensive example }
of comment placement . This has been replicated in the module below to
show how this is rendered by [ odoc ] .
{{:#ss:ocamldoc-placement}comprehensive example}
of comment placement. This has been replicated in the module Foo below to
show how this is rendered by [odoc]. *)
module type Foo = sig
* The first special comment of the file is the comment associated
with the whole module .
with the whole module.*)
* Comments like the one above , with more than two asterisks ,
are ignored .
are ignored. *)
val f : int -> int -> int
exception My_exception of (int -> int) * int
type weather =
* The comment for constructor
* Comment for type weather2
type weather2 =
* The comment for constructor
* The comment for type my_record
type my_record = {
}
* Continuation of comment for type my_record
val foo : string
val bar : string
class cl :
object
end
* The comment for class my_class
class my_class :
object
inherit cl
val mutable tutu : string
val toto : int
val titi : string
method toto : string
method m : float -> int
end
class type my_class_type =
object
val mutable x : int
method m : int -> int
end
* The comment for module
module Foo : sig
val x : int
end
module type my_module_type = sig
val x : int
module M : sig
val y : int
end
end
end
module Stop : sig
class type foo =
object
method m : string
method bar : int
end
val foo : string
val bar : string
type t = string
end
* { 2 Scoping rules }
module Scope : sig
type t
val v : t
val x : int
val y : int
module A : sig
val y : string
end
type u
end
module Preamble_examples : sig
* This is the comment attached to the declaration of Hidden__Module
module Hidden__Module : sig
* This is the top comment declared in the module Hidden__module .
This is the second paragraph in the module Hidden__module .
@canonical Odoc_examples . . Module
This is the second paragraph in the module Hidden__module.
@canonical Odoc_examples.Markup.Module *)
type t
end
module Module = Hidden__Module
* This comment is on the declaration of Module as an alias of Hidden__Module
* This is the comment attached to the declaration of module Hidden__Module2
module Hidden__Module2 : sig
* This is the top comment declared in the module Hidden__module2 .
This is the second paragraph in the module Hidden__module2 .
@canonical Odoc_examples . .
This is the second paragraph in the module Hidden__module2.
@canonical Odoc_examples.Markup.Module2 *)
type t
end
module Module2 = Hidden__Module2
module Nonhidden_module : sig
* This is the top comment declared in the module Hidden__module2 .
This is the second paragraph in the module Hidden__module2 .
This is the second paragraph in the module Hidden__module2.
*)
end
module Module3 = Nonhidden_module
* This comment is on the declaration of Module3 as an alias of Nonhidden_module
module Nonhidden_module2 : sig
* This is the top comment declared in the module Hidden__module2 .
This is the second paragraph in the module Hidden__module2 .
This is the second paragraph in the module Hidden__module2.
*)
end
module Module4 = Nonhidden_module2
end
|
59f47095f23d09990da1924e19ceef0a4f1cd92cb05122dcd2479ceffffe4f77 | racket/drracket | get-defs.rkt | #lang racket/base
(require racket/class
racket/function
racket/list
racket/contract
string-constants)
(provide (struct-out defn)
get-definitions
get-define-popup-info
(struct-out define-popup-info))
;; defn = (make-defn number string number number)
(define-struct defn (indent name start-pos end-pos)
#:mutable #:transparent)
(struct define-popup-info (prefix long-name short-name) #:transparent)
;; get-define-popup-info :
;; valid-configurations-as-specified-in-the-drscheme:defined-popup-docs
;; -> (or/c (non-empty-listof define-popup-info) #f)
(define (get-define-popup-info cap)
(cond
[(not cap) #f]
[((cons/c string? string?) cap)
(list (define-popup-info (car cap) (cdr cap) "δ"))]
[((list/c string? string? string?) cap)
(list (define-popup-info (list-ref cap 0) (list-ref cap 1) (list-ref cap 2)))]
[((listof (list/c string? string? string?)) cap)
(for/list ([cap (in-list cap)])
(define-popup-info (list-ref cap 0) (list-ref cap 1) (list-ref cap 2)))]
[else #f]))
get - definitions : string boolean text - > ( )
(define (get-definitions the-define-popup-infos indent? text)
(define min-indent 0)
pos :
latest - positions : ( listof ( or / c natural + inf.0 # f ) )
;; latest positions are where we found each of these strings in the last go;
;; with a #f on the one we actually returned as the next result last time
( or all # fs if this is the first time )
;; in this go, we'll fill in the #fs and then pick the smallest to return
(define (find-next pos latest-positions)
(define filled-in-positions
(for/list ([latest-position (in-list latest-positions)]
[a-define-popup-info (in-list the-define-popup-infos)])
(cond
[latest-position latest-position]
[else
(define tag-string (define-popup-info-prefix a-define-popup-info))
(let loop ([pos pos])
(define search-pos-result (send text find-string tag-string 'forward pos 'eof #t #f))
(cond
[(and search-pos-result
(in-semicolon-comment? text search-pos-result))
(if (< search-pos-result (send text last-position))
(loop (+ search-pos-result 1))
+inf.0)]
[search-pos-result search-pos-result]
[else +inf.0]))])))
(define-values (smallest-i smallest-pos)
(for/fold ([smallest-i #f] [smallest-pos #f])
([pos (in-list filled-in-positions)]
[i (in-naturals)])
(cond
[(not smallest-i) (values i pos)]
[(< pos smallest-pos) (values i pos)]
[else (values smallest-i smallest-pos)])))
(when (and smallest-pos (= +inf.0 smallest-pos))
(set! smallest-pos #f)
(set! smallest-i #f))
(define final-positions
(for/list ([position (in-list filled-in-positions)]
[i (in-naturals)])
(cond
[(equal? i smallest-i) #f]
[else position])))
(values smallest-pos
(and smallest-i
(string-length (define-popup-info-prefix
(list-ref the-define-popup-infos smallest-i))))
final-positions))
(define defs
(let loop ([pos 0][find-state (map (λ (x) #f) the-define-popup-infos)])
(define-values (defn-pos tag-length new-find-state) (find-next pos find-state))
(cond
[(not defn-pos) null]
[else
(define indent (get-defn-indent text defn-pos))
(define name (get-defn-name text (+ defn-pos tag-length)))
(set! min-indent (min indent min-indent))
(define next-defn (make-defn indent (or name (string-constant end-of-buffer-define))
defn-pos defn-pos))
(cons next-defn
(loop (+ defn-pos tag-length)
new-find-state))])))
update end - pos 's based on the start pos of the next defn
(unless (null? defs)
(let loop ([first (car defs)]
[defs (cdr defs)])
(cond
[(null? defs)
(set-defn-end-pos! first (send text last-position))]
[else (set-defn-end-pos! first (max (- (defn-start-pos (car defs)) 1)
(defn-start-pos first)))
(loop (car defs) (cdr defs))])))
(when indent?
(for ([defn (in-list defs)])
(set-defn-name! defn
(string-append
(apply string
(vector->list
(make-vector
(- (defn-indent defn) min-indent) #\space)))
(defn-name defn)))))
defs)
;; in-semicolon-comment: text number -> boolean
;; returns #t if `define-start-pos' is in a semicolon comment and #f otherwise
(define (in-semicolon-comment? text define-start-pos)
(let* ([para (send text position-paragraph define-start-pos)]
[start (send text paragraph-start-position para)])
(let loop ([pos start])
(cond
[(pos . >= . define-start-pos) #f]
[(char=? #\; (send text get-character pos)) #t]
[else (loop (+ pos 1))]))))
;; get-defn-indent : text number -> number
;; returns the amount to indent a particular definition
(define (get-defn-indent text pos)
(let* ([para (send text position-paragraph pos)]
[para-start (send text paragraph-start-position para #t)])
(let loop ([c-pos para-start]
[offset 0])
(if (< c-pos pos)
(let ([char (send text get-character c-pos)])
(cond
[(char=? char #\tab)
(loop (+ c-pos 1) (+ offset (- 8 (modulo offset 8))))]
[else
(loop (+ c-pos 1) (+ offset 1))]))
offset))))
;; whitespace-or-paren?
(define (whitespace-or-paren? char)
(or (char=? #\) char)
(char=? #\( char)
(char=? #\] char)
(char=? #\[ char)
(char-whitespace? char)))
;; skip : text number (char -> bool) -> number
;; Skips characters recognized by `skip?'
(define (skip text pos skip?)
(let loop ([pos pos])
(if (>= pos (send text last-position))
(send text last-position)
(let ([char (send text get-character pos)])
(cond
[(skip? char)
(loop (+ pos 1))]
[else pos])))))
;; skip-to-whitespace/paren : text number -> number
;; skips to the next parenthesis or whitespace after `pos', returns that position.
(define (skip-to-whitespace/paren text pos)
(skip text pos (negate whitespace-or-paren?)))
;; skip-whitespace/paren : text number -> number
;; skips past any parenthesis or whitespace
(define (skip-whitespace/paren text pos)
(skip text pos whitespace-or-paren?))
;; skip-past-non-whitespace : text number -> number
skips to the first whitespace character after the first non - whitespace character
(define (skip-past-non-whitespace text pos)
(skip text (skip text pos char-whitespace?) (negate char-whitespace?)))
(define (forward-to-next-token text pos)
(send text forward-match pos (send text last-position)))
;; get-defn-name : text number -> string
;; returns the name of the definition starting at `define-pos',
assuming that the bound name is the first symbol to appear
;; after the one beginning at `define-pos'. This heuristic
;; usually finds the bound name, but it breaks for Redex
;; metafunction definitions (thus the hack below).
(define (get-defn-name text define-pos)
(define end-suffix-pos (skip-to-whitespace/paren text define-pos))
(define suffix (send text get-text define-pos end-suffix-pos))
(define end-header-pos
(cond [(regexp-match #rx"^-metafunction(/extension)?$" suffix)
=> (λ (m)
(let ([extension? (second m)])
(skip-past-non-whitespace
text
(if extension?
(skip-past-non-whitespace text end-suffix-pos)
end-suffix-pos))))]
[else end-suffix-pos]))
(define start-name-pos (skip-whitespace/paren text end-header-pos))
(define end-name-pos (forward-to-next-token text start-name-pos))
(cond
[(not end-name-pos) #f]
[(>= end-suffix-pos (send text last-position))
(string-constant end-of-buffer-define)]
[else (send text get-text start-name-pos end-name-pos)]))
;; more tests are in tests/drracket/get-defs-test
(module+ test
(require rackunit racket/gui/base framework)
(let ()
(define t (new racket:text%))
(send t insert "(define (f x) x)\n")
(send t insert " (define (g x) x)\n")
(send t insert "(module m racket/base)\n")
(check-equal?
(get-definitions
(list (define-popup-info "(define" "(define ...)" "δ")
(define-popup-info "(module" "(module ...)" "ρ"))
#t
t)
(list (defn 0 "f" 0 18)
(defn 2 " g" 19 35)
(defn 0 "m" 36 59)))
(check-equal?
(get-definitions
(list (define-popup-info "(module" "(module ...)" "ρ"))
#t
t)
(list (defn 0 "m" 36 59))))
(let ()
(define t (new racket:text%))
(send t insert "(define-metafunction L\n")
(send t insert " M : any -> any\n")
(send t insert " [(M any_1) any_1])\n")
(check-equal?
(get-definitions
(list (define-popup-info "(define" "(define ...)" "δ"))
#t
t)
(list (defn 0 "M" 0 61))))
(let ()
(define t (new racket:text%))
(send t insert "(define-metafunction L\n")
(send t insert " [(M any_1) any_1])\n")
(check-equal?
(get-definitions
(list (define-popup-info "(define" "(define ...)" "δ"))
#t
t)
(list (defn 0 "M" 0 44))))
(let ()
(define t (new racket:text%))
(send t insert "(define (|(| x) x)\n")
(check-equal?
(get-definitions
(list (define-popup-info "(define" "(define ...)" "δ"))
#t
t)
(list (defn 0 "|(|" 0 19))))
(let ()
(define t (new racket:text%))
(send t insert "(define)\n")
(check-equal?
(get-definitions
(list (define-popup-info "(define" "(define ...)" "δ"))
#t
t)
(list (defn 0 "<< end of buffer >>" 0 9))))
)
| null | https://raw.githubusercontent.com/racket/drracket/2d7c2cded99e630a69f05fb135d1bf7543096a23/drracket/drracket/private/get-defs.rkt | racket | defn = (make-defn number string number number)
get-define-popup-info :
valid-configurations-as-specified-in-the-drscheme:defined-popup-docs
-> (or/c (non-empty-listof define-popup-info) #f)
latest positions are where we found each of these strings in the last go;
with a #f on the one we actually returned as the next result last time
in this go, we'll fill in the #fs and then pick the smallest to return
in-semicolon-comment: text number -> boolean
returns #t if `define-start-pos' is in a semicolon comment and #f otherwise
(send text get-character pos)) #t]
get-defn-indent : text number -> number
returns the amount to indent a particular definition
whitespace-or-paren?
skip : text number (char -> bool) -> number
Skips characters recognized by `skip?'
skip-to-whitespace/paren : text number -> number
skips to the next parenthesis or whitespace after `pos', returns that position.
skip-whitespace/paren : text number -> number
skips past any parenthesis or whitespace
skip-past-non-whitespace : text number -> number
get-defn-name : text number -> string
returns the name of the definition starting at `define-pos',
after the one beginning at `define-pos'. This heuristic
usually finds the bound name, but it breaks for Redex
metafunction definitions (thus the hack below).
more tests are in tests/drracket/get-defs-test | #lang racket/base
(require racket/class
racket/function
racket/list
racket/contract
string-constants)
(provide (struct-out defn)
get-definitions
get-define-popup-info
(struct-out define-popup-info))
(define-struct defn (indent name start-pos end-pos)
#:mutable #:transparent)
(struct define-popup-info (prefix long-name short-name) #:transparent)
(define (get-define-popup-info cap)
(cond
[(not cap) #f]
[((cons/c string? string?) cap)
(list (define-popup-info (car cap) (cdr cap) "δ"))]
[((list/c string? string? string?) cap)
(list (define-popup-info (list-ref cap 0) (list-ref cap 1) (list-ref cap 2)))]
[((listof (list/c string? string? string?)) cap)
(for/list ([cap (in-list cap)])
(define-popup-info (list-ref cap 0) (list-ref cap 1) (list-ref cap 2)))]
[else #f]))
get - definitions : string boolean text - > ( )
(define (get-definitions the-define-popup-infos indent? text)
(define min-indent 0)
pos :
latest - positions : ( listof ( or / c natural + inf.0 # f ) )
( or all # fs if this is the first time )
(define (find-next pos latest-positions)
(define filled-in-positions
(for/list ([latest-position (in-list latest-positions)]
[a-define-popup-info (in-list the-define-popup-infos)])
(cond
[latest-position latest-position]
[else
(define tag-string (define-popup-info-prefix a-define-popup-info))
(let loop ([pos pos])
(define search-pos-result (send text find-string tag-string 'forward pos 'eof #t #f))
(cond
[(and search-pos-result
(in-semicolon-comment? text search-pos-result))
(if (< search-pos-result (send text last-position))
(loop (+ search-pos-result 1))
+inf.0)]
[search-pos-result search-pos-result]
[else +inf.0]))])))
(define-values (smallest-i smallest-pos)
(for/fold ([smallest-i #f] [smallest-pos #f])
([pos (in-list filled-in-positions)]
[i (in-naturals)])
(cond
[(not smallest-i) (values i pos)]
[(< pos smallest-pos) (values i pos)]
[else (values smallest-i smallest-pos)])))
(when (and smallest-pos (= +inf.0 smallest-pos))
(set! smallest-pos #f)
(set! smallest-i #f))
(define final-positions
(for/list ([position (in-list filled-in-positions)]
[i (in-naturals)])
(cond
[(equal? i smallest-i) #f]
[else position])))
(values smallest-pos
(and smallest-i
(string-length (define-popup-info-prefix
(list-ref the-define-popup-infos smallest-i))))
final-positions))
(define defs
(let loop ([pos 0][find-state (map (λ (x) #f) the-define-popup-infos)])
(define-values (defn-pos tag-length new-find-state) (find-next pos find-state))
(cond
[(not defn-pos) null]
[else
(define indent (get-defn-indent text defn-pos))
(define name (get-defn-name text (+ defn-pos tag-length)))
(set! min-indent (min indent min-indent))
(define next-defn (make-defn indent (or name (string-constant end-of-buffer-define))
defn-pos defn-pos))
(cons next-defn
(loop (+ defn-pos tag-length)
new-find-state))])))
update end - pos 's based on the start pos of the next defn
(unless (null? defs)
(let loop ([first (car defs)]
[defs (cdr defs)])
(cond
[(null? defs)
(set-defn-end-pos! first (send text last-position))]
[else (set-defn-end-pos! first (max (- (defn-start-pos (car defs)) 1)
(defn-start-pos first)))
(loop (car defs) (cdr defs))])))
(when indent?
(for ([defn (in-list defs)])
(set-defn-name! defn
(string-append
(apply string
(vector->list
(make-vector
(- (defn-indent defn) min-indent) #\space)))
(defn-name defn)))))
defs)
(define (in-semicolon-comment? text define-start-pos)
(let* ([para (send text position-paragraph define-start-pos)]
[start (send text paragraph-start-position para)])
(let loop ([pos start])
(cond
[(pos . >= . define-start-pos) #f]
[else (loop (+ pos 1))]))))
(define (get-defn-indent text pos)
(let* ([para (send text position-paragraph pos)]
[para-start (send text paragraph-start-position para #t)])
(let loop ([c-pos para-start]
[offset 0])
(if (< c-pos pos)
(let ([char (send text get-character c-pos)])
(cond
[(char=? char #\tab)
(loop (+ c-pos 1) (+ offset (- 8 (modulo offset 8))))]
[else
(loop (+ c-pos 1) (+ offset 1))]))
offset))))
(define (whitespace-or-paren? char)
(or (char=? #\) char)
(char=? #\( char)
(char=? #\] char)
(char=? #\[ char)
(char-whitespace? char)))
(define (skip text pos skip?)
(let loop ([pos pos])
(if (>= pos (send text last-position))
(send text last-position)
(let ([char (send text get-character pos)])
(cond
[(skip? char)
(loop (+ pos 1))]
[else pos])))))
(define (skip-to-whitespace/paren text pos)
(skip text pos (negate whitespace-or-paren?)))
(define (skip-whitespace/paren text pos)
(skip text pos whitespace-or-paren?))
skips to the first whitespace character after the first non - whitespace character
(define (skip-past-non-whitespace text pos)
(skip text (skip text pos char-whitespace?) (negate char-whitespace?)))
(define (forward-to-next-token text pos)
(send text forward-match pos (send text last-position)))
assuming that the bound name is the first symbol to appear
(define (get-defn-name text define-pos)
(define end-suffix-pos (skip-to-whitespace/paren text define-pos))
(define suffix (send text get-text define-pos end-suffix-pos))
(define end-header-pos
(cond [(regexp-match #rx"^-metafunction(/extension)?$" suffix)
=> (λ (m)
(let ([extension? (second m)])
(skip-past-non-whitespace
text
(if extension?
(skip-past-non-whitespace text end-suffix-pos)
end-suffix-pos))))]
[else end-suffix-pos]))
(define start-name-pos (skip-whitespace/paren text end-header-pos))
(define end-name-pos (forward-to-next-token text start-name-pos))
(cond
[(not end-name-pos) #f]
[(>= end-suffix-pos (send text last-position))
(string-constant end-of-buffer-define)]
[else (send text get-text start-name-pos end-name-pos)]))
(module+ test
(require rackunit racket/gui/base framework)
(let ()
(define t (new racket:text%))
(send t insert "(define (f x) x)\n")
(send t insert " (define (g x) x)\n")
(send t insert "(module m racket/base)\n")
(check-equal?
(get-definitions
(list (define-popup-info "(define" "(define ...)" "δ")
(define-popup-info "(module" "(module ...)" "ρ"))
#t
t)
(list (defn 0 "f" 0 18)
(defn 2 " g" 19 35)
(defn 0 "m" 36 59)))
(check-equal?
(get-definitions
(list (define-popup-info "(module" "(module ...)" "ρ"))
#t
t)
(list (defn 0 "m" 36 59))))
(let ()
(define t (new racket:text%))
(send t insert "(define-metafunction L\n")
(send t insert " M : any -> any\n")
(send t insert " [(M any_1) any_1])\n")
(check-equal?
(get-definitions
(list (define-popup-info "(define" "(define ...)" "δ"))
#t
t)
(list (defn 0 "M" 0 61))))
(let ()
(define t (new racket:text%))
(send t insert "(define-metafunction L\n")
(send t insert " [(M any_1) any_1])\n")
(check-equal?
(get-definitions
(list (define-popup-info "(define" "(define ...)" "δ"))
#t
t)
(list (defn 0 "M" 0 44))))
(let ()
(define t (new racket:text%))
(send t insert "(define (|(| x) x)\n")
(check-equal?
(get-definitions
(list (define-popup-info "(define" "(define ...)" "δ"))
#t
t)
(list (defn 0 "|(|" 0 19))))
(let ()
(define t (new racket:text%))
(send t insert "(define)\n")
(check-equal?
(get-definitions
(list (define-popup-info "(define" "(define ...)" "δ"))
#t
t)
(list (defn 0 "<< end of buffer >>" 0 9))))
)
|
d76c6cd234c1aa5ad435dea125d327dd13bea6736ebc45dbf9152a468202ba39 | 8c6794b6/guile-tjit | ra.scm | ;;;; Assign resiters to IR
Copyright ( C ) 2015 , 2016 Free Software Foundation , Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation ; either
version 3 of the License , or ( at your option ) any later version .
;;;;
;;;; This library is distributed in the hope that it will be useful,
;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;;;; Lesser General Public License for more details.
;;;;
You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , MA
02110 - 1301 USA
;;;;
;;; Commentary:
;;;
Assign registers to ANF IR , compile to list of primitive operations .
;;; Applying naive strategy to assign registers to locals, does nothing
;;; sophisticated such as linear-scan, binpacking, graph coloring, etc.
;;;
;;; Code:
(define-module (language trace ra)
#:use-module (ice-9 format)
#:use-module (ice-9 match)
#:use-module (srfi srfi-9)
#:use-module (srfi srfi-11)
#:use-module (system foreign)
#:use-module (system vm native debug)
#:use-module (language trace assembler)
#:use-module (language trace error)
#:use-module (language trace fragment)
#:use-module (language trace env)
#:use-module (language trace primitives)
#:use-module (language trace registers)
#:use-module (language trace snapshot)
#:use-module (language trace types)
#:use-module (language trace variables)
#:export ($primops
primops?
primops-entry
primops-loop
primops-nspills
anf->primops
make-empty-storage
storage-ref
storage-set!
fold-storage
volatiles-in-storage))
;;;; Data types
;; Record type to hold lists of primitives.
(define-record-type $primops
(make-primops entry loop nspills storage)
primops?
;; List of primitives for entry clause.
(entry primops-entry)
;; List of primitives for loop body.
(loop primops-loop)
;; Number of spilled variables.
(nspills primops-nspills)
;; Hash-table containing variable information.
(storage primops-storage))
(define-syntax-rule (%make-storage alist)
(cons 'storage alist))
(define-syntax-rule (storage-alist storage)
(cdr storage))
(define-syntax-rule (set-storage-alist! storage alist)
(set-cdr! storage alist))
(define-inlinable (storage-ref storage key)
(assq-ref (storage-alist storage) key))
(define-inlinable (storage-set! storage key* val)
(let ((key key*))
(cond
((assq key (storage-alist storage))
=> (lambda (handle)
(set-cdr! handle val)))
(else
(set-storage-alist! storage (cons (cons key val)
(storage-alist storage)))))))
(define-inlinable (fold-storage proc init* storage)
(let lp ((alist (storage-alist storage)) (init init*))
(if (null? alist)
init
(let ((kv (car alist)))
(lp (cdr alist) (proc (car kv) (cdr kv) init))))))
(define (make-empty-storage)
(%make-storage '()))
(define (make-storage env free-gprs free-fprs mem-idx)
(let ((alist '())
(parent-storage (and=> (env-parent-fragment env) fragment-storage)))
(%make-storage
(if parent-storage
(let lp ((parent-alist (storage-alist parent-storage))
(acc '()))
(match parent-alist
(((k . v) . parent-alist)
(cond
((not v) (lp parent-alist acc))
((gpr? v)
(let ((i (ref-value v)))
(when (<= 0 i)
(vector-set! free-gprs i #f))
(lp parent-alist (acons k v acc))))
((fpr? v)
(let ((i (ref-value v)))
(when (<= 0 i)
(vector-set! free-fprs i #f))
(lp parent-alist (acons k v acc))))
((memory? v)
(let ((i (ref-value v)))
(when (<= (variable-ref mem-idx) i)
(variable-set! mem-idx (+ i 1)))
(lp parent-alist (acons k v acc))))
(else
(failure 'make-storage "unknown var ~s" v))))
(() acc)))
(let* ((alist (acons (make-tmpvar 0) (make-gpr -1) alist))
(alist (acons (make-tmpvar 1) (make-gpr -2) alist))
(alist (acons (make-tmpvar 2) (make-gpr -3) alist))
(alist (acons (make-tmpvar/f 0) (make-fpr -1) alist))
(aistt (acons (make-tmpvar/f 1) (make-fpr -2) alist))
(alist (acons (make-tmpvar/f 2) (make-fpr -3) alist))
(alist (acons (make-spill 0) (make-memory -1) alist)))
alist)))))
(define (volatiles-in-storage storage)
(fold-storage
(lambda (k reg acc)
(if (or (and reg (gpr? reg)
(<= *num-non-volatiles* (ref-value reg)))
(and reg (fpr? reg)
(<= 0 (ref-value reg))))
(cons reg acc)
acc))
'() storage))
;;;; Auxiliary
(define-syntax-rule (make-initial-free-gprs)
(make-vector *num-gpr* #t))
(define-syntax-rule (make-initial-free-fprs)
(make-vector *num-fpr* #t))
(define-syntax define-register-acquire!
(syntax-rules ()
((_ name num constructor)
(define (name free-regs)
(let lp ((i 0))
(cond
((= i num) #f)
((vector-ref free-regs i)
(let ((ret (constructor i)))
(vector-set! free-regs i #f)
ret))
(else (lp (+ i 1)))))))))
(define-register-acquire! acquire-gpr! *num-gpr* make-gpr)
(define-register-acquire! acquire-fpr! *num-fpr* make-fpr)
(define-syntax-parameter mem-idx
(lambda (x)
(syntax-violation 'mem-idx "mem-idx undefined" x)))
(define-syntax-parameter free-gprs
(lambda (x)
(syntax-violation 'free-gprs "free-gprs undefined" x)))
(define-syntax-parameter free-fprs
(lambda (x)
(syntax-violation 'free-fprs "free-fprs undefined" x)))
(define-syntax-parameter storage
(lambda (x)
(syntax-violation 'storage "storage undefined" x)))
(define-syntax-rule (gen-mem)
(let ((ret (make-memory (variable-ref mem-idx))))
(variable-set! mem-idx (+ 1 (variable-ref mem-idx)))
ret))
(define-syntax-rule (set-storage! gen var)
(let ((ret gen))
(storage-set! storage var ret)
ret))
(define-syntax-rule (get-mem! var)
(set-storage! (gen-mem) var))
(define-syntax-rule (get-gpr! var)
(set-storage! (or (acquire-gpr! free-gprs) (gen-mem)) var))
(define-syntax-rule (get-fpr! var)
(set-storage! (or (acquire-fpr! free-fprs) (gen-mem)) var))
(define (assign-registers term snapshots arg-storage arg-free-gprs
arg-free-fprs arg-mem-idx snapshot-id)
"Compile ANF term to list of primitive operations."
(syntax-parameterize
((storage (identifier-syntax arg-storage))
(free-gprs (identifier-syntax arg-free-gprs))
(free-fprs (identifier-syntax arg-free-fprs))
(mem-idx (identifier-syntax arg-mem-idx)))
(define (get-arg-types! op dst args)
(let ((types (prim-types-ref op)))
(let lp ((types (if dst
(if (pair? types)
(cdr types)
(failure 'get-arg-types!
"unknown type ~s ~s"
op types))
types))
(args args)
(acc '()))
(match (list types args)
(((type . types) (arg . args))
(cond
((symbol? arg)
(cond
((storage-ref storage arg)
=> (lambda (reg)
(lp types args (cons reg acc))))
((= type int)
(let ((reg (get-gpr! arg)))
(lp types args (cons reg acc))))
((= type double)
(let ((reg (get-fpr! arg)))
(lp types args (cons reg acc))))
(else
(lp types args acc))))
((constant-value? arg)
(lp types args (cons (make-con arg) acc)))
(else
(failure 'get-arg-types! "arg ~s ~s" arg type))))
(_
(reverse! acc))))))
(define (get-dst-type! op dst)
;; Get assigned register. Will assign new register if not assigned yet.
(let ((type (car (prim-types-ref op)))
(assigned (storage-ref storage dst)))
(cond
(assigned assigned)
((= type int) (get-gpr! dst))
((= type double) (get-fpr! dst))
(else (failure 'get-dst-types! "dst ~s ~s" dst type)))))
(define (ref k)
(cond
((symbol? k) (storage-ref storage k))
((constant-value? k) (make-con k))
(else (failure 'assign-registers "ref ~s not found" k))))
(define (ref-map ks)
(let lp ((ks ks))
(if (null? ks)
'()
(cons (ref (car ks)) (lp (cdr ks))))))
(define (constant-value? x)
(or (boolean? x)
(number? x)))
(define (assign-term term acc)
(match term
(('let (('_ '_)) term1)
(assign-term term1 acc))
(('let (('_ ('%snap id . args))) term1)
(let* ((regs (ref-map args))
(prim `(%snap ,id ,@regs)))
(set! snapshot-id id)
(set-snapshot-variables! (snapshots-ref snapshots id) regs)
(assign-term term1 (cons prim acc))))
(('let (('_ (op . args))) term1)
(let ((prim `(,op ,@(ref-map args))))
(assign-term term1 (cons prim acc))))
(('let ((dst (? constant-value? val))) term1)
(let* ((reg (cond
((ref dst) => identity)
((flonum? val) (get-fpr! dst))
(else (get-gpr! dst))))
(prim `(,%move ,reg ,(make-con val))))
(assign-term term1 (cons prim acc))))
(('let ((dst (? symbol? src))) term1)
(let ((src-reg (ref src)))
(if src-reg
(let* ((dst-reg (cond
((ref dst) => identity)
((gpr? src-reg) (get-gpr! dst))
((fpr? src-reg) (get-fpr! dst))
((memory? src-reg) (get-mem! dst))))
(prim `(,%move ,dst-reg ,src-reg)))
(assign-term term1 (cons prim acc)))
(assign-term term1 acc))))
(('let ((dst (op . args))) term1)
;; Set and get argument types before destination type.
(let* ((arg-regs (get-arg-types! op dst args))
(prim `(,op ,(get-dst-type! op dst) ,@arg-regs)))
(assign-term term1 (cons prim acc))))
(_ acc)))
(let ((plist (reverse! (assign-term term '()))))
(values plist snapshot-id))))
;;;; IR to list of primitive operations
(define (anf->primops term env initial-snapshot vars snapshots)
(let* ((parent-snapshot (env-parent-snapshot env))
(initial-free-gprs (make-initial-free-gprs))
(initial-free-fprs (make-initial-free-fprs))
(initial-mem-idx (make-variable 0))
(initial-storage (make-storage env initial-free-gprs
initial-free-fprs initial-mem-idx))
(initial-local-x-types (snapshot-locals initial-snapshot)))
;; Assign scratch registers to tmporary variables.
(syntax-parameterize
((free-gprs (identifier-syntax initial-free-gprs))
(free-fprs (identifier-syntax initial-free-fprs))
(mem-idx (identifier-syntax initial-mem-idx))
(storage (identifier-syntax initial-storage)))
(define-syntax-rule (set-initial-args! initial-args initial-locals)
(let lp ((args initial-args)
(local-x-types initial-locals)
(acc '()))
(match (list args local-x-types)
(((arg . args) ((local . type) . local-x-types))
(let ((reg (cond
((storage-ref storage arg) => identity)
((eq? type &flonum) (get-fpr! arg))
(else (get-gpr! arg)))))
(lp args local-x-types (cons reg acc))))
(_ (reverse! acc)))))
(define (sort-variables-in-storage t) ; For debug.
(define (var-index sym)
(string->number (substring (symbol->string sym) 1)))
(sort (hash-map->list (lambda (k v)
(list k (and v (physical-name v)))) t)
(lambda (a b)
(< (var-index (car a))
(var-index (car b))))))
(match term
ANF with entry clause and loop body .
(`(letrec ((entry (lambda ,entry-args ,entry-body))
(loop (lambda ,loop-args ,loop-body)))
entry)
(set-initial-args! entry-args initial-local-x-types)
(let*-values (((entry-ops snapshot-idx)
(assign-registers entry-body snapshots storage
free-gprs free-fprs mem-idx
0))
((loop-ops snapshot-idx)
(assign-registers loop-body snapshots storage
free-gprs free-fprs mem-idx
snapshot-idx)))
(make-primops entry-ops loop-ops (variable-ref mem-idx) storage)))
ANF without loop .
(`(letrec ((patch (lambda ,patch-args ,patch-body)))
patch)
;; Refill variables. Using the locals assigned in snapshot, which are
;; determined at the time of exit from parent trace.
(match parent-snapshot
(($ $snapshot _ _ _ _ locals variables _ _)
;; The number of assigned variables might fewer than the number of
;; locals. Reversed and assigning from highest frame to lowest
;; frame.
(let lp ((variables (reverse variables))
(locals (reverse locals)))
(match (list variables locals)
(((var . vars) ((local . type) . locals))
(storage-set! storage (make-var local) var)
(match var
(('gpr . n) (vector-set! free-gprs n #f))
(('fpr . n) (vector-set! free-fprs n #f))
(('mem . n)
(when (<= (variable-ref mem-idx) n)
(variable-set! mem-idx (+ n 1))))
(_
(unless (or (return-address? type)
(dynamic-link? type)
(constant? type)
(eq? &undefined type)
(eq? &false type)
(eq? &any type))
(failure 'ir->primops "var ~a at local ~a, type ~a"
var local (pretty-type type)))))
(lp vars locals))
(_ (values)))))
(_
(debug 2 ";;; ir->primops: perhaps loop-less root trace~%")))
(let-values (((patch-ops snapshot-idx)
(assign-registers patch-body snapshots storage
free-gprs free-fprs mem-idx 0)))
(make-primops patch-ops '() (variable-ref mem-idx) storage)))
(_ (failure 'ir->primops "malformed term" term))))))
| null | https://raw.githubusercontent.com/8c6794b6/guile-tjit/9566e480af2ff695e524984992626426f393414f/module/language/trace/ra.scm | scheme | Assign resiters to IR
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
either
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
License along with this library; if not, write to the Free Software
Commentary:
Applying naive strategy to assign registers to locals, does nothing
sophisticated such as linear-scan, binpacking, graph coloring, etc.
Code:
Data types
Record type to hold lists of primitives.
List of primitives for entry clause.
List of primitives for loop body.
Number of spilled variables.
Hash-table containing variable information.
Auxiliary
Get assigned register. Will assign new register if not assigned yet.
Set and get argument types before destination type.
IR to list of primitive operations
Assign scratch registers to tmporary variables.
For debug.
Refill variables. Using the locals assigned in snapshot, which are
determined at the time of exit from parent trace.
The number of assigned variables might fewer than the number of
locals. Reversed and assigning from highest frame to lowest
frame. |
Copyright ( C ) 2015 , 2016 Free Software Foundation , Inc.
version 3 of the License , or ( at your option ) any later version .
You should have received a copy of the GNU Lesser General Public
Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , MA
02110 - 1301 USA
Assign registers to ANF IR , compile to list of primitive operations .
(define-module (language trace ra)
#:use-module (ice-9 format)
#:use-module (ice-9 match)
#:use-module (srfi srfi-9)
#:use-module (srfi srfi-11)
#:use-module (system foreign)
#:use-module (system vm native debug)
#:use-module (language trace assembler)
#:use-module (language trace error)
#:use-module (language trace fragment)
#:use-module (language trace env)
#:use-module (language trace primitives)
#:use-module (language trace registers)
#:use-module (language trace snapshot)
#:use-module (language trace types)
#:use-module (language trace variables)
#:export ($primops
primops?
primops-entry
primops-loop
primops-nspills
anf->primops
make-empty-storage
storage-ref
storage-set!
fold-storage
volatiles-in-storage))
(define-record-type $primops
(make-primops entry loop nspills storage)
primops?
(entry primops-entry)
(loop primops-loop)
(nspills primops-nspills)
(storage primops-storage))
(define-syntax-rule (%make-storage alist)
(cons 'storage alist))
(define-syntax-rule (storage-alist storage)
(cdr storage))
(define-syntax-rule (set-storage-alist! storage alist)
(set-cdr! storage alist))
(define-inlinable (storage-ref storage key)
(assq-ref (storage-alist storage) key))
(define-inlinable (storage-set! storage key* val)
(let ((key key*))
(cond
((assq key (storage-alist storage))
=> (lambda (handle)
(set-cdr! handle val)))
(else
(set-storage-alist! storage (cons (cons key val)
(storage-alist storage)))))))
(define-inlinable (fold-storage proc init* storage)
(let lp ((alist (storage-alist storage)) (init init*))
(if (null? alist)
init
(let ((kv (car alist)))
(lp (cdr alist) (proc (car kv) (cdr kv) init))))))
(define (make-empty-storage)
(%make-storage '()))
(define (make-storage env free-gprs free-fprs mem-idx)
(let ((alist '())
(parent-storage (and=> (env-parent-fragment env) fragment-storage)))
(%make-storage
(if parent-storage
(let lp ((parent-alist (storage-alist parent-storage))
(acc '()))
(match parent-alist
(((k . v) . parent-alist)
(cond
((not v) (lp parent-alist acc))
((gpr? v)
(let ((i (ref-value v)))
(when (<= 0 i)
(vector-set! free-gprs i #f))
(lp parent-alist (acons k v acc))))
((fpr? v)
(let ((i (ref-value v)))
(when (<= 0 i)
(vector-set! free-fprs i #f))
(lp parent-alist (acons k v acc))))
((memory? v)
(let ((i (ref-value v)))
(when (<= (variable-ref mem-idx) i)
(variable-set! mem-idx (+ i 1)))
(lp parent-alist (acons k v acc))))
(else
(failure 'make-storage "unknown var ~s" v))))
(() acc)))
(let* ((alist (acons (make-tmpvar 0) (make-gpr -1) alist))
(alist (acons (make-tmpvar 1) (make-gpr -2) alist))
(alist (acons (make-tmpvar 2) (make-gpr -3) alist))
(alist (acons (make-tmpvar/f 0) (make-fpr -1) alist))
(aistt (acons (make-tmpvar/f 1) (make-fpr -2) alist))
(alist (acons (make-tmpvar/f 2) (make-fpr -3) alist))
(alist (acons (make-spill 0) (make-memory -1) alist)))
alist)))))
(define (volatiles-in-storage storage)
(fold-storage
(lambda (k reg acc)
(if (or (and reg (gpr? reg)
(<= *num-non-volatiles* (ref-value reg)))
(and reg (fpr? reg)
(<= 0 (ref-value reg))))
(cons reg acc)
acc))
'() storage))
(define-syntax-rule (make-initial-free-gprs)
(make-vector *num-gpr* #t))
(define-syntax-rule (make-initial-free-fprs)
(make-vector *num-fpr* #t))
(define-syntax define-register-acquire!
(syntax-rules ()
((_ name num constructor)
(define (name free-regs)
(let lp ((i 0))
(cond
((= i num) #f)
((vector-ref free-regs i)
(let ((ret (constructor i)))
(vector-set! free-regs i #f)
ret))
(else (lp (+ i 1)))))))))
(define-register-acquire! acquire-gpr! *num-gpr* make-gpr)
(define-register-acquire! acquire-fpr! *num-fpr* make-fpr)
(define-syntax-parameter mem-idx
(lambda (x)
(syntax-violation 'mem-idx "mem-idx undefined" x)))
(define-syntax-parameter free-gprs
(lambda (x)
(syntax-violation 'free-gprs "free-gprs undefined" x)))
(define-syntax-parameter free-fprs
(lambda (x)
(syntax-violation 'free-fprs "free-fprs undefined" x)))
(define-syntax-parameter storage
(lambda (x)
(syntax-violation 'storage "storage undefined" x)))
(define-syntax-rule (gen-mem)
(let ((ret (make-memory (variable-ref mem-idx))))
(variable-set! mem-idx (+ 1 (variable-ref mem-idx)))
ret))
(define-syntax-rule (set-storage! gen var)
(let ((ret gen))
(storage-set! storage var ret)
ret))
(define-syntax-rule (get-mem! var)
(set-storage! (gen-mem) var))
(define-syntax-rule (get-gpr! var)
(set-storage! (or (acquire-gpr! free-gprs) (gen-mem)) var))
(define-syntax-rule (get-fpr! var)
(set-storage! (or (acquire-fpr! free-fprs) (gen-mem)) var))
(define (assign-registers term snapshots arg-storage arg-free-gprs
arg-free-fprs arg-mem-idx snapshot-id)
"Compile ANF term to list of primitive operations."
(syntax-parameterize
((storage (identifier-syntax arg-storage))
(free-gprs (identifier-syntax arg-free-gprs))
(free-fprs (identifier-syntax arg-free-fprs))
(mem-idx (identifier-syntax arg-mem-idx)))
(define (get-arg-types! op dst args)
(let ((types (prim-types-ref op)))
(let lp ((types (if dst
(if (pair? types)
(cdr types)
(failure 'get-arg-types!
"unknown type ~s ~s"
op types))
types))
(args args)
(acc '()))
(match (list types args)
(((type . types) (arg . args))
(cond
((symbol? arg)
(cond
((storage-ref storage arg)
=> (lambda (reg)
(lp types args (cons reg acc))))
((= type int)
(let ((reg (get-gpr! arg)))
(lp types args (cons reg acc))))
((= type double)
(let ((reg (get-fpr! arg)))
(lp types args (cons reg acc))))
(else
(lp types args acc))))
((constant-value? arg)
(lp types args (cons (make-con arg) acc)))
(else
(failure 'get-arg-types! "arg ~s ~s" arg type))))
(_
(reverse! acc))))))
(define (get-dst-type! op dst)
(let ((type (car (prim-types-ref op)))
(assigned (storage-ref storage dst)))
(cond
(assigned assigned)
((= type int) (get-gpr! dst))
((= type double) (get-fpr! dst))
(else (failure 'get-dst-types! "dst ~s ~s" dst type)))))
(define (ref k)
(cond
((symbol? k) (storage-ref storage k))
((constant-value? k) (make-con k))
(else (failure 'assign-registers "ref ~s not found" k))))
(define (ref-map ks)
(let lp ((ks ks))
(if (null? ks)
'()
(cons (ref (car ks)) (lp (cdr ks))))))
(define (constant-value? x)
(or (boolean? x)
(number? x)))
(define (assign-term term acc)
(match term
(('let (('_ '_)) term1)
(assign-term term1 acc))
(('let (('_ ('%snap id . args))) term1)
(let* ((regs (ref-map args))
(prim `(%snap ,id ,@regs)))
(set! snapshot-id id)
(set-snapshot-variables! (snapshots-ref snapshots id) regs)
(assign-term term1 (cons prim acc))))
(('let (('_ (op . args))) term1)
(let ((prim `(,op ,@(ref-map args))))
(assign-term term1 (cons prim acc))))
(('let ((dst (? constant-value? val))) term1)
(let* ((reg (cond
((ref dst) => identity)
((flonum? val) (get-fpr! dst))
(else (get-gpr! dst))))
(prim `(,%move ,reg ,(make-con val))))
(assign-term term1 (cons prim acc))))
(('let ((dst (? symbol? src))) term1)
(let ((src-reg (ref src)))
(if src-reg
(let* ((dst-reg (cond
((ref dst) => identity)
((gpr? src-reg) (get-gpr! dst))
((fpr? src-reg) (get-fpr! dst))
((memory? src-reg) (get-mem! dst))))
(prim `(,%move ,dst-reg ,src-reg)))
(assign-term term1 (cons prim acc)))
(assign-term term1 acc))))
(('let ((dst (op . args))) term1)
(let* ((arg-regs (get-arg-types! op dst args))
(prim `(,op ,(get-dst-type! op dst) ,@arg-regs)))
(assign-term term1 (cons prim acc))))
(_ acc)))
(let ((plist (reverse! (assign-term term '()))))
(values plist snapshot-id))))
(define (anf->primops term env initial-snapshot vars snapshots)
(let* ((parent-snapshot (env-parent-snapshot env))
(initial-free-gprs (make-initial-free-gprs))
(initial-free-fprs (make-initial-free-fprs))
(initial-mem-idx (make-variable 0))
(initial-storage (make-storage env initial-free-gprs
initial-free-fprs initial-mem-idx))
(initial-local-x-types (snapshot-locals initial-snapshot)))
(syntax-parameterize
((free-gprs (identifier-syntax initial-free-gprs))
(free-fprs (identifier-syntax initial-free-fprs))
(mem-idx (identifier-syntax initial-mem-idx))
(storage (identifier-syntax initial-storage)))
(define-syntax-rule (set-initial-args! initial-args initial-locals)
(let lp ((args initial-args)
(local-x-types initial-locals)
(acc '()))
(match (list args local-x-types)
(((arg . args) ((local . type) . local-x-types))
(let ((reg (cond
((storage-ref storage arg) => identity)
((eq? type &flonum) (get-fpr! arg))
(else (get-gpr! arg)))))
(lp args local-x-types (cons reg acc))))
(_ (reverse! acc)))))
(define (var-index sym)
(string->number (substring (symbol->string sym) 1)))
(sort (hash-map->list (lambda (k v)
(list k (and v (physical-name v)))) t)
(lambda (a b)
(< (var-index (car a))
(var-index (car b))))))
(match term
ANF with entry clause and loop body .
(`(letrec ((entry (lambda ,entry-args ,entry-body))
(loop (lambda ,loop-args ,loop-body)))
entry)
(set-initial-args! entry-args initial-local-x-types)
(let*-values (((entry-ops snapshot-idx)
(assign-registers entry-body snapshots storage
free-gprs free-fprs mem-idx
0))
((loop-ops snapshot-idx)
(assign-registers loop-body snapshots storage
free-gprs free-fprs mem-idx
snapshot-idx)))
(make-primops entry-ops loop-ops (variable-ref mem-idx) storage)))
ANF without loop .
(`(letrec ((patch (lambda ,patch-args ,patch-body)))
patch)
(match parent-snapshot
(($ $snapshot _ _ _ _ locals variables _ _)
(let lp ((variables (reverse variables))
(locals (reverse locals)))
(match (list variables locals)
(((var . vars) ((local . type) . locals))
(storage-set! storage (make-var local) var)
(match var
(('gpr . n) (vector-set! free-gprs n #f))
(('fpr . n) (vector-set! free-fprs n #f))
(('mem . n)
(when (<= (variable-ref mem-idx) n)
(variable-set! mem-idx (+ n 1))))
(_
(unless (or (return-address? type)
(dynamic-link? type)
(constant? type)
(eq? &undefined type)
(eq? &false type)
(eq? &any type))
(failure 'ir->primops "var ~a at local ~a, type ~a"
var local (pretty-type type)))))
(lp vars locals))
(_ (values)))))
(_
(debug 2 ";;; ir->primops: perhaps loop-less root trace~%")))
(let-values (((patch-ops snapshot-idx)
(assign-registers patch-body snapshots storage
free-gprs free-fprs mem-idx 0)))
(make-primops patch-ops '() (variable-ref mem-idx) storage)))
(_ (failure 'ir->primops "malformed term" term))))))
|
7725568e0646b22e49a3b97844cd673450cbe02ff44515121a4c94e8055be4c9 | FranklinChen/learn-you-some-erlang | pq_enemy.erl | %% Gives random enemies
-module(pq_enemy).
-export([fetch/0]).
fetch() ->
L = enemies(),
lists:nth(random:uniform(length(L)), L).
enemies() ->
[{<<"Ant">>, [{drop, {<<"Ant Egg">>, 1}}, {experience, 1}]},
{<<"Wildcat">>, [{drop, {<<"Pelt">>, 1}}, {experience, 1}]},
{<<"Pig">>, [{drop, {<<"Bacon">>, 1}}, {experience, 1}]},
{<<"Wild Pig">>, [{drop, {<<"Tasty Ribs">>, 2}}, {experience, 1}]},
{<<"Goblin">>, [{drop, {<<"Goblin hair">>, 1}}, {experience, 2}]},
{<<"Robot">>, [{drop, {<<"Chunks of Metal">>, 3}}, {experience, 2}]}].
| null | https://raw.githubusercontent.com/FranklinChen/learn-you-some-erlang/878c8bc2011a12862fe72dd7fdc6c921348c79d6/processquest/apps/processquest-1.0.0/src/pq_enemy.erl | erlang | Gives random enemies | -module(pq_enemy).
-export([fetch/0]).
fetch() ->
L = enemies(),
lists:nth(random:uniform(length(L)), L).
enemies() ->
[{<<"Ant">>, [{drop, {<<"Ant Egg">>, 1}}, {experience, 1}]},
{<<"Wildcat">>, [{drop, {<<"Pelt">>, 1}}, {experience, 1}]},
{<<"Pig">>, [{drop, {<<"Bacon">>, 1}}, {experience, 1}]},
{<<"Wild Pig">>, [{drop, {<<"Tasty Ribs">>, 2}}, {experience, 1}]},
{<<"Goblin">>, [{drop, {<<"Goblin hair">>, 1}}, {experience, 2}]},
{<<"Robot">>, [{drop, {<<"Chunks of Metal">>, 3}}, {experience, 2}]}].
|
d6e8e84bb22d47ee43cb1c41d1cd756b99443989fbf2c6b39f63aebbf51be005 | biocom-uib/vpf-tools | SingleProcess.hs | # language DeriveGeneric #
# language NoPolyKinds #
# language StaticPointers #
{-# language Strict #-}
# language TemplateHaskell #
{-# language UndecidableInstances #-}
module Control.Carrier.Distributed.SingleProcess
( SingleProcessT
, runSingleProcessT
, LocalWorker
) where
import GHC.Generics (Generic)
import Control.Carrier.MTL.TH (deriveMonadTrans, deriveAlgebra)
import Control.Distributed.SClosure
import Control.Effect.Distributed
import Data.Store (Store)
newtype SingleProcessT m a = SingleProcessT { runSingleProcessT :: m a }
deriveMonadTrans ''SingleProcessT
data LocalWorker = LocalWorker
deriving (Generic, Typeable, Show)
instance Store LocalWorker
instance SInstance (Show LocalWorker) where
sinst = static Dict
instance SInstance (Serializable LocalWorker) where
sinst = static Dict
interpretSingleProcessT :: (Monad m, n ~ m) => Distributed n LocalWorker (SingleProcessT m) a -> SingleProcessT m a
interpretSingleProcessT (GetNumWorkers k) = k 1
interpretSingleProcessT (WithWorkers block k) = k . pure =<< block LocalWorker
interpretSingleProcessT (RunInWorker LocalWorker _ clo k) = k =<< SingleProcessT (seval clo)
deriveAlgebra 'interpretSingleProcessT
| null | https://raw.githubusercontent.com/biocom-uib/vpf-tools/dd88a543f28eb339cf0dcb89f34479c84b3a8056/src/Control/Carrier/Distributed/SingleProcess.hs | haskell | # language Strict #
# language UndecidableInstances # | # language DeriveGeneric #
# language NoPolyKinds #
# language StaticPointers #
# language TemplateHaskell #
module Control.Carrier.Distributed.SingleProcess
( SingleProcessT
, runSingleProcessT
, LocalWorker
) where
import GHC.Generics (Generic)
import Control.Carrier.MTL.TH (deriveMonadTrans, deriveAlgebra)
import Control.Distributed.SClosure
import Control.Effect.Distributed
import Data.Store (Store)
newtype SingleProcessT m a = SingleProcessT { runSingleProcessT :: m a }
deriveMonadTrans ''SingleProcessT
data LocalWorker = LocalWorker
deriving (Generic, Typeable, Show)
instance Store LocalWorker
instance SInstance (Show LocalWorker) where
sinst = static Dict
instance SInstance (Serializable LocalWorker) where
sinst = static Dict
interpretSingleProcessT :: (Monad m, n ~ m) => Distributed n LocalWorker (SingleProcessT m) a -> SingleProcessT m a
interpretSingleProcessT (GetNumWorkers k) = k 1
interpretSingleProcessT (WithWorkers block k) = k . pure =<< block LocalWorker
interpretSingleProcessT (RunInWorker LocalWorker _ clo k) = k =<< SingleProcessT (seval clo)
deriveAlgebra 'interpretSingleProcessT
|
9a7076b793c0da714846e972a2fb7b48f97ef02e510525f22088d2286120b857 | cj1128/sicp-review | 2.37.scm | (load "accumulate.scm")
(load "accumulate-n.scm")
(define (dot-product v w)
(accumulate + 0 (map * v w)))
(define (matrix-*-vector m v)
(map (lambda (m-row)
(dot-product m-row v))
m))
(define (transpose mat)
(accumulate-n cons '() mat))
(define (matrix-*-matrix m n)
(let ((cols (transpose n)))
(map (lambda (m-row)
(map (lambda (col)
(dot-product col m-row))
cols))
m)))
(define m1 '((1 2 3 4) (5 6 7 8) (9 10 11 12)))
(define v1 '(1 2 3 4))
(define m2 '((1 2 3) (4 5 6) (7 8 9) (10 11 12)))
(display (dot-product '(1 2 3) '(4 5 6)))
(newline)
(display (matrix-*-vector m1 v1))
(newline)
(display (matrix-*-matrix m1 m2))
(newline)
(display (transpose m1))
| null | https://raw.githubusercontent.com/cj1128/sicp-review/efaa2f863b7f03c51641c22d701bac97e398a050/chapter-2/2.2/2.37.scm | scheme | (load "accumulate.scm")
(load "accumulate-n.scm")
(define (dot-product v w)
(accumulate + 0 (map * v w)))
(define (matrix-*-vector m v)
(map (lambda (m-row)
(dot-product m-row v))
m))
(define (transpose mat)
(accumulate-n cons '() mat))
(define (matrix-*-matrix m n)
(let ((cols (transpose n)))
(map (lambda (m-row)
(map (lambda (col)
(dot-product col m-row))
cols))
m)))
(define m1 '((1 2 3 4) (5 6 7 8) (9 10 11 12)))
(define v1 '(1 2 3 4))
(define m2 '((1 2 3) (4 5 6) (7 8 9) (10 11 12)))
(display (dot-product '(1 2 3) '(4 5 6)))
(newline)
(display (matrix-*-vector m1 v1))
(newline)
(display (matrix-*-matrix m1 m2))
(newline)
(display (transpose m1))
| |
b3fb13b312d44010813fbc4fa6687d5a54b823f77d47c23abf7b16ac87af3bf6 | dparis/gen-phzr | distance_constraint.cljs | (ns phzr.impl.accessors.physics.p2.distance-constraint)
(def distance-constraint-get-properties
{:game "game"
:world "world"})
(def distance-constraint-set-properties
{:game "game"
:world "world"}) | null | https://raw.githubusercontent.com/dparis/gen-phzr/e4c7b272e225ac343718dc15fc84f5f0dce68023/out/impl/accessors/physics/p2/distance_constraint.cljs | clojure | (ns phzr.impl.accessors.physics.p2.distance-constraint)
(def distance-constraint-get-properties
{:game "game"
:world "world"})
(def distance-constraint-set-properties
{:game "game"
:world "world"}) | |
562095023815c0d1c6945c3d820b5a085c0a373552bb7cd3cfc7f580b5eb134a | styx/Raincat | Rain.hs | module Rain.Rain
(updateRain,
drawRain,
rainRect,
rainPoly) where
import System.Random
import Graphics.Rendering.OpenGL
import World.World
import Panels.MainPanel
import Nxt.Types
import Items.Items
import Level.Level
import Settings.RainSettings as RainSettings
import Settings.WorldSettings as WorldSettings
import Nxt.Graphics
-- updateRain
updateRain :: WorldState -> IO [Vector2d]
updateRain worldState = do
let rain = raindrops (mainPanel worldState)
(cameraX, cameraY) = cameraPos (mainPanel worldState)
let fallenRain = fallRain rain cameraY
let spawnList = [(1.0 - cameraX)..(maxWorldX - cameraX)]
let xPos = [x::Double | x <- spawnList, ceiling x `mod` rainSpacing == 0]
gen <- newStdGen
let lvlHeight = fromIntegral(levelHeight $ curLevel worldState)::Double
let yPos = randomRs (lvlHeight - rainHeight - cameraY, lvlHeight - cameraY) gen
let rainPositions = zip xPos yPos
newRainSeq <- mapM createNewRain rainPositions
let newRain = concat newRainSeq
let totalRain = newRain ++ fallenRain
let rainPolyCol = collideRainPoly totalRain (polySurfaces (mainPanel worldState))
let rectSurfaces' = map itemRect (tarpList (mainPanel worldState))
++
map itemRect (corkList (mainPanel worldState))
++
rectSurfaces (mainPanel worldState)
let rainRectCol = collideRainRect rainPolyCol rectSurfaces'
return rainRectCol
-- createNewRain
createNewRain :: Vector2d -> IO [Vector2d]
createNewRain rainPos = do
raindropDiceRoll <- getStdRandom $ randomR (0::Int, rainSpawnChance)
return [rainPos | raindropDiceRoll == 0]
-- fallRain
fallRain :: [Vector2d] -> Double -> [Vector2d]
fallRain [] _ = []
fallRain ((raindropX, raindropY) : rain) cameraY
| raindropY > (-cameraY) = (raindropX, raindropY - rainFallSpeed) : fallRain rain cameraY
| otherwise = fallRain rain cameraY
-- drawRain
drawRain :: [Vector2d] -> IO ()
drawRain [] = return ()
drawRain ((raindropX, raindropY) : rain) = do
renderPrimitive Quads $ do
mapM_ color rainColor
mapM_ vertex (raindropVertices raindropX raindropY)
drawRain rain
-- raindropVertices
raindropVertices :: Double -> Double -> [Vertex3 GLdouble]
raindropVertices x y =
[Vertex3 x' y' 0.0,
Vertex3 (x' + rainWidth') y' 0.0,
Vertex3 (x' + rainWidth') (y' + rainHeight') 0.0,
Vertex3 x' (y' + rainHeight') 0.0]
where x' = toGLdouble x
y' = toGLdouble y
rainWidth' = toGLdouble rainWidth
rainHeight' = toGLdouble rainHeight
-- rainPoly
rainPoly :: Vector2d -> Nxt.Types.Poly
rainPoly (raindropX, raindropY) =
Poly 3 [(raindropX,raindropY),
(raindropX+RainSettings.rainWidth,raindropY),
(raindropX+RainSettings.rainWidth,raindropY+RainSettings.rainHeight)]
-- collideRainPoly
collideRainPoly :: [Vector2d] -> [Nxt.Types.Poly] -> [Vector2d]
collideRainPoly [] _ = []
collideRainPoly (raindrop:rain) polys =
if foldr (\poly -> (polyIntersect poly (rainPoly raindrop) ||)) False polys
then
collideRainPoly rain polys
else
raindrop : collideRainPoly rain polys
-- rainRect
rainRect :: Vector2d -> Nxt.Types.Rect
rainRect (raindropX, raindropY) =
Rect raindropX raindropY RainSettings.rainWidth RainSettings.rainHeight
-- collideRainRect
collideRainRect :: [Vector2d] -> [Nxt.Types.Rect] -> [Vector2d]
collideRainRect [] _ = []
collideRainRect (raindrop:rain) rects =
if foldr ((||) . rectIntersect (rainRect raindrop)) False rects
then
collideRainRect rain rects
else
raindrop : collideRainRect rain rects
| null | https://raw.githubusercontent.com/styx/Raincat/49b688c73335c9a4090708bc75f6af9575a65670/src/Rain/Rain.hs | haskell | updateRain
createNewRain
fallRain
drawRain
raindropVertices
rainPoly
collideRainPoly
rainRect
collideRainRect | module Rain.Rain
(updateRain,
drawRain,
rainRect,
rainPoly) where
import System.Random
import Graphics.Rendering.OpenGL
import World.World
import Panels.MainPanel
import Nxt.Types
import Items.Items
import Level.Level
import Settings.RainSettings as RainSettings
import Settings.WorldSettings as WorldSettings
import Nxt.Graphics
updateRain :: WorldState -> IO [Vector2d]
updateRain worldState = do
let rain = raindrops (mainPanel worldState)
(cameraX, cameraY) = cameraPos (mainPanel worldState)
let fallenRain = fallRain rain cameraY
let spawnList = [(1.0 - cameraX)..(maxWorldX - cameraX)]
let xPos = [x::Double | x <- spawnList, ceiling x `mod` rainSpacing == 0]
gen <- newStdGen
let lvlHeight = fromIntegral(levelHeight $ curLevel worldState)::Double
let yPos = randomRs (lvlHeight - rainHeight - cameraY, lvlHeight - cameraY) gen
let rainPositions = zip xPos yPos
newRainSeq <- mapM createNewRain rainPositions
let newRain = concat newRainSeq
let totalRain = newRain ++ fallenRain
let rainPolyCol = collideRainPoly totalRain (polySurfaces (mainPanel worldState))
let rectSurfaces' = map itemRect (tarpList (mainPanel worldState))
++
map itemRect (corkList (mainPanel worldState))
++
rectSurfaces (mainPanel worldState)
let rainRectCol = collideRainRect rainPolyCol rectSurfaces'
return rainRectCol
createNewRain :: Vector2d -> IO [Vector2d]
createNewRain rainPos = do
raindropDiceRoll <- getStdRandom $ randomR (0::Int, rainSpawnChance)
return [rainPos | raindropDiceRoll == 0]
fallRain :: [Vector2d] -> Double -> [Vector2d]
fallRain [] _ = []
fallRain ((raindropX, raindropY) : rain) cameraY
| raindropY > (-cameraY) = (raindropX, raindropY - rainFallSpeed) : fallRain rain cameraY
| otherwise = fallRain rain cameraY
drawRain :: [Vector2d] -> IO ()
drawRain [] = return ()
drawRain ((raindropX, raindropY) : rain) = do
renderPrimitive Quads $ do
mapM_ color rainColor
mapM_ vertex (raindropVertices raindropX raindropY)
drawRain rain
raindropVertices :: Double -> Double -> [Vertex3 GLdouble]
raindropVertices x y =
[Vertex3 x' y' 0.0,
Vertex3 (x' + rainWidth') y' 0.0,
Vertex3 (x' + rainWidth') (y' + rainHeight') 0.0,
Vertex3 x' (y' + rainHeight') 0.0]
where x' = toGLdouble x
y' = toGLdouble y
rainWidth' = toGLdouble rainWidth
rainHeight' = toGLdouble rainHeight
rainPoly :: Vector2d -> Nxt.Types.Poly
rainPoly (raindropX, raindropY) =
Poly 3 [(raindropX,raindropY),
(raindropX+RainSettings.rainWidth,raindropY),
(raindropX+RainSettings.rainWidth,raindropY+RainSettings.rainHeight)]
collideRainPoly :: [Vector2d] -> [Nxt.Types.Poly] -> [Vector2d]
collideRainPoly [] _ = []
collideRainPoly (raindrop:rain) polys =
if foldr (\poly -> (polyIntersect poly (rainPoly raindrop) ||)) False polys
then
collideRainPoly rain polys
else
raindrop : collideRainPoly rain polys
rainRect :: Vector2d -> Nxt.Types.Rect
rainRect (raindropX, raindropY) =
Rect raindropX raindropY RainSettings.rainWidth RainSettings.rainHeight
collideRainRect :: [Vector2d] -> [Nxt.Types.Rect] -> [Vector2d]
collideRainRect [] _ = []
collideRainRect (raindrop:rain) rects =
if foldr ((||) . rectIntersect (rainRect raindrop)) False rects
then
collideRainRect rain rects
else
raindrop : collideRainRect rain rects
|
26d796e2d8d04f2d2b2a15170f60b310e681afc68db8ada7d91ab85462c594b8 | ndmitchell/catch | CaseCheck.hs |
module Graph.CaseCheck(graphCaseCheck) where
import Graph.Type
import Graph.Create
import Graph.Solve
import IO
import Hite
graphCaseCheck :: String -> Handle -> Hite -> IO Bool
graphCaseCheck file hndl hite =
do
let graph = createGraph hite
putStrLn "Checking graph"
res <- solveGraph file hite graph
putStrLn $ "Result: " ++ show res
return res
| null | https://raw.githubusercontent.com/ndmitchell/catch/5d834416a27b4df3f7ce7830c4757d4505aaf96e/src/Graph/CaseCheck.hs | haskell |
module Graph.CaseCheck(graphCaseCheck) where
import Graph.Type
import Graph.Create
import Graph.Solve
import IO
import Hite
graphCaseCheck :: String -> Handle -> Hite -> IO Bool
graphCaseCheck file hndl hite =
do
let graph = createGraph hite
putStrLn "Checking graph"
res <- solveGraph file hite graph
putStrLn $ "Result: " ++ show res
return res
| |
5ea95c8ca6c7b1823540f746bf46c42cdfb5927468701c82a36c6254d3092634 | wireapp/wire-server | V17.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 V17
( migration,
)
where
import Cassandra.Schema
import Imports
import Text.RawString.QQ
migration :: Migration
migration = Migration 17 "Remove table `scim_external_ids` (from db migration V10, deprecated in favor of `scim_external`, data migrated in `/services/spar/migrate-data/src/Spar/DataMigration/V1_ExternalIds.hs`)" $ do
void $
schema'
[r|
DROP TABLE if exists scim_external_ids;
|]
| null | https://raw.githubusercontent.com/wireapp/wire-server/f72b09756102a5c66169cca0343aa7b7e6e54491/services/spar/schema/src/V17.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 V17
( migration,
)
where
import Cassandra.Schema
import Imports
import Text.RawString.QQ
migration :: Migration
migration = Migration 17 "Remove table `scim_external_ids` (from db migration V10, deprecated in favor of `scim_external`, data migrated in `/services/spar/migrate-data/src/Spar/DataMigration/V1_ExternalIds.hs`)" $ do
void $
schema'
[r|
DROP TABLE if exists scim_external_ids;
|]
|
9bf836293f9972b12e755026da7cb99b32e7415d52eaa63ee1ebe5cee55e7a3b | jaredly/belt | belt_internalMapString.ml | # 2 "../others/internal_map.cppo.ml"
type key = string
# 9 "../others/internal_map.cppo.ml"
module N = Belt_internalAVLtree
module A = Belt_Array
module S = Belt_SortArray
type 'a t = (key,'a) N.t
let rec add t (x : key) (data : _) =
match N.toOpt t with
| None ->
N.singleton x data
| Some n ->
let k = N.key n in
if x = k then
N.return (N.updateValue n data)
else
let v = N.value n in
if x < k then
N.bal (add (N.left n) x data ) k v (N.right n)
else
N.bal (N.left n) k v (add (N.right n) x data )
let rec get n (x : key) =
match N.toOpt n with
None -> None
| Some n ->
let v = N.key n in
if x = v then Some (N.value n)
else get (if x < v then N.left n else N.right n) x
let rec getUndefined n (x : key) =
match N.toOpt n with
| None ->
Js.undefined
| Some n ->
let v = N.key n in
if x = v then Js.Undefined.return (N.value n)
else getUndefined (if x < v then (N.left n) else (N.right n)) x
let rec getExn n (x : key) =
match N.toOpt n with
| None -> [%assert "getExn"]
| Some n ->
let v = N.key n in
if x = v then (N.value n)
else getExn (if x < v then (N.left n) else (N.right n)) x
let rec getWithDefault n (x : key) def =
match N.toOpt n with
| None -> def
| Some n ->
let v = N.key n in
if x = v then (N.value n)
else getWithDefault (if x < v then (N.left n) else (N.right n)) x def
let rec has n (x : key)=
match N.toOpt n with
None -> false
Node(l , v , d , r , _ )
let v = N.key n in
x = v || has (if x < v then N.left n else N.right n) x
let rec remove n (x : key) =
match N.toOpt n with
| None -> n
| Some n ->
let l,v,r = N.(left n, key n, right n) in
if x = v then
match N.toOpt l, N.toOpt r with
| None, _ -> r
| _, None -> l
| _, Some rn ->
let kr, vr = ref (N.key rn), ref (N.value rn) in
let r = N.removeMinAuxWithRef rn kr vr in
N.bal l !kr !vr r
else if x < v then
N.(bal (remove l x ) v (value n) r)
else
N.(bal l v (value n) (remove r x ))
let rec splitAux (x : key) (n : _ N.node) : _ t * _ option * _ t =
let l,v,d,r = N.(left n , key n, value n, right n) in
if x = v then (l, Some d, r)
else
if x < v then
match N.toOpt l with
| None ->
N.(empty , None, return n)
| Some l ->
let (ll, pres, rl) = splitAux x l in (ll, pres, N.join rl v d r)
else
match N.toOpt r with
| None ->
N.(return n, None, empty)
| Some r ->
let (lr, pres, rr) = splitAux x r in (N.join l v d lr, pres, rr)
let rec split (x : key) n =
match N.toOpt n with
None ->
N.(empty, None, empty)
| Some n ->
splitAux x n
let rec mergeU s1 s2 f =
match N.(toOpt s1, toOpt s2) with
(None, None) -> N.empty
( Node ( l1 , v1 , d1 , r1 , h1 ) , _ )
when N.(height n >= (match N.toOpt s2 with None -> 0 | Some n -> N.height n)) ->
let (l1,v1,d1,r1) = N.(left n, key n, value n, right n ) in
let (l2, d2, r2) = split v1 s2 in
N.concatOrJoin (mergeU l1 l2 f) v1 (f v1 (Some d1) d2 [@bs]) (mergeU r1 r2 f)
| (_, Some n) (* Node (l2, v2, d2, r2, h2) *) ->
let (l2, v2, d2, r2) = N.(left n, key n, value n, right n) in
let (l1, d1, r1) = split v2 s1 in
N.concatOrJoin (mergeU l1 l2 f) v2 (f v2 d1 (Some d2) [@bs]) (mergeU r1 r2 f)
| _ ->
assert false
let merge s1 s2 f = mergeU s1 s2 (fun [@bs] a b c -> f a b c)
let rec compareAux e1 e2 vcmp =
match e1,e2 with
| h1::t1, h2::t2 ->
let c = Pervasives.compare (N.key h1 : key) (N.key h2) in
if c = 0 then
let cx = vcmp (N.value h1) (N.value h2) [@bs] in
if cx = 0 then
compareAux
(N.stackAllLeft (N.right h1) t1 )
(N.stackAllLeft (N.right h2) t2)
vcmp
else cx
else c
| _, _ -> 0
let cmpU s1 s2 cmp =
let len1, len2 = N.size s1, N.size s2 in
if len1 = len2 then
compareAux
(N.stackAllLeft s1 [])
(N.stackAllLeft s2 [])
cmp
else if len1 < len2 then -1
else 1
let cmp s1 s2 f = cmpU s1 s2 (fun[@bs] a b -> f a b)
let rec eqAux e1 e2 eq =
match e1,e2 with
| h1::t1, h2::t2 ->
if (N.key h1 : key) = (N.key h2) &&
eq (N.value h1) (N.value h2) [@bs] then
eqAux (
N.stackAllLeft (N.right h1) t1 )
(N.stackAllLeft (N.right h2) t2)
eq
else false
| _, _ -> true (*end *)
let eqU s1 s2 eq =
let len1,len2 = N.size s1, N.size s2 in
if len1 = len2 then
eqAux
(N.stackAllLeft s1 [])
(N.stackAllLeft s2 []) eq
else false
let eq s1 s2 f = eqU s1 s2 (fun[@bs] a b -> f a b)
let rec addMutate (t : _ t) x data : _ t =
match N.toOpt t with
| None -> N.singleton x data
| Some nt ->
let k = N.key nt in
(* let c = (Belt_Cmp.getCmpInternal cmp) x k [@bs] in *)
if x = k then begin
N.keySet nt x;
N.valueSet nt data;
N.return nt
end
else
let l, r = (N.left nt, N.right nt) in
(if x < k then
let ll = addMutate l x data in
N.leftSet nt ll
else
N.rightSet nt (addMutate r x data);
);
N.return (N.balMutate nt)
let fromArray (xs : (key * _) array) =
let len = A.length xs in
if len = 0 then N.empty
else
let next =
ref (S.strictlySortedLengthU xs
(fun[@bs] (x0,_) (y0,_) ->
x0 < y0
))
in
let result = ref (
if !next >= 0 then
N.fromSortedArrayAux xs 0 !next
else begin
next := - !next;
N.fromSortedArrayRevAux xs (!next - 1) (!next)
end
) in
for i = !next to len - 1 do
let k, v = (A.getUnsafe xs i) in
result := addMutate !result k v
done ;
!result
| null | https://raw.githubusercontent.com/jaredly/belt/4d07f859403fdbd3fbfc5a9547c6066d657a2131/belt_src/belt_internalMapString.ml | ocaml | Node (l2, v2, d2, r2, h2)
end
let c = (Belt_Cmp.getCmpInternal cmp) x k [@bs] in | # 2 "../others/internal_map.cppo.ml"
type key = string
# 9 "../others/internal_map.cppo.ml"
module N = Belt_internalAVLtree
module A = Belt_Array
module S = Belt_SortArray
type 'a t = (key,'a) N.t
let rec add t (x : key) (data : _) =
match N.toOpt t with
| None ->
N.singleton x data
| Some n ->
let k = N.key n in
if x = k then
N.return (N.updateValue n data)
else
let v = N.value n in
if x < k then
N.bal (add (N.left n) x data ) k v (N.right n)
else
N.bal (N.left n) k v (add (N.right n) x data )
let rec get n (x : key) =
match N.toOpt n with
None -> None
| Some n ->
let v = N.key n in
if x = v then Some (N.value n)
else get (if x < v then N.left n else N.right n) x
let rec getUndefined n (x : key) =
match N.toOpt n with
| None ->
Js.undefined
| Some n ->
let v = N.key n in
if x = v then Js.Undefined.return (N.value n)
else getUndefined (if x < v then (N.left n) else (N.right n)) x
let rec getExn n (x : key) =
match N.toOpt n with
| None -> [%assert "getExn"]
| Some n ->
let v = N.key n in
if x = v then (N.value n)
else getExn (if x < v then (N.left n) else (N.right n)) x
let rec getWithDefault n (x : key) def =
match N.toOpt n with
| None -> def
| Some n ->
let v = N.key n in
if x = v then (N.value n)
else getWithDefault (if x < v then (N.left n) else (N.right n)) x def
let rec has n (x : key)=
match N.toOpt n with
None -> false
Node(l , v , d , r , _ )
let v = N.key n in
x = v || has (if x < v then N.left n else N.right n) x
let rec remove n (x : key) =
match N.toOpt n with
| None -> n
| Some n ->
let l,v,r = N.(left n, key n, right n) in
if x = v then
match N.toOpt l, N.toOpt r with
| None, _ -> r
| _, None -> l
| _, Some rn ->
let kr, vr = ref (N.key rn), ref (N.value rn) in
let r = N.removeMinAuxWithRef rn kr vr in
N.bal l !kr !vr r
else if x < v then
N.(bal (remove l x ) v (value n) r)
else
N.(bal l v (value n) (remove r x ))
let rec splitAux (x : key) (n : _ N.node) : _ t * _ option * _ t =
let l,v,d,r = N.(left n , key n, value n, right n) in
if x = v then (l, Some d, r)
else
if x < v then
match N.toOpt l with
| None ->
N.(empty , None, return n)
| Some l ->
let (ll, pres, rl) = splitAux x l in (ll, pres, N.join rl v d r)
else
match N.toOpt r with
| None ->
N.(return n, None, empty)
| Some r ->
let (lr, pres, rr) = splitAux x r in (N.join l v d lr, pres, rr)
let rec split (x : key) n =
match N.toOpt n with
None ->
N.(empty, None, empty)
| Some n ->
splitAux x n
let rec mergeU s1 s2 f =
match N.(toOpt s1, toOpt s2) with
(None, None) -> N.empty
( Node ( l1 , v1 , d1 , r1 , h1 ) , _ )
when N.(height n >= (match N.toOpt s2 with None -> 0 | Some n -> N.height n)) ->
let (l1,v1,d1,r1) = N.(left n, key n, value n, right n ) in
let (l2, d2, r2) = split v1 s2 in
N.concatOrJoin (mergeU l1 l2 f) v1 (f v1 (Some d1) d2 [@bs]) (mergeU r1 r2 f)
let (l2, v2, d2, r2) = N.(left n, key n, value n, right n) in
let (l1, d1, r1) = split v2 s1 in
N.concatOrJoin (mergeU l1 l2 f) v2 (f v2 d1 (Some d2) [@bs]) (mergeU r1 r2 f)
| _ ->
assert false
let merge s1 s2 f = mergeU s1 s2 (fun [@bs] a b c -> f a b c)
let rec compareAux e1 e2 vcmp =
match e1,e2 with
| h1::t1, h2::t2 ->
let c = Pervasives.compare (N.key h1 : key) (N.key h2) in
if c = 0 then
let cx = vcmp (N.value h1) (N.value h2) [@bs] in
if cx = 0 then
compareAux
(N.stackAllLeft (N.right h1) t1 )
(N.stackAllLeft (N.right h2) t2)
vcmp
else cx
else c
| _, _ -> 0
let cmpU s1 s2 cmp =
let len1, len2 = N.size s1, N.size s2 in
if len1 = len2 then
compareAux
(N.stackAllLeft s1 [])
(N.stackAllLeft s2 [])
cmp
else if len1 < len2 then -1
else 1
let cmp s1 s2 f = cmpU s1 s2 (fun[@bs] a b -> f a b)
let rec eqAux e1 e2 eq =
match e1,e2 with
| h1::t1, h2::t2 ->
if (N.key h1 : key) = (N.key h2) &&
eq (N.value h1) (N.value h2) [@bs] then
eqAux (
N.stackAllLeft (N.right h1) t1 )
(N.stackAllLeft (N.right h2) t2)
eq
else false
let eqU s1 s2 eq =
let len1,len2 = N.size s1, N.size s2 in
if len1 = len2 then
eqAux
(N.stackAllLeft s1 [])
(N.stackAllLeft s2 []) eq
else false
let eq s1 s2 f = eqU s1 s2 (fun[@bs] a b -> f a b)
let rec addMutate (t : _ t) x data : _ t =
match N.toOpt t with
| None -> N.singleton x data
| Some nt ->
let k = N.key nt in
if x = k then begin
N.keySet nt x;
N.valueSet nt data;
N.return nt
end
else
let l, r = (N.left nt, N.right nt) in
(if x < k then
let ll = addMutate l x data in
N.leftSet nt ll
else
N.rightSet nt (addMutate r x data);
);
N.return (N.balMutate nt)
let fromArray (xs : (key * _) array) =
let len = A.length xs in
if len = 0 then N.empty
else
let next =
ref (S.strictlySortedLengthU xs
(fun[@bs] (x0,_) (y0,_) ->
x0 < y0
))
in
let result = ref (
if !next >= 0 then
N.fromSortedArrayAux xs 0 !next
else begin
next := - !next;
N.fromSortedArrayRevAux xs (!next - 1) (!next)
end
) in
for i = !next to len - 1 do
let k, v = (A.getUnsafe xs i) in
result := addMutate !result k v
done ;
!result
|
3fe2bcb1a1f13fbae75c633e87c7ae9cffdf58173fdc92843af303b9af54b96d | leksah/leksah | Trace.hs | # LANGUAGE DeriveGeneric #
# LANGUAGE FlexibleInstances #
{-# LANGUAGE TypeSynonymInstances #-}
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE RecordWildCards #
# LANGUAGE LambdaCase #
-----------------------------------------------------------------------------
--
-- Module : IDE.Pane.Trace
Copyright : 2007 - 2011 ,
-- License : GPL
--
-- Maintainer :
-- Stability : provisional
-- Portability :
--
-- |
--
-----------------------------------------------------------------------------
module IDE.Pane.Trace (
IDETrace
, TraceState
, showTrace
, fillTraceList
) where
import Prelude ()
import Prelude.Compat
import Data.Typeable (Typeable)
import IDE.Core.State
(SrcSpan, IDEM, IDEAction, IDERef, displaySrcSpan,
liftIDE, readIDE, currentHist, reflectIDE)
import IDE.Gtk.State
(Pane(..), RecoverablePane(..), PanePath, Connections,
getNotebook, onIDE, postAsyncIDE)
import IDE.Gtk.Package (tryDebug)
import IDE.Debug
(debugForward, debugBack, debugCommand')
import IDE.Utils.Tool (ToolOutput(..))
import IDE.LogRef (srcSpanParser)
import System.Log.Logger (debugM)
import IDE.Gtk.Workspaces (packageTry)
import qualified Data.Conduit.List as CL (consume)
import Control.Applicative (optional, (<$>), (<|>), many)
import Control.Monad.Trans.Class (MonadTrans(..))
import Control.Monad.IO.Class (MonadIO(..))
import IDE.Utils.GUIUtils (treeViewContextMenu, __, printf)
import Data.Text (Text)
import qualified Data.Text as T (pack, unpack)
import GI.Gtk.Objects.ScrolledWindow
(scrolledWindowSetPolicy, scrolledWindowSetShadowType,
scrolledWindowNew, ScrolledWindow(..))
import GI.Gtk.Objects.TreeView
(treeViewGetSelection, treeViewSetHeadersVisible,
treeViewAppendColumn, treeViewSetModel, treeViewNew, TreeView(..))
import Data.GI.Gtk.ModelView.ForestStore
(forestStoreGetValue, ForestStore(..),
forestStoreInsert, forestStoreClear, forestStoreNew)
import GI.Gtk.Objects.Widget (afterWidgetFocusInEvent, toWidget)
import GI.Gtk.Objects.Notebook (Notebook(..))
import GI.Gtk.Objects.Window (Window(..))
import GI.Gtk.Objects.CellRendererToggle
(setCellRendererToggleActive, cellRendererToggleNew)
import GI.Gtk.Objects.TreeViewColumn
(treeViewColumnSetReorderable, treeViewColumnSetResizable,
treeViewColumnSetSizing, treeViewColumnSetTitle, treeViewColumnNew)
import GI.Gtk.Enums
(PolicyType(..), ShadowType(..), SelectionMode(..),
TreeViewColumnSizing(..))
import GI.Gtk.Interfaces.CellLayout (cellLayoutPackStart)
import Data.GI.Gtk.ModelView.CellLayout
(cellLayoutSetDataFunction)
import GI.Gtk.Objects.CellRendererText
(setCellRendererTextText, cellRendererTextNew)
import GI.Gtk.Objects.TreeSelection
(onTreeSelectionChanged, treeSelectionSetMode)
import GI.Gtk.Objects.Adjustment (Adjustment)
import GI.Gtk.Objects.Container (containerAdd)
import GI.Gtk.Objects.Menu (Menu(..))
import GI.Gtk.Objects.MenuItem
(toMenuItem, onMenuItemActivate, menuItemNewWithLabel)
import GI.Gtk.Objects.SeparatorMenuItem (separatorMenuItemNew)
import GI.Gtk.Objects.MenuShell (menuShellAppend)
import Control.Monad.Reader (MonadReader(..))
import Data.GI.Gtk.ModelView.Types
(treeSelectionGetSelectedRows', treePathNewFromIndices')
import Data.Attoparsec.Text
(string, manyTill, char, (<?>), endOfInput, anyChar, skipMany, try,
parseOnly, Parser)
import qualified Data.Attoparsec.Text as AP
(decimal, string, skipSpace)
import Data.Aeson (FromJSON, ToJSON)
import GHC.Generics (Generic)
-- | A debugger pane description
--
data IDETrace = IDETrace {
scrolledView :: ScrolledWindow
, treeView :: TreeView
, tracepoints :: ForestStore TraceHist
} deriving Typeable
data TraceState = TraceState {
} deriving(Eq,Ord,Read,Show,Typeable,Generic)
instance ToJSON TraceState
instance FromJSON TraceState
data TraceHist = TraceHist {
thSelected :: Bool,
thIndex :: Int,
thFunction :: Text,
thPosition :: SrcSpan
}
instance Pane IDETrace IDEM
where
primPaneName _ = __ "Trace"
getAddedIndex _ = 0
getTopWidget = liftIO . toWidget . scrolledView
paneId _ = "*Trace"
instance RecoverablePane IDETrace TraceState IDEM where
saveState _ = return (Just TraceState)
recoverState pp TraceState = do
nb <- getNotebook pp
buildPane pp nb builder
builder = builder'
getTrace :: IDEM IDETrace
getTrace = forceGetPane (Right "*Trace")
showTrace :: IDEAction
showTrace = do
pane <- getTrace
displayPane pane False
builder' :: PanePath ->
Notebook ->
Window ->
IDEM (Maybe IDETrace,Connections)
builder' _pp _nb _windows = do
ideR <- ask
tracepoints <- forestStoreNew []
treeView <- treeViewNew
treeViewSetModel treeView (Just tracepoints)
renderer0 <- cellRendererToggleNew
col0 <- treeViewColumnNew
treeViewColumnSetTitle col0 ""
treeViewColumnSetSizing col0 TreeViewColumnSizingAutosize
treeViewColumnSetResizable col0 False
treeViewColumnSetReorderable col0 True
_ <- treeViewAppendColumn treeView col0
cellLayoutPackStart col0 renderer0 False
cellLayoutSetDataFunction col0 renderer0 tracepoints
$ setCellRendererToggleActive renderer0 . thSelected
renderer1 <- cellRendererTextNew
col1 <- treeViewColumnNew
treeViewColumnSetTitle col1 (__ "Index")
treeViewColumnSetSizing col1 TreeViewColumnSizingAutosize
treeViewColumnSetResizable col1 True
treeViewColumnSetReorderable col1 True
_ <- treeViewAppendColumn treeView col1
cellLayoutPackStart col1 renderer1 False
cellLayoutSetDataFunction col1 renderer1 tracepoints
$ setCellRendererTextText renderer1 . T.pack . show . thIndex
renderer2 <- cellRendererTextNew
col2 <- treeViewColumnNew
treeViewColumnSetTitle col2 (__ "Function")
treeViewColumnSetSizing col2 TreeViewColumnSizingAutosize
treeViewColumnSetResizable col2 True
treeViewColumnSetReorderable col2 True
_ <- treeViewAppendColumn treeView col2
cellLayoutPackStart col2 renderer2 False
cellLayoutSetDataFunction col2 renderer2 tracepoints
$ setCellRendererTextText renderer2 . thFunction
renderer3 <- cellRendererTextNew
col3 <- treeViewColumnNew
treeViewColumnSetTitle col3 (__ "Position")
treeViewColumnSetSizing col3 TreeViewColumnSizingAutosize
treeViewColumnSetResizable col3 True
treeViewColumnSetReorderable col3 True
_ <- treeViewAppendColumn treeView col3
cellLayoutPackStart col3 renderer3 False
cellLayoutSetDataFunction col3 renderer3 tracepoints
$ setCellRendererTextText renderer3 . T.pack . displaySrcSpan . thPosition
treeViewSetHeadersVisible treeView True
sel <- treeViewGetSelection treeView
treeSelectionSetMode sel SelectionModeSingle
scrolledView <- scrolledWindowNew (Nothing :: Maybe Adjustment) (Nothing :: Maybe Adjustment)
scrolledWindowSetShadowType scrolledView ShadowTypeIn
containerAdd scrolledView treeView
scrolledWindowSetPolicy scrolledView PolicyTypeAutomatic PolicyTypeAutomatic
let pane = IDETrace {..}
cid1 <- onIDE afterWidgetFocusInEvent treeView (do
liftIDE $ makeActive pane
return True)
cids2 <- treeViewContextMenu treeView $ traceContextMenu ideR tracepoints treeView
_ <- onTreeSelectionChanged sel $
getSelectedTracepoint treeView tracepoints >>= \case
TODO reflectIDE ( selectRef ( Just ref ) ) ideR
Nothing -> return ()
return (Just pane, cid1 : cids2)
fillTraceList :: IDEAction
fillTraceList = packageTry $ do
currentHist' <- readIDE currentHist
mbTraces <- liftIDE getPane
case mbTraces of
Nothing -> return ()
Just tracePane -> tryDebug $ debugCommand' ":history" $ do
to <- CL.consume
lift $ postAsyncIDE $ do
let parseRes = parseOnly tracesParser $ selectString to
r <- case parseRes of
Left err -> do
liftIO $ debugM "leksah" (printf (__ "trace parse error %s\ninput: %s") (show err)
(T.unpack $ selectString to))
return []
Right traces -> return traces
forestStoreClear (tracepoints tracePane)
let r' = map (\h@(TraceHist _ i _ _) -> if i == currentHist'
then h{thSelected = True}
else h) r
mapM_ (insertTrace (tracepoints tracePane))
(zip r' [0..length r'])
where
insertTrace forestStore (tr,index) = do
emptyPath <- treePathNewFromIndices' []
forestStoreInsert forestStore emptyPath index tr
selectString :: [ToolOutput] -> Text
selectString (ToolOutput str:r) = "\n" <> str <> selectString r
selectString (_:r) = selectString r
selectString [] = ""
getSelectedTracepoint :: TreeView
-> ForestStore TraceHist
-> IO (Maybe TraceHist)
getSelectedTracepoint treeView forestStore = do
treeSelection <- treeViewGetSelection treeView
paths <- treeSelectionGetSelectedRows' treeSelection
case paths of
a:_ -> do
val <- forestStoreGetValue forestStore a
return (Just val)
_ -> return Nothing
--selectStrings :: [ToolOutput] -> [Text]
selectStrings ( ToolOutput str : r ) = str : r
--selectStrings (_:r) = selectStrings r
--selectStrings [] = []
traceContextMenu :: IDERef
-> ForestStore TraceHist
-> TreeView
-> Menu
-> IO ()
traceContextMenu ideR _store _treeView theMenu = do
item1 <- menuItemNewWithLabel (__ "Back")
_ <- onMenuItemActivate item1 $ reflectIDE debugBack ideR
sep1 <- separatorMenuItemNew >>= liftIO . toMenuItem
item2 <- menuItemNewWithLabel (__ "Forward")
_ <- onMenuItemActivate item2 $ reflectIDE debugForward ideR
item3 <- menuItemNewWithLabel (__ "Update")
_ <- onMenuItemActivate item3 $ reflectIDE fillTraceList ideR
mapM_ (menuShellAppend theMenu) [item1, sep1, item2, item3]
tracesParser :: Parser [TraceHist]
tracesParser = try (do
whiteSpace
_ <- symbol (__ "Empty history.")
skipMany anyChar
endOfInput
return [])
<|> do
traces <- many (try traceParser)
whiteSpace
_ <- symbol (__ "<end of history>")
endOfInput
return traces
<|> do
whiteSpace
_ <- symbol (__ "Not stopped at a breakpoint")
skipMany anyChar
endOfInput
return []
<?>
T.unpack (__ "traces parser")
traceParser :: Parser TraceHist
traceParser = do
whiteSpace
index <- int
_ <- char ':'
whiteSpace
_ <- optional (symbol "\ESC[1m")
function <- T.pack <$> manyTill anyChar (string "(\ESC")
_ <- optional (symbol "\ESC[0m")
_ <- symbol "("
span' <- srcSpanParser
_ <- symbol ")"
return (TraceHist False index function span')
<?> T.unpack (__ "trace parser")
whiteSpace :: Parser ()
whiteSpace = AP.skipSpace
symbol :: Text -> Parser Text
symbol = AP.string
int :: Parser Int
int = AP.decimal
| null | https://raw.githubusercontent.com/leksah/leksah/ec95f33af27fea09cba140d7cddd010935a2cf52/src-gtk/IDE/Pane/Trace.hs | haskell | # LANGUAGE TypeSynonymInstances #
# LANGUAGE DeriveDataTypeable #
# LANGUAGE OverloadedStrings #
---------------------------------------------------------------------------
Module : IDE.Pane.Trace
License : GPL
Maintainer :
Stability : provisional
Portability :
|
---------------------------------------------------------------------------
| A debugger pane description
selectStrings :: [ToolOutput] -> [Text]
selectStrings (_:r) = selectStrings r
selectStrings [] = [] | # LANGUAGE DeriveGeneric #
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE RecordWildCards #
# LANGUAGE LambdaCase #
Copyright : 2007 - 2011 ,
module IDE.Pane.Trace (
IDETrace
, TraceState
, showTrace
, fillTraceList
) where
import Prelude ()
import Prelude.Compat
import Data.Typeable (Typeable)
import IDE.Core.State
(SrcSpan, IDEM, IDEAction, IDERef, displaySrcSpan,
liftIDE, readIDE, currentHist, reflectIDE)
import IDE.Gtk.State
(Pane(..), RecoverablePane(..), PanePath, Connections,
getNotebook, onIDE, postAsyncIDE)
import IDE.Gtk.Package (tryDebug)
import IDE.Debug
(debugForward, debugBack, debugCommand')
import IDE.Utils.Tool (ToolOutput(..))
import IDE.LogRef (srcSpanParser)
import System.Log.Logger (debugM)
import IDE.Gtk.Workspaces (packageTry)
import qualified Data.Conduit.List as CL (consume)
import Control.Applicative (optional, (<$>), (<|>), many)
import Control.Monad.Trans.Class (MonadTrans(..))
import Control.Monad.IO.Class (MonadIO(..))
import IDE.Utils.GUIUtils (treeViewContextMenu, __, printf)
import Data.Text (Text)
import qualified Data.Text as T (pack, unpack)
import GI.Gtk.Objects.ScrolledWindow
(scrolledWindowSetPolicy, scrolledWindowSetShadowType,
scrolledWindowNew, ScrolledWindow(..))
import GI.Gtk.Objects.TreeView
(treeViewGetSelection, treeViewSetHeadersVisible,
treeViewAppendColumn, treeViewSetModel, treeViewNew, TreeView(..))
import Data.GI.Gtk.ModelView.ForestStore
(forestStoreGetValue, ForestStore(..),
forestStoreInsert, forestStoreClear, forestStoreNew)
import GI.Gtk.Objects.Widget (afterWidgetFocusInEvent, toWidget)
import GI.Gtk.Objects.Notebook (Notebook(..))
import GI.Gtk.Objects.Window (Window(..))
import GI.Gtk.Objects.CellRendererToggle
(setCellRendererToggleActive, cellRendererToggleNew)
import GI.Gtk.Objects.TreeViewColumn
(treeViewColumnSetReorderable, treeViewColumnSetResizable,
treeViewColumnSetSizing, treeViewColumnSetTitle, treeViewColumnNew)
import GI.Gtk.Enums
(PolicyType(..), ShadowType(..), SelectionMode(..),
TreeViewColumnSizing(..))
import GI.Gtk.Interfaces.CellLayout (cellLayoutPackStart)
import Data.GI.Gtk.ModelView.CellLayout
(cellLayoutSetDataFunction)
import GI.Gtk.Objects.CellRendererText
(setCellRendererTextText, cellRendererTextNew)
import GI.Gtk.Objects.TreeSelection
(onTreeSelectionChanged, treeSelectionSetMode)
import GI.Gtk.Objects.Adjustment (Adjustment)
import GI.Gtk.Objects.Container (containerAdd)
import GI.Gtk.Objects.Menu (Menu(..))
import GI.Gtk.Objects.MenuItem
(toMenuItem, onMenuItemActivate, menuItemNewWithLabel)
import GI.Gtk.Objects.SeparatorMenuItem (separatorMenuItemNew)
import GI.Gtk.Objects.MenuShell (menuShellAppend)
import Control.Monad.Reader (MonadReader(..))
import Data.GI.Gtk.ModelView.Types
(treeSelectionGetSelectedRows', treePathNewFromIndices')
import Data.Attoparsec.Text
(string, manyTill, char, (<?>), endOfInput, anyChar, skipMany, try,
parseOnly, Parser)
import qualified Data.Attoparsec.Text as AP
(decimal, string, skipSpace)
import Data.Aeson (FromJSON, ToJSON)
import GHC.Generics (Generic)
data IDETrace = IDETrace {
scrolledView :: ScrolledWindow
, treeView :: TreeView
, tracepoints :: ForestStore TraceHist
} deriving Typeable
data TraceState = TraceState {
} deriving(Eq,Ord,Read,Show,Typeable,Generic)
instance ToJSON TraceState
instance FromJSON TraceState
data TraceHist = TraceHist {
thSelected :: Bool,
thIndex :: Int,
thFunction :: Text,
thPosition :: SrcSpan
}
instance Pane IDETrace IDEM
where
primPaneName _ = __ "Trace"
getAddedIndex _ = 0
getTopWidget = liftIO . toWidget . scrolledView
paneId _ = "*Trace"
instance RecoverablePane IDETrace TraceState IDEM where
saveState _ = return (Just TraceState)
recoverState pp TraceState = do
nb <- getNotebook pp
buildPane pp nb builder
builder = builder'
getTrace :: IDEM IDETrace
getTrace = forceGetPane (Right "*Trace")
showTrace :: IDEAction
showTrace = do
pane <- getTrace
displayPane pane False
builder' :: PanePath ->
Notebook ->
Window ->
IDEM (Maybe IDETrace,Connections)
builder' _pp _nb _windows = do
ideR <- ask
tracepoints <- forestStoreNew []
treeView <- treeViewNew
treeViewSetModel treeView (Just tracepoints)
renderer0 <- cellRendererToggleNew
col0 <- treeViewColumnNew
treeViewColumnSetTitle col0 ""
treeViewColumnSetSizing col0 TreeViewColumnSizingAutosize
treeViewColumnSetResizable col0 False
treeViewColumnSetReorderable col0 True
_ <- treeViewAppendColumn treeView col0
cellLayoutPackStart col0 renderer0 False
cellLayoutSetDataFunction col0 renderer0 tracepoints
$ setCellRendererToggleActive renderer0 . thSelected
renderer1 <- cellRendererTextNew
col1 <- treeViewColumnNew
treeViewColumnSetTitle col1 (__ "Index")
treeViewColumnSetSizing col1 TreeViewColumnSizingAutosize
treeViewColumnSetResizable col1 True
treeViewColumnSetReorderable col1 True
_ <- treeViewAppendColumn treeView col1
cellLayoutPackStart col1 renderer1 False
cellLayoutSetDataFunction col1 renderer1 tracepoints
$ setCellRendererTextText renderer1 . T.pack . show . thIndex
renderer2 <- cellRendererTextNew
col2 <- treeViewColumnNew
treeViewColumnSetTitle col2 (__ "Function")
treeViewColumnSetSizing col2 TreeViewColumnSizingAutosize
treeViewColumnSetResizable col2 True
treeViewColumnSetReorderable col2 True
_ <- treeViewAppendColumn treeView col2
cellLayoutPackStart col2 renderer2 False
cellLayoutSetDataFunction col2 renderer2 tracepoints
$ setCellRendererTextText renderer2 . thFunction
renderer3 <- cellRendererTextNew
col3 <- treeViewColumnNew
treeViewColumnSetTitle col3 (__ "Position")
treeViewColumnSetSizing col3 TreeViewColumnSizingAutosize
treeViewColumnSetResizable col3 True
treeViewColumnSetReorderable col3 True
_ <- treeViewAppendColumn treeView col3
cellLayoutPackStart col3 renderer3 False
cellLayoutSetDataFunction col3 renderer3 tracepoints
$ setCellRendererTextText renderer3 . T.pack . displaySrcSpan . thPosition
treeViewSetHeadersVisible treeView True
sel <- treeViewGetSelection treeView
treeSelectionSetMode sel SelectionModeSingle
scrolledView <- scrolledWindowNew (Nothing :: Maybe Adjustment) (Nothing :: Maybe Adjustment)
scrolledWindowSetShadowType scrolledView ShadowTypeIn
containerAdd scrolledView treeView
scrolledWindowSetPolicy scrolledView PolicyTypeAutomatic PolicyTypeAutomatic
let pane = IDETrace {..}
cid1 <- onIDE afterWidgetFocusInEvent treeView (do
liftIDE $ makeActive pane
return True)
cids2 <- treeViewContextMenu treeView $ traceContextMenu ideR tracepoints treeView
_ <- onTreeSelectionChanged sel $
getSelectedTracepoint treeView tracepoints >>= \case
TODO reflectIDE ( selectRef ( Just ref ) ) ideR
Nothing -> return ()
return (Just pane, cid1 : cids2)
fillTraceList :: IDEAction
fillTraceList = packageTry $ do
currentHist' <- readIDE currentHist
mbTraces <- liftIDE getPane
case mbTraces of
Nothing -> return ()
Just tracePane -> tryDebug $ debugCommand' ":history" $ do
to <- CL.consume
lift $ postAsyncIDE $ do
let parseRes = parseOnly tracesParser $ selectString to
r <- case parseRes of
Left err -> do
liftIO $ debugM "leksah" (printf (__ "trace parse error %s\ninput: %s") (show err)
(T.unpack $ selectString to))
return []
Right traces -> return traces
forestStoreClear (tracepoints tracePane)
let r' = map (\h@(TraceHist _ i _ _) -> if i == currentHist'
then h{thSelected = True}
else h) r
mapM_ (insertTrace (tracepoints tracePane))
(zip r' [0..length r'])
where
insertTrace forestStore (tr,index) = do
emptyPath <- treePathNewFromIndices' []
forestStoreInsert forestStore emptyPath index tr
selectString :: [ToolOutput] -> Text
selectString (ToolOutput str:r) = "\n" <> str <> selectString r
selectString (_:r) = selectString r
selectString [] = ""
getSelectedTracepoint :: TreeView
-> ForestStore TraceHist
-> IO (Maybe TraceHist)
getSelectedTracepoint treeView forestStore = do
treeSelection <- treeViewGetSelection treeView
paths <- treeSelectionGetSelectedRows' treeSelection
case paths of
a:_ -> do
val <- forestStoreGetValue forestStore a
return (Just val)
_ -> return Nothing
selectStrings ( ToolOutput str : r ) = str : r
traceContextMenu :: IDERef
-> ForestStore TraceHist
-> TreeView
-> Menu
-> IO ()
traceContextMenu ideR _store _treeView theMenu = do
item1 <- menuItemNewWithLabel (__ "Back")
_ <- onMenuItemActivate item1 $ reflectIDE debugBack ideR
sep1 <- separatorMenuItemNew >>= liftIO . toMenuItem
item2 <- menuItemNewWithLabel (__ "Forward")
_ <- onMenuItemActivate item2 $ reflectIDE debugForward ideR
item3 <- menuItemNewWithLabel (__ "Update")
_ <- onMenuItemActivate item3 $ reflectIDE fillTraceList ideR
mapM_ (menuShellAppend theMenu) [item1, sep1, item2, item3]
tracesParser :: Parser [TraceHist]
tracesParser = try (do
whiteSpace
_ <- symbol (__ "Empty history.")
skipMany anyChar
endOfInput
return [])
<|> do
traces <- many (try traceParser)
whiteSpace
_ <- symbol (__ "<end of history>")
endOfInput
return traces
<|> do
whiteSpace
_ <- symbol (__ "Not stopped at a breakpoint")
skipMany anyChar
endOfInput
return []
<?>
T.unpack (__ "traces parser")
traceParser :: Parser TraceHist
traceParser = do
whiteSpace
index <- int
_ <- char ':'
whiteSpace
_ <- optional (symbol "\ESC[1m")
function <- T.pack <$> manyTill anyChar (string "(\ESC")
_ <- optional (symbol "\ESC[0m")
_ <- symbol "("
span' <- srcSpanParser
_ <- symbol ")"
return (TraceHist False index function span')
<?> T.unpack (__ "trace parser")
whiteSpace :: Parser ()
whiteSpace = AP.skipSpace
symbol :: Text -> Parser Text
symbol = AP.string
int :: Parser Int
int = AP.decimal
|
c0ef434058c22510b2323c77261dca37641cb240a77bf9fd81d3ea98c6ed461e | NorfairKing/validity | VectorSpec.hs | # LANGUAGE TypeApplications #
module Test.Validity.VectorSpec where
import Data.GenValidity.Vector ()
import qualified Data.Vector as V
import qualified Data.Vector.Storable as SV
import Test.Hspec
import Test.Validity.GenValidity
spec :: Spec
spec = do
genValidSpec @(V.Vector Int)
genValidSpec @(V.Vector Rational)
genValidSpec @(SV.Vector Int)
| null | https://raw.githubusercontent.com/NorfairKing/validity/35bc8d45b27e6c21429e4b681b16e46ccd541b3b/genvalidity-vector/test/Test/Validity/VectorSpec.hs | haskell | # LANGUAGE TypeApplications #
module Test.Validity.VectorSpec where
import Data.GenValidity.Vector ()
import qualified Data.Vector as V
import qualified Data.Vector.Storable as SV
import Test.Hspec
import Test.Validity.GenValidity
spec :: Spec
spec = do
genValidSpec @(V.Vector Int)
genValidSpec @(V.Vector Rational)
genValidSpec @(SV.Vector Int)
| |
c049c826395ba4cc0d121a9759c0f733edb663baabdadaa60bd88cd724689977 | scarf-sh/tie | Name.hs | # LANGUAGE GeneralizedNewtypeDeriving #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE ScopedTypeVariables #
module Tie.Name
( PackageName,
ApiName,
Name,
fromText,
cabalFileName,
toDataTypeName,
toOneOfDataTypeName,
toOneOfConstructorName,
toFunctionName,
toConstructorName,
toFieldName,
toJsonFieldName,
toParamName,
toParamBinder,
toApiTypeName,
toSchemaHaskellFileName,
toSchemaHaskellModuleName,
toOperationHaskellFileName,
toOperationHaskellModuleName,
toResponseHaskellFileName,
toResponseHaskellModuleName,
toApiResponseTypeName,
toApiResponseConstructorName,
toApiDefaultResponseConstructorName,
toApiMemberName,
toEnumConstructorName,
apiHaskellModuleName,
apiHaskellFileName,
requestHaskellModuleName,
requestHaskellFileName,
responseHaskellModuleName,
responseHaskellFileName,
inlineObjectTypeName,
additionalPropertiesTypeName,
inlineVariantTypeName,
inlineArrayElementTypeName,
operationParamTypeName,
operationRequestBodyName,
apiResponseConstructorName,
apiDefaultResponseConstructorName,
extractHaskellModule,
)
where
import Data.Char (isUpper, toLower, toUpper)
import qualified Data.List as List
import qualified Data.Text as Text
import qualified Prettyprinter as PP
-- | Name of the API to generate code for
type ApiName = Text
| Cabal package name
type PackageName = Text
| Names identify things in the OpenApi universe . Name 's are coming directly
from the OpenApi spec .
newtype Name = Name {unName :: Text}
deriving (IsString, Eq, Ord, Show, Hashable)
fromText :: Text -> Name
fromText = Name
cabalFileName :: PackageName -> FilePath
cabalFileName packageName =
Text.unpack packageName <> ".cabal"
apiHaskellModuleName :: ApiName -> Text
apiHaskellModuleName apiName =
apiName <> ".Api"
apiHaskellFileName :: ApiName -> FilePath
apiHaskellFileName apiName =
haskellModuleToFilePath apiName <> "/Api.hs"
requestHaskellModuleName :: ApiName -> Text
requestHaskellModuleName apiName =
apiName <> ".Request"
requestHaskellFileName :: ApiName -> FilePath
requestHaskellFileName apiName =
haskellModuleToFilePath apiName <> "/Request.hs"
responseHaskellModuleName :: ApiName -> Text
responseHaskellModuleName apiName =
apiName <> ".Response"
responseHaskellFileName :: ApiName -> FilePath
responseHaskellFileName apiName =
haskellModuleToFilePath apiName <> "/Response.hs"
toSchemaHaskellModuleName :: ApiName -> Name -> Text
toSchemaHaskellModuleName apiName (Name name) =
Text.pack $ Text.unpack apiName <> ".Schemas." <> capitalizeFirstLetter (Text.unpack name)
toSchemaHaskellFileName :: ApiName -> Name -> FilePath
toSchemaHaskellFileName apiName (Name name) =
haskellModuleToFilePath apiName <> "/Schemas/" <> capitalizeFirstLetter (Text.unpack name) <> ".hs"
haskellModuleToFilePath :: ApiName -> FilePath
haskellModuleToFilePath =
Text.unpack . Text.replace "." "/"
toOperationHaskellModuleName :: ApiName -> Name -> Text
toOperationHaskellModuleName apiName (Name name) =
Text.pack $ Text.unpack apiName <> ".Api." <> capitalizeFirstLetter (Text.unpack name)
toOperationHaskellFileName :: ApiName -> Name -> FilePath
toOperationHaskellFileName apiName (Name name) =
haskellModuleToFilePath apiName <> "/Api/" <> capitalizeFirstLetter (Text.unpack name) <> ".hs"
toResponseHaskellModuleName :: ApiName -> Name -> Text
toResponseHaskellModuleName apiName (Name name) =
Text.pack $ Text.unpack apiName <> ".Response." <> capitalizeFirstLetter (Text.unpack name)
toResponseHaskellFileName :: ApiName -> Name -> FilePath
toResponseHaskellFileName apiName (Name name) =
haskellModuleToFilePath apiName <> "/Response/" <> capitalizeFirstLetter (Text.unpack name) <> ".hs"
toApiTypeName :: Name -> PP.Doc ann
toApiTypeName =
toDataTypeName
toJsonFieldName :: Name -> PP.Doc ann
toJsonFieldName = PP.pretty . unName
toDataTypeName :: Name -> PP.Doc ann
toDataTypeName =
PP.pretty . Text.pack . capitalizeFirstLetter . toCamelCase . Text.unpack . unName
toOneOfDataTypeName :: Name -> PP.Doc ann
toOneOfDataTypeName =
PP.pretty . Text.pack . capitalizeFirstLetter . toCamelCase . Text.unpack . unName
toOneOfConstructorName :: Name -> Name -> PP.Doc ann
toOneOfConstructorName (Name oneOfType) (Name variant) =
PP.pretty $
Text.pack $
escapeKeyword $
capitalizeFirstLetter (toCamelCase $ Text.unpack oneOfType)
<> capitalizeFirstLetter (toCamelCase $ Text.unpack variant)
toConstructorName :: Name -> PP.Doc ann
toConstructorName = toDataTypeName
toFunctionName :: Name -> PP.Doc ann
toFunctionName =
PP.pretty . Text.pack . escapeKeyword . lowerFirstLetter . toCamelCase . Text.unpack . unName
toFieldName :: Name -> PP.Doc ann
toFieldName =
PP.pretty . Text.pack . escapeKeyword . lowerFirstLetter . toCamelCase . Text.unpack . unName
-- | Returns the name as written, should be used within quotes only.
toParamName :: Name -> PP.Doc ann
toParamName =
PP.pretty . filterNUL . unName
where
-- Filter away '\0' to support the weird cookie trick
-- (see test/golden/weird-cookie-trick.yaml)
filterNUL = Text.filter (/= '\0')
toParamBinder :: Name -> PP.Doc ann
toParamBinder =
PP.pretty . Text.pack . escapeKeyword . lowerFirstLetter . ("__" <>) . Text.unpack . unName
operationParamTypeName :: Name -> Name -> Name
operationParamTypeName (Name operationName) (Name paramName) =
Name $
Text.pack $
escapeKeyword $
capitalizeFirstLetter (Text.unpack operationName)
<> capitalizeFirstLetter (Text.unpack paramName)
<> "Param"
operationRequestBodyName :: Name -> Name
operationRequestBodyName (Name operationName) =
Name $
Text.pack $
escapeKeyword $
capitalizeFirstLetter (Text.unpack operationName)
<> "RequestBody"
toApiMemberName :: Name -> PP.Doc ann
toApiMemberName =
PP.pretty . Text.pack . escapeKeyword . lowerFirstLetter . toCamelCase . Text.unpack . unName
toApiResponseTypeName :: Name -> PP.Doc ann
toApiResponseTypeName =
PP.pretty . Text.pack . escapeKeyword . (<> "Response") . capitalizeFirstLetter . Text.unpack . unName
toApiResponseConstructorName :: Name -> Int -> PP.Doc ann
toApiResponseConstructorName name statusCode =
PP.pretty . Text.pack . escapeKeyword . (<> show statusCode) . (<> "Response") . capitalizeFirstLetter . Text.unpack . unName $ name
apiResponseConstructorName :: Name -> Int -> Name
apiResponseConstructorName name statusCode =
Name . Text.pack . escapeKeyword . (<> show statusCode) . (<> "ResponseBody") . capitalizeFirstLetter . Text.unpack . unName $ name
toApiDefaultResponseConstructorName :: Name -> PP.Doc ann
toApiDefaultResponseConstructorName name =
PP.pretty . Text.pack . escapeKeyword . (<> "DefaultResponse") . capitalizeFirstLetter . Text.unpack . unName $ name
apiDefaultResponseConstructorName :: Name -> Name
apiDefaultResponseConstructorName name =
Name . Text.pack . escapeKeyword . (<> "DefaultResponseBody") . capitalizeFirstLetter . Text.unpack . unName $ name
toEnumConstructorName :: Name -> Text -> PP.Doc ann
toEnumConstructorName (Name typName) variant =
PP.pretty $
Text.pack $
escapeKeyword $
toCamelCase $
capitalizeFirstLetter (Text.unpack typName)
<> capitalizeFirstLetter (Text.unpack variant)
-- | Constructs a name for an object defined inline. Based on the containing data
-- type as well as the field name.
inlineObjectTypeName :: Name -> Name -> Name
inlineObjectTypeName (Name parentType) (Name fieldName) =
Name $
Text.pack $
escapeKeyword $
capitalizeFirstLetter (Text.unpack parentType)
<> capitalizeFirstLetter (Text.unpack fieldName)
| Generate a name for additionalProperties type name within an
ObjectType .
additionalPropertiesTypeName :: Name -> Name
additionalPropertiesTypeName (Name parentObjectType) =
Name $
Text.pack $
escapeKeyword $
capitalizeFirstLetter (Text.unpack parentObjectType)
<> "AdditionalProperties"
-- | Construct a name for an inline type in a oneOf.
inlineVariantTypeName :: Name -> Int -> Name
inlineVariantTypeName (Name parentType) ith =
Name $
Text.pack $
escapeKeyword $
capitalizeFirstLetter (Text.unpack parentType) <> "OneOf" <> show ith
inlineArrayElementTypeName :: Name -> Name
inlineArrayElementTypeName (Name parentType) =
Name $
Text.pack $
escapeKeyword $
capitalizeFirstLetter (Text.unpack parentType) <> "Elem"
lowerFirstLetter :: String -> String
lowerFirstLetter [] = []
lowerFirstLetter (x : xs) = toLower x : xs
capitalizeFirstLetter :: String -> String
capitalizeFirstLetter [] = []
capitalizeFirstLetter (x : xs) = toUpper x : xs
escapeKeyword :: String -> String
escapeKeyword input = haskelify $ case input of
"type" -> "type'"
"class" -> "class'"
"where" -> "where'"
"case" -> "case'"
"of" -> "of'"
"data" -> "data'"
"import" -> "import'"
"qualified" -> "qualified'"
"as" -> "as'"
"instance" -> "instance'"
"module" -> "module'"
"pattern" -> "pattern'"
_ -> input
haskelify :: String -> String
haskelify = concatMap escape
where
escape c = case c of
'-' -> "_"
'\0' -> "NUL"
_ -> [c]
toCamelCase :: String -> String
toCamelCase input =
(prefix <>)
. (<> suffix)
. concat
. map (capitalizeFirstLetter . Text.unpack)
. Text.split (\c -> c == '_' || c == '-')
. Text.pack
$ input
where
-- Preserve leading and trailing _
prefix = takeWhile ('_' ==) input
suffix = takeWhile ('_' ==) (reverse input)
-- @
-- extractHaskellModules "Int" = []
extractHaskellModules " . Int " = = [ " " ]
extractHaskellModules " Scarf . Hashids . . Int = = [ " Scarf . Hashids " , " " ] "
-- @
extractHaskellModule :: Text -> [Text]
extractHaskellModule =
let extractModule ty =
case List.init (Text.splitOn "." ty) of
[] ->
[]
xs ->
[Text.intercalate "." xs]
in concatMap extractModule . Text.words
| null | https://raw.githubusercontent.com/scarf-sh/tie/61a154f14d729ad79136f71f28763f7fd9fe7ce7/src/Tie/Name.hs | haskell | # LANGUAGE OverloadedStrings #
| Name of the API to generate code for
| Returns the name as written, should be used within quotes only.
Filter away '\0' to support the weird cookie trick
(see test/golden/weird-cookie-trick.yaml)
| Constructs a name for an object defined inline. Based on the containing data
type as well as the field name.
| Construct a name for an inline type in a oneOf.
Preserve leading and trailing _
@
extractHaskellModules "Int" = []
@ | # LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE ScopedTypeVariables #
module Tie.Name
( PackageName,
ApiName,
Name,
fromText,
cabalFileName,
toDataTypeName,
toOneOfDataTypeName,
toOneOfConstructorName,
toFunctionName,
toConstructorName,
toFieldName,
toJsonFieldName,
toParamName,
toParamBinder,
toApiTypeName,
toSchemaHaskellFileName,
toSchemaHaskellModuleName,
toOperationHaskellFileName,
toOperationHaskellModuleName,
toResponseHaskellFileName,
toResponseHaskellModuleName,
toApiResponseTypeName,
toApiResponseConstructorName,
toApiDefaultResponseConstructorName,
toApiMemberName,
toEnumConstructorName,
apiHaskellModuleName,
apiHaskellFileName,
requestHaskellModuleName,
requestHaskellFileName,
responseHaskellModuleName,
responseHaskellFileName,
inlineObjectTypeName,
additionalPropertiesTypeName,
inlineVariantTypeName,
inlineArrayElementTypeName,
operationParamTypeName,
operationRequestBodyName,
apiResponseConstructorName,
apiDefaultResponseConstructorName,
extractHaskellModule,
)
where
import Data.Char (isUpper, toLower, toUpper)
import qualified Data.List as List
import qualified Data.Text as Text
import qualified Prettyprinter as PP
type ApiName = Text
| Cabal package name
type PackageName = Text
| Names identify things in the OpenApi universe . Name 's are coming directly
from the OpenApi spec .
newtype Name = Name {unName :: Text}
deriving (IsString, Eq, Ord, Show, Hashable)
fromText :: Text -> Name
fromText = Name
cabalFileName :: PackageName -> FilePath
cabalFileName packageName =
Text.unpack packageName <> ".cabal"
apiHaskellModuleName :: ApiName -> Text
apiHaskellModuleName apiName =
apiName <> ".Api"
apiHaskellFileName :: ApiName -> FilePath
apiHaskellFileName apiName =
haskellModuleToFilePath apiName <> "/Api.hs"
requestHaskellModuleName :: ApiName -> Text
requestHaskellModuleName apiName =
apiName <> ".Request"
requestHaskellFileName :: ApiName -> FilePath
requestHaskellFileName apiName =
haskellModuleToFilePath apiName <> "/Request.hs"
responseHaskellModuleName :: ApiName -> Text
responseHaskellModuleName apiName =
apiName <> ".Response"
responseHaskellFileName :: ApiName -> FilePath
responseHaskellFileName apiName =
haskellModuleToFilePath apiName <> "/Response.hs"
toSchemaHaskellModuleName :: ApiName -> Name -> Text
toSchemaHaskellModuleName apiName (Name name) =
Text.pack $ Text.unpack apiName <> ".Schemas." <> capitalizeFirstLetter (Text.unpack name)
toSchemaHaskellFileName :: ApiName -> Name -> FilePath
toSchemaHaskellFileName apiName (Name name) =
haskellModuleToFilePath apiName <> "/Schemas/" <> capitalizeFirstLetter (Text.unpack name) <> ".hs"
haskellModuleToFilePath :: ApiName -> FilePath
haskellModuleToFilePath =
Text.unpack . Text.replace "." "/"
toOperationHaskellModuleName :: ApiName -> Name -> Text
toOperationHaskellModuleName apiName (Name name) =
Text.pack $ Text.unpack apiName <> ".Api." <> capitalizeFirstLetter (Text.unpack name)
toOperationHaskellFileName :: ApiName -> Name -> FilePath
toOperationHaskellFileName apiName (Name name) =
haskellModuleToFilePath apiName <> "/Api/" <> capitalizeFirstLetter (Text.unpack name) <> ".hs"
toResponseHaskellModuleName :: ApiName -> Name -> Text
toResponseHaskellModuleName apiName (Name name) =
Text.pack $ Text.unpack apiName <> ".Response." <> capitalizeFirstLetter (Text.unpack name)
toResponseHaskellFileName :: ApiName -> Name -> FilePath
toResponseHaskellFileName apiName (Name name) =
haskellModuleToFilePath apiName <> "/Response/" <> capitalizeFirstLetter (Text.unpack name) <> ".hs"
toApiTypeName :: Name -> PP.Doc ann
toApiTypeName =
toDataTypeName
toJsonFieldName :: Name -> PP.Doc ann
toJsonFieldName = PP.pretty . unName
toDataTypeName :: Name -> PP.Doc ann
toDataTypeName =
PP.pretty . Text.pack . capitalizeFirstLetter . toCamelCase . Text.unpack . unName
toOneOfDataTypeName :: Name -> PP.Doc ann
toOneOfDataTypeName =
PP.pretty . Text.pack . capitalizeFirstLetter . toCamelCase . Text.unpack . unName
toOneOfConstructorName :: Name -> Name -> PP.Doc ann
toOneOfConstructorName (Name oneOfType) (Name variant) =
PP.pretty $
Text.pack $
escapeKeyword $
capitalizeFirstLetter (toCamelCase $ Text.unpack oneOfType)
<> capitalizeFirstLetter (toCamelCase $ Text.unpack variant)
toConstructorName :: Name -> PP.Doc ann
toConstructorName = toDataTypeName
toFunctionName :: Name -> PP.Doc ann
toFunctionName =
PP.pretty . Text.pack . escapeKeyword . lowerFirstLetter . toCamelCase . Text.unpack . unName
toFieldName :: Name -> PP.Doc ann
toFieldName =
PP.pretty . Text.pack . escapeKeyword . lowerFirstLetter . toCamelCase . Text.unpack . unName
toParamName :: Name -> PP.Doc ann
toParamName =
PP.pretty . filterNUL . unName
where
filterNUL = Text.filter (/= '\0')
toParamBinder :: Name -> PP.Doc ann
toParamBinder =
PP.pretty . Text.pack . escapeKeyword . lowerFirstLetter . ("__" <>) . Text.unpack . unName
operationParamTypeName :: Name -> Name -> Name
operationParamTypeName (Name operationName) (Name paramName) =
Name $
Text.pack $
escapeKeyword $
capitalizeFirstLetter (Text.unpack operationName)
<> capitalizeFirstLetter (Text.unpack paramName)
<> "Param"
operationRequestBodyName :: Name -> Name
operationRequestBodyName (Name operationName) =
Name $
Text.pack $
escapeKeyword $
capitalizeFirstLetter (Text.unpack operationName)
<> "RequestBody"
toApiMemberName :: Name -> PP.Doc ann
toApiMemberName =
PP.pretty . Text.pack . escapeKeyword . lowerFirstLetter . toCamelCase . Text.unpack . unName
toApiResponseTypeName :: Name -> PP.Doc ann
toApiResponseTypeName =
PP.pretty . Text.pack . escapeKeyword . (<> "Response") . capitalizeFirstLetter . Text.unpack . unName
toApiResponseConstructorName :: Name -> Int -> PP.Doc ann
toApiResponseConstructorName name statusCode =
PP.pretty . Text.pack . escapeKeyword . (<> show statusCode) . (<> "Response") . capitalizeFirstLetter . Text.unpack . unName $ name
apiResponseConstructorName :: Name -> Int -> Name
apiResponseConstructorName name statusCode =
Name . Text.pack . escapeKeyword . (<> show statusCode) . (<> "ResponseBody") . capitalizeFirstLetter . Text.unpack . unName $ name
toApiDefaultResponseConstructorName :: Name -> PP.Doc ann
toApiDefaultResponseConstructorName name =
PP.pretty . Text.pack . escapeKeyword . (<> "DefaultResponse") . capitalizeFirstLetter . Text.unpack . unName $ name
apiDefaultResponseConstructorName :: Name -> Name
apiDefaultResponseConstructorName name =
Name . Text.pack . escapeKeyword . (<> "DefaultResponseBody") . capitalizeFirstLetter . Text.unpack . unName $ name
toEnumConstructorName :: Name -> Text -> PP.Doc ann
toEnumConstructorName (Name typName) variant =
PP.pretty $
Text.pack $
escapeKeyword $
toCamelCase $
capitalizeFirstLetter (Text.unpack typName)
<> capitalizeFirstLetter (Text.unpack variant)
inlineObjectTypeName :: Name -> Name -> Name
inlineObjectTypeName (Name parentType) (Name fieldName) =
Name $
Text.pack $
escapeKeyword $
capitalizeFirstLetter (Text.unpack parentType)
<> capitalizeFirstLetter (Text.unpack fieldName)
| Generate a name for additionalProperties type name within an
ObjectType .
additionalPropertiesTypeName :: Name -> Name
additionalPropertiesTypeName (Name parentObjectType) =
Name $
Text.pack $
escapeKeyword $
capitalizeFirstLetter (Text.unpack parentObjectType)
<> "AdditionalProperties"
inlineVariantTypeName :: Name -> Int -> Name
inlineVariantTypeName (Name parentType) ith =
Name $
Text.pack $
escapeKeyword $
capitalizeFirstLetter (Text.unpack parentType) <> "OneOf" <> show ith
inlineArrayElementTypeName :: Name -> Name
inlineArrayElementTypeName (Name parentType) =
Name $
Text.pack $
escapeKeyword $
capitalizeFirstLetter (Text.unpack parentType) <> "Elem"
lowerFirstLetter :: String -> String
lowerFirstLetter [] = []
lowerFirstLetter (x : xs) = toLower x : xs
capitalizeFirstLetter :: String -> String
capitalizeFirstLetter [] = []
capitalizeFirstLetter (x : xs) = toUpper x : xs
escapeKeyword :: String -> String
escapeKeyword input = haskelify $ case input of
"type" -> "type'"
"class" -> "class'"
"where" -> "where'"
"case" -> "case'"
"of" -> "of'"
"data" -> "data'"
"import" -> "import'"
"qualified" -> "qualified'"
"as" -> "as'"
"instance" -> "instance'"
"module" -> "module'"
"pattern" -> "pattern'"
_ -> input
haskelify :: String -> String
haskelify = concatMap escape
where
escape c = case c of
'-' -> "_"
'\0' -> "NUL"
_ -> [c]
toCamelCase :: String -> String
toCamelCase input =
(prefix <>)
. (<> suffix)
. concat
. map (capitalizeFirstLetter . Text.unpack)
. Text.split (\c -> c == '_' || c == '-')
. Text.pack
$ input
where
prefix = takeWhile ('_' ==) input
suffix = takeWhile ('_' ==) (reverse input)
extractHaskellModules " . Int " = = [ " " ]
extractHaskellModules " Scarf . Hashids . . Int = = [ " Scarf . Hashids " , " " ] "
extractHaskellModule :: Text -> [Text]
extractHaskellModule =
let extractModule ty =
case List.init (Text.splitOn "." ty) of
[] ->
[]
xs ->
[Text.intercalate "." xs]
in concatMap extractModule . Text.words
|
c5c1f8cbd29dd4ccb47d1cfbdc1a7fbff667827a8e68842f42b896e55f961fde | mzp/coq-ide-for-ios | flags.ml | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
i $ I d : flags.ml 13436 2010 - 09 - 19 10:18:18Z herbelin $ i
let with_option o f x =
let old = !o in o:=true;
try let r = f x in o := old; r
with e -> o := old; raise e
let without_option o f x =
let old = !o in o:=false;
try let r = f x in o := old; r
with e -> o := old; raise e
let boot = ref false
let batch_mode = ref false
let debug = ref false
let print_emacs = ref false
let print_emacs_safechar = ref false
let term_quality = ref false
let xml_export = ref false
let dont_load_proofs = ref false
let raw_print = ref false
(* Compatibility mode *)
type compat_version = V8_2
let compat_version = ref None
let version_strictly_greater v =
match !compat_version with None -> true | Some v' -> v'>v
let version_less_or_equal v = not (version_strictly_greater v)
Translate
let beautify = ref false
let make_beautify f = beautify := f
let do_beautify () = !beautify
let beautify_file = ref false
(* Silent / Verbose *)
let silent = ref false
let make_silent flag = silent := flag; ()
let is_silent () = !silent
let is_verbose () = not !silent
let silently f x = with_option silent f x
let verbosely f x = without_option silent f x
let if_silent f x = if !silent then f x
let if_verbose f x = if not !silent then f x
let auto_intros = ref true
let make_auto_intros flag = auto_intros := flag
let is_auto_intros () = version_strictly_greater V8_2 && !auto_intros
let hash_cons_proofs = ref true
let warn = ref true
let make_warn flag = warn := flag; ()
let if_warn f x = if !warn then f x
(* The number of printed hypothesis in a goal *)
let print_hyps_limit = ref (None : int option)
let set_print_hyps_limit n = print_hyps_limit := n
let print_hyps_limit () = !print_hyps_limit
(* A list of the areas of the system where "unsafe" operation
* has been requested *)
module Stringset = Set.Make(struct type t = string let compare = compare end)
let unsafe_set = ref Stringset.empty
let add_unsafe s = unsafe_set := Stringset.add s !unsafe_set
let is_unsafe s = Stringset.mem s !unsafe_set
(* Flags for the virtual machine *)
let boxed_definitions = ref true
let set_boxed_definitions b = boxed_definitions := b
let boxed_definitions _ = !boxed_definitions
(* Flags for external tools *)
let subst_command_placeholder s t =
let buff = Buffer.create (String.length s + String.length t) in
let i = ref 0 in
while (!i < String.length s) do
if s.[!i] = '%' & !i+1 < String.length s & s.[!i+1] = 's'
then (Buffer.add_string buff t;incr i)
else Buffer.add_char buff s.[!i];
incr i
done;
Buffer.contents buff
let browser_cmd_fmt =
try
let coq_netscape_remote_var = "COQREMOTEBROWSER" in
Sys.getenv coq_netscape_remote_var
with
Not_found -> Coq_config.browser
let is_standard_doc_url url =
let wwwcompatprefix = "/" in
let n = String.length Coq_config.wwwcoq in
let n' = String.length Coq_config.wwwrefman in
url = Coq_config.localwwwrefman ||
url = Coq_config.wwwrefman ||
url = wwwcompatprefix ^ String.sub Coq_config.wwwrefman n (n'-n)
(* Options for changing coqlib *)
let coqlib_spec = ref false
let coqlib = ref Coq_config.coqlib
(* Options for changing camlbin (used by coqmktop) *)
let camlbin_spec = ref false
let camlbin = ref Coq_config.camlbin
(* Options for changing camlp4bin (used by coqmktop) *)
let camlp4bin_spec = ref false
let camlp4bin = ref Coq_config.camlp4bin
| null | https://raw.githubusercontent.com/mzp/coq-ide-for-ios/4cdb389bbecd7cdd114666a8450ecf5b5f0391d3/coqlib/lib/flags.ml | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
Compatibility mode
Silent / Verbose
The number of printed hypothesis in a goal
A list of the areas of the system where "unsafe" operation
* has been requested
Flags for the virtual machine
Flags for external tools
Options for changing coqlib
Options for changing camlbin (used by coqmktop)
Options for changing camlp4bin (used by coqmktop) | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
i $ I d : flags.ml 13436 2010 - 09 - 19 10:18:18Z herbelin $ i
let with_option o f x =
let old = !o in o:=true;
try let r = f x in o := old; r
with e -> o := old; raise e
let without_option o f x =
let old = !o in o:=false;
try let r = f x in o := old; r
with e -> o := old; raise e
let boot = ref false
let batch_mode = ref false
let debug = ref false
let print_emacs = ref false
let print_emacs_safechar = ref false
let term_quality = ref false
let xml_export = ref false
let dont_load_proofs = ref false
let raw_print = ref false
type compat_version = V8_2
let compat_version = ref None
let version_strictly_greater v =
match !compat_version with None -> true | Some v' -> v'>v
let version_less_or_equal v = not (version_strictly_greater v)
Translate
let beautify = ref false
let make_beautify f = beautify := f
let do_beautify () = !beautify
let beautify_file = ref false
let silent = ref false
let make_silent flag = silent := flag; ()
let is_silent () = !silent
let is_verbose () = not !silent
let silently f x = with_option silent f x
let verbosely f x = without_option silent f x
let if_silent f x = if !silent then f x
let if_verbose f x = if not !silent then f x
let auto_intros = ref true
let make_auto_intros flag = auto_intros := flag
let is_auto_intros () = version_strictly_greater V8_2 && !auto_intros
let hash_cons_proofs = ref true
let warn = ref true
let make_warn flag = warn := flag; ()
let if_warn f x = if !warn then f x
let print_hyps_limit = ref (None : int option)
let set_print_hyps_limit n = print_hyps_limit := n
let print_hyps_limit () = !print_hyps_limit
module Stringset = Set.Make(struct type t = string let compare = compare end)
let unsafe_set = ref Stringset.empty
let add_unsafe s = unsafe_set := Stringset.add s !unsafe_set
let is_unsafe s = Stringset.mem s !unsafe_set
let boxed_definitions = ref true
let set_boxed_definitions b = boxed_definitions := b
let boxed_definitions _ = !boxed_definitions
let subst_command_placeholder s t =
let buff = Buffer.create (String.length s + String.length t) in
let i = ref 0 in
while (!i < String.length s) do
if s.[!i] = '%' & !i+1 < String.length s & s.[!i+1] = 's'
then (Buffer.add_string buff t;incr i)
else Buffer.add_char buff s.[!i];
incr i
done;
Buffer.contents buff
let browser_cmd_fmt =
try
let coq_netscape_remote_var = "COQREMOTEBROWSER" in
Sys.getenv coq_netscape_remote_var
with
Not_found -> Coq_config.browser
let is_standard_doc_url url =
let wwwcompatprefix = "/" in
let n = String.length Coq_config.wwwcoq in
let n' = String.length Coq_config.wwwrefman in
url = Coq_config.localwwwrefman ||
url = Coq_config.wwwrefman ||
url = wwwcompatprefix ^ String.sub Coq_config.wwwrefman n (n'-n)
let coqlib_spec = ref false
let coqlib = ref Coq_config.coqlib
let camlbin_spec = ref false
let camlbin = ref Coq_config.camlbin
let camlp4bin_spec = ref false
let camlp4bin = ref Coq_config.camlp4bin
|
f5b6248fc8bafc59d0b6b962cd82058d836b97f48ea75287005683016e7cf166 | tommaisey/aeon | latch.help.scm | (hear (mul (blip ar (mul-add (latch (white-noise ar) (impulse ar 9 0)) 400 500) 4) 0.2))
The above is just meant as example . lf - noise0 is a faster way to
;; generate random steps :
(hear (mul (blip ar (mul-add (lf-noise0 kr 9) 400 500) 4) 0.2))
;; -users/2006-December/029991.html
(hear
(let* ((n0 (mul-add (lf-noise2 kr 8) 200 300))
(n1 (mul-add (lf-noise2 kr 3) 10 20))
(s (blip ar n0 n1))
(x (mouse-x kr 1000 (mul sample-rate 0.1) 1 0.1)))
(latch s (impulse ar x 0))))
| null | https://raw.githubusercontent.com/tommaisey/aeon/80744a7235425c47a061ec8324d923c53ebedf15/libs/third-party/sc3/rsc3/help/ugen/controls/latch.help.scm | scheme | generate random steps :
-users/2006-December/029991.html | (hear (mul (blip ar (mul-add (latch (white-noise ar) (impulse ar 9 0)) 400 500) 4) 0.2))
The above is just meant as example . lf - noise0 is a faster way to
(hear (mul (blip ar (mul-add (lf-noise0 kr 9) 400 500) 4) 0.2))
(hear
(let* ((n0 (mul-add (lf-noise2 kr 8) 200 300))
(n1 (mul-add (lf-noise2 kr 3) 10 20))
(s (blip ar n0 n1))
(x (mouse-x kr 1000 (mul sample-rate 0.1) 1 0.1)))
(latch s (impulse ar x 0))))
|
a94e2f94cbd6a53bd43a9f8ec5c5b7af0cdc8a5afc5a5a689cff156a35d76785 | input-output-hk/marlowe-cardano | Local.hs | # LANGUAGE DuplicateRecordFields #
# LANGUAGE FlexibleContexts #
{-# LANGUAGE StrictData #-}
module Test.Integration.Cardano.Local
( Delegator(..)
, LocalTestnet(..)
, LocalTestnetOptions(..)
, Network(..)
, PaymentKeyPair(..)
, SpoNode(..)
, StakingKeyPair(..)
, TestnetException(..)
, defaultOptions
, withLocalTestnet
, withLocalTestnet'
) where
import Control.Concurrent (threadDelay)
import Control.Concurrent.Async (mapConcurrently_, race_)
import Control.Exception (Exception(displayException), throw)
import Control.Exception.Lifted (SomeException, catch)
import Control.Monad.Base (MonadBase)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.Control (MonadBaseControl)
import Control.Monad.Trans.Resource (MonadResource, MonadThrow(throwM), MonadUnliftIO)
import Data.Aeson (FromJSON, Key, Result(..), ToJSON, fromJSON, object, toJSON, (.=))
import Data.Aeson.KeyMap (KeyMap)
import qualified Data.Aeson.KeyMap as KM
import Data.Aeson.Types (Value)
import Data.Functor (void, (<&>))
import Data.List (isInfixOf)
import Data.Maybe (fromJust)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import Data.Time (UTCTime, getCurrentTime, nominalDiffTimeToSeconds, secondsToNominalDiffTime)
import Data.Time.Clock.POSIX (posixSecondsToUTCTime, utcTimeToPOSIXSeconds)
import Data.Time.Format.ISO8601 (iso8601Show)
import qualified Data.Yaml.Aeson as YAML
import GHC.Generics (Generic)
import System.FilePath ((</>))
import System.IO (Handle, IOMode(..), hClose, openFile)
import System.Process (CreateProcess(..), ProcessHandle, StdStream(..), cleanupProcess, createProcess, proc)
import System.Random (randomRIO)
import Test.HUnit.Lang (HUnitFailure(..))
import Test.Integration.Cardano.Process (execCli_)
import Test.Integration.Workspace
( Workspace(..)
, copyToWorkspace
, createWorkspace
, createWorkspaceDir
, moveToWorkspace
, resolveWorkspacePath
, rewriteJSONFile
, rewriteYAMLFile
, writeWorkspaceFileJSON
)
import qualified Test.Integration.Workspace as W
import Text.Printf (printf)
import UnliftIO.Async (concurrently)
import UnliftIO.Exception (catchAny)
import UnliftIO.Resource (allocate, runResourceT, unprotect)
data LocalTestnetOptions = LocalTestnetOptions
{ slotDuration :: Int
, securityParameter :: Int
, numSpoNodes :: Int
, numDelegators :: Int
, numWallets :: Int
, totalBalance :: Int
} deriving (Show, Eq, Ord)
data LocalTestnet = LocalTestnet
{ delegators :: [Delegator]
, network :: Network
, spoNodes :: [SpoNode]
, testnetMagic :: Int
, wallets :: [PaymentKeyPair]
, workspace :: Workspace
, securityParameter :: Int
}
data PaymentKeyPair = PaymentKeyPair
{ paymentSKey :: FilePath
, paymentVKey :: FilePath
} deriving (Show, Eq, Ord, Generic)
instance ToJSON PaymentKeyPair
data StakingKeyPair = StakingKeyPair
{ stakingSKey :: FilePath
, stakingVKey :: FilePath
} deriving (Show, Eq, Ord, Generic)
instance ToJSON StakingKeyPair
data Delegator = Delegator
{ paymentKeyPair :: PaymentKeyPair
, stakingKeyPair :: StakingKeyPair
} deriving (Show, Eq, Ord, Generic)
instance ToJSON Delegator
data SpoNode = SpoNode
{ byronDelegateKey :: FilePath
, byronDelegationCert :: FilePath
, coldSKey :: FilePath
, coldVKey :: FilePath
, db :: FilePath
, kesSKey :: FilePath
, kesVKey :: FilePath
, nodeName :: String
, opcert :: FilePath
, port :: Int
, processHandle :: ProcessHandle
, socket :: FilePath
, stakingRewardSKey :: FilePath
, stakingRewardVKey :: FilePath
, stderrLogs :: FilePath
, stdin :: Handle
, stdoutLogs :: FilePath
, topology :: FilePath
, vrfSKey :: FilePath
, vrfVKey :: FilePath
}
data Network = Network
{ configurationYaml :: FilePath
, byronGenesisJson :: FilePath
, shelleyGenesisJson :: FilePath
, alonzoGenesisJson :: FilePath
} deriving (Show, Eq, Ord, Generic)
instance ToJSON Network
defaultOptions :: LocalTestnetOptions
defaultOptions = LocalTestnetOptions
{ slotDuration = 100
, securityParameter = 10
, numSpoNodes = 3
, numDelegators = 3
, numWallets = 3
, totalBalance = 10020000000
}
-- | Run a test script in the context of a local testnet using default options.
withLocalTestnet :: (MonadUnliftIO m, MonadBaseControl IO m, MonadThrow m) => (LocalTestnet -> m a) -> m a
withLocalTestnet = withLocalTestnet' defaultOptions
-- | A version of @@withLocalTestnet@@ that accepts custom options.
withLocalTestnet'
:: (MonadUnliftIO m, MonadBaseControl IO m, MonadThrow m)
=> LocalTestnetOptions
-> (LocalTestnet -> m a)
-> m a
withLocalTestnet' options test = runResourceT do
testnet <- startLocalTestnet options
result <- lift $ (Right <$> test testnet)
`catch` (\ex@HUnitFailure{} -> pure $ Left ex)
`catch` rethrowAsTestnetException testnet
either throw pure result
data TestnetException = TestnetException
{ workspace :: FilePath
, exception :: String
} deriving (Generic)
instance ToJSON TestnetException
instance Show TestnetException where
show = T.unpack . T.decodeUtf8 . YAML.encode . object . pure . ("TestnetException" .=)
instance Exception TestnetException where
-- | Whenever an exception occurs, this function will decorate it with
-- information about the local testnet.
rethrowAsTestnetException :: (MonadBase IO m, MonadIO m, MonadThrow m) => LocalTestnet -> SomeException -> m a
rethrowAsTestnetException LocalTestnet{..} ex = do
-- prevent workspace from being cleaned up for diagnosing errors.
void $ unprotect $ W.releaseKey workspace
let exception = displayException ex
throwM $ TestnetException (workspaceDir workspace) exception
startLocalTestnet :: (MonadResource m, MonadUnliftIO m) => LocalTestnetOptions -> m LocalTestnet
startLocalTestnet options@LocalTestnetOptions{..} = do
workspace <- createWorkspace "local-testnet"
catchAny
do
testnetMagic <- randomRIO (1000, 2000)
socketDir <- createWorkspaceDir workspace "socket"
logsDir <- createWorkspaceDir workspace "logs"
currentTime <- round . utcTimeToPOSIXSeconds <$> liftIO getCurrentTime
-- Add time to execute the CLI commands to set everything up
let startTime = posixSecondsToUTCTime $ secondsToNominalDiffTime $ fromInteger currentTime + 1
(byronGenesisDir, shelleyGenesisDir) <- concurrently
(createByronGenesis workspace startTime testnetMagic options)
(createShelleyGenesisStaked workspace startTime testnetMagic options)
let
wallets = [1..numWallets] <&> \n -> PaymentKeyPair
{ paymentSKey = shelleyGenesisDir </> "utxo-keys" </> "utxo" <> show n <> ".skey"
, paymentVKey = shelleyGenesisDir </> "utxo-keys" </> "utxo" <> show n <> ".vkey"
}
delegators = [1..numDelegators] <&> \n -> Delegator
{ paymentKeyPair = PaymentKeyPair
{ paymentSKey = shelleyGenesisDir </> "stake-delegator-keys" </> "payment" <> show n <> ".skey"
, paymentVKey = shelleyGenesisDir </> "stake-delegator-keys" </> "payment" <> show n <> ".vkey"
}
, stakingKeyPair = StakingKeyPair
{ stakingSKey = shelleyGenesisDir </> "stake-delegator-keys" </> "staking" <> show n <> ".skey"
, stakingVKey = shelleyGenesisDir </> "stake-delegator-keys" </> "staking" <> show n <> ".vkey"
}
}
network <- setupNetwork workspace options byronGenesisDir shelleyGenesisDir
spoNodes <- traverse (setupSpoNode workspace options network logsDir socketDir byronGenesisDir shelleyGenesisDir) [1..numSpoNodes]
liftIO $ mapConcurrently_ assertChainExtended spoNodes
pure LocalTestnet{..}
\e -> do
-- prevent workspace from being cleaned up for diagnosing errors.
_ <- unprotect $ W.releaseKey workspace
throw e
createByronGenesis :: MonadIO m => Workspace -> UTCTime -> Int -> LocalTestnetOptions -> m FilePath
createByronGenesis workspace startTime testnetMagic LocalTestnetOptions{..} = do
byronGenesisSpecFile <- writeWorkspaceFileJSON workspace "byron.genesis.spec.json" $ object
[ "heavyDelThd" .= ("300000000000" :: String)
, "maxBlockSize" .= ("2000000" :: String)
, "maxTxSize" .= ("4096" :: String)
, "maxHeaderSize" .= ("2000000" :: String)
, "maxProposalSize" .= ("700" :: String)
, "mpcThd" .= ("20000000000000" :: String)
, "scriptVersion" .= (0 :: Int)
, "slotDuration" .= show slotDuration
, "unlockStakeEpoch" .= ("18446744073709551615" :: String)
, "updateImplicit" .= ("10000" :: String)
, "updateProposalThd" .= ("100000000000000" :: String)
, "updateVoteThd" .= ("1000000000000" :: String)
, "softforkRule" .= object
[ "initThd" .= ("900000000000000" :: String)
, "minThd" .= ("600000000000000" :: String)
, "thdDecrement" .= ("50000000000000" :: String)
]
, "txFeePolicy" .= object
[ "multiplier" .= ("43946000000" :: String)
, "summand" .= ("155381000000000" :: String)
]
]
let byronGenesisDir = resolveWorkspacePath workspace "byron-genesis"
execCli_
[ "byron", "genesis", "genesis"
, "--protocol-magic", show testnetMagic
, "--start-time", show @Int $ floor $ nominalDiffTimeToSeconds $ utcTimeToPOSIXSeconds startTime
, "--k", show securityParameter
, "--n-poor-addresses", "0"
, "--n-delegate-addresses", show numSpoNodes
, "--total-balance", show totalBalance
, "--delegate-share", "1"
, "--avvm-entry-count", "0"
, "--avvm-entry-balance", "0"
, "--protocol-parameters-file", byronGenesisSpecFile
, "--genesis-output-dir", byronGenesisDir
]
pure byronGenesisDir
createShelleyGenesisStaked :: MonadIO m => Workspace -> UTCTime -> Int -> LocalTestnetOptions -> m FilePath
createShelleyGenesisStaked workspace startTime testnetMagic LocalTestnetOptions{..} = do
let shelleyGenesisDir = "shelley-genesis"
let shelleyGenesisDirInWorkspace = resolveWorkspacePath workspace shelleyGenesisDir
_ <- copyToWorkspace
workspace
"./configuration/alonzo-babbage-test-genesis.json"
(shelleyGenesisDir </> "genesis.alonzo.spec.json")
configFile <- copyToWorkspace
workspace
"./configuration/byron-mainnet/configuration.yaml"
(shelleyGenesisDir </> "configuration.yaml")
rewriteYAMLFile configFile
( KM.delete "GenesisFile"
. KM.insert "Protocol" (toJSON @String "Cardano")
. KM.insert "PBftSignatureThreshold" (toJSON @Double 0.6)
. KM.insert "minSeverity" (toJSON @String "Debug")
. KM.insert "ByronGenesisFile" (toJSON @String "genesis/byron/genesis.json")
. KM.insert "ShelleyGenesisFile" (toJSON @String "genesis/shelley/genesis.json")
. KM.insert "AlonzoGenesisFile" (toJSON @String "genesis/shelley/genesis.alonzo.json")
. KM.insert "RequiresNetworkMagic" (toJSON @String "RequiresMagic")
. KM.insert "LastKnownBlockVersion-Major" (toJSON @Int 6)
. KM.insert "LastKnownBlockVersion-Minor" (toJSON @Int 0)
. KM.insert "TestShelleyHardForkAtEpoch" (toJSON @Int 0)
. KM.insert "TestAllegraHardForkAtEpoch" (toJSON @Int 0)
. KM.insert "TestMaryHardForkAtEpoch" (toJSON @Int 0)
. KM.insert "TestAlonzoHardForkAtEpoch" (toJSON @Int 0)
. KM.insert "TestBabbageHardForkAtEpoch" (toJSON @Int 0)
. KM.insert "TestEnableDevelopmentHardForkEras" (toJSON True)
)
execCli_
[ "genesis", "create-staked"
, "--genesis-dir", shelleyGenesisDirInWorkspace
, "--testnet-magic", show testnetMagic
, "--gen-pools", show numSpoNodes
, "--supply", "1000000000000"
, "--supply-delegated", "1000000000000"
, "--start-time", iso8601Show startTime
, "--gen-stake-delegs", show numDelegators
, "--gen-utxo-keys", show numWallets
]
pure shelleyGenesisDirInWorkspace
setupNetwork :: MonadIO m => Workspace -> LocalTestnetOptions -> FilePath -> FilePath -> m Network
setupNetwork workspace LocalTestnetOptions{..} byronGenesisDir shelleyGenesisDir = do
configurationYaml <- moveToWorkspace workspace (shelleyGenesisDir </> "configuration.yaml") "configuration.yaml"
byronGenesisJson <- moveToWorkspace workspace (byronGenesisDir </> "genesis.json") "genesis/byron/genesis.json"
shelleyGenesisJson <- moveToWorkspace workspace (shelleyGenesisDir </> "genesis.json") "genesis/shelley/genesis.json"
alonzoGenesisJson <- moveToWorkspace workspace (shelleyGenesisDir </> "genesis.alonzo.json") "genesis/shelley/genesis.alonzo.json"
rewriteJSONFile shelleyGenesisJson
( KM.insert "slotLength" (toJSON @Double (fromIntegral slotDuration / 1000))
. KM.insert "activeSlotsCoeff" (toJSON @Double 0.2)
. KM.insert "securityParam" (toJSON @Int securityParameter)
. KM.insert "epochLength" (toJSON @Int 500)
. KM.insert "maxLovelaceSupply" (toJSON @Int 1000000000000)
. KM.insert "updateQuorum" (toJSON @Int 2)
. updateKeyMap "protocolParams"
( KM.insert "minFeeA" (toJSON @Int 44)
. KM.insert "minFeeB" (toJSON @Int 155381)
. KM.insert "minUTxOValue" (toJSON @Int 1000000)
. KM.insert "decentralisationParam" (toJSON @Double 0.7)
. KM.insert "rho" (toJSON @Double 0.1)
. KM.insert "tau" (toJSON @Double 0.1)
. updateKeyMap "protocolVersion" (KM.insert "major" (toJSON @Int 7))
)
)
pure Network{..}
updateKeyMap :: (FromJSON a, ToJSON b) => Key -> (a -> b) -> KeyMap Value -> KeyMap Value
updateKeyMap key f km = case KM.lookup key km of
Nothing -> km
Just v -> case fromJSON v of
Success a -> KM.insert key (toJSON $ f a) km
_ -> km
setupSpoNode
:: MonadResource m
=> Workspace
-> LocalTestnetOptions
-> Network
-> FilePath
-> FilePath
-> FilePath
-> FilePath
-> Int
-> m SpoNode
setupSpoNode workspace LocalTestnetOptions{..} Network{..} logsDir socketDir byronGenesisDir shelleyGenesisDir n = do
let nodeName = "node-spo" <> show n
let
movePoolFile name extension =
moveToWorkspace workspace (shelleyGenesisDir </> "pools" </> name <> show n <> "." <> extension) (nodeName </> name <> "." <> extension)
let stdoutLogs = resolveWorkspacePath workspace $ logsDir </> nodeName <> ".stdout.log"
let stderrLogs = resolveWorkspacePath workspace $ logsDir </> nodeName <> ".stderr.log"
let socket = resolveWorkspacePath workspace $ socketDir </> nodeName <> ".socket"
let port = 3000 + n
vrfSKey <- movePoolFile "vrf" "skey"
vrfVKey <- movePoolFile "vrf" "vkey"
coldSKey <- movePoolFile "cold" "skey"
coldVKey <- movePoolFile "cold" "vkey"
stakingRewardSKey <- movePoolFile "staking-reward" "skey"
stakingRewardVKey <- movePoolFile "staking-reward" "vkey"
opcert <- movePoolFile "opcert" "cert"
kesSKey <- movePoolFile "kes" "skey"
kesVKey <- movePoolFile "kes" "vkey"
byronDelegateKey <- moveToWorkspace workspace (byronGenesisDir </> "delegate-keys." <> printf "%03d" (n - 1) <> ".key") (nodeName </> "byron-delegate.key")
byronDelegationCert <- moveToWorkspace workspace (byronGenesisDir </> "delegation-cert." <> printf "%03d" (n - 1) <> ".json") (nodeName </> "byron-delegation.cert")
db <- createWorkspaceDir workspace $ nodeName </> "db"
let
mkProducer i = object
[ "addr" .= ("127.0.0.1" :: String)
, "port" .= (3000 + i :: Int)
, "valency" .= (1 :: Int)
]
topology <- writeWorkspaceFileJSON workspace (nodeName </> "topology.json") $ object
[ "Producers" .= (mkProducer <$> filter (/= n) [1..numSpoNodes])
]
(_, nodeStdout) <- allocate (openFile stdoutLogs WriteMode) hClose
(_, nodeStderr) <- allocate (openFile stderrLogs WriteMode) hClose
(_, (mStdin, _, _, processHandle)) <- allocate
( createProcess
( proc "cardano-node"
[ "run"
, "--config", configurationYaml
, "--topology", topology
, "--database-path", db
, "--socket-path", socket
, "--shelley-kes-key", kesSKey
, "--shelley-vrf-key", vrfSKey
, "--byron-delegation-certificate", byronDelegationCert
, "--byron-signing-key", byronDelegateKey
, "--shelley-operational-certificate", opcert
, "--port", show port
]
)
{ std_in = CreatePipe
, std_out = UseHandle nodeStdout
, std_err = UseHandle nodeStderr
, cwd = Just $ workspaceDir workspace
}
)
cleanupProcess
let stdin = fromJust mStdin
pure SpoNode{..}
assertChainExtended :: SpoNode -> IO ()
assertChainExtended SpoNode{..} = race_ waitForChainExtendedMessage do
threadDelay 90_000_000
fail $ "SPO Node " <> show nodeName <> " failed to start"
where
waitForChainExtendedMessage = do
logs <- readFile stdoutLogs
if "Chain extended, new tip:" `isInfixOf` logs
then pure ()
else threadDelay 1000 *> waitForChainExtendedMessage
| null | https://raw.githubusercontent.com/input-output-hk/marlowe-cardano/d6e5e401b5bcd033ed7b37f7f7a3d79447b29b06/cardano-integration/src/Test/Integration/Cardano/Local.hs | haskell | # LANGUAGE StrictData #
| Run a test script in the context of a local testnet using default options.
| A version of @@withLocalTestnet@@ that accepts custom options.
| Whenever an exception occurs, this function will decorate it with
information about the local testnet.
prevent workspace from being cleaned up for diagnosing errors.
Add time to execute the CLI commands to set everything up
prevent workspace from being cleaned up for diagnosing errors. | # LANGUAGE DuplicateRecordFields #
# LANGUAGE FlexibleContexts #
module Test.Integration.Cardano.Local
( Delegator(..)
, LocalTestnet(..)
, LocalTestnetOptions(..)
, Network(..)
, PaymentKeyPair(..)
, SpoNode(..)
, StakingKeyPair(..)
, TestnetException(..)
, defaultOptions
, withLocalTestnet
, withLocalTestnet'
) where
import Control.Concurrent (threadDelay)
import Control.Concurrent.Async (mapConcurrently_, race_)
import Control.Exception (Exception(displayException), throw)
import Control.Exception.Lifted (SomeException, catch)
import Control.Monad.Base (MonadBase)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.Control (MonadBaseControl)
import Control.Monad.Trans.Resource (MonadResource, MonadThrow(throwM), MonadUnliftIO)
import Data.Aeson (FromJSON, Key, Result(..), ToJSON, fromJSON, object, toJSON, (.=))
import Data.Aeson.KeyMap (KeyMap)
import qualified Data.Aeson.KeyMap as KM
import Data.Aeson.Types (Value)
import Data.Functor (void, (<&>))
import Data.List (isInfixOf)
import Data.Maybe (fromJust)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import Data.Time (UTCTime, getCurrentTime, nominalDiffTimeToSeconds, secondsToNominalDiffTime)
import Data.Time.Clock.POSIX (posixSecondsToUTCTime, utcTimeToPOSIXSeconds)
import Data.Time.Format.ISO8601 (iso8601Show)
import qualified Data.Yaml.Aeson as YAML
import GHC.Generics (Generic)
import System.FilePath ((</>))
import System.IO (Handle, IOMode(..), hClose, openFile)
import System.Process (CreateProcess(..), ProcessHandle, StdStream(..), cleanupProcess, createProcess, proc)
import System.Random (randomRIO)
import Test.HUnit.Lang (HUnitFailure(..))
import Test.Integration.Cardano.Process (execCli_)
import Test.Integration.Workspace
( Workspace(..)
, copyToWorkspace
, createWorkspace
, createWorkspaceDir
, moveToWorkspace
, resolveWorkspacePath
, rewriteJSONFile
, rewriteYAMLFile
, writeWorkspaceFileJSON
)
import qualified Test.Integration.Workspace as W
import Text.Printf (printf)
import UnliftIO.Async (concurrently)
import UnliftIO.Exception (catchAny)
import UnliftIO.Resource (allocate, runResourceT, unprotect)
data LocalTestnetOptions = LocalTestnetOptions
{ slotDuration :: Int
, securityParameter :: Int
, numSpoNodes :: Int
, numDelegators :: Int
, numWallets :: Int
, totalBalance :: Int
} deriving (Show, Eq, Ord)
data LocalTestnet = LocalTestnet
{ delegators :: [Delegator]
, network :: Network
, spoNodes :: [SpoNode]
, testnetMagic :: Int
, wallets :: [PaymentKeyPair]
, workspace :: Workspace
, securityParameter :: Int
}
data PaymentKeyPair = PaymentKeyPair
{ paymentSKey :: FilePath
, paymentVKey :: FilePath
} deriving (Show, Eq, Ord, Generic)
instance ToJSON PaymentKeyPair
data StakingKeyPair = StakingKeyPair
{ stakingSKey :: FilePath
, stakingVKey :: FilePath
} deriving (Show, Eq, Ord, Generic)
instance ToJSON StakingKeyPair
data Delegator = Delegator
{ paymentKeyPair :: PaymentKeyPair
, stakingKeyPair :: StakingKeyPair
} deriving (Show, Eq, Ord, Generic)
instance ToJSON Delegator
data SpoNode = SpoNode
{ byronDelegateKey :: FilePath
, byronDelegationCert :: FilePath
, coldSKey :: FilePath
, coldVKey :: FilePath
, db :: FilePath
, kesSKey :: FilePath
, kesVKey :: FilePath
, nodeName :: String
, opcert :: FilePath
, port :: Int
, processHandle :: ProcessHandle
, socket :: FilePath
, stakingRewardSKey :: FilePath
, stakingRewardVKey :: FilePath
, stderrLogs :: FilePath
, stdin :: Handle
, stdoutLogs :: FilePath
, topology :: FilePath
, vrfSKey :: FilePath
, vrfVKey :: FilePath
}
data Network = Network
{ configurationYaml :: FilePath
, byronGenesisJson :: FilePath
, shelleyGenesisJson :: FilePath
, alonzoGenesisJson :: FilePath
} deriving (Show, Eq, Ord, Generic)
instance ToJSON Network
defaultOptions :: LocalTestnetOptions
defaultOptions = LocalTestnetOptions
{ slotDuration = 100
, securityParameter = 10
, numSpoNodes = 3
, numDelegators = 3
, numWallets = 3
, totalBalance = 10020000000
}
withLocalTestnet :: (MonadUnliftIO m, MonadBaseControl IO m, MonadThrow m) => (LocalTestnet -> m a) -> m a
withLocalTestnet = withLocalTestnet' defaultOptions
withLocalTestnet'
:: (MonadUnliftIO m, MonadBaseControl IO m, MonadThrow m)
=> LocalTestnetOptions
-> (LocalTestnet -> m a)
-> m a
withLocalTestnet' options test = runResourceT do
testnet <- startLocalTestnet options
result <- lift $ (Right <$> test testnet)
`catch` (\ex@HUnitFailure{} -> pure $ Left ex)
`catch` rethrowAsTestnetException testnet
either throw pure result
data TestnetException = TestnetException
{ workspace :: FilePath
, exception :: String
} deriving (Generic)
instance ToJSON TestnetException
instance Show TestnetException where
show = T.unpack . T.decodeUtf8 . YAML.encode . object . pure . ("TestnetException" .=)
instance Exception TestnetException where
rethrowAsTestnetException :: (MonadBase IO m, MonadIO m, MonadThrow m) => LocalTestnet -> SomeException -> m a
rethrowAsTestnetException LocalTestnet{..} ex = do
void $ unprotect $ W.releaseKey workspace
let exception = displayException ex
throwM $ TestnetException (workspaceDir workspace) exception
startLocalTestnet :: (MonadResource m, MonadUnliftIO m) => LocalTestnetOptions -> m LocalTestnet
startLocalTestnet options@LocalTestnetOptions{..} = do
workspace <- createWorkspace "local-testnet"
catchAny
do
testnetMagic <- randomRIO (1000, 2000)
socketDir <- createWorkspaceDir workspace "socket"
logsDir <- createWorkspaceDir workspace "logs"
currentTime <- round . utcTimeToPOSIXSeconds <$> liftIO getCurrentTime
let startTime = posixSecondsToUTCTime $ secondsToNominalDiffTime $ fromInteger currentTime + 1
(byronGenesisDir, shelleyGenesisDir) <- concurrently
(createByronGenesis workspace startTime testnetMagic options)
(createShelleyGenesisStaked workspace startTime testnetMagic options)
let
wallets = [1..numWallets] <&> \n -> PaymentKeyPair
{ paymentSKey = shelleyGenesisDir </> "utxo-keys" </> "utxo" <> show n <> ".skey"
, paymentVKey = shelleyGenesisDir </> "utxo-keys" </> "utxo" <> show n <> ".vkey"
}
delegators = [1..numDelegators] <&> \n -> Delegator
{ paymentKeyPair = PaymentKeyPair
{ paymentSKey = shelleyGenesisDir </> "stake-delegator-keys" </> "payment" <> show n <> ".skey"
, paymentVKey = shelleyGenesisDir </> "stake-delegator-keys" </> "payment" <> show n <> ".vkey"
}
, stakingKeyPair = StakingKeyPair
{ stakingSKey = shelleyGenesisDir </> "stake-delegator-keys" </> "staking" <> show n <> ".skey"
, stakingVKey = shelleyGenesisDir </> "stake-delegator-keys" </> "staking" <> show n <> ".vkey"
}
}
network <- setupNetwork workspace options byronGenesisDir shelleyGenesisDir
spoNodes <- traverse (setupSpoNode workspace options network logsDir socketDir byronGenesisDir shelleyGenesisDir) [1..numSpoNodes]
liftIO $ mapConcurrently_ assertChainExtended spoNodes
pure LocalTestnet{..}
\e -> do
_ <- unprotect $ W.releaseKey workspace
throw e
createByronGenesis :: MonadIO m => Workspace -> UTCTime -> Int -> LocalTestnetOptions -> m FilePath
createByronGenesis workspace startTime testnetMagic LocalTestnetOptions{..} = do
byronGenesisSpecFile <- writeWorkspaceFileJSON workspace "byron.genesis.spec.json" $ object
[ "heavyDelThd" .= ("300000000000" :: String)
, "maxBlockSize" .= ("2000000" :: String)
, "maxTxSize" .= ("4096" :: String)
, "maxHeaderSize" .= ("2000000" :: String)
, "maxProposalSize" .= ("700" :: String)
, "mpcThd" .= ("20000000000000" :: String)
, "scriptVersion" .= (0 :: Int)
, "slotDuration" .= show slotDuration
, "unlockStakeEpoch" .= ("18446744073709551615" :: String)
, "updateImplicit" .= ("10000" :: String)
, "updateProposalThd" .= ("100000000000000" :: String)
, "updateVoteThd" .= ("1000000000000" :: String)
, "softforkRule" .= object
[ "initThd" .= ("900000000000000" :: String)
, "minThd" .= ("600000000000000" :: String)
, "thdDecrement" .= ("50000000000000" :: String)
]
, "txFeePolicy" .= object
[ "multiplier" .= ("43946000000" :: String)
, "summand" .= ("155381000000000" :: String)
]
]
let byronGenesisDir = resolveWorkspacePath workspace "byron-genesis"
execCli_
[ "byron", "genesis", "genesis"
, "--protocol-magic", show testnetMagic
, "--start-time", show @Int $ floor $ nominalDiffTimeToSeconds $ utcTimeToPOSIXSeconds startTime
, "--k", show securityParameter
, "--n-poor-addresses", "0"
, "--n-delegate-addresses", show numSpoNodes
, "--total-balance", show totalBalance
, "--delegate-share", "1"
, "--avvm-entry-count", "0"
, "--avvm-entry-balance", "0"
, "--protocol-parameters-file", byronGenesisSpecFile
, "--genesis-output-dir", byronGenesisDir
]
pure byronGenesisDir
createShelleyGenesisStaked :: MonadIO m => Workspace -> UTCTime -> Int -> LocalTestnetOptions -> m FilePath
createShelleyGenesisStaked workspace startTime testnetMagic LocalTestnetOptions{..} = do
let shelleyGenesisDir = "shelley-genesis"
let shelleyGenesisDirInWorkspace = resolveWorkspacePath workspace shelleyGenesisDir
_ <- copyToWorkspace
workspace
"./configuration/alonzo-babbage-test-genesis.json"
(shelleyGenesisDir </> "genesis.alonzo.spec.json")
configFile <- copyToWorkspace
workspace
"./configuration/byron-mainnet/configuration.yaml"
(shelleyGenesisDir </> "configuration.yaml")
rewriteYAMLFile configFile
( KM.delete "GenesisFile"
. KM.insert "Protocol" (toJSON @String "Cardano")
. KM.insert "PBftSignatureThreshold" (toJSON @Double 0.6)
. KM.insert "minSeverity" (toJSON @String "Debug")
. KM.insert "ByronGenesisFile" (toJSON @String "genesis/byron/genesis.json")
. KM.insert "ShelleyGenesisFile" (toJSON @String "genesis/shelley/genesis.json")
. KM.insert "AlonzoGenesisFile" (toJSON @String "genesis/shelley/genesis.alonzo.json")
. KM.insert "RequiresNetworkMagic" (toJSON @String "RequiresMagic")
. KM.insert "LastKnownBlockVersion-Major" (toJSON @Int 6)
. KM.insert "LastKnownBlockVersion-Minor" (toJSON @Int 0)
. KM.insert "TestShelleyHardForkAtEpoch" (toJSON @Int 0)
. KM.insert "TestAllegraHardForkAtEpoch" (toJSON @Int 0)
. KM.insert "TestMaryHardForkAtEpoch" (toJSON @Int 0)
. KM.insert "TestAlonzoHardForkAtEpoch" (toJSON @Int 0)
. KM.insert "TestBabbageHardForkAtEpoch" (toJSON @Int 0)
. KM.insert "TestEnableDevelopmentHardForkEras" (toJSON True)
)
execCli_
[ "genesis", "create-staked"
, "--genesis-dir", shelleyGenesisDirInWorkspace
, "--testnet-magic", show testnetMagic
, "--gen-pools", show numSpoNodes
, "--supply", "1000000000000"
, "--supply-delegated", "1000000000000"
, "--start-time", iso8601Show startTime
, "--gen-stake-delegs", show numDelegators
, "--gen-utxo-keys", show numWallets
]
pure shelleyGenesisDirInWorkspace
setupNetwork :: MonadIO m => Workspace -> LocalTestnetOptions -> FilePath -> FilePath -> m Network
setupNetwork workspace LocalTestnetOptions{..} byronGenesisDir shelleyGenesisDir = do
configurationYaml <- moveToWorkspace workspace (shelleyGenesisDir </> "configuration.yaml") "configuration.yaml"
byronGenesisJson <- moveToWorkspace workspace (byronGenesisDir </> "genesis.json") "genesis/byron/genesis.json"
shelleyGenesisJson <- moveToWorkspace workspace (shelleyGenesisDir </> "genesis.json") "genesis/shelley/genesis.json"
alonzoGenesisJson <- moveToWorkspace workspace (shelleyGenesisDir </> "genesis.alonzo.json") "genesis/shelley/genesis.alonzo.json"
rewriteJSONFile shelleyGenesisJson
( KM.insert "slotLength" (toJSON @Double (fromIntegral slotDuration / 1000))
. KM.insert "activeSlotsCoeff" (toJSON @Double 0.2)
. KM.insert "securityParam" (toJSON @Int securityParameter)
. KM.insert "epochLength" (toJSON @Int 500)
. KM.insert "maxLovelaceSupply" (toJSON @Int 1000000000000)
. KM.insert "updateQuorum" (toJSON @Int 2)
. updateKeyMap "protocolParams"
( KM.insert "minFeeA" (toJSON @Int 44)
. KM.insert "minFeeB" (toJSON @Int 155381)
. KM.insert "minUTxOValue" (toJSON @Int 1000000)
. KM.insert "decentralisationParam" (toJSON @Double 0.7)
. KM.insert "rho" (toJSON @Double 0.1)
. KM.insert "tau" (toJSON @Double 0.1)
. updateKeyMap "protocolVersion" (KM.insert "major" (toJSON @Int 7))
)
)
pure Network{..}
updateKeyMap :: (FromJSON a, ToJSON b) => Key -> (a -> b) -> KeyMap Value -> KeyMap Value
updateKeyMap key f km = case KM.lookup key km of
Nothing -> km
Just v -> case fromJSON v of
Success a -> KM.insert key (toJSON $ f a) km
_ -> km
setupSpoNode
:: MonadResource m
=> Workspace
-> LocalTestnetOptions
-> Network
-> FilePath
-> FilePath
-> FilePath
-> FilePath
-> Int
-> m SpoNode
setupSpoNode workspace LocalTestnetOptions{..} Network{..} logsDir socketDir byronGenesisDir shelleyGenesisDir n = do
let nodeName = "node-spo" <> show n
let
movePoolFile name extension =
moveToWorkspace workspace (shelleyGenesisDir </> "pools" </> name <> show n <> "." <> extension) (nodeName </> name <> "." <> extension)
let stdoutLogs = resolveWorkspacePath workspace $ logsDir </> nodeName <> ".stdout.log"
let stderrLogs = resolveWorkspacePath workspace $ logsDir </> nodeName <> ".stderr.log"
let socket = resolveWorkspacePath workspace $ socketDir </> nodeName <> ".socket"
let port = 3000 + n
vrfSKey <- movePoolFile "vrf" "skey"
vrfVKey <- movePoolFile "vrf" "vkey"
coldSKey <- movePoolFile "cold" "skey"
coldVKey <- movePoolFile "cold" "vkey"
stakingRewardSKey <- movePoolFile "staking-reward" "skey"
stakingRewardVKey <- movePoolFile "staking-reward" "vkey"
opcert <- movePoolFile "opcert" "cert"
kesSKey <- movePoolFile "kes" "skey"
kesVKey <- movePoolFile "kes" "vkey"
byronDelegateKey <- moveToWorkspace workspace (byronGenesisDir </> "delegate-keys." <> printf "%03d" (n - 1) <> ".key") (nodeName </> "byron-delegate.key")
byronDelegationCert <- moveToWorkspace workspace (byronGenesisDir </> "delegation-cert." <> printf "%03d" (n - 1) <> ".json") (nodeName </> "byron-delegation.cert")
db <- createWorkspaceDir workspace $ nodeName </> "db"
let
mkProducer i = object
[ "addr" .= ("127.0.0.1" :: String)
, "port" .= (3000 + i :: Int)
, "valency" .= (1 :: Int)
]
topology <- writeWorkspaceFileJSON workspace (nodeName </> "topology.json") $ object
[ "Producers" .= (mkProducer <$> filter (/= n) [1..numSpoNodes])
]
(_, nodeStdout) <- allocate (openFile stdoutLogs WriteMode) hClose
(_, nodeStderr) <- allocate (openFile stderrLogs WriteMode) hClose
(_, (mStdin, _, _, processHandle)) <- allocate
( createProcess
( proc "cardano-node"
[ "run"
, "--config", configurationYaml
, "--topology", topology
, "--database-path", db
, "--socket-path", socket
, "--shelley-kes-key", kesSKey
, "--shelley-vrf-key", vrfSKey
, "--byron-delegation-certificate", byronDelegationCert
, "--byron-signing-key", byronDelegateKey
, "--shelley-operational-certificate", opcert
, "--port", show port
]
)
{ std_in = CreatePipe
, std_out = UseHandle nodeStdout
, std_err = UseHandle nodeStderr
, cwd = Just $ workspaceDir workspace
}
)
cleanupProcess
let stdin = fromJust mStdin
pure SpoNode{..}
assertChainExtended :: SpoNode -> IO ()
assertChainExtended SpoNode{..} = race_ waitForChainExtendedMessage do
threadDelay 90_000_000
fail $ "SPO Node " <> show nodeName <> " failed to start"
where
waitForChainExtendedMessage = do
logs <- readFile stdoutLogs
if "Chain extended, new tip:" `isInfixOf` logs
then pure ()
else threadDelay 1000 *> waitForChainExtendedMessage
|
e16b5435ef80c47f887a9a937d691a4d9eb46d98bcb579176a525de1690cf042 | fyquah/hardcaml_zprize | test_ec_fpn_mixed_add_with_montgomery_mult.ml | open Core
open Elliptic_curve_lib
open Test_ec_fpn_mixed_add
let config = Config_presets.For_bls12_377.ec_fpn_ops_with_montgomery_reduction
let latency = Ec_fpn_mixed_add.latency config
let%expect_test "latency" =
Stdio.printf "latency = %d\n" latency;
[%expect {| latency = 283 |}]
;;
let%expect_test "Test on some test cases" =
Random.init 123;
test
~config
~sim:(create_sim config)
~montgomery:true
(List.concat
[ (* Handcrafted test cases. *)
[ ( Ark_bls12_377_g1.subgroup_generator ()
, Ark_bls12_377_g1.mul (Ark_bls12_377_g1.subgroup_generator ()) ~by:2 )
]
; (* Randomly generated test cases of points added to the generator. *)
List.init 50 ~f:(fun _ ->
let gen = Ark_bls12_377_g1.subgroup_generator () in
let by = Int.max 1 (Random.int Int.max_value) in
Ark_bls12_377_g1.mul gen ~by, gen)
]
|> List.map ~f:(fun (p0, p1) ->
( affine_to_jacobian p0
, { Point.Affine.x = Ark_bls12_377_g1.x p1; y = Ark_bls12_377_g1.y p1 } )));
[%expect {| (Ok ()) |}]
;;
| null | https://raw.githubusercontent.com/fyquah/hardcaml_zprize/553b1be10ae9b977decbca850df6ee2d0595e7ff/libs/elliptic_curve/test/test_ec_fpn_mixed_add_with_montgomery_mult.ml | ocaml | Handcrafted test cases.
Randomly generated test cases of points added to the generator. | open Core
open Elliptic_curve_lib
open Test_ec_fpn_mixed_add
let config = Config_presets.For_bls12_377.ec_fpn_ops_with_montgomery_reduction
let latency = Ec_fpn_mixed_add.latency config
let%expect_test "latency" =
Stdio.printf "latency = %d\n" latency;
[%expect {| latency = 283 |}]
;;
let%expect_test "Test on some test cases" =
Random.init 123;
test
~config
~sim:(create_sim config)
~montgomery:true
(List.concat
[ ( Ark_bls12_377_g1.subgroup_generator ()
, Ark_bls12_377_g1.mul (Ark_bls12_377_g1.subgroup_generator ()) ~by:2 )
]
List.init 50 ~f:(fun _ ->
let gen = Ark_bls12_377_g1.subgroup_generator () in
let by = Int.max 1 (Random.int Int.max_value) in
Ark_bls12_377_g1.mul gen ~by, gen)
]
|> List.map ~f:(fun (p0, p1) ->
( affine_to_jacobian p0
, { Point.Affine.x = Ark_bls12_377_g1.x p1; y = Ark_bls12_377_g1.y p1 } )));
[%expect {| (Ok ()) |}]
;;
|
612334f4c623b053f540680e98193124a74781214e1a04535d3d4a4c567d4e4a | BitGameEN/bitgamex | data_autogen_usr.erl | %%%--------------------------------------------------------
%%% @Module : data_autogen_usr
@Description : 连接usr库获取表结构,自动生成数据访问代码
%%%--------------------------------------------------------
-module(data_autogen_usr).
-export([run/0]).
-define(DB, bg_mysql_usr).
-define(DB_HOST, "localhost").
-define(DB_PORT, 3306).
-define(DB_USER, "bitgame").
-define(DB_PASS, "bitgame123").
-define(DB_NAME, "bitgame_usr").
-define(DB_ENCODE, utf8).
init_db() ->
mysql:start_link(?DB, ?DB_HOST, ?DB_PORT, ?DB_USER, ?DB_PASS, ?DB_NAME, fun(_, _, _, _) -> ok end, ?DB_ENCODE),
mysql:connect(?DB, ?DB_HOST, ?DB_PORT, ?DB_USER, ?DB_PASS, ?DB_NAME, ?DB_ENCODE, true),
ok.
%% 取出查询结果中的所有行
db_get_all(Sql) ->
case mysql:fetch(?DB, Sql) of
{data, {_, _, R, _, _}} -> R;
{error, {_, _, _, _, Reason}} -> mysql_halt([Sql, Reason])
end.
mysql_halt([Sql, Reason]) ->
erlang:error({db_error, [Sql, Reason]}).
run() ->
init_db(),
gen("game", 0),
gen("game_package", 2),
gen("game_reclaimed_gold"),
gen("global_config"),
gen("user", 1),
gen("user_gold"),
gen("gold_transfer", 0),
gen("useractivation", 0),
ok.
gen(Table0) ->
gen(Table0, 2).
NeedGid : 0 - id通过数据库自增键生成
% 1 - id通过id_gen生成
2 - id已提供,不需要生成
gen(Table0, NeedGid) ->
Table = list_to_binary(Table0),
SqlNTDC = io_lib:format(<<"SELECT column_name,data_type,column_default,column_comment from information_schema.columns WHERE information_schema.columns.TABLE_NAME = '~s' and information_schema.columns.TABLE_SCHEMA = '~s'">>, [Table, ?DB_NAME]),
FieldInfos = db_get_all(SqlNTDC),
FieldNames = [N || [N|_] <- FieldInfos],
FieldTypes = [T || [_,T|_] <- FieldInfos],
FieldDefaults = [D || [_,_,D|_] <- FieldInfos],
FieldComments = [C || [_,_,_,C|_] <- FieldInfos],
SqlK = io_lib:format(<<"SELECT index_name,column_name from information_schema.statistics WHERE information_schema.statistics.TABLE_NAME = '~s' and information_schema.statistics.TABLE_SCHEMA = '~s' order by index_name">>, [Table, ?DB_NAME]),
FieldKeyInfos0 = db_get_all(SqlK),
F = fun(F, [[IndexName, ColumnName] | RestFieldKeyInfos], Acc) ->
case lists:keyfind(IndexName, 1, Acc) of
false ->
F(F, RestFieldKeyInfos, [{IndexName, [ColumnName]} | Acc]);
{_, L} ->
F(F, RestFieldKeyInfos, lists:keyreplace(IndexName, 1, Acc, {IndexName, [ColumnName | L]}))
end;
(_, [], Acc) ->
[{Index, lists:sort(fun compare_column/2, Columns)} || {Index, Columns} <- Acc]
end,
FieldKeyInfos = F(F, FieldKeyInfos0, []),
RecordName = list_to_binary(io_lib:format(<<"usr_~s">>, [Table])),
gen_record(io_lib:format(<<"record_usr_~s.hrl">>, [Table]), RecordName, FieldNames, FieldTypes, FieldDefaults, FieldComments),
gen_erl(Table, io_lib:format(<<"usr_~s.erl">>, [Table]), RecordName, FieldNames, FieldTypes, FieldComments, FieldKeyInfos, RecordName, NeedGid).
compare_column(A, B) ->
A < B.
gen_record(HrlName, RecordName, FieldNames, FieldTypes, FieldDefaults, FieldComments) ->
{ok, S} = file:open(HrlName, write),
io:format(S, "%%%--------------------------------------------------------~n", []),
io:format(S, "%%% @Module: ~s~n", [RecordName]),
io:format(S, <<"%%% @Description: 自动生成~n"/utf8>>, []),
io:format(S, "%%%--------------------------------------------------------~n", []),
io:format(S, "~n", []),
io:format(S, "-record(~s, {~n", [RecordName]),
io:format(S, "\t\tkey_id,~n", []),
gen_record_fields(FieldNames, FieldTypes, FieldDefaults, FieldComments, S),
io:format(S, "}).~n", []),
file:close(S).
gen_record_fields([Name0 | RestNames], [Type | RestTypes], [Default0 | RestDefaults], [Comment | RestComments], S) ->
Name = string:to_lower(binary_to_list(Name0)),
Default = case Default0 of
undefined ->
case Type of
<<"char">> -> <<"">>;
<<"varchar">> -> <<"">>;
<<"tinytext">> -> <<"">>;
<<"text">> -> <<"">>;
_-> <<"0">>
end;
_ ->
Default0
end,
case Comment of
<<"erlang", _/binary>> ->
case Default of
<<"">> ->
io:format(S, "\t\t~s", [Name]);
_ ->
io:format(S, "\t\t~s = ~s", [Name, Default])
end;
_ ->
case Type of
<<"char">> ->
io:format(S, "\t\t~s = <<\"~s\">>", [Name, Default]);
<<"varchar">> ->
io:format(S, "\t\t~s = <<\"~s\">>", [Name, Default]);
<<"tinytext">> ->
io:format(S, "\t\t~s = <<\"~s\">>", [Name, Default]);
<<"text">> ->
io:format(S, "\t\t~s = <<\"~s\">>", [Name, Default]);
_ ->
io:format(S, "\t\t~s = ~s", [Name, Default])
end
end,
case RestNames of
[] ->
io:format(S, " % ~s~n", [Comment]);
_ ->
io:format(S, ", % ~s~n", [Comment]),
gen_record_fields(RestNames, RestTypes, RestDefaults, RestComments, S)
end.
gen_erl(Table, ErlName, ModuleName, FieldNames, FieldTypes, FieldComments, FieldKeyInfos, RecordName, NeedGid) ->
FieldNames2 = get_names_upper_1st(FieldNames),
PriNames = get_pri_names(FieldKeyInfos),
PriNames2 = get_names_upper_1st(PriNames),
PriNames3 = get_names_underscore(PriNames2),
PriId = gen_id(PriNames2),
PirId2 = gen_id_no_bracket(PriNames2, ", "),
PirId3 = gen_id_no_bracket(PriNames3, ", "),
OtherKeys = get_other_names(FieldKeyInfos),
OtherKeysLower = [get_names_lower(UnionNames) || UnionNames <- OtherKeys],
OtherKeys2 = lists:zip(OtherKeys, OtherKeysLower),
{ok, S} = file:open(ErlName, write),
gen_erl_note(Table, ModuleName, OtherKeysLower, S),
io:format(S, "get_one(~s = Id) ->~n", [PriId]),
io:format(S, "\tcase run_data:in_trans() of~n", []),
io:format(S, "\t\ttrue ->~n", []),
io:format(S, "\t\t\tcase run_data:trans_get(~s, Id) of~n", [RecordName]),
io:format(S, "\t\t\t\t[] ->~n", []),
io:format(S, "\t\t\t\t\tget_one_(Id);~n", []),
io:format(S, "\t\t\t\ttrans_deleted -> [];~n", []),
io:format(S, "\t\t\t\tR -> R~n", []),
io:format(S, "\t\t\tend;~n", []),
io:format(S, "\t\tfalse ->~n", []),
io:format(S, "\t\t\tget_one_(Id)~n", []),
io:format(S, "\tend.~n~n", []),
io:format(S, "get_one_(~s = Id) ->~n", [PriId]),
io:format(S, "\tcase cache:get(cache_key(Id)) of~n", []),
io:format(S, "\t\t{true, _Cas, Val} ->~n", []),
io:format(S, "\t\t\tVal;~n", []),
io:format(S, "\t\t_ ->~n", []),
io:format(S, "\t\t\tcase db_esql:get_row(?DB_USR, <<\"select ~s from ~s where ~s\">>, [~s]) of~n",
[gen_id_no_bracket(FieldNames, ","), Table, gen_id_sql(PriNames), PirId2]),
io:format(S, "\t\t\t\t[] -> [];~n", []),
io:format(S, "\t\t\t\tRow ->~n", []),
io:format(S, "\t\t\t\t\tR = build_record_from_row(Row),~n", []),
io:format(S, "\t\t\t\t\tcache:set(cache_key(R#~s.key_id), R),~n", [RecordName]),
io:format(S, "\t\t\t\t\tR~n", []),
io:format(S, "\t\t\tend~n", []),
io:format(S, "\tend.~n~n", []),
GenOtherKeyGetF = fun(OtherKey, OtherKeyLower) ->
OtherKey2 = get_names_upper_1st(OtherKeyLower),
OtherId = gen_id(OtherKey2),
OtherId2 = gen_id_no_bracket(OtherKey2, ", "),
OtherIdAnd = gen_id_no_bracket(OtherKeyLower, "_and_"),
io:format(S, "get_~s_gids_by_~s(~s = Id) ->~n", [Table, OtherIdAnd, OtherId]),
io:format(S, "\tcase db_esql:get_all(?DB_USR, <<\"select ~s from ~s where ~s\">>, [~s]) of~n",
[gen_id_no_bracket(PriNames, ", "), Table, gen_id_sql(OtherKey), OtherId2]),
io:format(S, "\t\t[] -> [];~n", []),
io:format(S, "\t\tRows ->~n", []),
io:format(S, "\t\t\t[~s || [~s | _] <- Rows]~n", [PirId3, PirId3]),
io:format(S, "\tend.~n~n", [])
end,
[GenOtherKeyGetF(K, KL) || {K, KL} <- OtherKeys2],
io:format(S, "set_field(~s = Id, Field, Val) ->~n", [PriId]),
io:format(S, "\tFields = record_info(fields, ~s),~n", [RecordName]),
io:format(S, "\tL = lists:zip(Fields, lists:seq(1, length(Fields))),~n", []),
io:format(S, "\t{_, N} = lists:keyfind(Field, 1, L),~n", []),
io:format(S, "\tR0 = get_one(Id),~n", []),
io:format(S, "\tR = setelement(N+1, R0, Val),~n", []),
io:format(S, "\tset_one(R),~n", []),
io:format(S, "\tR.~n~n", []),
io:format(S, "set_one(R0) when is_record(R0, ~s) ->~n", [RecordName]),
io:format(S, "\tcase R0#~s.key_id =:= undefined of~n", [RecordName]),
io:format(S, "\t\tfalse ->~n", []),
io:format(S, "\t\t\tcase run_data:in_trans() of~n", []),
io:format(S, "\t\t\t\ttrue ->~n", []),
io:format(S, "\t\t\t\t\trun_data:trans_set(~s, R0#~s.key_id, R0,~n", [RecordName, RecordName]),
io:format(S, "\t\t\t\t\t\tvoid,~n", []),
io:format(S, "\t\t\t\t\t\tvoid);~n", []),
io:format(S, "\t\t\t\tfalse ->~n", []),
io:format(S, "\t\t\t\t\tsyncdb(R0),~n", []),
io : format(S , " \t\t\t\t\tcache : del(cache_key(R0#~s.key_id))~n " , [ RecordName ] ) ,
io:format(S, "\t\t\t\t\tcache:set(cache_key(R0#~s.key_id), R0)~n", [RecordName]),
io:format(S, "\t\t\tend,~n", []),
io:format(S, "\t\t\tR0#~s.key_id;~n", [RecordName]),
io:format(S, "\t\ttrue ->~n", []),
io:format(S, "\t\t\t#~s{~n", [RecordName]),
case NeedGid of
1 ->
[PriFieldName | FieldNames_] = FieldNames,
[PriFieldName2 | FieldNames2_] = FieldNames2,
io:format(S, "\t\t\t\t~s = ~s_0,~n", [PriFieldName, PriFieldName2]),
gen_erl_fields(FieldNames_, FieldNames2_, S),
io:format(S, "\t\t\t} = R0,~n", []),
io:format(S, "\t\t\t~s = id_gen:gen_id(~s),~n", [PriFieldName2, RecordName]),
io:format(S, "\t\t\tR = R0#~s{key_id = ~s, ~s = ~s},~n", [RecordName, PriFieldName2, gen_pri_id(PriNames), PriFieldName2]);
2 ->
[PriFieldName2 | _] = FieldNames2,
gen_erl_fields(FieldNames, FieldNames2, S),
io:format(S, "\t\t\t} = R0,~n", []),
io:format(S, "\t\t\tR = R0#~s{key_id = ~s},~n", [RecordName, PriId]);
0 ->
gen_erl_fields(FieldNames, FieldNames2, S),
io:format(S, "\t\t\t} = R0,~n", []),
io:format(S, "\t\t\t{ok, [[Insert_id|_]]} = db_esql:multi_execute(?DB_USR, io_lib:format(<<\"insert into ~s(~s) values(~s); select last_insert_id()\">>,~n\t\t\t\t[~s])),~n",
[Table, gen_id_no_bracket(FieldNames, ","), gen_fields_placeholder2(FieldTypes), gen_fields_sql(FieldNames2, FieldTypes, FieldComments)]),
io:format(S, "\t\t\tR = R0#~s{key_id = Insert_id, ~s = Insert_id},~n", [RecordName, gen_pri_id(PriNames)])
end,
io:format(S, "\t\t\tF = fun() ->~n", []),
case NeedGid of
1 ->
io:format(S, "\t\t\t\t\trun_data:db_write(add, R, fun() -> 1 = db_esql:execute(?DB_USR, io_lib:format(<<\"insert into ~s(~s) values(~s)\">>,~n\t\t\t\t\t\t[~s])) end),~n",
[Table, gen_id_no_bracket(FieldNames, ","), gen_fields_placeholder2(FieldTypes), gen_fields_sql(FieldNames2, FieldTypes, FieldComments)]);
2 ->
io:format(S, "\t\t\t\t\trun_data:db_write(add, R, fun() -> 1 = db_esql:execute(?DB_USR, io_lib:format(<<\"insert into ~s(~s) values(~s)\">>,~n\t\t\t\t\t\t[~s])) end),~n",
[Table, gen_id_no_bracket(FieldNames, ","), gen_fields_placeholder2(FieldTypes), gen_fields_sql(FieldNames2, FieldTypes, FieldComments)]);
0 -> void
end,
io:format(S, "\t\t\t\t\tcache:set(cache_key(R#~s.key_id), R)~n", [RecordName]),
io:format(S, "\t\t\t\tend,~n", []),
io:format(S, "\t\t\tcase run_data:in_trans() of~n", []),
io:format(S, "\t\t\t\ttrue ->~n", []),
io:format(S, "\t\t\t\t\trun_data:trans_set(~s, R#~s.key_id, {trans_inserted, R}, F, fun() -> ~s:del_one(R) end);~n", [RecordName, RecordName, RecordName]),
io:format(S, "\t\t\t\tfalse ->~n", []),
io:format(S, "\t\t\t\t\tF()~n", []),
io:format(S, "\t\t\tend,~n", []),
io:format(S, "\t\t\tR#~s.key_id~n", [RecordName]),
io:format(S, "\tend.~n~n", []),
io:format(S, "del_one(R) when is_record(R, ~s) ->~n", [RecordName]),
io:format(S, "\tcase run_data:in_trans() of~n", []),
io:format(S, "\t\ttrue ->~n", []),
io:format(S, "\t\t\trun_data:trans_del(~s, R#~s.key_id,~n", [RecordName, RecordName]),
io:format(S, "\t\t\t\tfun() -> ~s:del_one(R) end,~n", [RecordName]),
io:format(S, "\t\t\t\tvoid);~n", []),
io:format(S, "\t\tfalse ->~n", []),
io:format(S, "\t\t\t~s = R#~s.key_id,~n", [PriId, RecordName]),
io:format(S, "\t\t\trun_data:db_write(del, R, fun() -> db_esql:execute(?DB_USR, <<\"delete from ~s where ~s\">>, [~s]) end),~n", [Table, gen_id_sql(PriNames), PirId2]),
io:format(S, "\t\t\tcache:del(cache_key(R#~s.key_id))~n", [RecordName]),
io:format(S, "\tend,~n", []),
io:format(S, "\tok.~n~n", []),
io:format(S, "clean_all_cache() ->~n", []),
io:format(S, "\tclean_all_cache(0),~n", []),
io:format(S, "\tok.~n~n", []),
io:format(S, "clean_all_cache(N) ->~n", []),
io:format(S, "\tcase db_esql:get_all(?DB_USR, <<\"select ~s from ~s limit ?, 1000\">>, [N * 1000]) of~n", [gen_id_no_bracket(PriNames, ","), Table]),
io:format(S, "\t\t[] -> ok;~n", []),
io:format(S, "\t\tRows ->~n", []),
io:format(S, "\t\t\tF = fun(Id) -> cache:del(cache_key(Id)) end,~n", []),
io:format(S, "\t\t\t[F(Id) || [Id | _] <- Rows],~n", []),
io:format(S, "\t\t\tclean_all_cache(N + 1)~n", []),
io:format(S, "\tend.~n~n", []),
io:format(S, "syncdb(R) when is_record(R, ~s) ->~n", [RecordName]),
io:format(S, "\t#~s{~n", [RecordName]),
gen_erl_fields(FieldNames, FieldNames2, S, <<"\t\t">>),
io:format(S, "\t} = R,~n", []),
[_ | NonPriFieldNames] = FieldNames,
[_ | NonPriFieldNames2] = FieldNames2,
[_ | NonPriFieldTypes] = FieldTypes,
[_ | NonPriFieldComments] = FieldComments,
io:format(S, "\trun_data:db_write(upd, R, fun() -> db_esql:execute(?DB_USR, io_lib:format(<<\"insert into ~s(~s) values(~s) on duplicate key update \"~n\t\t\"~s\">>, []),~n\t\t[~s, ~s]) end).~n~n",
[Table, gen_id_no_bracket(FieldNames, ","), gen_fields_placeholder(length(FieldNames)), gen_update_fields_sql(NonPriFieldNames),
gen_fields_sql(FieldNames2, FieldTypes, FieldComments), gen_fields_sql(NonPriFieldNames2, NonPriFieldTypes, NonPriFieldComments)]),
io:format(S, "build_record_from_row([", []),
[FieldName | RestFieldNames] = FieldNames2,
io:format(S, "~s", [FieldName]),
GenFieldsStrF = fun(FieldName_, S_) -> io:format(S_, ", ~s", [FieldName_]) end,
[GenFieldsStrF(FName, S) || FName <- RestFieldNames],
io:format(S, "]) ->~n", []),
io:format(S, "\t#~s{~n", [RecordName]),
io:format(S, "\t\tkey_id = ~s,~n", [PriId]),
gen_erl_fields_string2term(FieldNames, FieldNames2, FieldComments, S),
io:format(S, "\t}.~n~n", []),
io:format(S, "cache_key(~s = Id) ->~n", [PriId]),
case length(PriNames) of
1 ->
io:format(S, "\tlist_to_binary(io_lib:format(<<\"~s_~s\">>, [~s])).~n~n", [RecordName, "~p", PirId2]);
2 ->
io:format(S, "\tlist_to_binary(io_lib:format(<<\"~s_~s_~s\">>, [~s])).~n~n", [RecordName, "~p", "~p", PirId2])
end,
file:close(S).
gen_erl_note(Table, ModuleName, OtherKeysLower, S) ->
io:format(S, "%%%--------------------------------------------------------~n", []),
io:format(S, "%%% @Module: ~s~n", [ModuleName]),
io:format(S, <<"%%% @Description: 自动生成~n"/utf8>>, []),
io:format(S, "%%%--------------------------------------------------------~n", []),
io:format(S, "-module(~s).~n", [ModuleName]),
io:format(S, "-export([get_one/1, ~sset_one/1, set_field/3, del_one/1, syncdb/1, clean_all_cache/0, cache_key/1]).~n",
[gen_getonebyotherkey(Table, OtherKeysLower)]),
io:format(S, "-include(\"common.hrl\").~n", []),
io:format(S, "-include(\"record_~s.hrl\").~n~n", [ModuleName]).
gen_getonebyotherkey(_, []) ->
"";
gen_getonebyotherkey(Table, OtherKeysLower) ->
F = fun(UnionNames) ->
By = gen_id_no_bracket(UnionNames, "_and_"),
<<"get_", Table/binary, "_gids_by_", By/binary, "/1">>
end,
L = [F(UnionNames) || UnionNames <- OtherKeysLower],
L2 = util:implode(", ", L),
L3 = L2 ++ ", ",
list_to_binary(L3).
gen_erl_fields_string2term([Name|RestNames], [Value|RestValues], [Comment|RestComments], S) ->
case Comment of
<<"erlang", _/binary>> ->
io:format(S, "\t\t~s = ?B2T(~s)", [Name, Value]);
_->
io:format(S, "\t\t~s = ~s", [Name, Value])
end,
case RestNames of
[] ->
io:format(S, "~n", []);
_ ->
io:format(S, ",~n", []),
gen_erl_fields_string2term(RestNames, RestValues, RestComments, S)
end.
gen_erl_fields(Names, Values, S) ->
gen_erl_fields(Names, Values, S, <<"\t\t\t\t">>).
gen_erl_fields([Name|RestNames], [Value|RestValues], S, Indent) ->
io:format(S, <<Indent/binary, "~s = ~s">>, [Name, Value]),
case RestNames of
[] ->
io:format(S, "~n", []);
_ ->
io:format(S, ",~n", []),
gen_erl_fields(RestNames, RestValues, S, Indent)
end.
get_pri_names(FieldKeyInfos) ->
{_, PriNames} = lists:keyfind(<<"PRIMARY">>, 1, FieldKeyInfos),
PriNames.
get_other_names(FieldKeyInfos) ->
OtherKeyInfos = lists:keydelete(<<"PRIMARY">>, 1, FieldKeyInfos),
[UnionNames || {_, UnionNames} <- OtherKeyInfos].
[ F1 , F2 ]
get_names_upper_1st(FieldNames) ->
[util:upper_1st_char(N) || N <- FieldNames].
% [F1_, F2_]
get_names_underscore(FieldNames) ->
[<<N/binary, "_">> || N <- FieldNames].
% [f1, f2]
get_names_lower(FieldNames) ->
[list_to_binary(string:to_lower(binary_to_list(N))) || N <- FieldNames].
% <<"{x, y}">>
gen_id([FieldName]) ->
FieldName;
gen_id(FieldNames) ->
L = util:implode(", ", FieldNames),
B = list_to_binary(L),
<<"{", B/binary, "}">>.
% <<"x, y">>
gen_id_no_bracket([FieldName], _) ->
FieldName;
gen_id_no_bracket(FieldNames, Imploder) ->
L = util:implode(Imploder, FieldNames),
list_to_binary(L).
gen_pri_id([FieldName]) ->
FieldName;
gen_pri_id([FieldName1, FieldName2]) ->
<<"{", FieldName1/binary, ",", FieldName2/binary, "}">>.
gen_id_sql([FieldName]) ->
<<FieldName/binary, "=?">>;
gen_id_sql(FieldNames) ->
L = [<<FieldName/binary, "=?">> || FieldName <- FieldNames],
L2 = util:implode(" and ", L),
list_to_binary(L2).
gen_fields_sql(FieldNames, FieldTypes, FieldComments) ->
NameF = fun({Name, Type, Comment}) ->
case Comment of
<<"erlang", _/binary>> -> <<"?T2B(", Name/binary, ")">>;
_ ->
case Type =:= <<"tinytext">> orelse Type =:= <<"text">> orelse Type =:= <<"varchar">> orelse Type =:= <<"char">> of
true ->
case util:contains(Name, [<<"name">>, <<"msg">>, <<"description">>, <<"notice">>, <<"title">>]) of
true -> <<"util:esc(", Name/binary, ")">>;
false -> Name
end;
false -> Name
end
end
end,
Fields = lists:zip3(FieldNames, FieldTypes, FieldComments),
FieldNames2 = [NameF(Field) || Field <- Fields],
L = util:implode(", ", FieldNames2),
list_to_binary(L).
gen_update_fields_sql(FieldNames) ->
FieldNamesN = [<<Name/binary, " = ?">> || Name <- FieldNames],
L = util:implode(", ", FieldNamesN),
list_to_binary(L).
gen_fields_placeholder(Len) ->
L = lists:duplicate(Len, "?"),
L2 = util:implode(",", L),
list_to_binary(L2).
gen_fields_placeholder2(FieldTypes) ->
F = fun(Type) ->
case Type =:= <<"tinytext">> orelse Type =:= <<"text">> orelse Type =:= <<"varchar">> orelse Type =:= <<"char">> of
true -> "'~s'";
false -> "~p"
end
end,
L = [F(T) || T <- FieldTypes],
L2 = util:implode(",", L),
list_to_binary(L2).
| null | https://raw.githubusercontent.com/BitGameEN/bitgamex/151ba70a481615379f9648581a5d459b503abe19/aux_scripts/codegen/data_autogen_usr.erl | erlang | --------------------------------------------------------
@Module : data_autogen_usr
--------------------------------------------------------
取出查询结果中的所有行
1 - id通过id_gen生成
[F1_, F2_]
[f1, f2]
<<"{x, y}">>
<<"x, y">>
| @Description : 连接usr库获取表结构,自动生成数据访问代码
-module(data_autogen_usr).
-export([run/0]).
-define(DB, bg_mysql_usr).
-define(DB_HOST, "localhost").
-define(DB_PORT, 3306).
-define(DB_USER, "bitgame").
-define(DB_PASS, "bitgame123").
-define(DB_NAME, "bitgame_usr").
-define(DB_ENCODE, utf8).
init_db() ->
mysql:start_link(?DB, ?DB_HOST, ?DB_PORT, ?DB_USER, ?DB_PASS, ?DB_NAME, fun(_, _, _, _) -> ok end, ?DB_ENCODE),
mysql:connect(?DB, ?DB_HOST, ?DB_PORT, ?DB_USER, ?DB_PASS, ?DB_NAME, ?DB_ENCODE, true),
ok.
db_get_all(Sql) ->
case mysql:fetch(?DB, Sql) of
{data, {_, _, R, _, _}} -> R;
{error, {_, _, _, _, Reason}} -> mysql_halt([Sql, Reason])
end.
mysql_halt([Sql, Reason]) ->
erlang:error({db_error, [Sql, Reason]}).
run() ->
init_db(),
gen("game", 0),
gen("game_package", 2),
gen("game_reclaimed_gold"),
gen("global_config"),
gen("user", 1),
gen("user_gold"),
gen("gold_transfer", 0),
gen("useractivation", 0),
ok.
gen(Table0) ->
gen(Table0, 2).
NeedGid : 0 - id通过数据库自增键生成
2 - id已提供,不需要生成
gen(Table0, NeedGid) ->
Table = list_to_binary(Table0),
SqlNTDC = io_lib:format(<<"SELECT column_name,data_type,column_default,column_comment from information_schema.columns WHERE information_schema.columns.TABLE_NAME = '~s' and information_schema.columns.TABLE_SCHEMA = '~s'">>, [Table, ?DB_NAME]),
FieldInfos = db_get_all(SqlNTDC),
FieldNames = [N || [N|_] <- FieldInfos],
FieldTypes = [T || [_,T|_] <- FieldInfos],
FieldDefaults = [D || [_,_,D|_] <- FieldInfos],
FieldComments = [C || [_,_,_,C|_] <- FieldInfos],
SqlK = io_lib:format(<<"SELECT index_name,column_name from information_schema.statistics WHERE information_schema.statistics.TABLE_NAME = '~s' and information_schema.statistics.TABLE_SCHEMA = '~s' order by index_name">>, [Table, ?DB_NAME]),
FieldKeyInfos0 = db_get_all(SqlK),
F = fun(F, [[IndexName, ColumnName] | RestFieldKeyInfos], Acc) ->
case lists:keyfind(IndexName, 1, Acc) of
false ->
F(F, RestFieldKeyInfos, [{IndexName, [ColumnName]} | Acc]);
{_, L} ->
F(F, RestFieldKeyInfos, lists:keyreplace(IndexName, 1, Acc, {IndexName, [ColumnName | L]}))
end;
(_, [], Acc) ->
[{Index, lists:sort(fun compare_column/2, Columns)} || {Index, Columns} <- Acc]
end,
FieldKeyInfos = F(F, FieldKeyInfos0, []),
RecordName = list_to_binary(io_lib:format(<<"usr_~s">>, [Table])),
gen_record(io_lib:format(<<"record_usr_~s.hrl">>, [Table]), RecordName, FieldNames, FieldTypes, FieldDefaults, FieldComments),
gen_erl(Table, io_lib:format(<<"usr_~s.erl">>, [Table]), RecordName, FieldNames, FieldTypes, FieldComments, FieldKeyInfos, RecordName, NeedGid).
compare_column(A, B) ->
A < B.
gen_record(HrlName, RecordName, FieldNames, FieldTypes, FieldDefaults, FieldComments) ->
{ok, S} = file:open(HrlName, write),
io:format(S, "%%%--------------------------------------------------------~n", []),
io:format(S, "%%% @Module: ~s~n", [RecordName]),
io:format(S, <<"%%% @Description: 自动生成~n"/utf8>>, []),
io:format(S, "%%%--------------------------------------------------------~n", []),
io:format(S, "~n", []),
io:format(S, "-record(~s, {~n", [RecordName]),
io:format(S, "\t\tkey_id,~n", []),
gen_record_fields(FieldNames, FieldTypes, FieldDefaults, FieldComments, S),
io:format(S, "}).~n", []),
file:close(S).
gen_record_fields([Name0 | RestNames], [Type | RestTypes], [Default0 | RestDefaults], [Comment | RestComments], S) ->
Name = string:to_lower(binary_to_list(Name0)),
Default = case Default0 of
undefined ->
case Type of
<<"char">> -> <<"">>;
<<"varchar">> -> <<"">>;
<<"tinytext">> -> <<"">>;
<<"text">> -> <<"">>;
_-> <<"0">>
end;
_ ->
Default0
end,
case Comment of
<<"erlang", _/binary>> ->
case Default of
<<"">> ->
io:format(S, "\t\t~s", [Name]);
_ ->
io:format(S, "\t\t~s = ~s", [Name, Default])
end;
_ ->
case Type of
<<"char">> ->
io:format(S, "\t\t~s = <<\"~s\">>", [Name, Default]);
<<"varchar">> ->
io:format(S, "\t\t~s = <<\"~s\">>", [Name, Default]);
<<"tinytext">> ->
io:format(S, "\t\t~s = <<\"~s\">>", [Name, Default]);
<<"text">> ->
io:format(S, "\t\t~s = <<\"~s\">>", [Name, Default]);
_ ->
io:format(S, "\t\t~s = ~s", [Name, Default])
end
end,
case RestNames of
[] ->
io:format(S, " % ~s~n", [Comment]);
_ ->
io:format(S, ", % ~s~n", [Comment]),
gen_record_fields(RestNames, RestTypes, RestDefaults, RestComments, S)
end.
gen_erl(Table, ErlName, ModuleName, FieldNames, FieldTypes, FieldComments, FieldKeyInfos, RecordName, NeedGid) ->
FieldNames2 = get_names_upper_1st(FieldNames),
PriNames = get_pri_names(FieldKeyInfos),
PriNames2 = get_names_upper_1st(PriNames),
PriNames3 = get_names_underscore(PriNames2),
PriId = gen_id(PriNames2),
PirId2 = gen_id_no_bracket(PriNames2, ", "),
PirId3 = gen_id_no_bracket(PriNames3, ", "),
OtherKeys = get_other_names(FieldKeyInfos),
OtherKeysLower = [get_names_lower(UnionNames) || UnionNames <- OtherKeys],
OtherKeys2 = lists:zip(OtherKeys, OtherKeysLower),
{ok, S} = file:open(ErlName, write),
gen_erl_note(Table, ModuleName, OtherKeysLower, S),
io:format(S, "get_one(~s = Id) ->~n", [PriId]),
io:format(S, "\tcase run_data:in_trans() of~n", []),
io:format(S, "\t\ttrue ->~n", []),
io:format(S, "\t\t\tcase run_data:trans_get(~s, Id) of~n", [RecordName]),
io:format(S, "\t\t\t\t[] ->~n", []),
io:format(S, "\t\t\t\t\tget_one_(Id);~n", []),
io:format(S, "\t\t\t\ttrans_deleted -> [];~n", []),
io:format(S, "\t\t\t\tR -> R~n", []),
io:format(S, "\t\t\tend;~n", []),
io:format(S, "\t\tfalse ->~n", []),
io:format(S, "\t\t\tget_one_(Id)~n", []),
io:format(S, "\tend.~n~n", []),
io:format(S, "get_one_(~s = Id) ->~n", [PriId]),
io:format(S, "\tcase cache:get(cache_key(Id)) of~n", []),
io:format(S, "\t\t{true, _Cas, Val} ->~n", []),
io:format(S, "\t\t\tVal;~n", []),
io:format(S, "\t\t_ ->~n", []),
io:format(S, "\t\t\tcase db_esql:get_row(?DB_USR, <<\"select ~s from ~s where ~s\">>, [~s]) of~n",
[gen_id_no_bracket(FieldNames, ","), Table, gen_id_sql(PriNames), PirId2]),
io:format(S, "\t\t\t\t[] -> [];~n", []),
io:format(S, "\t\t\t\tRow ->~n", []),
io:format(S, "\t\t\t\t\tR = build_record_from_row(Row),~n", []),
io:format(S, "\t\t\t\t\tcache:set(cache_key(R#~s.key_id), R),~n", [RecordName]),
io:format(S, "\t\t\t\t\tR~n", []),
io:format(S, "\t\t\tend~n", []),
io:format(S, "\tend.~n~n", []),
GenOtherKeyGetF = fun(OtherKey, OtherKeyLower) ->
OtherKey2 = get_names_upper_1st(OtherKeyLower),
OtherId = gen_id(OtherKey2),
OtherId2 = gen_id_no_bracket(OtherKey2, ", "),
OtherIdAnd = gen_id_no_bracket(OtherKeyLower, "_and_"),
io:format(S, "get_~s_gids_by_~s(~s = Id) ->~n", [Table, OtherIdAnd, OtherId]),
io:format(S, "\tcase db_esql:get_all(?DB_USR, <<\"select ~s from ~s where ~s\">>, [~s]) of~n",
[gen_id_no_bracket(PriNames, ", "), Table, gen_id_sql(OtherKey), OtherId2]),
io:format(S, "\t\t[] -> [];~n", []),
io:format(S, "\t\tRows ->~n", []),
io:format(S, "\t\t\t[~s || [~s | _] <- Rows]~n", [PirId3, PirId3]),
io:format(S, "\tend.~n~n", [])
end,
[GenOtherKeyGetF(K, KL) || {K, KL} <- OtherKeys2],
io:format(S, "set_field(~s = Id, Field, Val) ->~n", [PriId]),
io:format(S, "\tFields = record_info(fields, ~s),~n", [RecordName]),
io:format(S, "\tL = lists:zip(Fields, lists:seq(1, length(Fields))),~n", []),
io:format(S, "\t{_, N} = lists:keyfind(Field, 1, L),~n", []),
io:format(S, "\tR0 = get_one(Id),~n", []),
io:format(S, "\tR = setelement(N+1, R0, Val),~n", []),
io:format(S, "\tset_one(R),~n", []),
io:format(S, "\tR.~n~n", []),
io:format(S, "set_one(R0) when is_record(R0, ~s) ->~n", [RecordName]),
io:format(S, "\tcase R0#~s.key_id =:= undefined of~n", [RecordName]),
io:format(S, "\t\tfalse ->~n", []),
io:format(S, "\t\t\tcase run_data:in_trans() of~n", []),
io:format(S, "\t\t\t\ttrue ->~n", []),
io:format(S, "\t\t\t\t\trun_data:trans_set(~s, R0#~s.key_id, R0,~n", [RecordName, RecordName]),
io:format(S, "\t\t\t\t\t\tvoid,~n", []),
io:format(S, "\t\t\t\t\t\tvoid);~n", []),
io:format(S, "\t\t\t\tfalse ->~n", []),
io:format(S, "\t\t\t\t\tsyncdb(R0),~n", []),
io : format(S , " \t\t\t\t\tcache : del(cache_key(R0#~s.key_id))~n " , [ RecordName ] ) ,
io:format(S, "\t\t\t\t\tcache:set(cache_key(R0#~s.key_id), R0)~n", [RecordName]),
io:format(S, "\t\t\tend,~n", []),
io:format(S, "\t\t\tR0#~s.key_id;~n", [RecordName]),
io:format(S, "\t\ttrue ->~n", []),
io:format(S, "\t\t\t#~s{~n", [RecordName]),
case NeedGid of
1 ->
[PriFieldName | FieldNames_] = FieldNames,
[PriFieldName2 | FieldNames2_] = FieldNames2,
io:format(S, "\t\t\t\t~s = ~s_0,~n", [PriFieldName, PriFieldName2]),
gen_erl_fields(FieldNames_, FieldNames2_, S),
io:format(S, "\t\t\t} = R0,~n", []),
io:format(S, "\t\t\t~s = id_gen:gen_id(~s),~n", [PriFieldName2, RecordName]),
io:format(S, "\t\t\tR = R0#~s{key_id = ~s, ~s = ~s},~n", [RecordName, PriFieldName2, gen_pri_id(PriNames), PriFieldName2]);
2 ->
[PriFieldName2 | _] = FieldNames2,
gen_erl_fields(FieldNames, FieldNames2, S),
io:format(S, "\t\t\t} = R0,~n", []),
io:format(S, "\t\t\tR = R0#~s{key_id = ~s},~n", [RecordName, PriId]);
0 ->
gen_erl_fields(FieldNames, FieldNames2, S),
io:format(S, "\t\t\t} = R0,~n", []),
io:format(S, "\t\t\t{ok, [[Insert_id|_]]} = db_esql:multi_execute(?DB_USR, io_lib:format(<<\"insert into ~s(~s) values(~s); select last_insert_id()\">>,~n\t\t\t\t[~s])),~n",
[Table, gen_id_no_bracket(FieldNames, ","), gen_fields_placeholder2(FieldTypes), gen_fields_sql(FieldNames2, FieldTypes, FieldComments)]),
io:format(S, "\t\t\tR = R0#~s{key_id = Insert_id, ~s = Insert_id},~n", [RecordName, gen_pri_id(PriNames)])
end,
io:format(S, "\t\t\tF = fun() ->~n", []),
case NeedGid of
1 ->
io:format(S, "\t\t\t\t\trun_data:db_write(add, R, fun() -> 1 = db_esql:execute(?DB_USR, io_lib:format(<<\"insert into ~s(~s) values(~s)\">>,~n\t\t\t\t\t\t[~s])) end),~n",
[Table, gen_id_no_bracket(FieldNames, ","), gen_fields_placeholder2(FieldTypes), gen_fields_sql(FieldNames2, FieldTypes, FieldComments)]);
2 ->
io:format(S, "\t\t\t\t\trun_data:db_write(add, R, fun() -> 1 = db_esql:execute(?DB_USR, io_lib:format(<<\"insert into ~s(~s) values(~s)\">>,~n\t\t\t\t\t\t[~s])) end),~n",
[Table, gen_id_no_bracket(FieldNames, ","), gen_fields_placeholder2(FieldTypes), gen_fields_sql(FieldNames2, FieldTypes, FieldComments)]);
0 -> void
end,
io:format(S, "\t\t\t\t\tcache:set(cache_key(R#~s.key_id), R)~n", [RecordName]),
io:format(S, "\t\t\t\tend,~n", []),
io:format(S, "\t\t\tcase run_data:in_trans() of~n", []),
io:format(S, "\t\t\t\ttrue ->~n", []),
io:format(S, "\t\t\t\t\trun_data:trans_set(~s, R#~s.key_id, {trans_inserted, R}, F, fun() -> ~s:del_one(R) end);~n", [RecordName, RecordName, RecordName]),
io:format(S, "\t\t\t\tfalse ->~n", []),
io:format(S, "\t\t\t\t\tF()~n", []),
io:format(S, "\t\t\tend,~n", []),
io:format(S, "\t\t\tR#~s.key_id~n", [RecordName]),
io:format(S, "\tend.~n~n", []),
io:format(S, "del_one(R) when is_record(R, ~s) ->~n", [RecordName]),
io:format(S, "\tcase run_data:in_trans() of~n", []),
io:format(S, "\t\ttrue ->~n", []),
io:format(S, "\t\t\trun_data:trans_del(~s, R#~s.key_id,~n", [RecordName, RecordName]),
io:format(S, "\t\t\t\tfun() -> ~s:del_one(R) end,~n", [RecordName]),
io:format(S, "\t\t\t\tvoid);~n", []),
io:format(S, "\t\tfalse ->~n", []),
io:format(S, "\t\t\t~s = R#~s.key_id,~n", [PriId, RecordName]),
io:format(S, "\t\t\trun_data:db_write(del, R, fun() -> db_esql:execute(?DB_USR, <<\"delete from ~s where ~s\">>, [~s]) end),~n", [Table, gen_id_sql(PriNames), PirId2]),
io:format(S, "\t\t\tcache:del(cache_key(R#~s.key_id))~n", [RecordName]),
io:format(S, "\tend,~n", []),
io:format(S, "\tok.~n~n", []),
io:format(S, "clean_all_cache() ->~n", []),
io:format(S, "\tclean_all_cache(0),~n", []),
io:format(S, "\tok.~n~n", []),
io:format(S, "clean_all_cache(N) ->~n", []),
io:format(S, "\tcase db_esql:get_all(?DB_USR, <<\"select ~s from ~s limit ?, 1000\">>, [N * 1000]) of~n", [gen_id_no_bracket(PriNames, ","), Table]),
io:format(S, "\t\t[] -> ok;~n", []),
io:format(S, "\t\tRows ->~n", []),
io:format(S, "\t\t\tF = fun(Id) -> cache:del(cache_key(Id)) end,~n", []),
io:format(S, "\t\t\t[F(Id) || [Id | _] <- Rows],~n", []),
io:format(S, "\t\t\tclean_all_cache(N + 1)~n", []),
io:format(S, "\tend.~n~n", []),
io:format(S, "syncdb(R) when is_record(R, ~s) ->~n", [RecordName]),
io:format(S, "\t#~s{~n", [RecordName]),
gen_erl_fields(FieldNames, FieldNames2, S, <<"\t\t">>),
io:format(S, "\t} = R,~n", []),
[_ | NonPriFieldNames] = FieldNames,
[_ | NonPriFieldNames2] = FieldNames2,
[_ | NonPriFieldTypes] = FieldTypes,
[_ | NonPriFieldComments] = FieldComments,
io:format(S, "\trun_data:db_write(upd, R, fun() -> db_esql:execute(?DB_USR, io_lib:format(<<\"insert into ~s(~s) values(~s) on duplicate key update \"~n\t\t\"~s\">>, []),~n\t\t[~s, ~s]) end).~n~n",
[Table, gen_id_no_bracket(FieldNames, ","), gen_fields_placeholder(length(FieldNames)), gen_update_fields_sql(NonPriFieldNames),
gen_fields_sql(FieldNames2, FieldTypes, FieldComments), gen_fields_sql(NonPriFieldNames2, NonPriFieldTypes, NonPriFieldComments)]),
io:format(S, "build_record_from_row([", []),
[FieldName | RestFieldNames] = FieldNames2,
io:format(S, "~s", [FieldName]),
GenFieldsStrF = fun(FieldName_, S_) -> io:format(S_, ", ~s", [FieldName_]) end,
[GenFieldsStrF(FName, S) || FName <- RestFieldNames],
io:format(S, "]) ->~n", []),
io:format(S, "\t#~s{~n", [RecordName]),
io:format(S, "\t\tkey_id = ~s,~n", [PriId]),
gen_erl_fields_string2term(FieldNames, FieldNames2, FieldComments, S),
io:format(S, "\t}.~n~n", []),
io:format(S, "cache_key(~s = Id) ->~n", [PriId]),
case length(PriNames) of
1 ->
io:format(S, "\tlist_to_binary(io_lib:format(<<\"~s_~s\">>, [~s])).~n~n", [RecordName, "~p", PirId2]);
2 ->
io:format(S, "\tlist_to_binary(io_lib:format(<<\"~s_~s_~s\">>, [~s])).~n~n", [RecordName, "~p", "~p", PirId2])
end,
file:close(S).
gen_erl_note(Table, ModuleName, OtherKeysLower, S) ->
io:format(S, "%%%--------------------------------------------------------~n", []),
io:format(S, "%%% @Module: ~s~n", [ModuleName]),
io:format(S, <<"%%% @Description: 自动生成~n"/utf8>>, []),
io:format(S, "%%%--------------------------------------------------------~n", []),
io:format(S, "-module(~s).~n", [ModuleName]),
io:format(S, "-export([get_one/1, ~sset_one/1, set_field/3, del_one/1, syncdb/1, clean_all_cache/0, cache_key/1]).~n",
[gen_getonebyotherkey(Table, OtherKeysLower)]),
io:format(S, "-include(\"common.hrl\").~n", []),
io:format(S, "-include(\"record_~s.hrl\").~n~n", [ModuleName]).
gen_getonebyotherkey(_, []) ->
"";
gen_getonebyotherkey(Table, OtherKeysLower) ->
F = fun(UnionNames) ->
By = gen_id_no_bracket(UnionNames, "_and_"),
<<"get_", Table/binary, "_gids_by_", By/binary, "/1">>
end,
L = [F(UnionNames) || UnionNames <- OtherKeysLower],
L2 = util:implode(", ", L),
L3 = L2 ++ ", ",
list_to_binary(L3).
gen_erl_fields_string2term([Name|RestNames], [Value|RestValues], [Comment|RestComments], S) ->
case Comment of
<<"erlang", _/binary>> ->
io:format(S, "\t\t~s = ?B2T(~s)", [Name, Value]);
_->
io:format(S, "\t\t~s = ~s", [Name, Value])
end,
case RestNames of
[] ->
io:format(S, "~n", []);
_ ->
io:format(S, ",~n", []),
gen_erl_fields_string2term(RestNames, RestValues, RestComments, S)
end.
gen_erl_fields(Names, Values, S) ->
gen_erl_fields(Names, Values, S, <<"\t\t\t\t">>).
gen_erl_fields([Name|RestNames], [Value|RestValues], S, Indent) ->
io:format(S, <<Indent/binary, "~s = ~s">>, [Name, Value]),
case RestNames of
[] ->
io:format(S, "~n", []);
_ ->
io:format(S, ",~n", []),
gen_erl_fields(RestNames, RestValues, S, Indent)
end.
get_pri_names(FieldKeyInfos) ->
{_, PriNames} = lists:keyfind(<<"PRIMARY">>, 1, FieldKeyInfos),
PriNames.
get_other_names(FieldKeyInfos) ->
OtherKeyInfos = lists:keydelete(<<"PRIMARY">>, 1, FieldKeyInfos),
[UnionNames || {_, UnionNames} <- OtherKeyInfos].
[ F1 , F2 ]
get_names_upper_1st(FieldNames) ->
[util:upper_1st_char(N) || N <- FieldNames].
get_names_underscore(FieldNames) ->
[<<N/binary, "_">> || N <- FieldNames].
get_names_lower(FieldNames) ->
[list_to_binary(string:to_lower(binary_to_list(N))) || N <- FieldNames].
gen_id([FieldName]) ->
FieldName;
gen_id(FieldNames) ->
L = util:implode(", ", FieldNames),
B = list_to_binary(L),
<<"{", B/binary, "}">>.
gen_id_no_bracket([FieldName], _) ->
FieldName;
gen_id_no_bracket(FieldNames, Imploder) ->
L = util:implode(Imploder, FieldNames),
list_to_binary(L).
gen_pri_id([FieldName]) ->
FieldName;
gen_pri_id([FieldName1, FieldName2]) ->
<<"{", FieldName1/binary, ",", FieldName2/binary, "}">>.
gen_id_sql([FieldName]) ->
<<FieldName/binary, "=?">>;
gen_id_sql(FieldNames) ->
L = [<<FieldName/binary, "=?">> || FieldName <- FieldNames],
L2 = util:implode(" and ", L),
list_to_binary(L2).
gen_fields_sql(FieldNames, FieldTypes, FieldComments) ->
NameF = fun({Name, Type, Comment}) ->
case Comment of
<<"erlang", _/binary>> -> <<"?T2B(", Name/binary, ")">>;
_ ->
case Type =:= <<"tinytext">> orelse Type =:= <<"text">> orelse Type =:= <<"varchar">> orelse Type =:= <<"char">> of
true ->
case util:contains(Name, [<<"name">>, <<"msg">>, <<"description">>, <<"notice">>, <<"title">>]) of
true -> <<"util:esc(", Name/binary, ")">>;
false -> Name
end;
false -> Name
end
end
end,
Fields = lists:zip3(FieldNames, FieldTypes, FieldComments),
FieldNames2 = [NameF(Field) || Field <- Fields],
L = util:implode(", ", FieldNames2),
list_to_binary(L).
gen_update_fields_sql(FieldNames) ->
FieldNamesN = [<<Name/binary, " = ?">> || Name <- FieldNames],
L = util:implode(", ", FieldNamesN),
list_to_binary(L).
gen_fields_placeholder(Len) ->
L = lists:duplicate(Len, "?"),
L2 = util:implode(",", L),
list_to_binary(L2).
gen_fields_placeholder2(FieldTypes) ->
F = fun(Type) ->
case Type =:= <<"tinytext">> orelse Type =:= <<"text">> orelse Type =:= <<"varchar">> orelse Type =:= <<"char">> of
true -> "'~s'";
false -> "~p"
end
end,
L = [F(T) || T <- FieldTypes],
L2 = util:implode(",", L),
list_to_binary(L2).
|
bfad5a6b71c7c2ffe07b3d5c92e17a5bf9e3225c10f2ce17893d4d43c2c4fcfc | CryptoKami/cryptokami-core | Misc.hs | -- | Interface for the Misc DB
module Pos.Update.DB.Misc
( isUpdateInstalled
, affirmUpdateInstalled
) where
import Universum
import Formatting (sformat)
import Pos.Binary.Class (Raw)
import Pos.Crypto (Hash, hashHexF)
import Pos.DB.Class (MonadDB)
import Pos.DB.Misc.Common (miscGetBi, miscPutBi)
isUpdateInstalled :: MonadDB m => Hash Raw -> m Bool
isUpdateInstalled h = isJust <$> miscGetBi @() (updateTrackKey h)
affirmUpdateInstalled :: MonadDB m => Hash Raw -> m ()
affirmUpdateInstalled h = miscPutBi (updateTrackKey h) ()
updateTrackKey :: Hash Raw -> ByteString
updateTrackKey h = "updinst/" <> encodeUtf8 (sformat hashHexF h)
| null | https://raw.githubusercontent.com/CryptoKami/cryptokami-core/12ca60a9ad167b6327397b3b2f928c19436ae114/update/Pos/Update/DB/Misc.hs | haskell | | Interface for the Misc DB |
module Pos.Update.DB.Misc
( isUpdateInstalled
, affirmUpdateInstalled
) where
import Universum
import Formatting (sformat)
import Pos.Binary.Class (Raw)
import Pos.Crypto (Hash, hashHexF)
import Pos.DB.Class (MonadDB)
import Pos.DB.Misc.Common (miscGetBi, miscPutBi)
isUpdateInstalled :: MonadDB m => Hash Raw -> m Bool
isUpdateInstalled h = isJust <$> miscGetBi @() (updateTrackKey h)
affirmUpdateInstalled :: MonadDB m => Hash Raw -> m ()
affirmUpdateInstalled h = miscPutBi (updateTrackKey h) ()
updateTrackKey :: Hash Raw -> ByteString
updateTrackKey h = "updinst/" <> encodeUtf8 (sformat hashHexF h)
|
53923f4c68d2f56139bce22db2360f965caa4fbe58abc35c2fd6d2f29555ef06 | ghcjs/ghcjs-dom | Debug.hs | {-# LANGUAGE ConstraintKinds #-}
# LANGUAGE LambdaCase #
# LANGUAGE ScopedTypeVariables #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE RecordWildCards #
module GHCJS.DOM.Debug (
DomHasCallStack
, debugEnabled
, getElementStack
, addDebugMenu
, addDebugMenu'
) where
import Control.Arrow (Arrow(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Char (toLower)
import Data.Foldable (forM_)
import Data.Monoid ((<>))
import System.IO (stderr, hPutStrLn)
import GHC.Stack
(srcLocStartLine, srcLocFile, SrcLoc(..), HasCallStack)
import GHC.Exts (Constraint)
import GHCJS.DOM (currentDocumentUnchecked)
import GHCJS.DOM.Types
(HTMLDivElement(..), HTMLStyleElement(..), uncheckedCastTo,
HTMLUListElement(..), MouseEvent(..), Document(..), Element(..),
HTMLAnchorElement(..), MonadJSM, JSM, liftJSM, JSString)
import GHCJS.DOM.Debug.Internal (DomHasCallStack, getElementStack, debugEnabled)
import GHCJS.DOM.Document
(createTextNode, getBodyUnchecked,
getElementsByTagName, createElement)
import GHCJS.DOM.DocumentOrShadowRoot (elementFromPoint)
import GHCJS.DOM.Element
(getTagName, setAttribute, getAttribute, setInnerHTML)
import GHCJS.DOM.EventM
(addListener, uiPageXY, mouseClientXY, mouseShiftKey, target,
newListener, on, preventDefault)
import GHCJS.DOM.EventTargetClosures (SaferEventListener(..))
import GHCJS.DOM.GlobalEventHandlers (click, contextMenu)
import GHCJS.DOM.HTMLCollection (itemUnchecked)
import GHCJS.DOM.HTMLStyleElement (setType)
import GHCJS.DOM.Node (getParentElement, appendChild_)
import GHCJS.DOM.NonElementParentNode (getElementById)
addDebugMenu :: MonadJSM m => m (JSM ())
addDebugMenu = addDebugMenu' (const Nothing)
addDebugMenu' :: MonadJSM m => (SrcLoc -> Maybe String) -> m (JSM ())
addDebugMenu' getSourceLink = liftJSM $ do
let menuId = "ghcjs-dom-debug" :: JSString
doc <- currentDocumentUnchecked
style <- uncheckedCastTo HTMLStyleElement <$> createElement doc ("style" :: JSString)
setType style ("text/css" :: JSString)
setInnerHTML style $ mconcat [
"#", menuId, ", #", menuId, " ul ul{"
, " display: block;"
, " position: absolute;"
, " box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);"
, " padding: 2px;"
, " z-index:1000;"
, " margin: 0;"
, " list-style-type: none;"
, " list-style: none;"
, " background-color:#fff;"
, " color:#000;"
, "}\n"
, "#", menuId, " ul{"
, " list-style-type: none;"
, " margin: 0;"
, " padding: 2px;"
, " cursor: pointer;"
, "}\n"
, "#", menuId, " li{"
, " white-space: nowrap;"
, "}\n"
, "#", menuId, " ul ul{"
, " display: none;"
, "}\n"
, "#", menuId, ">li:hover{"
, " background-color:#ddd;"
, "}\n"
, "#", menuId, " li:hover ul{"
, " display: inline-block;"
, " position: absolute;"
, " z-index:1001;"
, "}\n"
]
getElementsByTagName doc ("head" :: JSString) >>= (`itemUnchecked` 0) >>= (`appendChild_` style)
body <- getBodyUnchecked doc
clickListener <- newListener $ do
target >>= \case
Just (t :: HTMLAnchorElement) ->
getAttribute t ("hs-srcloc" :: JSString)
>>= mapM_ (liftIO . hPutStrLn stderr . ("OPEN " <>))
Nothing -> return ()
getElementById doc menuId >>= mapM_
(\e -> setAttribute e ("style" :: JSString) ("display: none;" :: JSString))
on doc contextMenu $ mouseShiftKey >>= \case
True -> ((fromIntegral *** fromIntegral) <$> mouseClientXY) >>= uncurry (elementFromPoint doc) >>= \case
Just e -> do
preventDefault
menu <- getElementById doc menuId >>= \case
Just menu -> setInnerHTML menu ("" :: JSString) >> return (uncheckedCastTo HTMLDivElement menu)
Nothing -> do
menu <- uncheckedCastTo HTMLDivElement <$> createElement doc ("div" :: JSString)
setAttribute menu ("id" :: JSString) menuId
appendChild_ body menu
return menu
if debugEnabled
then do
ul <- uncheckedCastTo HTMLUListElement <$> createElement doc ("ul" :: JSString)
appendChild_ menu ul
addMenu doc clickListener ul e
else do
a <- uncheckedCastTo HTMLAnchorElement <$> createElement doc ("a" :: JSString)
appendChild_ menu a
createTextNode doc ("The ghcjs-dom debug cabal flag is switched off" :: JSString)
>>= appendChild_ a
setAttribute a ("href" :: JSString)
("-dom/blob/master/README.md#debug" :: JSString)
setAttribute a ("target" :: JSString) ("_blank" :: JSString)
liftJSM $ addListener a click clickListener False
(pageX, pageY) <- uiPageXY
setAttribute menu ("style" :: JSString) ("display: block; left: " <> show pageX <> "px; top:" <> show pageY <> "px;" )
Nothing -> return ()
False -> return ()
where
addMenu :: MonadJSM m => Document -> SaferEventListener HTMLAnchorElement MouseEvent -> HTMLUListElement -> Element -> m ()
addMenu doc clickListener parentMenu = loop
where
loop e = do
getElementStack e >>= mapM_ (addElementMenu doc clickListener parentMenu e)
getParentElement e >>= mapM_ loop
addElementMenu
:: MonadJSM m
=> Document
-> SaferEventListener HTMLAnchorElement MouseEvent
-> HTMLUListElement
-> Element
-> [(String, SrcLoc)]
-> m ()
addElementMenu doc clickListener parentMenu e cs = do
tagName <- map toLower <$> getTagName e
parentLi <- createElement doc ("li" :: JSString)
appendChild_ parentMenu parentLi
createTextNode doc tagName >>= appendChild_ parentLi
ul <- createElement doc ("ul" :: JSString)
appendChild_ parentLi ul
forM_ (reverse cs) $ \(f, loc) -> do
li <- createElement doc ("li" :: JSString)
appendChild_ ul li
a <- uncheckedCastTo HTMLAnchorElement <$> createElement doc ("a" :: JSString)
appendChild_ li a
createTextNode doc (f <> " " <> srcLocFile loc <> ":" <> show (srcLocStartLine loc))
>>= appendChild_ a
forM_ (getSourceLink loc) $ \link -> do
setAttribute a ("href" :: JSString) link
setAttribute a ("target" :: JSString) ("_blank" :: JSString)
setAttribute a ("hs-srcloc" :: JSString) $ prettySrcLoc loc
liftJSM $ addListener a click clickListener False
prettySrcLoc :: SrcLoc -> String
prettySrcLoc SrcLoc {..} = mconcat
[ srcLocFile , ":("
, show srcLocStartLine, ","
, show srcLocStartCol , ")-("
, show srcLocEndLine , ","
, show srcLocEndCol , ") in "
, srcLocPackage, ":", srcLocModule
]
| null | https://raw.githubusercontent.com/ghcjs/ghcjs-dom/749963557d878d866be2d0184079836f367dd0ea/ghcjs-dom/src/GHCJS/DOM/Debug.hs | haskell | # LANGUAGE ConstraintKinds #
# LANGUAGE OverloadedStrings # | # LANGUAGE LambdaCase #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE RecordWildCards #
module GHCJS.DOM.Debug (
DomHasCallStack
, debugEnabled
, getElementStack
, addDebugMenu
, addDebugMenu'
) where
import Control.Arrow (Arrow(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Char (toLower)
import Data.Foldable (forM_)
import Data.Monoid ((<>))
import System.IO (stderr, hPutStrLn)
import GHC.Stack
(srcLocStartLine, srcLocFile, SrcLoc(..), HasCallStack)
import GHC.Exts (Constraint)
import GHCJS.DOM (currentDocumentUnchecked)
import GHCJS.DOM.Types
(HTMLDivElement(..), HTMLStyleElement(..), uncheckedCastTo,
HTMLUListElement(..), MouseEvent(..), Document(..), Element(..),
HTMLAnchorElement(..), MonadJSM, JSM, liftJSM, JSString)
import GHCJS.DOM.Debug.Internal (DomHasCallStack, getElementStack, debugEnabled)
import GHCJS.DOM.Document
(createTextNode, getBodyUnchecked,
getElementsByTagName, createElement)
import GHCJS.DOM.DocumentOrShadowRoot (elementFromPoint)
import GHCJS.DOM.Element
(getTagName, setAttribute, getAttribute, setInnerHTML)
import GHCJS.DOM.EventM
(addListener, uiPageXY, mouseClientXY, mouseShiftKey, target,
newListener, on, preventDefault)
import GHCJS.DOM.EventTargetClosures (SaferEventListener(..))
import GHCJS.DOM.GlobalEventHandlers (click, contextMenu)
import GHCJS.DOM.HTMLCollection (itemUnchecked)
import GHCJS.DOM.HTMLStyleElement (setType)
import GHCJS.DOM.Node (getParentElement, appendChild_)
import GHCJS.DOM.NonElementParentNode (getElementById)
addDebugMenu :: MonadJSM m => m (JSM ())
addDebugMenu = addDebugMenu' (const Nothing)
addDebugMenu' :: MonadJSM m => (SrcLoc -> Maybe String) -> m (JSM ())
addDebugMenu' getSourceLink = liftJSM $ do
let menuId = "ghcjs-dom-debug" :: JSString
doc <- currentDocumentUnchecked
style <- uncheckedCastTo HTMLStyleElement <$> createElement doc ("style" :: JSString)
setType style ("text/css" :: JSString)
setInnerHTML style $ mconcat [
"#", menuId, ", #", menuId, " ul ul{"
, " display: block;"
, " position: absolute;"
, " box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);"
, " padding: 2px;"
, " z-index:1000;"
, " margin: 0;"
, " list-style-type: none;"
, " list-style: none;"
, " background-color:#fff;"
, " color:#000;"
, "}\n"
, "#", menuId, " ul{"
, " list-style-type: none;"
, " margin: 0;"
, " padding: 2px;"
, " cursor: pointer;"
, "}\n"
, "#", menuId, " li{"
, " white-space: nowrap;"
, "}\n"
, "#", menuId, " ul ul{"
, " display: none;"
, "}\n"
, "#", menuId, ">li:hover{"
, " background-color:#ddd;"
, "}\n"
, "#", menuId, " li:hover ul{"
, " display: inline-block;"
, " position: absolute;"
, " z-index:1001;"
, "}\n"
]
getElementsByTagName doc ("head" :: JSString) >>= (`itemUnchecked` 0) >>= (`appendChild_` style)
body <- getBodyUnchecked doc
clickListener <- newListener $ do
target >>= \case
Just (t :: HTMLAnchorElement) ->
getAttribute t ("hs-srcloc" :: JSString)
>>= mapM_ (liftIO . hPutStrLn stderr . ("OPEN " <>))
Nothing -> return ()
getElementById doc menuId >>= mapM_
(\e -> setAttribute e ("style" :: JSString) ("display: none;" :: JSString))
on doc contextMenu $ mouseShiftKey >>= \case
True -> ((fromIntegral *** fromIntegral) <$> mouseClientXY) >>= uncurry (elementFromPoint doc) >>= \case
Just e -> do
preventDefault
menu <- getElementById doc menuId >>= \case
Just menu -> setInnerHTML menu ("" :: JSString) >> return (uncheckedCastTo HTMLDivElement menu)
Nothing -> do
menu <- uncheckedCastTo HTMLDivElement <$> createElement doc ("div" :: JSString)
setAttribute menu ("id" :: JSString) menuId
appendChild_ body menu
return menu
if debugEnabled
then do
ul <- uncheckedCastTo HTMLUListElement <$> createElement doc ("ul" :: JSString)
appendChild_ menu ul
addMenu doc clickListener ul e
else do
a <- uncheckedCastTo HTMLAnchorElement <$> createElement doc ("a" :: JSString)
appendChild_ menu a
createTextNode doc ("The ghcjs-dom debug cabal flag is switched off" :: JSString)
>>= appendChild_ a
setAttribute a ("href" :: JSString)
("-dom/blob/master/README.md#debug" :: JSString)
setAttribute a ("target" :: JSString) ("_blank" :: JSString)
liftJSM $ addListener a click clickListener False
(pageX, pageY) <- uiPageXY
setAttribute menu ("style" :: JSString) ("display: block; left: " <> show pageX <> "px; top:" <> show pageY <> "px;" )
Nothing -> return ()
False -> return ()
where
addMenu :: MonadJSM m => Document -> SaferEventListener HTMLAnchorElement MouseEvent -> HTMLUListElement -> Element -> m ()
addMenu doc clickListener parentMenu = loop
where
loop e = do
getElementStack e >>= mapM_ (addElementMenu doc clickListener parentMenu e)
getParentElement e >>= mapM_ loop
addElementMenu
:: MonadJSM m
=> Document
-> SaferEventListener HTMLAnchorElement MouseEvent
-> HTMLUListElement
-> Element
-> [(String, SrcLoc)]
-> m ()
addElementMenu doc clickListener parentMenu e cs = do
tagName <- map toLower <$> getTagName e
parentLi <- createElement doc ("li" :: JSString)
appendChild_ parentMenu parentLi
createTextNode doc tagName >>= appendChild_ parentLi
ul <- createElement doc ("ul" :: JSString)
appendChild_ parentLi ul
forM_ (reverse cs) $ \(f, loc) -> do
li <- createElement doc ("li" :: JSString)
appendChild_ ul li
a <- uncheckedCastTo HTMLAnchorElement <$> createElement doc ("a" :: JSString)
appendChild_ li a
createTextNode doc (f <> " " <> srcLocFile loc <> ":" <> show (srcLocStartLine loc))
>>= appendChild_ a
forM_ (getSourceLink loc) $ \link -> do
setAttribute a ("href" :: JSString) link
setAttribute a ("target" :: JSString) ("_blank" :: JSString)
setAttribute a ("hs-srcloc" :: JSString) $ prettySrcLoc loc
liftJSM $ addListener a click clickListener False
prettySrcLoc :: SrcLoc -> String
prettySrcLoc SrcLoc {..} = mconcat
[ srcLocFile , ":("
, show srcLocStartLine, ","
, show srcLocStartCol , ")-("
, show srcLocEndLine , ","
, show srcLocEndCol , ") in "
, srcLocPackage, ":", srcLocModule
]
|
ed49113dbbbf403a83e535c95acfb5f98896b3235fe91fca9b033c1c6a0e51c4 | Zilliqa/scilla | StateIPCIdl.ml |
This file is part of scilla .
Copyright ( c ) 2018 - present Zilliqa Research Pvt . Ltd.
scilla 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 .
scilla 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
scilla . If not , see < / > .
This file is part of scilla.
Copyright (c) 2018 - present Zilliqa Research Pvt. Ltd.
scilla 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.
scilla 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
scilla. If not, see </>.
*)
open Idl
open IPCUtil
module IPCIdl (R : RPC) = struct
open R
let description =
Interface.
{
name = "IPCIdl";
namespace = None;
description =
[
"This is a functor used to generate Clients and Servers that \
follow the json rpc protocol";
];
version = (1, 0, 0);
}
let implementation = implement description
let query = Param.mk ~name:"query" Rpc.Types.string
let value = Param.mk ~name:"value" Rpc.Types.string
let scilla_type = Param.mk ~name:"scilla_type" Rpc.Types.string
let addr = Param.mk ~name:"addr" Rpc.Types.string
let query_name = Param.mk ~name:"query_name" Rpc.Types.string
let query_args = Param.mk ~name:"query_args" Rpc.Types.string
The return value for ` fetchStateValue ` will be a pair ( found : bool , value : string )
* " value " is valid only if " found & & ! query.ignoreval "
* "value" is valid only if "found && !query.ignoreval" *)
(* TODO: [@warning "-32"] doesn't seem to work for "unused" types. *)
type _fetch_ret_t = bool * string [@@deriving rpcty]
The return value for ` fetchExternalStateValue will be a triple
* ( found : bool , value : string , type : string ) . " value " is valid only
* if " found & & ! query.ignoreval "
* (found : bool, value : string, type : string). "value" is valid only
* if "found && !query.ignoreval" *)
type _fetch_ext_ret_t = bool * string * string [@@deriving rpcty]
(* defines `typ_of__fetch_ret_t` *)
let return_fetch =
Param.mk
{ name = ""; description = [ "(found,value)" ]; ty = typ_of__fetch_ret_t }
let return_ext_fetch =
Param.mk
{
name = "";
description = [ "(found,value,type)" ];
ty = typ_of__fetch_ext_ret_t;
}
let return_update = Param.mk Rpc.Types.unit
let fetch_state_value =
declare "fetchStateValue"
[ "Fetch state value from blockchain" ]
(query @-> returning return_fetch RPCError.err)
let fetch_ext_state_value =
declare "fetchExternalStateValue"
[ "Fetch state value of another contract from the blockchain" ]
(addr @-> query @-> returning return_ext_fetch RPCError.err)
let fetch_bcinfo =
declare "fetchBlockchainInfo"
[ "Fetch various information about the current blockchain state" ]
(query_name @-> query_args @-> returning return_fetch RPCError.err)
let set_bcinfo =
declare "setBlockchainInfo" [ "Set blockchain info" ]
(query_name @-> query_args @-> value
@-> returning return_update RPCError.err)
(* This is a utility to test the testsuite server with JSON data.
* It isn't part of the Zilliqa<->Scilla IPC protocol. *)
let set_ext_state_value =
declare "setExternalStateValue"
[
"Set state value and field type of another contract from the blockchain";
]
(addr @-> query @-> value @-> scilla_type
@-> returning return_update RPCError.err)
let update_state_value =
declare "updateStateValue"
[ "Update state value in blockchain" ]
(query @-> value @-> returning return_update RPCError.err)
end
| null | https://raw.githubusercontent.com/Zilliqa/scilla/011323ac5da48ee16890b71424e057ffbc4216da/src/eval/StateIPCIdl.ml | ocaml | TODO: [@warning "-32"] doesn't seem to work for "unused" types.
defines `typ_of__fetch_ret_t`
This is a utility to test the testsuite server with JSON data.
* It isn't part of the Zilliqa<->Scilla IPC protocol. |
This file is part of scilla .
Copyright ( c ) 2018 - present Zilliqa Research Pvt . Ltd.
scilla 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 .
scilla 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
scilla . If not , see < / > .
This file is part of scilla.
Copyright (c) 2018 - present Zilliqa Research Pvt. Ltd.
scilla 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.
scilla 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
scilla. If not, see </>.
*)
open Idl
open IPCUtil
module IPCIdl (R : RPC) = struct
open R
let description =
Interface.
{
name = "IPCIdl";
namespace = None;
description =
[
"This is a functor used to generate Clients and Servers that \
follow the json rpc protocol";
];
version = (1, 0, 0);
}
let implementation = implement description
let query = Param.mk ~name:"query" Rpc.Types.string
let value = Param.mk ~name:"value" Rpc.Types.string
let scilla_type = Param.mk ~name:"scilla_type" Rpc.Types.string
let addr = Param.mk ~name:"addr" Rpc.Types.string
let query_name = Param.mk ~name:"query_name" Rpc.Types.string
let query_args = Param.mk ~name:"query_args" Rpc.Types.string
The return value for ` fetchStateValue ` will be a pair ( found : bool , value : string )
* " value " is valid only if " found & & ! query.ignoreval "
* "value" is valid only if "found && !query.ignoreval" *)
type _fetch_ret_t = bool * string [@@deriving rpcty]
The return value for ` fetchExternalStateValue will be a triple
* ( found : bool , value : string , type : string ) . " value " is valid only
* if " found & & ! query.ignoreval "
* (found : bool, value : string, type : string). "value" is valid only
* if "found && !query.ignoreval" *)
type _fetch_ext_ret_t = bool * string * string [@@deriving rpcty]
let return_fetch =
Param.mk
{ name = ""; description = [ "(found,value)" ]; ty = typ_of__fetch_ret_t }
let return_ext_fetch =
Param.mk
{
name = "";
description = [ "(found,value,type)" ];
ty = typ_of__fetch_ext_ret_t;
}
let return_update = Param.mk Rpc.Types.unit
let fetch_state_value =
declare "fetchStateValue"
[ "Fetch state value from blockchain" ]
(query @-> returning return_fetch RPCError.err)
let fetch_ext_state_value =
declare "fetchExternalStateValue"
[ "Fetch state value of another contract from the blockchain" ]
(addr @-> query @-> returning return_ext_fetch RPCError.err)
let fetch_bcinfo =
declare "fetchBlockchainInfo"
[ "Fetch various information about the current blockchain state" ]
(query_name @-> query_args @-> returning return_fetch RPCError.err)
let set_bcinfo =
declare "setBlockchainInfo" [ "Set blockchain info" ]
(query_name @-> query_args @-> value
@-> returning return_update RPCError.err)
let set_ext_state_value =
declare "setExternalStateValue"
[
"Set state value and field type of another contract from the blockchain";
]
(addr @-> query @-> value @-> scilla_type
@-> returning return_update RPCError.err)
let update_state_value =
declare "updateStateValue"
[ "Update state value in blockchain" ]
(query @-> value @-> returning return_update RPCError.err)
end
|
cf421e374c07adfcf68c3d0064062d99ca9a40057de6910206c59cbd3ff8564d | rizo/snowflake-os | translcore.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 .
(* *)
(***********************************************************************)
$ Id$
(* Translation from typed abstract syntax to lambda terms,
for the core language *)
open Asttypes
open Types
open Typedtree
open Lambda
val name_pattern: string -> (pattern * 'a) list -> Ident.t
val transl_exp: expression -> lambda
val transl_apply: lambda -> (expression option * optional) list
-> Location.t -> lambda
val transl_let:
rec_flag -> (pattern * expression) list -> lambda -> lambda
val transl_primitive: Primitive.description -> lambda
val transl_exception:
Ident.t -> Path.t option -> exception_declaration -> lambda
val check_recursive_lambda: Ident.t list -> lambda -> bool
type error =
Illegal_letrec_pat
| Illegal_letrec_expr
| Free_super_var
exception Error of Location.t * error
open Format
val report_error: formatter -> error -> unit
Forward declaration -- to be filled in by Translmod.transl_module
val transl_module :
(module_coercion -> Path.t option -> module_expr -> lambda) ref
val transl_object :
(Ident.t -> string list -> class_expr -> lambda) ref
| null | https://raw.githubusercontent.com/rizo/snowflake-os/51df43d9ba715532d325e8880d3b8b2c589cd075/plugins/ocamlopt.opt/bytecomp/translcore.mli | ocaml | *********************************************************************
Objective Caml
*********************************************************************
Translation from typed abstract syntax to lambda terms,
for the core language | , 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 .
$ Id$
open Asttypes
open Types
open Typedtree
open Lambda
val name_pattern: string -> (pattern * 'a) list -> Ident.t
val transl_exp: expression -> lambda
val transl_apply: lambda -> (expression option * optional) list
-> Location.t -> lambda
val transl_let:
rec_flag -> (pattern * expression) list -> lambda -> lambda
val transl_primitive: Primitive.description -> lambda
val transl_exception:
Ident.t -> Path.t option -> exception_declaration -> lambda
val check_recursive_lambda: Ident.t list -> lambda -> bool
type error =
Illegal_letrec_pat
| Illegal_letrec_expr
| Free_super_var
exception Error of Location.t * error
open Format
val report_error: formatter -> error -> unit
Forward declaration -- to be filled in by Translmod.transl_module
val transl_module :
(module_coercion -> Path.t option -> module_expr -> lambda) ref
val transl_object :
(Ident.t -> string list -> class_expr -> lambda) ref
|
2272c0ae5a6340d82414bf8e7f20381bd03dc948ddf803196aea47e38657c5bc | andersfugmann/ppx_protocol_conv | unittest.ml | module Driver = struct
let name = "yaml"
let serialize t = Yaml.to_string_exn t
let deserialize t = Yaml.of_string_exn t
include Protocol_conv_yaml.Yaml
let of_driver_exn = of_yaml_exn
let of_driver = of_yaml
let to_driver = to_yaml
let sexp_of_t : t -> Sexplib.Sexp.t = fun t ->
Sexplib.Std.sexp_of_string (to_string_hum t)
end
module Unittest = Test.Unittest.Make (Driver)
let () = Unittest.run ()
| null | https://raw.githubusercontent.com/andersfugmann/ppx_protocol_conv/e93eb01ca8ba8c7dd734070316cd281a199dee0d/drivers/yaml/test/unittest.ml | ocaml | module Driver = struct
let name = "yaml"
let serialize t = Yaml.to_string_exn t
let deserialize t = Yaml.of_string_exn t
include Protocol_conv_yaml.Yaml
let of_driver_exn = of_yaml_exn
let of_driver = of_yaml
let to_driver = to_yaml
let sexp_of_t : t -> Sexplib.Sexp.t = fun t ->
Sexplib.Std.sexp_of_string (to_string_hum t)
end
module Unittest = Test.Unittest.Make (Driver)
let () = Unittest.run ()
| |
bc4dbcf01d5c192ae500a69f7d75b9b18909f615433287cf76b8da0b9afe7559 | arbor/antiope | Messages.hs | # LANGUAGE DeriveGeneric #
module Antiope.SNS.Messages
( SnsMessage (..)
) where
import Data.Aeson as Aeson
import Data.Text (Text)
import Data.Time.Clock (UTCTime)
import GHC.Generics (Generic)
import qualified Data.Aeson.Types as Aeson
import qualified Data.ByteString.Lazy as LBS
import qualified Data.Text.Encoding as Text
data SnsMessage a = SnsMessage
{ type' :: !(Maybe Text)
, messageId :: !(Maybe Text)
, topicArn :: !(Maybe Text)
, subject :: !(Maybe Text)
, timestamp :: !(Maybe UTCTime)
, message :: !a
} deriving (Show, Eq, Generic)
instance FromJSON a => FromJSON (SnsMessage a) where
parseJSON = withObject "SnsMessage" $ \obj -> SnsMessage
<$> obj .:? "Type"
<*> obj .:? "MessageId"
<*> obj .:? "TopicArn"
<*> obj .:? "Subject"
<*> obj .:? "Timestamp"
<*> decodeEscaped obj "Message"
instance ToJSON a => ToJSON (SnsMessage a) where
toJSON msg = object
[ "Type" .= type' msg
, "MessageId" .= messageId msg
, "TopicArn" .= topicArn msg
, "Subject" .= subject msg
, "Timestamp" .= timestamp msg
, "Message" .= (Text.decodeUtf8 . LBS.toStrict . encode . message) msg
]
decodeEscaped :: FromJSON b => Object -> Text -> Aeson.Parser b
decodeEscaped o t =
(o .: t) >>= (either fail pure . eitherDecodeStrict . Text.encodeUtf8)
| null | https://raw.githubusercontent.com/arbor/antiope/86ad3df07b8d3fd5d2c8bef4111a73b85850e1ba/antiope-sns/src/Antiope/SNS/Messages.hs | haskell | # LANGUAGE DeriveGeneric #
module Antiope.SNS.Messages
( SnsMessage (..)
) where
import Data.Aeson as Aeson
import Data.Text (Text)
import Data.Time.Clock (UTCTime)
import GHC.Generics (Generic)
import qualified Data.Aeson.Types as Aeson
import qualified Data.ByteString.Lazy as LBS
import qualified Data.Text.Encoding as Text
data SnsMessage a = SnsMessage
{ type' :: !(Maybe Text)
, messageId :: !(Maybe Text)
, topicArn :: !(Maybe Text)
, subject :: !(Maybe Text)
, timestamp :: !(Maybe UTCTime)
, message :: !a
} deriving (Show, Eq, Generic)
instance FromJSON a => FromJSON (SnsMessage a) where
parseJSON = withObject "SnsMessage" $ \obj -> SnsMessage
<$> obj .:? "Type"
<*> obj .:? "MessageId"
<*> obj .:? "TopicArn"
<*> obj .:? "Subject"
<*> obj .:? "Timestamp"
<*> decodeEscaped obj "Message"
instance ToJSON a => ToJSON (SnsMessage a) where
toJSON msg = object
[ "Type" .= type' msg
, "MessageId" .= messageId msg
, "TopicArn" .= topicArn msg
, "Subject" .= subject msg
, "Timestamp" .= timestamp msg
, "Message" .= (Text.decodeUtf8 . LBS.toStrict . encode . message) msg
]
decodeEscaped :: FromJSON b => Object -> Text -> Aeson.Parser b
decodeEscaped o t =
(o .: t) >>= (either fail pure . eitherDecodeStrict . Text.encodeUtf8)
| |
c9967cf93726b553ddc81b6317186d5b47e7bdaaf5270375c600783e8aef9a7e | gsdlab/clafer | GetURL.hs | ( c ) 2011 , see the file LICENSE for copying terms .
-- Simple wrapper around HTTP, allowing proxy use
module GetURL (getURL) where
import Network.HTTP
import Network.Browser
import Network.URI
getURL :: String -> IO String
getURL url = do
Network.Browser.browse $ do
setCheckForProxy True
setDebugLog Nothing
setOutHandler (const (return ()))
(_, rsp) <- request (getRequest' (escapeURIString isUnescapedInURI url))
return (rspBody rsp)
where
getRequest' :: String -> Request String
getRequest' urlString =
case parseURI urlString of
Nothing -> error ("getRequest: Not a valid URL - " ++ urlString)
Just u -> mkRequest GET u
| null | https://raw.githubusercontent.com/gsdlab/clafer/a30a645ae1e4fc793851e53446d220924038873a/src/GetURL.hs | haskell | Simple wrapper around HTTP, allowing proxy use | ( c ) 2011 , see the file LICENSE for copying terms .
module GetURL (getURL) where
import Network.HTTP
import Network.Browser
import Network.URI
getURL :: String -> IO String
getURL url = do
Network.Browser.browse $ do
setCheckForProxy True
setDebugLog Nothing
setOutHandler (const (return ()))
(_, rsp) <- request (getRequest' (escapeURIString isUnescapedInURI url))
return (rspBody rsp)
where
getRequest' :: String -> Request String
getRequest' urlString =
case parseURI urlString of
Nothing -> error ("getRequest: Not a valid URL - " ++ urlString)
Just u -> mkRequest GET u
|
1169783e1fc8cde13e8db063b09913d8ba964697a3ca894f6d0d519a6d7e2815 | argp/bap | test_num.ml | open OUnit
open BatNum
let tests = "Num" >::: [
"of_float" >::: [
"zero" >:: begin function () ->
assert_equal ~cmp:(=) ~printer:to_string zero (of_float 0.)
end;
"numbers" >:: begin function () ->
Array.iter begin function f ->
assert_equal ~printer:BatFloat.to_string f
(to_float (of_float f))
end
[|2.5; 1.0; 0.5; -0.5; -1.0; -2.5|]
end;
"infinity/nan" >:::
set / reset pair for ( re)setting the error_when_null_denominator state .
* A stack is used instead of simple ref to make calls nestable .
* A stack is used instead of simple ref to make calls nestable. *)
let (set, reset) =
let saved_state = Stack.create () in
begin fun state () ->
Stack.push
(Arith_status.get_error_when_null_denominator ())
saved_state;
Arith_status.set_error_when_null_denominator state;
end,
begin fun () ->
Arith_status.set_error_when_null_denominator
(Stack.pop saved_state)
end
in
let test () =
Array.iter
(* f is float, n/d are expected nominator and denominator *)
begin fun (f, (n,d)) ->
if Arith_status.get_error_when_null_denominator ()
then
(* expect error *)
assert_raises
(Failure "create_ratio infinite or undefined rational number")
(fun () -> ignore (of_float f))
else
(* expect result *)
assert_equal ~cmp:equal ~printer:to_string
(div n d)
(of_float f)
end
(* values to test *)
[| infinity, (one,zero); neg_infinity, (neg one,zero); nan, (zero,zero) |]
in
[
(* allow null denominator *)
"allow_null_denom" >:: bracket (set false) test reset;
(* disallow null denominator *)
"forbid_null_denom" >:: bracket (set true) test reset;
]
]
]
| null | https://raw.githubusercontent.com/argp/bap/2f60a35e822200a1ec50eea3a947a322b45da363/batteries/testsuite/test_num.ml | ocaml | f is float, n/d are expected nominator and denominator
expect error
expect result
values to test
allow null denominator
disallow null denominator | open OUnit
open BatNum
let tests = "Num" >::: [
"of_float" >::: [
"zero" >:: begin function () ->
assert_equal ~cmp:(=) ~printer:to_string zero (of_float 0.)
end;
"numbers" >:: begin function () ->
Array.iter begin function f ->
assert_equal ~printer:BatFloat.to_string f
(to_float (of_float f))
end
[|2.5; 1.0; 0.5; -0.5; -1.0; -2.5|]
end;
"infinity/nan" >:::
set / reset pair for ( re)setting the error_when_null_denominator state .
* A stack is used instead of simple ref to make calls nestable .
* A stack is used instead of simple ref to make calls nestable. *)
let (set, reset) =
let saved_state = Stack.create () in
begin fun state () ->
Stack.push
(Arith_status.get_error_when_null_denominator ())
saved_state;
Arith_status.set_error_when_null_denominator state;
end,
begin fun () ->
Arith_status.set_error_when_null_denominator
(Stack.pop saved_state)
end
in
let test () =
Array.iter
begin fun (f, (n,d)) ->
if Arith_status.get_error_when_null_denominator ()
then
assert_raises
(Failure "create_ratio infinite or undefined rational number")
(fun () -> ignore (of_float f))
else
assert_equal ~cmp:equal ~printer:to_string
(div n d)
(of_float f)
end
[| infinity, (one,zero); neg_infinity, (neg one,zero); nan, (zero,zero) |]
in
[
"allow_null_denom" >:: bracket (set false) test reset;
"forbid_null_denom" >:: bracket (set true) test reset;
]
]
]
|
aece476c5e63b32ca5bfbe1170cd8eaa9e3a7c24bab158985999d2af984c0f73 | clash-lang/clash-compiler | Tags.hs | -----------------------------------------------------------------------------
--
GHCi 's : ctags and : commands
--
( c ) The GHC Team 2005 - 2007
--
-----------------------------------------------------------------------------
# OPTIONS_GHC -fno - warn - name - shadowing #
module Clash.GHCi.UI.Tags (
createCTagsWithLineNumbersCmd,
createCTagsWithRegExesCmd,
createETagsFileCmd
) where
import Exception
import GHC
import Clash.GHCi.UI.Monad
import Outputable
ToDo : figure out whether we need these , and put something appropriate
into the GHC API instead
import Name (nameOccName)
import OccName (pprOccName)
import ConLike
import MonadUtils
import Control.Monad
import Data.Function
import Data.List
import Data.Maybe
import Data.Ord
import DriverPhases
import Panic
import Prelude
import System.Directory
import System.IO
import System.IO.Error
-----------------------------------------------------------------------------
-- create tags file for currently loaded modules.
createCTagsWithLineNumbersCmd, createCTagsWithRegExesCmd,
createETagsFileCmd :: String -> GHCi ()
createCTagsWithLineNumbersCmd "" =
ghciCreateTagsFile CTagsWithLineNumbers "tags"
createCTagsWithLineNumbersCmd file =
ghciCreateTagsFile CTagsWithLineNumbers file
createCTagsWithRegExesCmd "" =
ghciCreateTagsFile CTagsWithRegExes "tags"
createCTagsWithRegExesCmd file =
ghciCreateTagsFile CTagsWithRegExes file
createETagsFileCmd "" = ghciCreateTagsFile ETags "TAGS"
createETagsFileCmd file = ghciCreateTagsFile ETags file
data TagsKind = ETags | CTagsWithLineNumbers | CTagsWithRegExes
ghciCreateTagsFile :: TagsKind -> FilePath -> GHCi ()
ghciCreateTagsFile kind file = do
createTagsFile kind file
ToDo :
-- - remove restriction that all modules must be interpreted
-- (problem: we don't know source locations for entities unless
-- we compiled the module.
--
-- - extract createTagsFile so it can be used from the command-line
( probably need to fix first problem before this is useful ) .
--
createTagsFile :: TagsKind -> FilePath -> GHCi ()
createTagsFile tagskind tagsFile = do
graph <- GHC.getModuleGraph
mtags <- mapM listModuleTags (map GHC.ms_mod $ GHC.mgModSummaries graph)
either_res <- liftIO $ collateAndWriteTags tagskind tagsFile $ concat mtags
case either_res of
Left e -> liftIO $ hPutStrLn stderr $ ioeGetErrorString e
Right _ -> return ()
listModuleTags :: GHC.Module -> GHCi [TagInfo]
listModuleTags m = do
is_interpreted <- GHC.moduleIsInterpreted m
-- should we just skip these?
when (not is_interpreted) $
let mName = GHC.moduleNameString (GHC.moduleName m) in
throwGhcException (CmdLineError ("module '" ++ mName ++ "' is not interpreted"))
mbModInfo <- GHC.getModuleInfo m
case mbModInfo of
Nothing -> return []
Just mInfo -> do
dflags <- getDynFlags
mb_print_unqual <- GHC.mkPrintUnqualifiedForModule mInfo
let unqual = fromMaybe GHC.alwaysQualify mb_print_unqual
let names = fromMaybe [] $GHC.modInfoTopLevelScope mInfo
let localNames = filter ((m==) . nameModule) names
mbTyThings <- mapM GHC.lookupName localNames
return $! [ tagInfo dflags unqual exported kind name realLoc
| tyThing <- catMaybes mbTyThings
, let name = getName tyThing
, let exported = GHC.modInfoIsExportedName mInfo name
, let kind = tyThing2TagKind tyThing
, let loc = srcSpanStart (nameSrcSpan name)
, RealSrcLoc realLoc <- [loc]
]
where
tyThing2TagKind (AnId _) = 'v'
tyThing2TagKind (AConLike RealDataCon{}) = 'd'
tyThing2TagKind (AConLike PatSynCon{}) = 'p'
tyThing2TagKind (ATyCon _) = 't'
tyThing2TagKind (ACoAxiom _) = 'x'
data TagInfo = TagInfo
{ tagExported :: Bool -- is tag exported
, tagKind :: Char -- tag kind
, tagName :: String -- tag name
, tagFile :: String -- file name
, tagLine :: Int -- line number
, tagCol :: Int -- column number
, tagSrcInfo :: Maybe (String,Integer) -- source code line and char offset
}
get tag info , for later translation into Vim or Emacs style
tagInfo :: DynFlags -> PrintUnqualified -> Bool -> Char -> Name -> RealSrcLoc
-> TagInfo
tagInfo dflags unqual exported kind name loc
= TagInfo exported kind
(showSDocForUser dflags unqual $ pprOccName (nameOccName name))
(showSDocForUser dflags unqual $ ftext (srcLocFile loc))
(srcLocLine loc) (srcLocCol loc) Nothing
throw an exception when someone tries to overwrite existing source file ( fix for # 10989 )
writeTagsSafely :: FilePath -> String -> IO ()
writeTagsSafely file str = do
dfe <- doesFileExist file
if dfe && isSourceFilename file
then throwGhcException (CmdLineError (file ++ " is existing source file. " ++
"Please specify another file name to store tags data"))
else writeFile file str
collateAndWriteTags :: TagsKind -> FilePath -> [TagInfo] -> IO (Either IOError ())
ctags style with the Ex expression being just the line number ,
collateAndWriteTags CTagsWithLineNumbers file tagInfos = do
let tags = unlines $ sort $ map showCTag tagInfos
tryIO (writeTagsSafely file tags)
ctags style with the Ex expression being a regex searching the line ,
ctags style , Vim et al
tagInfoGroups <- makeTagGroupsWithSrcInfo tagInfos
let tags = unlines $ sort $ map showCTag $concat tagInfoGroups
tryIO (writeTagsSafely file tags)
etags style , Emacs / XEmacs
tagInfoGroups <- makeTagGroupsWithSrcInfo $filter tagExported tagInfos
let tagGroups = map processGroup tagInfoGroups
tryIO (writeTagsSafely file $ concat tagGroups)
where
processGroup [] = throwGhcException (CmdLineError "empty tag file group??")
processGroup group@(tagInfo:_) =
let tags = unlines $ map showETag group in
"\x0c\n" ++ tagFile tagInfo ++ "," ++ show (length tags) ++ "\n" ++ tags
makeTagGroupsWithSrcInfo :: [TagInfo] -> IO [[TagInfo]]
makeTagGroupsWithSrcInfo tagInfos = do
let groups = groupBy ((==) `on` tagFile) $ sortBy (comparing tagFile) tagInfos
mapM addTagSrcInfo groups
where
addTagSrcInfo [] = throwGhcException (CmdLineError "empty tag file group??")
addTagSrcInfo group@(tagInfo:_) = do
file <- readFile $tagFile tagInfo
let sortedGroup = sortBy (comparing tagLine) group
return $ perFile sortedGroup 1 0 $ lines file
perFile allTags@(tag:tags) cnt pos allLs@(l:ls)
| tagLine tag > cnt =
perFile allTags (cnt+1) (pos+fromIntegral(length l)) ls
| tagLine tag == cnt =
tag{ tagSrcInfo = Just(l,pos) } : perFile tags cnt pos allLs
perFile _ _ _ _ = []
ctags format , for Vim et al
showCTag :: TagInfo -> String
showCTag ti =
tagName ti ++ "\t" ++ tagFile ti ++ "\t" ++ tagCmd ++ ";\"\t" ++
tagKind ti : ( if tagExported ti then "" else "\tfile:" )
where
tagCmd =
case tagSrcInfo ti of
Nothing -> show $tagLine ti
Just (srcLine,_) -> "/^"++ foldr escapeSlashes [] srcLine ++"$/"
where
escapeSlashes '/' r = '\\' : '/' : r
escapeSlashes '\\' r = '\\' : '\\' : r
escapeSlashes c r = c : r
etags format , for Emacs / XEmacs
showETag :: TagInfo -> String
showETag TagInfo{ tagName = tag, tagLine = lineNo, tagCol = colNo,
tagSrcInfo = Just (srcLine,charPos) }
= take (colNo - 1) srcLine ++ tag
++ "\x7f" ++ tag
++ "\x01" ++ show lineNo
++ "," ++ show charPos
showETag _ = throwGhcException (CmdLineError "missing source file info in showETag")
| null | https://raw.githubusercontent.com/clash-lang/clash-compiler/8e461a910f2f37c900705a0847a9b533bce4d2ea/clash-ghc/src-bin-881/Clash/GHCi/UI/Tags.hs | haskell | ---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
create tags file for currently loaded modules.
- remove restriction that all modules must be interpreted
(problem: we don't know source locations for entities unless
we compiled the module.
- extract createTagsFile so it can be used from the command-line
should we just skip these?
is tag exported
tag kind
tag name
file name
line number
column number
source code line and char offset | GHCi 's : ctags and : commands
( c ) The GHC Team 2005 - 2007
# OPTIONS_GHC -fno - warn - name - shadowing #
module Clash.GHCi.UI.Tags (
createCTagsWithLineNumbersCmd,
createCTagsWithRegExesCmd,
createETagsFileCmd
) where
import Exception
import GHC
import Clash.GHCi.UI.Monad
import Outputable
ToDo : figure out whether we need these , and put something appropriate
into the GHC API instead
import Name (nameOccName)
import OccName (pprOccName)
import ConLike
import MonadUtils
import Control.Monad
import Data.Function
import Data.List
import Data.Maybe
import Data.Ord
import DriverPhases
import Panic
import Prelude
import System.Directory
import System.IO
import System.IO.Error
createCTagsWithLineNumbersCmd, createCTagsWithRegExesCmd,
createETagsFileCmd :: String -> GHCi ()
createCTagsWithLineNumbersCmd "" =
ghciCreateTagsFile CTagsWithLineNumbers "tags"
createCTagsWithLineNumbersCmd file =
ghciCreateTagsFile CTagsWithLineNumbers file
createCTagsWithRegExesCmd "" =
ghciCreateTagsFile CTagsWithRegExes "tags"
createCTagsWithRegExesCmd file =
ghciCreateTagsFile CTagsWithRegExes file
createETagsFileCmd "" = ghciCreateTagsFile ETags "TAGS"
createETagsFileCmd file = ghciCreateTagsFile ETags file
data TagsKind = ETags | CTagsWithLineNumbers | CTagsWithRegExes
ghciCreateTagsFile :: TagsKind -> FilePath -> GHCi ()
ghciCreateTagsFile kind file = do
createTagsFile kind file
ToDo :
( probably need to fix first problem before this is useful ) .
createTagsFile :: TagsKind -> FilePath -> GHCi ()
createTagsFile tagskind tagsFile = do
graph <- GHC.getModuleGraph
mtags <- mapM listModuleTags (map GHC.ms_mod $ GHC.mgModSummaries graph)
either_res <- liftIO $ collateAndWriteTags tagskind tagsFile $ concat mtags
case either_res of
Left e -> liftIO $ hPutStrLn stderr $ ioeGetErrorString e
Right _ -> return ()
listModuleTags :: GHC.Module -> GHCi [TagInfo]
listModuleTags m = do
is_interpreted <- GHC.moduleIsInterpreted m
when (not is_interpreted) $
let mName = GHC.moduleNameString (GHC.moduleName m) in
throwGhcException (CmdLineError ("module '" ++ mName ++ "' is not interpreted"))
mbModInfo <- GHC.getModuleInfo m
case mbModInfo of
Nothing -> return []
Just mInfo -> do
dflags <- getDynFlags
mb_print_unqual <- GHC.mkPrintUnqualifiedForModule mInfo
let unqual = fromMaybe GHC.alwaysQualify mb_print_unqual
let names = fromMaybe [] $GHC.modInfoTopLevelScope mInfo
let localNames = filter ((m==) . nameModule) names
mbTyThings <- mapM GHC.lookupName localNames
return $! [ tagInfo dflags unqual exported kind name realLoc
| tyThing <- catMaybes mbTyThings
, let name = getName tyThing
, let exported = GHC.modInfoIsExportedName mInfo name
, let kind = tyThing2TagKind tyThing
, let loc = srcSpanStart (nameSrcSpan name)
, RealSrcLoc realLoc <- [loc]
]
where
tyThing2TagKind (AnId _) = 'v'
tyThing2TagKind (AConLike RealDataCon{}) = 'd'
tyThing2TagKind (AConLike PatSynCon{}) = 'p'
tyThing2TagKind (ATyCon _) = 't'
tyThing2TagKind (ACoAxiom _) = 'x'
data TagInfo = TagInfo
}
get tag info , for later translation into Vim or Emacs style
tagInfo :: DynFlags -> PrintUnqualified -> Bool -> Char -> Name -> RealSrcLoc
-> TagInfo
tagInfo dflags unqual exported kind name loc
= TagInfo exported kind
(showSDocForUser dflags unqual $ pprOccName (nameOccName name))
(showSDocForUser dflags unqual $ ftext (srcLocFile loc))
(srcLocLine loc) (srcLocCol loc) Nothing
throw an exception when someone tries to overwrite existing source file ( fix for # 10989 )
writeTagsSafely :: FilePath -> String -> IO ()
writeTagsSafely file str = do
dfe <- doesFileExist file
if dfe && isSourceFilename file
then throwGhcException (CmdLineError (file ++ " is existing source file. " ++
"Please specify another file name to store tags data"))
else writeFile file str
collateAndWriteTags :: TagsKind -> FilePath -> [TagInfo] -> IO (Either IOError ())
ctags style with the Ex expression being just the line number ,
collateAndWriteTags CTagsWithLineNumbers file tagInfos = do
let tags = unlines $ sort $ map showCTag tagInfos
tryIO (writeTagsSafely file tags)
ctags style with the Ex expression being a regex searching the line ,
ctags style , Vim et al
tagInfoGroups <- makeTagGroupsWithSrcInfo tagInfos
let tags = unlines $ sort $ map showCTag $concat tagInfoGroups
tryIO (writeTagsSafely file tags)
etags style , Emacs / XEmacs
tagInfoGroups <- makeTagGroupsWithSrcInfo $filter tagExported tagInfos
let tagGroups = map processGroup tagInfoGroups
tryIO (writeTagsSafely file $ concat tagGroups)
where
processGroup [] = throwGhcException (CmdLineError "empty tag file group??")
processGroup group@(tagInfo:_) =
let tags = unlines $ map showETag group in
"\x0c\n" ++ tagFile tagInfo ++ "," ++ show (length tags) ++ "\n" ++ tags
makeTagGroupsWithSrcInfo :: [TagInfo] -> IO [[TagInfo]]
makeTagGroupsWithSrcInfo tagInfos = do
let groups = groupBy ((==) `on` tagFile) $ sortBy (comparing tagFile) tagInfos
mapM addTagSrcInfo groups
where
addTagSrcInfo [] = throwGhcException (CmdLineError "empty tag file group??")
addTagSrcInfo group@(tagInfo:_) = do
file <- readFile $tagFile tagInfo
let sortedGroup = sortBy (comparing tagLine) group
return $ perFile sortedGroup 1 0 $ lines file
perFile allTags@(tag:tags) cnt pos allLs@(l:ls)
| tagLine tag > cnt =
perFile allTags (cnt+1) (pos+fromIntegral(length l)) ls
| tagLine tag == cnt =
tag{ tagSrcInfo = Just(l,pos) } : perFile tags cnt pos allLs
perFile _ _ _ _ = []
ctags format , for Vim et al
showCTag :: TagInfo -> String
showCTag ti =
tagName ti ++ "\t" ++ tagFile ti ++ "\t" ++ tagCmd ++ ";\"\t" ++
tagKind ti : ( if tagExported ti then "" else "\tfile:" )
where
tagCmd =
case tagSrcInfo ti of
Nothing -> show $tagLine ti
Just (srcLine,_) -> "/^"++ foldr escapeSlashes [] srcLine ++"$/"
where
escapeSlashes '/' r = '\\' : '/' : r
escapeSlashes '\\' r = '\\' : '\\' : r
escapeSlashes c r = c : r
etags format , for Emacs / XEmacs
showETag :: TagInfo -> String
showETag TagInfo{ tagName = tag, tagLine = lineNo, tagCol = colNo,
tagSrcInfo = Just (srcLine,charPos) }
= take (colNo - 1) srcLine ++ tag
++ "\x7f" ++ tag
++ "\x01" ++ show lineNo
++ "," ++ show charPos
showETag _ = throwGhcException (CmdLineError "missing source file info in showETag")
|
37affc30c40998ca9b52d2bfe8049cabaa1db74560dffa469a75772a66acdff3 | alexandergunnarson/quantum | nondeterministic.cljc | (ns quantum.untyped.core.nondeterministic
(:require
[clojure.core :as core]
[quantum.untyped.core.error
:refer [TODO]])
#?(:clj
(:import
java.security.SecureRandom)))
#?(:clj (defonce ^SecureRandom secure-random-generator
(SecureRandom/getInstance "SHA1PRNG")))
(defn #?(:clj ^java.util.Random get-generator :cljs get-generator) [secure?]
#?(:clj (if secure?
secure-random-generator
(java.util.concurrent.ThreadLocalRandom/current))
:cljs (TODO)))
(defn double-between
"Yields a random double between a and b."
([ a b] (double-between false a b))
([secure? a b]
#?(:clj (let [generator (get-generator secure?)]
(+ a (* (.nextDouble generator) (- b a))))
:cljs (if secure?
(TODO "CLJS does not yet support secure random numbers")
(+ a (core/rand (inc (- b a))))))))
| null | https://raw.githubusercontent.com/alexandergunnarson/quantum/0c655af439734709566110949f9f2f482e468509/src-untyped/quantum/untyped/core/nondeterministic.cljc | clojure | (ns quantum.untyped.core.nondeterministic
(:require
[clojure.core :as core]
[quantum.untyped.core.error
:refer [TODO]])
#?(:clj
(:import
java.security.SecureRandom)))
#?(:clj (defonce ^SecureRandom secure-random-generator
(SecureRandom/getInstance "SHA1PRNG")))
(defn #?(:clj ^java.util.Random get-generator :cljs get-generator) [secure?]
#?(:clj (if secure?
secure-random-generator
(java.util.concurrent.ThreadLocalRandom/current))
:cljs (TODO)))
(defn double-between
"Yields a random double between a and b."
([ a b] (double-between false a b))
([secure? a b]
#?(:clj (let [generator (get-generator secure?)]
(+ a (* (.nextDouble generator) (- b a))))
:cljs (if secure?
(TODO "CLJS does not yet support secure random numbers")
(+ a (core/rand (inc (- b a))))))))
| |
f20079b8054db22c3e0b80ee011b5737d625125b772b3d5256f0af0e4ff0299f | ocaml-flambda/ocaml-jst | consistbl.ml | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 2002 Institut National de Recherche en Informatique et
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
Consistency tables : for checking consistency of module CRCs
open Misc
module Make (Module_name : sig
type t
module Set : Set.S with type elt = t
module Map : Map.S with type key = t
module Tbl : Hashtbl.S with type key = t
val compare : t -> t -> int
end) (Data : sig
type t
end) = struct
type t = (Data.t * Digest.t * filepath) Module_name.Tbl.t
let create () = Module_name.Tbl.create 13
let clear = Module_name.Tbl.clear
exception Inconsistency of {
unit_name : Module_name.t;
inconsistent_source : string;
original_source : string;
inconsistent_data : Data.t;
original_data : Data.t;
}
exception Not_available of Module_name.t
let check_ tbl name data crc source =
let (old_data, old_crc, old_source) = Module_name.Tbl.find tbl name in
if not (Digest.equal crc old_crc)
then raise(Inconsistency {
unit_name = name;
inconsistent_source = source;
original_source = old_source;
inconsistent_data = data;
original_data = old_data;
})
let check tbl name data crc source =
try check_ tbl name data crc source
with Not_found ->
Module_name.Tbl.add tbl name (data, crc, source)
let check_noadd tbl name data crc source =
try check_ tbl name data crc source
with Not_found ->
raise (Not_available name)
let set tbl name data crc source = Module_name.Tbl.add tbl name (data, crc, source)
let source tbl name = thd3 (Module_name.Tbl.find tbl name)
let find t name =
match Module_name.Tbl.find t name with
| exception Not_found -> None
| (data, crc, _) -> Some (data, crc)
let extract l tbl =
let l = List.sort_uniq Module_name.compare l in
List.fold_left (fun assc name -> (name, find tbl name) :: assc) [] l
let extract_map mod_names tbl =
Module_name.Set.fold
(fun name result -> Module_name.Map.add name (find tbl name) result)
mod_names
Module_name.Map.empty
let filter p tbl =
let to_remove = ref [] in
Module_name.Tbl.iter
(fun name _ ->
if not (p name) then to_remove := name :: !to_remove)
tbl;
List.iter
(fun name ->
while Module_name.Tbl.mem tbl name do
Module_name.Tbl.remove tbl name
done)
!to_remove
end
| null | https://raw.githubusercontent.com/ocaml-flambda/ocaml-jst/1bb6c797df7c63ddae1fc2e6f403a0ee9896cc8e/utils/consistbl.ml | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************ | , projet Cristal , INRIA Rocquencourt
Copyright 2002 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
Consistency tables : for checking consistency of module CRCs
open Misc
module Make (Module_name : sig
type t
module Set : Set.S with type elt = t
module Map : Map.S with type key = t
module Tbl : Hashtbl.S with type key = t
val compare : t -> t -> int
end) (Data : sig
type t
end) = struct
type t = (Data.t * Digest.t * filepath) Module_name.Tbl.t
let create () = Module_name.Tbl.create 13
let clear = Module_name.Tbl.clear
exception Inconsistency of {
unit_name : Module_name.t;
inconsistent_source : string;
original_source : string;
inconsistent_data : Data.t;
original_data : Data.t;
}
exception Not_available of Module_name.t
let check_ tbl name data crc source =
let (old_data, old_crc, old_source) = Module_name.Tbl.find tbl name in
if not (Digest.equal crc old_crc)
then raise(Inconsistency {
unit_name = name;
inconsistent_source = source;
original_source = old_source;
inconsistent_data = data;
original_data = old_data;
})
let check tbl name data crc source =
try check_ tbl name data crc source
with Not_found ->
Module_name.Tbl.add tbl name (data, crc, source)
let check_noadd tbl name data crc source =
try check_ tbl name data crc source
with Not_found ->
raise (Not_available name)
let set tbl name data crc source = Module_name.Tbl.add tbl name (data, crc, source)
let source tbl name = thd3 (Module_name.Tbl.find tbl name)
let find t name =
match Module_name.Tbl.find t name with
| exception Not_found -> None
| (data, crc, _) -> Some (data, crc)
let extract l tbl =
let l = List.sort_uniq Module_name.compare l in
List.fold_left (fun assc name -> (name, find tbl name) :: assc) [] l
let extract_map mod_names tbl =
Module_name.Set.fold
(fun name result -> Module_name.Map.add name (find tbl name) result)
mod_names
Module_name.Map.empty
let filter p tbl =
let to_remove = ref [] in
Module_name.Tbl.iter
(fun name _ ->
if not (p name) then to_remove := name :: !to_remove)
tbl;
List.iter
(fun name ->
while Module_name.Tbl.mem tbl name do
Module_name.Tbl.remove tbl name
done)
!to_remove
end
|
a09a3e48c5a0467b7d9929370b4185339dfe6b1d252a4d72fe057e2c4989d945 | ghc/testsuite | rnfail019.hs | module ShouldFail where
-- !!! Section with with a bad precedence
f x y = (x:y:)
GHC 4.04 ( as released ) let this by , but it 's a precedence error .
| null | https://raw.githubusercontent.com/ghc/testsuite/998a816ae89c4fd573f4abd7c6abb346cf7ee9af/tests/rename/should_fail/rnfail019.hs | haskell | !!! Section with with a bad precedence | module ShouldFail where
f x y = (x:y:)
GHC 4.04 ( as released ) let this by , but it 's a precedence error .
|
63375bbe2f0ff28e615fbd420b277f3d06efab965ef128341daf9211badb6f7d | janestreet/bonsai | search_bar.ml | open! Core
open! Import
module Search_container = [%css stylesheet {|
.class_ {
position: relative;
}
|}]
module Search_icon =
[%css
stylesheet {|
.class_ {
position: absolute;
left: 16px;
top: 8px;
}
|}]
module Search_bar =
[%css
stylesheet
{|
.class_ {
width: 100%;
height: 40px;
font-size: 16px;
text-indent: 40px;
}
|}]
let component =
let%sub search_bar =
Form.Elements.Textbox.string
~extra_attrs:
(Value.return [ Vdom.Attr.many [ Card_like.class_; Search_bar.class_ ] ])
~placeholder:"Search icons"
()
in
let%arr search_bar = search_bar in
let icons =
match Form.value search_bar with
| Error error ->
eprint_s [%message "failed to get value from search bar" (error : Error.t)];
Feather_icon.all
| Ok search ->
List.filter Feather_icon.all ~f:(fun icon ->
let icon_string = Feather_icon.to_string icon in
Fuzzy_match.is_match icon_string ~char_equal:Char.Caseless.equal ~pattern:search)
in
let search_icon =
let gray = `Hex "#959da5" in
Vdom.Node.div ~attr:Search_icon.class_ [ Feather_icon.svg Search ~stroke:gray ]
in
let view =
Vdom.Node.div
~attr:Search_container.class_
(search_icon :: (Form.view search_bar |> Form.View.to_vdom_plain))
in
icons, view
;;
| null | https://raw.githubusercontent.com/janestreet/bonsai/8643e8b3717b035386ac36f2bcfa4a05bca0d64f/examples/feather_icons/search_bar.ml | ocaml | open! Core
open! Import
module Search_container = [%css stylesheet {|
.class_ {
position: relative;
}
|}]
module Search_icon =
[%css
stylesheet {|
.class_ {
position: absolute;
left: 16px;
top: 8px;
}
|}]
module Search_bar =
[%css
stylesheet
{|
.class_ {
width: 100%;
height: 40px;
font-size: 16px;
text-indent: 40px;
}
|}]
let component =
let%sub search_bar =
Form.Elements.Textbox.string
~extra_attrs:
(Value.return [ Vdom.Attr.many [ Card_like.class_; Search_bar.class_ ] ])
~placeholder:"Search icons"
()
in
let%arr search_bar = search_bar in
let icons =
match Form.value search_bar with
| Error error ->
eprint_s [%message "failed to get value from search bar" (error : Error.t)];
Feather_icon.all
| Ok search ->
List.filter Feather_icon.all ~f:(fun icon ->
let icon_string = Feather_icon.to_string icon in
Fuzzy_match.is_match icon_string ~char_equal:Char.Caseless.equal ~pattern:search)
in
let search_icon =
let gray = `Hex "#959da5" in
Vdom.Node.div ~attr:Search_icon.class_ [ Feather_icon.svg Search ~stroke:gray ]
in
let view =
Vdom.Node.div
~attr:Search_container.class_
(search_icon :: (Form.view search_bar |> Form.View.to_vdom_plain))
in
icons, view
;;
| |
a90200c08a183c5c40e61d89c73258700e184c85e3bee6c0b7151fad390f3f96 | ds-wizard/engine-backend | AppConfigSM.hs | module Wizard.Api.Resource.Config.AppConfigSM where
import Data.Swagger
import Shared.Api.Resource.Package.PackagePatternSM ()
import Shared.Util.Swagger
import Wizard.Api.Resource.Config.AppConfigJM ()
import Wizard.Api.Resource.Config.SimpleFeatureSM ()
import Wizard.Api.Resource.Questionnaire.QuestionnaireSharingSM ()
import Wizard.Api.Resource.Questionnaire.QuestionnaireVisibilitySM ()
import Wizard.Database.Migration.Development.Config.Data.AppConfigs
import Wizard.Model.Config.AppConfig
instance ToSchema AppConfig where
declareNamedSchema = toSwagger defaultAppConfig
instance ToSchema AppConfigOrganization where
declareNamedSchema = toSwagger defaultOrganization
instance ToSchema AppConfigFeature where
declareNamedSchema = toSwagger defaultFeature
instance ToSchema AppConfigAuth where
declareNamedSchema = toSwagger defaultAuth
instance ToSchema AppConfigAuthInternal where
declareNamedSchema = toSwagger defaultAuthInternal
instance ToSchema AppConfigAuthInternalTwoFactorAuth where
declareNamedSchema = toSwagger defaultAuthInternalTwoFactorAuth
instance ToSchema AppConfigAuthExternal where
declareNamedSchema = toSwagger defaultAuthExternal
instance ToSchema AppConfigAuthExternalService where
declareNamedSchema = toSwagger defaultAuthExternalService
instance ToSchema AppConfigAuthExternalServiceParameter where
declareNamedSchema = toSwagger defaultAuthExternalServiceParameter
instance ToSchema AppConfigAuthExternalServiceStyle where
declareNamedSchema = toSwagger defaultAuthExternalServiceStyle
instance ToSchema AppConfigPrivacyAndSupport where
declareNamedSchema = toSwagger defaultPrivacyAndSupport
instance ToSchema AppConfigDashboard where
declareNamedSchema = toSwagger defaultDashboard
instance ToSchema AppConfigDashboardDashboardType
instance ToSchema AppConfigLookAndFeel where
declareNamedSchema = toSwagger defaultLookAndFeel
instance ToSchema AppConfigLookAndFeelCustomMenuLink where
declareNamedSchema = toSwagger defaultLookAndFeelCustomLink
instance ToSchema AppConfigRegistry where
declareNamedSchema = toSwagger defaultRegistry
instance ToSchema AppConfigKnowledgeModel where
declareNamedSchema = toSwagger defaultKnowledgeModel
instance ToSchema AppConfigKnowledgeModelPublic where
declareNamedSchema = toSwagger defaultKnowledgeModelPublic
instance ToSchema AppConfigQuestionnaire where
declareNamedSchema = toSwagger defaultQuestionnaire
instance ToSchema AppConfigQuestionnaireVisibility where
declareNamedSchema = toSwagger defaultQuestionnaireVisibility
instance ToSchema AppConfigQuestionnaireSharing where
declareNamedSchema = toSwagger defaultQuestionnaireSharing
instance ToSchema QuestionnaireCreation
instance ToSchema AppConfigQuestionnaireProjectTagging where
declareNamedSchema = toSwagger defaultQuestionnaireProjectTagging
instance ToSchema AppConfigQuestionnaireFeedback where
declareNamedSchema = toSwagger defaultFeedback
instance ToSchema AppConfigSubmission where
declareNamedSchema = toSwagger defaultSubmission
instance ToSchema AppConfigSubmissionService where
declareNamedSchema = toSwagger defaultSubmissionService
instance ToSchema AppConfigSubmissionServiceSupportedFormat where
declareNamedSchema =
toSwagger defaultSubmissionServiceSupportedFormat
instance ToSchema AppConfigSubmissionServiceRequest where
declareNamedSchema = toSwagger defaultSubmissionServiceRequest
instance ToSchema AppConfigSubmissionServiceRequestMultipart where
declareNamedSchema =
toSwagger defaultSubmissionServiceRequestMultipart
instance ToSchema AppConfigOwl where
declareNamedSchema = toSwagger defaultOwl
| null | https://raw.githubusercontent.com/ds-wizard/engine-backend/8f2fadd4a0dae84eb1f5f09230c4c5b58ac3e18d/engine-wizard/src/Wizard/Api/Resource/Config/AppConfigSM.hs | haskell | module Wizard.Api.Resource.Config.AppConfigSM where
import Data.Swagger
import Shared.Api.Resource.Package.PackagePatternSM ()
import Shared.Util.Swagger
import Wizard.Api.Resource.Config.AppConfigJM ()
import Wizard.Api.Resource.Config.SimpleFeatureSM ()
import Wizard.Api.Resource.Questionnaire.QuestionnaireSharingSM ()
import Wizard.Api.Resource.Questionnaire.QuestionnaireVisibilitySM ()
import Wizard.Database.Migration.Development.Config.Data.AppConfigs
import Wizard.Model.Config.AppConfig
instance ToSchema AppConfig where
declareNamedSchema = toSwagger defaultAppConfig
instance ToSchema AppConfigOrganization where
declareNamedSchema = toSwagger defaultOrganization
instance ToSchema AppConfigFeature where
declareNamedSchema = toSwagger defaultFeature
instance ToSchema AppConfigAuth where
declareNamedSchema = toSwagger defaultAuth
instance ToSchema AppConfigAuthInternal where
declareNamedSchema = toSwagger defaultAuthInternal
instance ToSchema AppConfigAuthInternalTwoFactorAuth where
declareNamedSchema = toSwagger defaultAuthInternalTwoFactorAuth
instance ToSchema AppConfigAuthExternal where
declareNamedSchema = toSwagger defaultAuthExternal
instance ToSchema AppConfigAuthExternalService where
declareNamedSchema = toSwagger defaultAuthExternalService
instance ToSchema AppConfigAuthExternalServiceParameter where
declareNamedSchema = toSwagger defaultAuthExternalServiceParameter
instance ToSchema AppConfigAuthExternalServiceStyle where
declareNamedSchema = toSwagger defaultAuthExternalServiceStyle
instance ToSchema AppConfigPrivacyAndSupport where
declareNamedSchema = toSwagger defaultPrivacyAndSupport
instance ToSchema AppConfigDashboard where
declareNamedSchema = toSwagger defaultDashboard
instance ToSchema AppConfigDashboardDashboardType
instance ToSchema AppConfigLookAndFeel where
declareNamedSchema = toSwagger defaultLookAndFeel
instance ToSchema AppConfigLookAndFeelCustomMenuLink where
declareNamedSchema = toSwagger defaultLookAndFeelCustomLink
instance ToSchema AppConfigRegistry where
declareNamedSchema = toSwagger defaultRegistry
instance ToSchema AppConfigKnowledgeModel where
declareNamedSchema = toSwagger defaultKnowledgeModel
instance ToSchema AppConfigKnowledgeModelPublic where
declareNamedSchema = toSwagger defaultKnowledgeModelPublic
instance ToSchema AppConfigQuestionnaire where
declareNamedSchema = toSwagger defaultQuestionnaire
instance ToSchema AppConfigQuestionnaireVisibility where
declareNamedSchema = toSwagger defaultQuestionnaireVisibility
instance ToSchema AppConfigQuestionnaireSharing where
declareNamedSchema = toSwagger defaultQuestionnaireSharing
instance ToSchema QuestionnaireCreation
instance ToSchema AppConfigQuestionnaireProjectTagging where
declareNamedSchema = toSwagger defaultQuestionnaireProjectTagging
instance ToSchema AppConfigQuestionnaireFeedback where
declareNamedSchema = toSwagger defaultFeedback
instance ToSchema AppConfigSubmission where
declareNamedSchema = toSwagger defaultSubmission
instance ToSchema AppConfigSubmissionService where
declareNamedSchema = toSwagger defaultSubmissionService
instance ToSchema AppConfigSubmissionServiceSupportedFormat where
declareNamedSchema =
toSwagger defaultSubmissionServiceSupportedFormat
instance ToSchema AppConfigSubmissionServiceRequest where
declareNamedSchema = toSwagger defaultSubmissionServiceRequest
instance ToSchema AppConfigSubmissionServiceRequestMultipart where
declareNamedSchema =
toSwagger defaultSubmissionServiceRequestMultipart
instance ToSchema AppConfigOwl where
declareNamedSchema = toSwagger defaultOwl
| |
a688ce86e86c285755363700888e825caa0d1556448e7e6b825b06ee8f0c2a16 | heliaxdev/extensible-data | DerivBase.hs | module DerivBase where
import Extensible
extensible [d|
data A a = A (B a) Int deriving Eq
data B a = B a deriving Eq
|]
| null | https://raw.githubusercontent.com/heliaxdev/extensible-data/d11dee6006169cb537e95af28c3541a24194dea8/examples/deriv/DerivBase.hs | haskell | module DerivBase where
import Extensible
extensible [d|
data A a = A (B a) Int deriving Eq
data B a = B a deriving Eq
|]
| |
372a104e46c03f02d3aa5a585964a0bdaba4d3e3dd00983a19b1d0a550a12476 | weblocks-framework/weblocks | company-presenter.lisp | (in-package :employer-employee)
(defwidget company-presenter (composite)
((data
:reader company-presenter-data
:initform nil
:initarg :data
:documentation
"Company data object rendered and modified by this widget.")
(data-class
:accessor company-presenter-data-class
:initform nil
:initarg :data-class
:documentation
"Company data object rendered and modified by this widget.")
(class-store
:accessor company-presenter-class-store
:initform nil
:initarg :class-store
:documentation
"Company data store used by this widget.")
(properties-data-view
:accessor company-presenter-properties-data-view
:initform nil
:initarg :properties-data-view
:documentation
"An optional custom data view for the company properties.")
(properties-form-view
:accessor company-presenter-properties-form-view
:initform nil
:initarg :properties-form-view
:documentation
"An optional custom form view for the company properties.")
(properties-ui-state
:reader company-presenter-properties-ui-state
:initform :data
:initarg :properties-ui-state
:documentation
"UI stete for the company properties. By default it's :data")
(properties-editor
:reader company-presenter-properties-editor
:initform nil
:documentation
"Editor for company properties")
(employee-list
:reader company-presenter-employee-list
:initform nil
:documentation
"Shows a list of employees. Employees are implicit, in that they are not directly
referred by the company data object. Instead, we rely on company's
storage to extract employees with slot 'data set to the value of company's id.")
(employee-data-class
:reader company-presenter-employee-data-class
:initform nil
:initarg :employee-data-class
:documentation
"Data class of the company employees")
(employee-class-store
:reader company-presenter-employee-class-store
:initform nil
:initarg :employee-class-store
:documentation
"Data store of the company employees")
(employee-list-view
:reader company-presenter-employee-list-view
:initform nil
:initarg :employee-list-view
:documentation
"View for the company employee list.")
(employee-list-on-add-employee
:reader company-presenter-employee-list-on-add-employee
:initform nil
:initarg :employee-list-on-add-employee
:documentation
"Function called when add employee is being added on the company's employee list.
Accepts three agruments: the employee list widget, the company object and the new
employee object.")
(employee-list-on-query
:reader company-presenter-employee-list-on-query
:initform nil
:initarg :employee-list-on-query
:documentation
"Function called when query for employees performed for the company's employee list.
Accepts four arguments: the employee list widget, the company object, the order
and the range parameters. ")
(employee-form-view
:reader company-presenter-employee-form-view
:initform nil
:initarg :employee-form-view
:documentation
"Company employees form view")
(employee-list-popover-editor-class
:reader company-presenter-employee-list-popover-editor-class
:initform nil
:initarg :employee-list-popover-editor-class
:documentation
"Symbol for the popover editor class.")
(state
:accessor company-presenter-state
:initform :drilldown
:initarg :state
:documentation
"State of the widget, either :drilldown or :add. The widget
will transition from :add to :drilldown when the new employee's
property values are successfully saved by the user for the first
time. From then on, the widget will remain in :drilldown state.")
(on-new-company-success
:accessor company-presenter-on-new-company-success
:initform nil
:initarg :on-new-company-success
:documentation
"Function called when new employee is successfully created")
(on-new-company-cancel
:accessor company-presenter-on-new-company-cancel
:initform nil
:initarg :on-new-company-cancel
:documentation
"Function called when new employee creation is cancelled.")
(on-drilldown-edit-success
:accessor company-presenter-on-drilldown-edit-success
:initform nil
:initarg :on-drilldown-edit-success
:documentation
"Function called when new employee is successfully created")
(on-drilldown-edit-cancel
:accessor company-presenter-on-drilldown-edit-cancel
:initform nil
:initarg :on-drilldown-edit-cancel
:documentation
"Function called when new employee creation is cancelled."))
(:documentation "A widget showing company properties and all company employees."))
(defgeneric (setf company-presenter-data) (value obj))
(defmethod (setf company-presenter-data) (value (cpw company-presenter))
(setf (slot-value cpw 'data) value)
(let ((properties-editor (company-presenter-properties-editor cpw)))
(when properties-editor
(setf (dataform-data properties-editor) value))))
(defmethod initialize-instance :after ((cpw company-presenter) &rest args)
(declare (ignore args))
(make-company-properties-widget cpw)
(unless (eql (company-presenter-state cpw) :add)
(make-employee-list-widget cpw)))
(defgeneric make-company-properties-widget (cpw)
(:documentation "Creates properties widget")
(:method ((cpw company-presenter))
(let ((company-properties-w
(make-instance 'dataform
:data (company-presenter-data cpw)
:data-class (company-presenter-data-class cpw)
:class-store (company-presenter-class-store cpw)
:data-view (company-presenter-properties-data-view cpw)
:form-view (company-presenter-properties-form-view cpw)
:ui-state (company-presenter-properties-ui-state cpw)
:on-cancel (lambda (dfw)
(declare (ignore dfw))
(if (eql (company-presenter-state cpw) :add)
(safe-funcall (company-presenter-on-new-company-cancel cpw) cpw)
(safe-funcall (company-presenter-on-drilldown-edit-cancel cpw) cpw)))
:on-success (lambda (dfw)
(if (eql (company-presenter-state cpw) :add)
(progn
(safe-funcall (company-presenter-on-new-company-success cpw) cpw)
(setf (company-presenter-state cpw) :drilldown)
;; note: we're setting the slot directly instead of
;; using the accessor to avoid setting
;; data on the editor (the dfw) - see method
( setf company - presenter - data )
(setf (slot-value cpw 'data) (dataform-data dfw))
(make-employee-list-widget cpw))
(safe-funcall (company-presenter-on-drilldown-edit-success cpw) cpw))))))
(setf (slot-value cpw 'properties-editor) company-properties-w)
(setf (widget-propagate-dirty company-properties-w) (list cpw))
(set-composite-widgets cpw))))
(defgeneric make-employee-list-widget (cpw)
(:documentation "Creates set's item list widget")
(:method ((cpw company-presenter))
(let ((employee-list-w
(make-instance 'popover-gridedit
:view (company-presenter-employee-list-view cpw)
:data-class (company-presenter-employee-data-class cpw)
:class-store (company-presenter-employee-class-store cpw)
:item-form-view (company-presenter-employee-form-view cpw)
:on-add-item (lambda (pop-grid employee)
(safe-funcall (company-presenter-employee-list-on-add-employee cpw)
pop-grid (company-presenter-data cpw)
employee))
:on-query (lambda (pop-grid order range &rest args)
(safe-apply (company-presenter-employee-list-on-query cpw)
pop-grid (company-presenter-data cpw)
order range args)))))
(setf (slot-value cpw 'employee-list) employee-list-w)
(setf (widget-propagate-dirty employee-list-w) (list cpw))
(set-composite-widgets cpw))))
(defun set-composite-widgets (cpw)
(let ((widget-list (list (company-presenter-properties-editor cpw) (company-presenter-employee-list cpw))))
(setf (composite-widgets cpw) (remove nil widget-list))))
(defmethod render-widget-body ((cpw company-presenter) &rest args)
(declare (ignore args))
(render-widget (company-presenter-properties-editor cpw))
(when (company-presenter-employee-list cpw)
(render-widget (company-presenter-employee-list cpw))))
(defmethod dataedit-item-widget-data ((cpw company-presenter))
(company-presenter-data cpw))
| null | https://raw.githubusercontent.com/weblocks-framework/weblocks/fe96152458c8eb54d74751b3201db42dafe1708b/contrib/yarek/examples/employer-employee/src/widgets/company-presenter.lisp | lisp | note: we're setting the slot directly instead of
using the accessor to avoid setting
data on the editor (the dfw) - see method | (in-package :employer-employee)
(defwidget company-presenter (composite)
((data
:reader company-presenter-data
:initform nil
:initarg :data
:documentation
"Company data object rendered and modified by this widget.")
(data-class
:accessor company-presenter-data-class
:initform nil
:initarg :data-class
:documentation
"Company data object rendered and modified by this widget.")
(class-store
:accessor company-presenter-class-store
:initform nil
:initarg :class-store
:documentation
"Company data store used by this widget.")
(properties-data-view
:accessor company-presenter-properties-data-view
:initform nil
:initarg :properties-data-view
:documentation
"An optional custom data view for the company properties.")
(properties-form-view
:accessor company-presenter-properties-form-view
:initform nil
:initarg :properties-form-view
:documentation
"An optional custom form view for the company properties.")
(properties-ui-state
:reader company-presenter-properties-ui-state
:initform :data
:initarg :properties-ui-state
:documentation
"UI stete for the company properties. By default it's :data")
(properties-editor
:reader company-presenter-properties-editor
:initform nil
:documentation
"Editor for company properties")
(employee-list
:reader company-presenter-employee-list
:initform nil
:documentation
"Shows a list of employees. Employees are implicit, in that they are not directly
referred by the company data object. Instead, we rely on company's
storage to extract employees with slot 'data set to the value of company's id.")
(employee-data-class
:reader company-presenter-employee-data-class
:initform nil
:initarg :employee-data-class
:documentation
"Data class of the company employees")
(employee-class-store
:reader company-presenter-employee-class-store
:initform nil
:initarg :employee-class-store
:documentation
"Data store of the company employees")
(employee-list-view
:reader company-presenter-employee-list-view
:initform nil
:initarg :employee-list-view
:documentation
"View for the company employee list.")
(employee-list-on-add-employee
:reader company-presenter-employee-list-on-add-employee
:initform nil
:initarg :employee-list-on-add-employee
:documentation
"Function called when add employee is being added on the company's employee list.
Accepts three agruments: the employee list widget, the company object and the new
employee object.")
(employee-list-on-query
:reader company-presenter-employee-list-on-query
:initform nil
:initarg :employee-list-on-query
:documentation
"Function called when query for employees performed for the company's employee list.
Accepts four arguments: the employee list widget, the company object, the order
and the range parameters. ")
(employee-form-view
:reader company-presenter-employee-form-view
:initform nil
:initarg :employee-form-view
:documentation
"Company employees form view")
(employee-list-popover-editor-class
:reader company-presenter-employee-list-popover-editor-class
:initform nil
:initarg :employee-list-popover-editor-class
:documentation
"Symbol for the popover editor class.")
(state
:accessor company-presenter-state
:initform :drilldown
:initarg :state
:documentation
"State of the widget, either :drilldown or :add. The widget
will transition from :add to :drilldown when the new employee's
property values are successfully saved by the user for the first
time. From then on, the widget will remain in :drilldown state.")
(on-new-company-success
:accessor company-presenter-on-new-company-success
:initform nil
:initarg :on-new-company-success
:documentation
"Function called when new employee is successfully created")
(on-new-company-cancel
:accessor company-presenter-on-new-company-cancel
:initform nil
:initarg :on-new-company-cancel
:documentation
"Function called when new employee creation is cancelled.")
(on-drilldown-edit-success
:accessor company-presenter-on-drilldown-edit-success
:initform nil
:initarg :on-drilldown-edit-success
:documentation
"Function called when new employee is successfully created")
(on-drilldown-edit-cancel
:accessor company-presenter-on-drilldown-edit-cancel
:initform nil
:initarg :on-drilldown-edit-cancel
:documentation
"Function called when new employee creation is cancelled."))
(:documentation "A widget showing company properties and all company employees."))
(defgeneric (setf company-presenter-data) (value obj))
(defmethod (setf company-presenter-data) (value (cpw company-presenter))
(setf (slot-value cpw 'data) value)
(let ((properties-editor (company-presenter-properties-editor cpw)))
(when properties-editor
(setf (dataform-data properties-editor) value))))
(defmethod initialize-instance :after ((cpw company-presenter) &rest args)
(declare (ignore args))
(make-company-properties-widget cpw)
(unless (eql (company-presenter-state cpw) :add)
(make-employee-list-widget cpw)))
(defgeneric make-company-properties-widget (cpw)
(:documentation "Creates properties widget")
(:method ((cpw company-presenter))
(let ((company-properties-w
(make-instance 'dataform
:data (company-presenter-data cpw)
:data-class (company-presenter-data-class cpw)
:class-store (company-presenter-class-store cpw)
:data-view (company-presenter-properties-data-view cpw)
:form-view (company-presenter-properties-form-view cpw)
:ui-state (company-presenter-properties-ui-state cpw)
:on-cancel (lambda (dfw)
(declare (ignore dfw))
(if (eql (company-presenter-state cpw) :add)
(safe-funcall (company-presenter-on-new-company-cancel cpw) cpw)
(safe-funcall (company-presenter-on-drilldown-edit-cancel cpw) cpw)))
:on-success (lambda (dfw)
(if (eql (company-presenter-state cpw) :add)
(progn
(safe-funcall (company-presenter-on-new-company-success cpw) cpw)
(setf (company-presenter-state cpw) :drilldown)
( setf company - presenter - data )
(setf (slot-value cpw 'data) (dataform-data dfw))
(make-employee-list-widget cpw))
(safe-funcall (company-presenter-on-drilldown-edit-success cpw) cpw))))))
(setf (slot-value cpw 'properties-editor) company-properties-w)
(setf (widget-propagate-dirty company-properties-w) (list cpw))
(set-composite-widgets cpw))))
(defgeneric make-employee-list-widget (cpw)
(:documentation "Creates set's item list widget")
(:method ((cpw company-presenter))
(let ((employee-list-w
(make-instance 'popover-gridedit
:view (company-presenter-employee-list-view cpw)
:data-class (company-presenter-employee-data-class cpw)
:class-store (company-presenter-employee-class-store cpw)
:item-form-view (company-presenter-employee-form-view cpw)
:on-add-item (lambda (pop-grid employee)
(safe-funcall (company-presenter-employee-list-on-add-employee cpw)
pop-grid (company-presenter-data cpw)
employee))
:on-query (lambda (pop-grid order range &rest args)
(safe-apply (company-presenter-employee-list-on-query cpw)
pop-grid (company-presenter-data cpw)
order range args)))))
(setf (slot-value cpw 'employee-list) employee-list-w)
(setf (widget-propagate-dirty employee-list-w) (list cpw))
(set-composite-widgets cpw))))
(defun set-composite-widgets (cpw)
(let ((widget-list (list (company-presenter-properties-editor cpw) (company-presenter-employee-list cpw))))
(setf (composite-widgets cpw) (remove nil widget-list))))
(defmethod render-widget-body ((cpw company-presenter) &rest args)
(declare (ignore args))
(render-widget (company-presenter-properties-editor cpw))
(when (company-presenter-employee-list cpw)
(render-widget (company-presenter-employee-list cpw))))
(defmethod dataedit-item-widget-data ((cpw company-presenter))
(company-presenter-data cpw))
|
4e437203b0d37b4b312874a4313eb94e9a1990d3eb1a21e010c394949f0d43ea | bobot/FetedelascienceINRIAsaclay | a_star.ml | File : a_star.ml
Copyright ( C ) 2008
< >
< >
WWW : /
This library is free software ; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2.1 or
later as published by the Free Software Foundation , with the special
exception on linking described in the file LICENSE .
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 file
LICENSE for more details .
Copyright (C) 2008
Julie de Pril <>
Christophe Troestler <>
WWW: /
This library is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2.1 or
later as published by the Free Software Foundation, with the special
exception on linking described in the file LICENSE.
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 file
LICENSE for more details. *)
(** Functor using a [Phase] module to develop some strategies to find a
sequence of moves to get into a goal state. *)
module Make(P:
sig
include Rubik.Coordinate
val max_moves : int
val in_goal : t -> bool
end) =
struct
open Rubik
module PQ = Priority_queue
let mul = P.initialize_mul()
let pruning = P.initialize_pruning()
(** [search_seq_to_goal p in_goal] returns a list of moves that lead
to the a permutation [q] (such that [in_goal q] is true) from
the permutation [p]. *)
let search_seq_to_goal first max_moves =
] returns the " children " of the permutation [ p ] ( ie all
the permutations we can reach by applying a single move to [ p ] ) with
the associated move .
the permutations we can reach by applying a single move to [p]) with
the associated move. *)
let get_children p = List.map (fun move -> (mul p move, move)) P.Move.all in
[ aStar ] recursively searches a sequence of moves to get into the goal
state . ( A * algorithm )
state. (A* algorithm) *)
let rec aStar opened =
(* [opened] is the set of all pending candidates. *)
if PQ.is_empty opened (* No more candidates. *) then []
else
let (p,seq,pcost) = PQ.take opened in
if P.in_goal p (* Get into the goal state! *) then [List.rev seq]
else begin
let children = get_children p in
(* We update the set [opened] with the children of [p]. *)
let opened =
List.fold_left begin fun opened (child,m) ->
let fchild = pcost+1 + pruning child in
if fchild <= max_moves then (* The path is not too long. *)
let c = (child, m::seq, pcost+1) in
PQ.add fchild c opened;
opened
else opened
end
opened children
in
aStar opened
end
in
let start = (first,[],0) in
let opened = PQ.make (max_moves+1) in
PQ.add (pruning first) start opened;
aStar opened
end
| null | https://raw.githubusercontent.com/bobot/FetedelascienceINRIAsaclay/87765db9f9c7211a26a09eb93e9c92f99a49b0bc/2010/robot/examples_mindstorm_lab/rubik/a_star.ml | ocaml | * Functor using a [Phase] module to develop some strategies to find a
sequence of moves to get into a goal state.
* [search_seq_to_goal p in_goal] returns a list of moves that lead
to the a permutation [q] (such that [in_goal q] is true) from
the permutation [p].
[opened] is the set of all pending candidates.
No more candidates.
Get into the goal state!
We update the set [opened] with the children of [p].
The path is not too long. | File : a_star.ml
Copyright ( C ) 2008
< >
< >
WWW : /
This library is free software ; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2.1 or
later as published by the Free Software Foundation , with the special
exception on linking described in the file LICENSE .
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 file
LICENSE for more details .
Copyright (C) 2008
Julie de Pril <>
Christophe Troestler <>
WWW: /
This library is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2.1 or
later as published by the Free Software Foundation, with the special
exception on linking described in the file LICENSE.
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 file
LICENSE for more details. *)
module Make(P:
sig
include Rubik.Coordinate
val max_moves : int
val in_goal : t -> bool
end) =
struct
open Rubik
module PQ = Priority_queue
let mul = P.initialize_mul()
let pruning = P.initialize_pruning()
let search_seq_to_goal first max_moves =
] returns the " children " of the permutation [ p ] ( ie all
the permutations we can reach by applying a single move to [ p ] ) with
the associated move .
the permutations we can reach by applying a single move to [p]) with
the associated move. *)
let get_children p = List.map (fun move -> (mul p move, move)) P.Move.all in
[ aStar ] recursively searches a sequence of moves to get into the goal
state . ( A * algorithm )
state. (A* algorithm) *)
let rec aStar opened =
else
let (p,seq,pcost) = PQ.take opened in
else begin
let children = get_children p in
let opened =
List.fold_left begin fun opened (child,m) ->
let fchild = pcost+1 + pruning child in
let c = (child, m::seq, pcost+1) in
PQ.add fchild c opened;
opened
else opened
end
opened children
in
aStar opened
end
in
let start = (first,[],0) in
let opened = PQ.make (max_moves+1) in
PQ.add (pruning first) start opened;
aStar opened
end
|
d2d1fdecd94352bec48b95baf61d77528b9c1265c0f99dd8382e5c319774038d | ollef/sixten | Compile.hs | # LANGUAGE CPP #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE ScopedTypeVariables #
module Backend.Compile where
import Protolude hiding (moduleName, (<.>))
import Data.Char
import Data.List(dropWhile, dropWhileEnd)
import Data.String
import qualified Data.Text.IO as Text
import Data.Version
import System.Directory
import System.FilePath
import System.IO.Temp
import System.Process
import Text.Printf
import qualified Backend.Generate as Generate
import qualified Backend.Generate.Submodule as Generate
import Backend.Target(Target)
import qualified Backend.Target as Target
import qualified Command.Compile.Options as Compile
import Syntax.Extern
import Syntax.ModuleHeader
import Syntax.QName
import Util
data Arguments = Arguments
{ cFiles :: [FilePath]
, llFiles :: [FilePath]
, linkedLlFileName :: !FilePath
, target :: !Target
, outputFile :: !FilePath
}
minLlvmVersion :: Int
minLlvmVersion = 4
maxLlvmVersion :: Int
maxLlvmVersion = 7
-- See -new-versioning-scheme.html
Tl;dr : minor versions are fixed to 0 , so only different major versions need
-- to be supported.
supportedLlvmVersions :: [Version]
supportedLlvmVersions = makeVersion . (: [minorVersion]) <$> supportedMajorVersions
where
minorVersion = 0
supportedMajorVersions = [maxLlvmVersion, maxLlvmVersion - 1 .. minLlvmVersion]
| llvm - config is not available in current LLVM distribution for windows , so we
need use @clang -print - prog - name = clang@ to get the full path of @clang@.
--
We simply assume that @clang.exe@ already exists in @%PATH%@.
--
clangBinPath :: IO FilePath
clangBinPath = trim <$> checkClangExists
where
checkClangExists =
handle (\(_ :: IOException) -> panic "Couldn't find clang.")
$ readProcess "clang" ["-print-prog-name=clang"] ""
trim = dropWhile isSpace . dropWhileEnd isSpace
llvmBinPath :: IO FilePath
llvmBinPath = checkLlvmExists candidates
where
suffixes
= ""
The naming scheme on e.g. :
: fmap (("-" <>) . showVersion) supportedLlvmVersions
prefixes =
[ ""
The installation path of Brew on :
, "/usr/local/opt/llvm/bin/"
]
candidates
= ["llvm-config" <> suffix | suffix <- suffixes]
++ [prefix <> "llvm-config" | prefix <- prefixes]
checkLlvmExists :: [String] -> IO FilePath
checkLlvmExists (path : xs) =
handle (\(_ :: IOException) -> checkLlvmExists xs)
$ readProcess path ["--bindir"] ""
checkLlvmExists [] = panic
"Couldn't find llvm-config. You can specify its path using the --llvm-config flag."
compileFiles :: Compile.Options -> Arguments -> IO ()
compileFiles opts args = do
#ifndef mingw32_HOST_OS
binPath <- takeWhile (not . isSpace) <$> case Compile.llvmConfig opts of
Nothing -> llvmBinPath
Just configBin -> do
maybeMajorVersion <- readMaybe . takeWhile (/= '.')
<$> readProcess configBin ["--version"] ""
case maybeMajorVersion of
Nothing -> printf
"Warning: Couldn't determine LLVM version. Currently supported versions are %d <= v <= %d.\n"
minLlvmVersion
maxLlvmVersion
Just majorVersion ->
when (majorVersion < minLlvmVersion || majorVersion > maxLlvmVersion) $
printf
"Warning: LLVM version out of range. Currently supported versions are %d <= v <= %d.\n"
minLlvmVersion
maxLlvmVersion
readProcess configBin ["--bindir"] ""
let opt = binPath </> "opt"
let clang = binPath </> "clang"
let linker = binPath </> "llvm-link"
let compiler = binPath </> "llc"
cLlFiles <- forM (cFiles args) $ compileC clang opts $ target args
linkedLlFile <- linkLlvm linker (llFiles args ++ toList cLlFiles)
$ linkedLlFileName args
optLlFile <- optimiseLlvm opt opts linkedLlFile
objFile <- compileLlvm compiler opts (target args) optLlFile
assemble clang opts [objFile] $ outputFile args
#else
In distribution for windows , @opt@ , @llvm - link@ and @llc@ are not
available . We use @clang@ to link files directly .
-- We enable @-fLTO@ in @assemble@ to perform link time optimizations.
clang <- clangBinPath
cLlFiles <- forM (cFiles args) $ compileC clang opts $ target args
assemble clang opts (llFiles args ++ toList cLlFiles) $ outputFile args
#endif
optimisationFlags :: Compile.Options -> [String]
optimisationFlags opts = case Compile.optimisation opts of
Nothing -> []
Just optLevel -> ["-O" <> optLevel]
type Binary = FilePath
optimiseLlvm :: Binary -> Compile.Options -> FilePath -> IO FilePath
optimiseLlvm opt opts file
| isNothing $ Compile.optimisation opts = return file
| otherwise = do
let optLlFile = replaceExtension file "opt.ll"
callProcess opt $ optimisationFlags opts ++
[ "-S", file
, "-o", optLlFile
]
return optLlFile
compileC :: Binary -> Compile.Options -> Target -> FilePath -> IO FilePath
compileC clang opts tgt cFile = do
let output = cFile <> ".ll"
callProcess clang $ optimisationFlags opts ++
[ "-march=" <> Target.architecture tgt
, "-fvisibility=internal"
#ifndef mingw32_HOST_OS
, "-fPIC"
#endif
, "-S"
, "-emit-llvm"
, cFile
, "-o", output
]
return output
linkLlvm :: Binary -> [FilePath] -> FilePath -> IO FilePath
linkLlvm _ [file] _outFile = return file
linkLlvm linker files outFile = do
callProcess linker $ ["-o=" <> outFile, "-S"] ++ files
return outFile
compileLlvm :: Binary -> Compile.Options -> Target -> FilePath -> IO FilePath
compileLlvm compiler opts tgt llFile = do
let flags ft o
= optimisationFlags opts ++
[ "-filetype=" <> ft
, "-march=" <> Target.architecture tgt
, "-relocation-model=pic"
, llFile
, "-o", o
]
asmFile = replaceExtension llFile "s"
objFile = replaceExtension llFile "o"
when (isJust $ Compile.assemblyDir opts) $
callProcess compiler $ flags "asm" asmFile
callProcess compiler $ flags "obj" objFile
return objFile
assemble :: Binary -> Compile.Options -> [FilePath] -> FilePath -> IO ()
assemble clang opts objFiles outFile = do
let extraLibDirFlag = ["-L" ++ dir | dir <- Compile.extraLibDir opts]
#ifndef mingw32_HOST_OS
ldFlags <- readProcess "pkg-config" ["--libs", "--static", "bdw-gc"] ""
#else
Currently the bdwgc can only output library linking with dynamic MSVCRT .
-- however clang will automatically pass static MSVCRT to linker.
let ldFlags = "-lgc-lib -fuse-ld=lld-link -Xlinker -nodefaultlib:libcmt -Xlinker -defaultlib:msvcrt.lib"
#endif
callProcess clang
$ concatMap words (extraLibDirFlag ++ lines ldFlags)
++ optimisationFlags opts
++ objFiles ++ ["-o", outFile]
compileModules
:: FilePath
-> Target
-> Compile.Options
-> [(ModuleHeader, [Generate.Submodule])]
-> IO ()
compileModules outputFile_ target_ opts modules =
withAssemblyDir (Compile.assemblyDir opts) $ \asmDir -> do
(externFiles, llFiles_)
<- fmap mconcat $ forM modules $ \(moduleHeader, subModules) -> do
let fileBase = asmDir </> fromModuleName (moduleName moduleHeader)
llName = fileBase <> ".ll"
cName = fileBase <> ".c"
externs <- writeModule moduleHeader subModules llName [(C, cName)]
return (externs, [llName])
let linkedLlFileName_ = asmDir </> "main" <.> "linked" <.> "ll"
compileFiles opts Arguments
{ cFiles = [cFile | (C, cFile) <- externFiles]
, llFiles = llFiles_
, linkedLlFileName = linkedLlFileName_
, target = target_
, outputFile = outputFile_
}
where
withAssemblyDir Nothing k = withSystemTempDirectory "sixten" k
withAssemblyDir (Just dir) k = do
createDirectoryIfMissing True dir
k dir
writeModule
:: ModuleHeader
-> [Generate.Submodule]
-> FilePath
-> [(Language, FilePath)]
-> IO [(Language, FilePath)]
writeModule moduleHeader subModules llOutputFile externOutputFiles = do
Util.withFile llOutputFile WriteMode $
Generate.writeLlvmModule
(moduleName moduleHeader)
(moduleImports moduleHeader)
subModules
fmap catMaybes $
forM externOutputFiles $ \(lang, outFile) ->
case fmap snd $ filter ((== lang) . fst) $ concatMap Generate.externs subModules of
[] -> return Nothing
externCode -> Util.withFile outFile WriteMode $ \h -> do
TODO this is C specific
Text.hPutStrLn h "#include <inttypes.h>"
Text.hPutStrLn h "#include <stdint.h>"
Text.hPutStrLn h "#include <stdio.h>"
Text.hPutStrLn h "#include <stdlib.h>"
Text.hPutStrLn h "#include <string.h>"
Text.hPutStrLn h "#ifdef _WIN32"
Text.hPutStrLn h "#include <io.h>"
Text.hPutStrLn h "#else"
Text.hPutStrLn h "#include <unistd.h>"
Text.hPutStrLn h "#endif"
forM_ externCode $ \code -> do
Text.hPutStrLn h ""
Text.hPutStrLn h code
return $ Just (lang, outFile)
| null | https://raw.githubusercontent.com/ollef/sixten/60d46eee20abd62599badea85774a9365c81af45/src/Backend/Compile.hs | haskell | # LANGUAGE OverloadedStrings #
See -new-versioning-scheme.html
to be supported.
We enable @-fLTO@ in @assemble@ to perform link time optimizations.
however clang will automatically pass static MSVCRT to linker. | # LANGUAGE CPP #
# LANGUAGE ScopedTypeVariables #
module Backend.Compile where
import Protolude hiding (moduleName, (<.>))
import Data.Char
import Data.List(dropWhile, dropWhileEnd)
import Data.String
import qualified Data.Text.IO as Text
import Data.Version
import System.Directory
import System.FilePath
import System.IO.Temp
import System.Process
import Text.Printf
import qualified Backend.Generate as Generate
import qualified Backend.Generate.Submodule as Generate
import Backend.Target(Target)
import qualified Backend.Target as Target
import qualified Command.Compile.Options as Compile
import Syntax.Extern
import Syntax.ModuleHeader
import Syntax.QName
import Util
data Arguments = Arguments
{ cFiles :: [FilePath]
, llFiles :: [FilePath]
, linkedLlFileName :: !FilePath
, target :: !Target
, outputFile :: !FilePath
}
minLlvmVersion :: Int
minLlvmVersion = 4
maxLlvmVersion :: Int
maxLlvmVersion = 7
Tl;dr : minor versions are fixed to 0 , so only different major versions need
supportedLlvmVersions :: [Version]
supportedLlvmVersions = makeVersion . (: [minorVersion]) <$> supportedMajorVersions
where
minorVersion = 0
supportedMajorVersions = [maxLlvmVersion, maxLlvmVersion - 1 .. minLlvmVersion]
| llvm - config is not available in current LLVM distribution for windows , so we
need use @clang -print - prog - name = clang@ to get the full path of @clang@.
We simply assume that @clang.exe@ already exists in @%PATH%@.
clangBinPath :: IO FilePath
clangBinPath = trim <$> checkClangExists
where
checkClangExists =
handle (\(_ :: IOException) -> panic "Couldn't find clang.")
$ readProcess "clang" ["-print-prog-name=clang"] ""
trim = dropWhile isSpace . dropWhileEnd isSpace
llvmBinPath :: IO FilePath
llvmBinPath = checkLlvmExists candidates
where
suffixes
= ""
The naming scheme on e.g. :
: fmap (("-" <>) . showVersion) supportedLlvmVersions
prefixes =
[ ""
The installation path of Brew on :
, "/usr/local/opt/llvm/bin/"
]
candidates
= ["llvm-config" <> suffix | suffix <- suffixes]
++ [prefix <> "llvm-config" | prefix <- prefixes]
checkLlvmExists :: [String] -> IO FilePath
checkLlvmExists (path : xs) =
handle (\(_ :: IOException) -> checkLlvmExists xs)
$ readProcess path ["--bindir"] ""
checkLlvmExists [] = panic
"Couldn't find llvm-config. You can specify its path using the --llvm-config flag."
compileFiles :: Compile.Options -> Arguments -> IO ()
compileFiles opts args = do
#ifndef mingw32_HOST_OS
binPath <- takeWhile (not . isSpace) <$> case Compile.llvmConfig opts of
Nothing -> llvmBinPath
Just configBin -> do
maybeMajorVersion <- readMaybe . takeWhile (/= '.')
<$> readProcess configBin ["--version"] ""
case maybeMajorVersion of
Nothing -> printf
"Warning: Couldn't determine LLVM version. Currently supported versions are %d <= v <= %d.\n"
minLlvmVersion
maxLlvmVersion
Just majorVersion ->
when (majorVersion < minLlvmVersion || majorVersion > maxLlvmVersion) $
printf
"Warning: LLVM version out of range. Currently supported versions are %d <= v <= %d.\n"
minLlvmVersion
maxLlvmVersion
readProcess configBin ["--bindir"] ""
let opt = binPath </> "opt"
let clang = binPath </> "clang"
let linker = binPath </> "llvm-link"
let compiler = binPath </> "llc"
cLlFiles <- forM (cFiles args) $ compileC clang opts $ target args
linkedLlFile <- linkLlvm linker (llFiles args ++ toList cLlFiles)
$ linkedLlFileName args
optLlFile <- optimiseLlvm opt opts linkedLlFile
objFile <- compileLlvm compiler opts (target args) optLlFile
assemble clang opts [objFile] $ outputFile args
#else
In distribution for windows , @opt@ , @llvm - link@ and @llc@ are not
available . We use @clang@ to link files directly .
clang <- clangBinPath
cLlFiles <- forM (cFiles args) $ compileC clang opts $ target args
assemble clang opts (llFiles args ++ toList cLlFiles) $ outputFile args
#endif
optimisationFlags :: Compile.Options -> [String]
optimisationFlags opts = case Compile.optimisation opts of
Nothing -> []
Just optLevel -> ["-O" <> optLevel]
type Binary = FilePath
optimiseLlvm :: Binary -> Compile.Options -> FilePath -> IO FilePath
optimiseLlvm opt opts file
| isNothing $ Compile.optimisation opts = return file
| otherwise = do
let optLlFile = replaceExtension file "opt.ll"
callProcess opt $ optimisationFlags opts ++
[ "-S", file
, "-o", optLlFile
]
return optLlFile
compileC :: Binary -> Compile.Options -> Target -> FilePath -> IO FilePath
compileC clang opts tgt cFile = do
let output = cFile <> ".ll"
callProcess clang $ optimisationFlags opts ++
[ "-march=" <> Target.architecture tgt
, "-fvisibility=internal"
#ifndef mingw32_HOST_OS
, "-fPIC"
#endif
, "-S"
, "-emit-llvm"
, cFile
, "-o", output
]
return output
linkLlvm :: Binary -> [FilePath] -> FilePath -> IO FilePath
linkLlvm _ [file] _outFile = return file
linkLlvm linker files outFile = do
callProcess linker $ ["-o=" <> outFile, "-S"] ++ files
return outFile
compileLlvm :: Binary -> Compile.Options -> Target -> FilePath -> IO FilePath
compileLlvm compiler opts tgt llFile = do
let flags ft o
= optimisationFlags opts ++
[ "-filetype=" <> ft
, "-march=" <> Target.architecture tgt
, "-relocation-model=pic"
, llFile
, "-o", o
]
asmFile = replaceExtension llFile "s"
objFile = replaceExtension llFile "o"
when (isJust $ Compile.assemblyDir opts) $
callProcess compiler $ flags "asm" asmFile
callProcess compiler $ flags "obj" objFile
return objFile
assemble :: Binary -> Compile.Options -> [FilePath] -> FilePath -> IO ()
assemble clang opts objFiles outFile = do
let extraLibDirFlag = ["-L" ++ dir | dir <- Compile.extraLibDir opts]
#ifndef mingw32_HOST_OS
ldFlags <- readProcess "pkg-config" ["--libs", "--static", "bdw-gc"] ""
#else
Currently the bdwgc can only output library linking with dynamic MSVCRT .
let ldFlags = "-lgc-lib -fuse-ld=lld-link -Xlinker -nodefaultlib:libcmt -Xlinker -defaultlib:msvcrt.lib"
#endif
callProcess clang
$ concatMap words (extraLibDirFlag ++ lines ldFlags)
++ optimisationFlags opts
++ objFiles ++ ["-o", outFile]
compileModules
:: FilePath
-> Target
-> Compile.Options
-> [(ModuleHeader, [Generate.Submodule])]
-> IO ()
compileModules outputFile_ target_ opts modules =
withAssemblyDir (Compile.assemblyDir opts) $ \asmDir -> do
(externFiles, llFiles_)
<- fmap mconcat $ forM modules $ \(moduleHeader, subModules) -> do
let fileBase = asmDir </> fromModuleName (moduleName moduleHeader)
llName = fileBase <> ".ll"
cName = fileBase <> ".c"
externs <- writeModule moduleHeader subModules llName [(C, cName)]
return (externs, [llName])
let linkedLlFileName_ = asmDir </> "main" <.> "linked" <.> "ll"
compileFiles opts Arguments
{ cFiles = [cFile | (C, cFile) <- externFiles]
, llFiles = llFiles_
, linkedLlFileName = linkedLlFileName_
, target = target_
, outputFile = outputFile_
}
where
withAssemblyDir Nothing k = withSystemTempDirectory "sixten" k
withAssemblyDir (Just dir) k = do
createDirectoryIfMissing True dir
k dir
writeModule
:: ModuleHeader
-> [Generate.Submodule]
-> FilePath
-> [(Language, FilePath)]
-> IO [(Language, FilePath)]
writeModule moduleHeader subModules llOutputFile externOutputFiles = do
Util.withFile llOutputFile WriteMode $
Generate.writeLlvmModule
(moduleName moduleHeader)
(moduleImports moduleHeader)
subModules
fmap catMaybes $
forM externOutputFiles $ \(lang, outFile) ->
case fmap snd $ filter ((== lang) . fst) $ concatMap Generate.externs subModules of
[] -> return Nothing
externCode -> Util.withFile outFile WriteMode $ \h -> do
TODO this is C specific
Text.hPutStrLn h "#include <inttypes.h>"
Text.hPutStrLn h "#include <stdint.h>"
Text.hPutStrLn h "#include <stdio.h>"
Text.hPutStrLn h "#include <stdlib.h>"
Text.hPutStrLn h "#include <string.h>"
Text.hPutStrLn h "#ifdef _WIN32"
Text.hPutStrLn h "#include <io.h>"
Text.hPutStrLn h "#else"
Text.hPutStrLn h "#include <unistd.h>"
Text.hPutStrLn h "#endif"
forM_ externCode $ \code -> do
Text.hPutStrLn h ""
Text.hPutStrLn h code
return $ Just (lang, outFile)
|
92870d1e635d93394ead83e95a4c2dedbe76db1758258a77347312d6efe4ebda | skanev/playground | 44.scm | EOPL exercise 3.44
;
; In the preceding example, the only use of f is as a known procedure.
; Therefore the procedure built by the expression proc (y) -(y, x) is never
; used. Modify the translator so that such a procedure is never constructred.
; We base this on the previous exercise. We just need to modify how let treats
; its value-exp. If value-exp is a procedure and the var is used only in
; operator position within the let body, then instead of translating the right
; side of the let, we put a sentinel value (unused-proc-exp) in there.
; We can, of course, interpret the exercise as having to inline the procedure,
; but I don't want to go as far.
; The known environment
(define (empty-kenv)
'())
(define (apply-kenv kenv var)
(let ((pair (assoc var kenv)))
(if pair
(cadr pair)
(eopl:error 'apply-kenv "Unknown variable: ~a" var))))
(define (kenv-defines? kenv var)
(if (assoc var kenv)
#t
#f))
(define (extend-kenv kenv var value)
(cons (list var value)
kenv))
(define (kenv-names kenv)
(map car kenv))
The data type needs to be pulled up , because of ,
(define-datatype expression expression?
(const-exp
(num number?))
(diff-exp
(minuend expression?)
(subtrahend expression?))
(zero?-exp
(expr expression?))
(if-exp
(predicate expression?)
(consequent expression?)
(alternative expression?))
(var-exp
(var symbol?))
(let-exp
(var symbol?)
(value expression?)
(body expression?))
(proc-exp
(var symbol?)
(body expression?))
(call-exp
(rator expression?)
(rand expression?))
(nameless-var-exp
(num integer?))
(nameless-let-exp
(exp1 expression?)
(body expression?))
(nameless-proc-exp
(body expression?))
(known-proc-exp
(procedure expval?))
(known-proc-call-exp
(procedure expval?)
(argument expression?))
(unused-proc-exp))
(define-datatype expval expval?
(num-val
(num number?))
(bool-val
(bool boolean?))
(proc-val
(proc proc?)))
; Some functions to work with known environments
(define (construct-nenv senv kenv)
(map (curry apply-kenv kenv) senv))
(define (constant? expr kenv)
(null? (free-variables expr (kenv-names kenv))))
(define (eval-const expr senv kenv)
(value-of (translation-of expr senv (empty-kenv))
(construct-nenv senv kenv)))
(define (known-procedure-ref kenv expr)
(cases expression expr
(var-exp (name)
(let ((pair (assoc name kenv)))
(if pair
(cadr pair)
#f)))
(else #f)))
; The new code
(define (var-exp? expr)
(cases expression expr
(var-exp (name) #t)
(else #f)))
(define (proc-val? val)
(cases expval val
(proc-val (proc) #t)
(else #f)))
(define (procedure-safe-to-remove? body var kenv)
(and (kenv-defines? kenv var)
(proc-val? (apply-kenv kenv var))
(used-only-as-operator? body var)))
(define (used-only-as-operator? expr var)
(cases expression expr
(const-exp (num) #t)
(var-exp (name)
(not (eqv? var name)))
(diff-exp (minuend subtrahend)
(and (used-only-as-operator? minuend var)
(used-only-as-operator? subtrahend var)))
(zero?-exp (arg)
(used-only-as-operator? arg var))
(if-exp (predicate consequent alternative)
(and (used-only-as-operator? predicate var)
(used-only-as-operator? consequent var)
(used-only-as-operator? alternative var)))
(let-exp (let-name value-exp body)
(and (used-only-as-operator? value-exp var)
(or (eqv? let-name var)
(used-only-as-operator? value-exp var))))
(proc-exp (param body)
(or (eqv? param var)
(used-only-as-operator? body var)))
(call-exp (rator rand)
(and (or (var-exp? rator)
(used-only-as-operator? rator var))
(used-only-as-operator? rand var)))
(else (eopl:error 'used-only-as-operator? "Unexpected expression: ~a" expr))))
; The environment
(define environment? (or/c pair? null?))
(define (empty-senv)
'())
(define (extend-senv var senv)
(cons var senv))
(define (apply-senv senv var)
(cond ((null? senv) (eopl:error 'apply-senv "Unbound variable: ~a" var))
((eqv? var (car senv)) 0)
(else (+ 1 (apply-senv (cdr senv) var)))))
(define (nameless-environment? x)
((list-of expval?) x))
(define (empty-nameless-env)
'())
(define (extend-nameless-env val nameless-env)
(cons val nameless-env))
(define (apply-nameless-env nameless-env n)
(list-ref nameless-env n))
; The parser
(define scanner-spec
'((white-sp (whitespace) skip)
(comment ("%" (arbno (not #\newline))) skip)
(identifier (letter (arbno (or letter digit))) symbol)
(number (digit (arbno digit)) number)))
(define grammar
'((expression (number) const-exp)
(expression ("-" "(" expression "," expression ")") diff-exp)
(expression ("zero?" "(" expression ")") zero?-exp)
(expression ("if" expression "then" expression "else" expression) if-exp)
(expression (identifier) var-exp)
(expression ("proc" "(" identifier ")" expression) proc-exp)
(expression ("let" identifier "=" expression "in" expression) let-exp)
(expression ("(" expression expression ")") call-exp)))
(define scan&parse
(sllgen:make-string-parser scanner-spec grammar))
; The evaluator
(define-datatype proc proc?
(procedure
(body expression?)
(saved-nameless-env nameless-environment?)))
(define (apply-procedure proc1 val)
(cases proc proc1
(procedure (body saved-nameless-env)
(value-of body (extend-nameless-env val saved-nameless-env)))))
(define (expval->num val)
(cases expval val
(num-val (num) num)
(else (eopl:error 'expval->num "Invalid number: ~s" val))))
(define (expval->bool val)
(cases expval val
(bool-val (bool) bool)
(else (eopl:error 'expval->bool "Invalid boolean: ~s" val))))
(define (expval->proc val)
(cases expval val
(proc-val (proc) proc)
(else (eopl:error 'expval->proc "Invalid procedure: ~s" val))))
(define (translation-of expr senv kenv)
(cases expression expr
(const-exp (num) (const-exp num))
(diff-exp (minuend subtrahend)
(diff-exp
(translation-of minuend senv kenv)
(translation-of subtrahend senv kenv)))
(zero?-exp (arg)
(zero?-exp (translation-of arg senv kenv)))
(if-exp (predicate consequent alternative)
(if-exp
(translation-of predicate senv kenv)
(translation-of consequent senv kenv)
(translation-of alternative senv kenv)))
(var-exp (var)
(nameless-var-exp (apply-senv senv var)))
(let-exp (var value-exp body)
(if (constant? value-exp kenv)
(let* ((value (eval-const value-exp senv kenv))
(body-kenv (extend-kenv kenv var value))
(body-senv (extend-senv var senv)))
(nameless-let-exp
(if (procedure-safe-to-remove? body var body-kenv)
(unused-proc-exp)
(known-proc-exp value))
(translation-of body body-senv body-kenv)))
(nameless-let-exp
(translation-of value-exp senv kenv)
(translation-of body (extend-senv var senv) kenv))))
(proc-exp (var body)
(nameless-proc-exp
(translation-of body (extend-senv var senv) kenv)))
(call-exp (rator rand)
(let ((proc (known-procedure-ref kenv rator)))
(if proc
(known-proc-call-exp
proc
(translation-of rand senv kenv))
(call-exp
(translation-of rator senv kenv)
(translation-of rand senv kenv)))))
(else
(eopl:error 'translation-of "Cannot translate ~a" expr))))
(define (value-of expr nenv)
(cases expression expr
(const-exp (num) (num-val num))
(diff-exp (minuend subtrahend)
(let ((minuend-val (value-of minuend nenv))
(subtrahend-val (value-of subtrahend nenv)))
(let ((minuend-num (expval->num minuend-val))
(subtrahend-num (expval->num subtrahend-val)))
(num-val
(- minuend-num subtrahend-num)))))
(zero?-exp (arg)
(let ((value (value-of arg nenv)))
(let ((number (expval->num value)))
(if (zero? number)
(bool-val #t)
(bool-val #f)))))
(if-exp (predicate consequent alternative)
(let ((value (value-of predicate nenv)))
(if (expval->bool value)
(value-of consequent nenv)
(value-of alternative nenv))))
(call-exp (rator rand)
(let ((proc (expval->proc (value-of rator nenv)))
(arg (value-of rand nenv)))
(apply-procedure proc arg)))
(nameless-var-exp (n)
(apply-nameless-env nenv n))
(nameless-let-exp (value-exp body)
(let ((val (value-of value-exp nenv)))
(value-of body
(extend-nameless-env val nenv))))
(nameless-proc-exp (body)
(proc-val
(procedure body nenv)))
(known-proc-exp (proc)
proc)
(known-proc-call-exp (proc rand)
(apply-procedure (expval->proc proc)
(value-of rand nenv)))
(unused-proc-exp () 'unused-procedure)
(else
(eopl:error 'value-of "Cannot evaluate ~a" expr))))
; Free-variables
(define (free-variables expr bound)
(remove-duplicates
(let recur ((expr expr) (bound bound))
(cases expression expr
(const-exp (num) '())
(var-exp (var)
(if (memq var bound)
'()
(list var)))
(diff-exp (minuend subtrahend)
(append (recur minuend bound)
(recur subtrahend bound)))
(zero?-exp (arg)
(recur arg bound))
(if-exp (predicate consequent alternative)
(append (recur predicate bound)
(recur consequent bound)
(recur alternative bound)))
(let-exp (var value-exp body)
(append (recur value-exp bound)
(recur body (cons var bound))))
(proc-exp (var body)
(recur body (cons var bound)))
(call-exp (rator rand)
(append (recur rator bound)
(recur rand bound)))
(else
(eopl:error 'free-variables "Can't find variables in: ~a" expr))))))
| null | https://raw.githubusercontent.com/skanev/playground/d88e53a7f277b35041c2f709771a0b96f993b310/scheme/eopl/03/44.scm | scheme |
In the preceding example, the only use of f is as a known procedure.
Therefore the procedure built by the expression proc (y) -(y, x) is never
used. Modify the translator so that such a procedure is never constructred.
We base this on the previous exercise. We just need to modify how let treats
its value-exp. If value-exp is a procedure and the var is used only in
operator position within the let body, then instead of translating the right
side of the let, we put a sentinel value (unused-proc-exp) in there.
We can, of course, interpret the exercise as having to inline the procedure,
but I don't want to go as far.
The known environment
Some functions to work with known environments
The new code
The environment
The parser
The evaluator
Free-variables | EOPL exercise 3.44
(define (empty-kenv)
'())
(define (apply-kenv kenv var)
(let ((pair (assoc var kenv)))
(if pair
(cadr pair)
(eopl:error 'apply-kenv "Unknown variable: ~a" var))))
(define (kenv-defines? kenv var)
(if (assoc var kenv)
#t
#f))
(define (extend-kenv kenv var value)
(cons (list var value)
kenv))
(define (kenv-names kenv)
(map car kenv))
The data type needs to be pulled up , because of ,
(define-datatype expression expression?
(const-exp
(num number?))
(diff-exp
(minuend expression?)
(subtrahend expression?))
(zero?-exp
(expr expression?))
(if-exp
(predicate expression?)
(consequent expression?)
(alternative expression?))
(var-exp
(var symbol?))
(let-exp
(var symbol?)
(value expression?)
(body expression?))
(proc-exp
(var symbol?)
(body expression?))
(call-exp
(rator expression?)
(rand expression?))
(nameless-var-exp
(num integer?))
(nameless-let-exp
(exp1 expression?)
(body expression?))
(nameless-proc-exp
(body expression?))
(known-proc-exp
(procedure expval?))
(known-proc-call-exp
(procedure expval?)
(argument expression?))
(unused-proc-exp))
(define-datatype expval expval?
(num-val
(num number?))
(bool-val
(bool boolean?))
(proc-val
(proc proc?)))
(define (construct-nenv senv kenv)
(map (curry apply-kenv kenv) senv))
(define (constant? expr kenv)
(null? (free-variables expr (kenv-names kenv))))
(define (eval-const expr senv kenv)
(value-of (translation-of expr senv (empty-kenv))
(construct-nenv senv kenv)))
(define (known-procedure-ref kenv expr)
(cases expression expr
(var-exp (name)
(let ((pair (assoc name kenv)))
(if pair
(cadr pair)
#f)))
(else #f)))
(define (var-exp? expr)
(cases expression expr
(var-exp (name) #t)
(else #f)))
(define (proc-val? val)
(cases expval val
(proc-val (proc) #t)
(else #f)))
(define (procedure-safe-to-remove? body var kenv)
(and (kenv-defines? kenv var)
(proc-val? (apply-kenv kenv var))
(used-only-as-operator? body var)))
(define (used-only-as-operator? expr var)
(cases expression expr
(const-exp (num) #t)
(var-exp (name)
(not (eqv? var name)))
(diff-exp (minuend subtrahend)
(and (used-only-as-operator? minuend var)
(used-only-as-operator? subtrahend var)))
(zero?-exp (arg)
(used-only-as-operator? arg var))
(if-exp (predicate consequent alternative)
(and (used-only-as-operator? predicate var)
(used-only-as-operator? consequent var)
(used-only-as-operator? alternative var)))
(let-exp (let-name value-exp body)
(and (used-only-as-operator? value-exp var)
(or (eqv? let-name var)
(used-only-as-operator? value-exp var))))
(proc-exp (param body)
(or (eqv? param var)
(used-only-as-operator? body var)))
(call-exp (rator rand)
(and (or (var-exp? rator)
(used-only-as-operator? rator var))
(used-only-as-operator? rand var)))
(else (eopl:error 'used-only-as-operator? "Unexpected expression: ~a" expr))))
(define environment? (or/c pair? null?))
(define (empty-senv)
'())
(define (extend-senv var senv)
(cons var senv))
(define (apply-senv senv var)
(cond ((null? senv) (eopl:error 'apply-senv "Unbound variable: ~a" var))
((eqv? var (car senv)) 0)
(else (+ 1 (apply-senv (cdr senv) var)))))
(define (nameless-environment? x)
((list-of expval?) x))
(define (empty-nameless-env)
'())
(define (extend-nameless-env val nameless-env)
(cons val nameless-env))
(define (apply-nameless-env nameless-env n)
(list-ref nameless-env n))
(define scanner-spec
'((white-sp (whitespace) skip)
(comment ("%" (arbno (not #\newline))) skip)
(identifier (letter (arbno (or letter digit))) symbol)
(number (digit (arbno digit)) number)))
(define grammar
'((expression (number) const-exp)
(expression ("-" "(" expression "," expression ")") diff-exp)
(expression ("zero?" "(" expression ")") zero?-exp)
(expression ("if" expression "then" expression "else" expression) if-exp)
(expression (identifier) var-exp)
(expression ("proc" "(" identifier ")" expression) proc-exp)
(expression ("let" identifier "=" expression "in" expression) let-exp)
(expression ("(" expression expression ")") call-exp)))
(define scan&parse
(sllgen:make-string-parser scanner-spec grammar))
(define-datatype proc proc?
(procedure
(body expression?)
(saved-nameless-env nameless-environment?)))
(define (apply-procedure proc1 val)
(cases proc proc1
(procedure (body saved-nameless-env)
(value-of body (extend-nameless-env val saved-nameless-env)))))
(define (expval->num val)
(cases expval val
(num-val (num) num)
(else (eopl:error 'expval->num "Invalid number: ~s" val))))
(define (expval->bool val)
(cases expval val
(bool-val (bool) bool)
(else (eopl:error 'expval->bool "Invalid boolean: ~s" val))))
(define (expval->proc val)
(cases expval val
(proc-val (proc) proc)
(else (eopl:error 'expval->proc "Invalid procedure: ~s" val))))
(define (translation-of expr senv kenv)
(cases expression expr
(const-exp (num) (const-exp num))
(diff-exp (minuend subtrahend)
(diff-exp
(translation-of minuend senv kenv)
(translation-of subtrahend senv kenv)))
(zero?-exp (arg)
(zero?-exp (translation-of arg senv kenv)))
(if-exp (predicate consequent alternative)
(if-exp
(translation-of predicate senv kenv)
(translation-of consequent senv kenv)
(translation-of alternative senv kenv)))
(var-exp (var)
(nameless-var-exp (apply-senv senv var)))
(let-exp (var value-exp body)
(if (constant? value-exp kenv)
(let* ((value (eval-const value-exp senv kenv))
(body-kenv (extend-kenv kenv var value))
(body-senv (extend-senv var senv)))
(nameless-let-exp
(if (procedure-safe-to-remove? body var body-kenv)
(unused-proc-exp)
(known-proc-exp value))
(translation-of body body-senv body-kenv)))
(nameless-let-exp
(translation-of value-exp senv kenv)
(translation-of body (extend-senv var senv) kenv))))
(proc-exp (var body)
(nameless-proc-exp
(translation-of body (extend-senv var senv) kenv)))
(call-exp (rator rand)
(let ((proc (known-procedure-ref kenv rator)))
(if proc
(known-proc-call-exp
proc
(translation-of rand senv kenv))
(call-exp
(translation-of rator senv kenv)
(translation-of rand senv kenv)))))
(else
(eopl:error 'translation-of "Cannot translate ~a" expr))))
(define (value-of expr nenv)
(cases expression expr
(const-exp (num) (num-val num))
(diff-exp (minuend subtrahend)
(let ((minuend-val (value-of minuend nenv))
(subtrahend-val (value-of subtrahend nenv)))
(let ((minuend-num (expval->num minuend-val))
(subtrahend-num (expval->num subtrahend-val)))
(num-val
(- minuend-num subtrahend-num)))))
(zero?-exp (arg)
(let ((value (value-of arg nenv)))
(let ((number (expval->num value)))
(if (zero? number)
(bool-val #t)
(bool-val #f)))))
(if-exp (predicate consequent alternative)
(let ((value (value-of predicate nenv)))
(if (expval->bool value)
(value-of consequent nenv)
(value-of alternative nenv))))
(call-exp (rator rand)
(let ((proc (expval->proc (value-of rator nenv)))
(arg (value-of rand nenv)))
(apply-procedure proc arg)))
(nameless-var-exp (n)
(apply-nameless-env nenv n))
(nameless-let-exp (value-exp body)
(let ((val (value-of value-exp nenv)))
(value-of body
(extend-nameless-env val nenv))))
(nameless-proc-exp (body)
(proc-val
(procedure body nenv)))
(known-proc-exp (proc)
proc)
(known-proc-call-exp (proc rand)
(apply-procedure (expval->proc proc)
(value-of rand nenv)))
(unused-proc-exp () 'unused-procedure)
(else
(eopl:error 'value-of "Cannot evaluate ~a" expr))))
(define (free-variables expr bound)
(remove-duplicates
(let recur ((expr expr) (bound bound))
(cases expression expr
(const-exp (num) '())
(var-exp (var)
(if (memq var bound)
'()
(list var)))
(diff-exp (minuend subtrahend)
(append (recur minuend bound)
(recur subtrahend bound)))
(zero?-exp (arg)
(recur arg bound))
(if-exp (predicate consequent alternative)
(append (recur predicate bound)
(recur consequent bound)
(recur alternative bound)))
(let-exp (var value-exp body)
(append (recur value-exp bound)
(recur body (cons var bound))))
(proc-exp (var body)
(recur body (cons var bound)))
(call-exp (rator rand)
(append (recur rator bound)
(recur rand bound)))
(else
(eopl:error 'free-variables "Can't find variables in: ~a" expr))))))
|
615bbe7570f820f16ba0d9cfa46e6a6b1cbd5f6b2f027db5c5f31d06db74a6f6 | zadean/xqerl | xqerl_module.erl | Copyright ( c ) 2019 - 2020 .
SPDX - FileCopyrightText : 2022
%
SPDX - License - Identifier : Apache-2.0
-module(xqerl_module).
-include("xqerl_parser.hrl").
%% ====================================================================
%% API functions
%% ====================================================================
-export([
merge_library_trees/1,
expand_imports/1,
module_namespace/2
]).
%% ====================================================================
Internal functions
%% ====================================================================
%% When given a list of {Uri, #xqModule{}} tuples, follows imports for each
%% module and makes a list of all functions and variable asts in the modules
%% the original module depends on. If an imported module is not in the list
%% nothing is added. It is then assumed that the code is compiled already
%% This function is here to allow cyclic dependencies among modules.
Returns : [ { , ImportedAstList } ]
expand_imports(List) ->
F = fun
({Uri, #xqError{}}) ->
{Uri, {[], [], [], []}};
({Uri, Mod}) ->
I = collect_imports(Mod, List),
Fs = filter(I, 'xqFunctionDef', Uri),
Vs = filter(I, 'xqVar', Uri),
{Uri, {clear_id(Fs), function_sigs(Fs), clear_id(Vs), variable_sigs(Vs)}}
end,
lists:map(F, List).
module_namespace(
#xqModule{
type = library,
declaration = #xqModuleDecl{namespace = ModNs}
},
_Def
) ->
ModNs;
module_namespace(_, Def) ->
Def.
collect_imports(
#xqModule{
type = library,
declaration = #xqModuleDecl{namespace = ModNs},
prolog = Prolog
},
All
) ->
Imports = get_imported(Prolog),
collect_imports(Imports, All, [ModNs]).
collect_imports([ModNs | Imports], All, Acc) ->
case lists:member(ModNs, Acc) of
true ->
% already in the list
collect_imports(Imports, All, Acc);
false ->
% find imports for this mod and add to the Imports
Pro = get_module_prolog(ModNs, All),
Imps = get_imported(Pro),
collect_imports(Imps ++ Imports, All, [ModNs | Acc])
end;
collect_imports([], All, Acc) ->
F = fun(Ns) ->
Prolog = get_module_prolog(Ns, All),
Vars = filter(Prolog, 'xqVar'),
Funs = filter(Prolog, 'xqFunctionDef'),
Funs ++ Vars
end,
lists:flatmap(F, Acc).
get_imported(undefined) -> [];
get_imported(Prolog) -> lists:usort([Ns || #xqImport{uri = Ns} <- Prolog]).
get_module_prolog(Ns, All) ->
P = [
Prolog
|| {ModNs, #xqModule{
type = library,
declaration = #xqModuleDecl{namespace = ModNs},
prolog = Prolog
}} <-
All,
ModNs == Ns
],
lists:flatten(P).
clear_id([#xqFunctionDef{} = H | T]) ->
[H#xqFunctionDef{id = 0} | clear_id(T)];
clear_id([#xqVar{} = H | T]) ->
[H#xqVar{id = 0} | clear_id(T)];
clear_id([]) ->
[].
merges library ASTs from the same target namespace into one module
merge_library_trees([Mod]) ->
Mod;
merge_library_trees([
#xqModule{
type = library,
declaration = #xqModuleDecl{namespace = ModNs, prefix = ModPxA},
prolog = PrologA
} = ModA,
#xqModule{
type = library,
declaration = #xqModuleDecl{namespace = ModNs, prefix = ModPxB},
prolog = PrologB
}
| Mods
]) ->
{PrologA1, PrologA2} = xqerl_static:prolog_order(PrologA),
{PrologB1, PrologB2} = xqerl_static:prolog_order(PrologB),
Prolog1 = unique_prolog_1(PrologA1, PrologB1),
Prolog2 = unique_prolog_2(PrologA2, PrologB2),
Prolog11 = patch_imports(Prolog1, ModNs),
Prolog12 =
case ModPxA == ModPxB of
true ->
Prolog11;
false ->
N = #xqNamespaceDecl{uri = ModNs, prefix = ModPxB},
[N | without(N, Prolog11)]
end,
NewA = ModA#xqModule{prolog = Prolog12 ++ Prolog2},
merge_library_trees([NewA | Mods]).
% if self is imported change it to namespace declaration unless already there.
patch_imports(Prolog, ModNs) ->
Self = [
#xqNamespaceDecl{uri = Ns, prefix = Px}
|| #xqImport{kind = module, uri = Ns, prefix = Px} <- Prolog,
Ns == ModNs
],
Flt = fun
(#xqImport{kind = module, uri = Ns}) when Ns == ModNs ->
false;
(_) ->
true
end,
case Self of
[] -> Prolog;
_ -> Self ++ lists:filter(Flt, Prolog)
end.
filter([E | T], Atom) when is_tuple(E), element(1, E) == Atom ->
[E | filter(T, Atom)];
filter([_ | T], Atom) ->
filter(T, Atom);
filter([], _) ->
[].
filter([#xqFunctionDef{name = #xqQName{namespace = Ns0}} = E | T], 'xqFunctionDef', Ns) when
Ns0 =/= Ns
->
[E | filter(T, 'xqFunctionDef', Ns)];
filter([#xqVar{name = #xqQName{namespace = Ns0}} = E | T], 'xqVar', Ns) when Ns0 =/= Ns ->
[E | filter(T, 'xqVar', Ns)];
filter([_ | T], Atom, Ns) ->
filter(T, Atom, Ns);
filter([], _, _) ->
[].
function_sigs(Functions) ->
ModName = xqerl_static : string_atom(ModNs ) ,
Specs = [
{
Name#xqQName{prefix = <<>>},
Type,
Annos,
begin
{F, A} = xqerl_static:function_hash_name(Name, Arity),
{xqerl_static:string_atom(Name#xqQName.namespace), F, A}
end,
Arity,
param_types(Params)
}
|| %id = Id,
#xqFunctionDef{
annotations = Annos,
arity = Arity,
params = Params,
name = Name,
type = Type
} <- Functions,
not_private(Annos)
],
Specs.
{ Name , Type , Annos , function_name , External }
variable_sigs(Variables) ->
[
{
Name#xqQName{prefix = <<>>},
Type,
Annos,
{
xqerl_static:string_atom(Name#xqQName.namespace),
xqerl_static:variable_hash_name(Name)
},
External
}
|| #xqVar{
annotations = Annos,
name = Name,
external = External,
type = Type
} <- Variables
].
not_private(Annos) ->
[
ok
|| #xqAnnotation{
name = #xqQName{
namespace = <<"">>,
local_name = <<"private">>
}
} <- Annos
] == [].
param_types(Params) ->
[T || #xqVar{type = T} <- Params].
unique_prolog_1(PrologA1, PrologB1) ->
F = fun(A, Acc) ->
without(A, Acc)
end,
Without = lists:foldl(F, PrologB1, PrologA1),
PrologA1 ++ Without.
unique_prolog_2(PrologA2, PrologB2) ->
F = fun
(#xqVar{}, Acc) -> Acc;
(#xqFunctionDef{}, Acc) -> Acc;
(A, Acc) -> without(A, Acc)
end,
Without = lists:foldl(F, PrologB2, PrologA2),
PrologA2 ++ Without.
without(
#xqOptionDecl{name = #xqQName{namespace = N, local_name = L}} = A,
[#xqOptionDecl{name = #xqQName{namespace = N, local_name = L}} | T]
) ->
without(A, T);
without(
#xqContextItemDecl{type = Y} = A,
[#xqContextItemDecl{type = Y} | T]
) ->
without(A, T);
without(
#xqDefaultNamespaceDecl{kind = K, uri = U} = A,
[#xqDefaultNamespaceDecl{kind = K, uri = U} | T]
) ->
without(A, T);
without(
#xqDecimalFormatDecl{name = #xqQName{namespace = N, local_name = L}} = A,
[#xqDecimalFormatDecl{name = #xqQName{namespace = N, local_name = L}} | T]
) ->
without(A, T);
without(
#xqCopyNamespacesDecl{inh = I, pre = P} = A,
[#xqCopyNamespacesDecl{inh = I, pre = P} | T]
) ->
without(A, T);
without(
#xqEmptyOrderDecl{mode = M} = A,
[#xqEmptyOrderDecl{mode = M} | T]
) ->
without(A, T);
without(
#xqOrderingModeDecl{mode = M} = A,
[#xqOrderingModeDecl{mode = M} | T]
) ->
without(A, T);
without(
#xqConstructionDecl{mode = M} = A,
[#xqConstructionDecl{mode = M} | T]
) ->
without(A, T);
without(
#xqBaseURIDecl{uri = U} = A,
[#xqBaseURIDecl{uri = U} | T]
) ->
without(A, T);
without(
#xqDefaultCollationDecl{uri = U} = A,
[#xqDefaultCollationDecl{uri = U} | T]
) ->
without(A, T);
without(
#xqBoundarySpaceDecl{mode = M} = A,
[#xqBoundarySpaceDecl{mode = M} | T]
) ->
without(A, T);
without(
#xqRevalidationDecl{kind = K} = A,
[#xqRevalidationDecl{kind = K} | T]
) ->
without(A, T);
without(
#xqNamespaceDecl{uri = U, prefix = P} = A,
[#xqNamespaceDecl{uri = U, prefix = P} | T]
) ->
without(A, T);
without(
#xqImport{kind = K, uri = U, prefix = P} = A,
[#xqImport{kind = K, uri = U, prefix = P} | T]
) ->
without(A, T);
without(A, [H | T]) ->
[H | without(A, T)];
without(_, []) ->
[].
| null | https://raw.githubusercontent.com/zadean/xqerl/06c651ec832d0ac2b77bef92c1b4ab14d8da8883/src/xqerl_module.erl | erlang |
====================================================================
API functions
====================================================================
====================================================================
====================================================================
When given a list of {Uri, #xqModule{}} tuples, follows imports for each
module and makes a list of all functions and variable asts in the modules
the original module depends on. If an imported module is not in the list
nothing is added. It is then assumed that the code is compiled already
This function is here to allow cyclic dependencies among modules.
already in the list
find imports for this mod and add to the Imports
if self is imported change it to namespace declaration unless already there.
id = Id, | Copyright ( c ) 2019 - 2020 .
SPDX - FileCopyrightText : 2022
SPDX - License - Identifier : Apache-2.0
-module(xqerl_module).
-include("xqerl_parser.hrl").
-export([
merge_library_trees/1,
expand_imports/1,
module_namespace/2
]).
Internal functions
Returns : [ { , ImportedAstList } ]
expand_imports(List) ->
F = fun
({Uri, #xqError{}}) ->
{Uri, {[], [], [], []}};
({Uri, Mod}) ->
I = collect_imports(Mod, List),
Fs = filter(I, 'xqFunctionDef', Uri),
Vs = filter(I, 'xqVar', Uri),
{Uri, {clear_id(Fs), function_sigs(Fs), clear_id(Vs), variable_sigs(Vs)}}
end,
lists:map(F, List).
module_namespace(
#xqModule{
type = library,
declaration = #xqModuleDecl{namespace = ModNs}
},
_Def
) ->
ModNs;
module_namespace(_, Def) ->
Def.
collect_imports(
#xqModule{
type = library,
declaration = #xqModuleDecl{namespace = ModNs},
prolog = Prolog
},
All
) ->
Imports = get_imported(Prolog),
collect_imports(Imports, All, [ModNs]).
collect_imports([ModNs | Imports], All, Acc) ->
case lists:member(ModNs, Acc) of
true ->
collect_imports(Imports, All, Acc);
false ->
Pro = get_module_prolog(ModNs, All),
Imps = get_imported(Pro),
collect_imports(Imps ++ Imports, All, [ModNs | Acc])
end;
collect_imports([], All, Acc) ->
F = fun(Ns) ->
Prolog = get_module_prolog(Ns, All),
Vars = filter(Prolog, 'xqVar'),
Funs = filter(Prolog, 'xqFunctionDef'),
Funs ++ Vars
end,
lists:flatmap(F, Acc).
get_imported(undefined) -> [];
get_imported(Prolog) -> lists:usort([Ns || #xqImport{uri = Ns} <- Prolog]).
get_module_prolog(Ns, All) ->
P = [
Prolog
|| {ModNs, #xqModule{
type = library,
declaration = #xqModuleDecl{namespace = ModNs},
prolog = Prolog
}} <-
All,
ModNs == Ns
],
lists:flatten(P).
clear_id([#xqFunctionDef{} = H | T]) ->
[H#xqFunctionDef{id = 0} | clear_id(T)];
clear_id([#xqVar{} = H | T]) ->
[H#xqVar{id = 0} | clear_id(T)];
clear_id([]) ->
[].
merges library ASTs from the same target namespace into one module
merge_library_trees([Mod]) ->
Mod;
merge_library_trees([
#xqModule{
type = library,
declaration = #xqModuleDecl{namespace = ModNs, prefix = ModPxA},
prolog = PrologA
} = ModA,
#xqModule{
type = library,
declaration = #xqModuleDecl{namespace = ModNs, prefix = ModPxB},
prolog = PrologB
}
| Mods
]) ->
{PrologA1, PrologA2} = xqerl_static:prolog_order(PrologA),
{PrologB1, PrologB2} = xqerl_static:prolog_order(PrologB),
Prolog1 = unique_prolog_1(PrologA1, PrologB1),
Prolog2 = unique_prolog_2(PrologA2, PrologB2),
Prolog11 = patch_imports(Prolog1, ModNs),
Prolog12 =
case ModPxA == ModPxB of
true ->
Prolog11;
false ->
N = #xqNamespaceDecl{uri = ModNs, prefix = ModPxB},
[N | without(N, Prolog11)]
end,
NewA = ModA#xqModule{prolog = Prolog12 ++ Prolog2},
merge_library_trees([NewA | Mods]).
patch_imports(Prolog, ModNs) ->
Self = [
#xqNamespaceDecl{uri = Ns, prefix = Px}
|| #xqImport{kind = module, uri = Ns, prefix = Px} <- Prolog,
Ns == ModNs
],
Flt = fun
(#xqImport{kind = module, uri = Ns}) when Ns == ModNs ->
false;
(_) ->
true
end,
case Self of
[] -> Prolog;
_ -> Self ++ lists:filter(Flt, Prolog)
end.
filter([E | T], Atom) when is_tuple(E), element(1, E) == Atom ->
[E | filter(T, Atom)];
filter([_ | T], Atom) ->
filter(T, Atom);
filter([], _) ->
[].
filter([#xqFunctionDef{name = #xqQName{namespace = Ns0}} = E | T], 'xqFunctionDef', Ns) when
Ns0 =/= Ns
->
[E | filter(T, 'xqFunctionDef', Ns)];
filter([#xqVar{name = #xqQName{namespace = Ns0}} = E | T], 'xqVar', Ns) when Ns0 =/= Ns ->
[E | filter(T, 'xqVar', Ns)];
filter([_ | T], Atom, Ns) ->
filter(T, Atom, Ns);
filter([], _, _) ->
[].
function_sigs(Functions) ->
ModName = xqerl_static : string_atom(ModNs ) ,
Specs = [
{
Name#xqQName{prefix = <<>>},
Type,
Annos,
begin
{F, A} = xqerl_static:function_hash_name(Name, Arity),
{xqerl_static:string_atom(Name#xqQName.namespace), F, A}
end,
Arity,
param_types(Params)
}
#xqFunctionDef{
annotations = Annos,
arity = Arity,
params = Params,
name = Name,
type = Type
} <- Functions,
not_private(Annos)
],
Specs.
{ Name , Type , Annos , function_name , External }
variable_sigs(Variables) ->
[
{
Name#xqQName{prefix = <<>>},
Type,
Annos,
{
xqerl_static:string_atom(Name#xqQName.namespace),
xqerl_static:variable_hash_name(Name)
},
External
}
|| #xqVar{
annotations = Annos,
name = Name,
external = External,
type = Type
} <- Variables
].
not_private(Annos) ->
[
ok
|| #xqAnnotation{
name = #xqQName{
namespace = <<"">>,
local_name = <<"private">>
}
} <- Annos
] == [].
param_types(Params) ->
[T || #xqVar{type = T} <- Params].
unique_prolog_1(PrologA1, PrologB1) ->
F = fun(A, Acc) ->
without(A, Acc)
end,
Without = lists:foldl(F, PrologB1, PrologA1),
PrologA1 ++ Without.
unique_prolog_2(PrologA2, PrologB2) ->
F = fun
(#xqVar{}, Acc) -> Acc;
(#xqFunctionDef{}, Acc) -> Acc;
(A, Acc) -> without(A, Acc)
end,
Without = lists:foldl(F, PrologB2, PrologA2),
PrologA2 ++ Without.
without(
#xqOptionDecl{name = #xqQName{namespace = N, local_name = L}} = A,
[#xqOptionDecl{name = #xqQName{namespace = N, local_name = L}} | T]
) ->
without(A, T);
without(
#xqContextItemDecl{type = Y} = A,
[#xqContextItemDecl{type = Y} | T]
) ->
without(A, T);
without(
#xqDefaultNamespaceDecl{kind = K, uri = U} = A,
[#xqDefaultNamespaceDecl{kind = K, uri = U} | T]
) ->
without(A, T);
without(
#xqDecimalFormatDecl{name = #xqQName{namespace = N, local_name = L}} = A,
[#xqDecimalFormatDecl{name = #xqQName{namespace = N, local_name = L}} | T]
) ->
without(A, T);
without(
#xqCopyNamespacesDecl{inh = I, pre = P} = A,
[#xqCopyNamespacesDecl{inh = I, pre = P} | T]
) ->
without(A, T);
without(
#xqEmptyOrderDecl{mode = M} = A,
[#xqEmptyOrderDecl{mode = M} | T]
) ->
without(A, T);
without(
#xqOrderingModeDecl{mode = M} = A,
[#xqOrderingModeDecl{mode = M} | T]
) ->
without(A, T);
without(
#xqConstructionDecl{mode = M} = A,
[#xqConstructionDecl{mode = M} | T]
) ->
without(A, T);
without(
#xqBaseURIDecl{uri = U} = A,
[#xqBaseURIDecl{uri = U} | T]
) ->
without(A, T);
without(
#xqDefaultCollationDecl{uri = U} = A,
[#xqDefaultCollationDecl{uri = U} | T]
) ->
without(A, T);
without(
#xqBoundarySpaceDecl{mode = M} = A,
[#xqBoundarySpaceDecl{mode = M} | T]
) ->
without(A, T);
without(
#xqRevalidationDecl{kind = K} = A,
[#xqRevalidationDecl{kind = K} | T]
) ->
without(A, T);
without(
#xqNamespaceDecl{uri = U, prefix = P} = A,
[#xqNamespaceDecl{uri = U, prefix = P} | T]
) ->
without(A, T);
without(
#xqImport{kind = K, uri = U, prefix = P} = A,
[#xqImport{kind = K, uri = U, prefix = P} | T]
) ->
without(A, T);
without(A, [H | T]) ->
[H | without(A, T)];
without(_, []) ->
[].
|
dd09456e0905d04a5743d9f901f2d79329d2417ac38edb7f0bb2a14850df73c2 | ympbyc/Carrot | Compiler.scm | S - expression to SECD instruction Compiler ; ; ; ;
2012 Minori Yamashita < > ; ; add your name here
;;;
;;; reference:
;;;
;;;
(load "./SECD.scm")
;;; Helpers ;;;
(define (atom? x)
(cond
[(string? x) #t]
[(number? x) #t]
[(boolean? x) #t]
[(char? x) #t]
[else #f]))
;;uncurry function applications
(define (complis exp code)
(if (null? exp)
code
(compile- `(delay ,(car exp)) (complis (cdr exp) code))))
;;stack all the arguments to the primitive procedure
;;and apply the procedure
(define (primitive-compile args prim)
(if (null? args)
prim
(compile- (car args) (primitive-compile (cdr args) prim))))
;;compile :: Lisp -> SECD
(define (compile program)
(fold-right compile- `((,stop)) program))
;;compile- :: Lisp -> code -> code
(define (compile- exp code)
;(print (format "exp : ~S" exp))
;(print (format "code: ~S" code))
;(newline)
(cond
[(atom? exp)
;;(stack-constant const)
(cons `(,stack-constant ,exp) code)]
[(symbol? exp)
;;(ref-arg symbol) (thaw)
(cons `(,ref-arg ,exp) (cons `(,thaw) code))]
[(eq? (car exp) 'quote)
;;(stack-constant symbol)
(cons `(,stack-constant ,(cadr exp)) code)]
[(eq? (car exp) '**)
;; call primitive procedures
(append (primitive-compile (cddr exp) `((,primitive ,(cadr exp)))) code)]
[(eq? (car exp) ':=)
;;(:= (foo bar baz) (bar baz))
;;bound (def symbol)
(if (< (length (cadr exp)) 2)
(compile- `(delay ,(caddr exp)) (cons `(,def ,(caadr exp)) code)) ;no param
(compile- `(delay (-> ,(cdadr exp) ,(caddr exp))) (cons `(,def ,(caadr exp)) code)))]
[(eq? (car exp) '->)
;;(-> (x y z) (x y z)) = (-> (x) (-> (y) (-> (z) (x y z)))) ;auto-currying
;;(stack-closure symbol ((code) (restore)))
(let ((params (cadr exp))
(body (caddr exp)))
(if (null? (cdr params))
(cons `(,stack-closure ,(car params) ,(compile- body `((,restore)))) code)
(cons `(,stack-closure ,(car params) ,(compile- `(-> ,(cdr params) ,body) `((,restore)))) code)))]
[(eq? (car exp) 'delay)
;;(freeze ((code) (restore)))
(cons `(,freeze ,(compile- (cadr exp) `((,restore)))) code)]
[else
( foo 1 2 3 ) = ( ( ( foo 1 ) 2 ) 3 )
;;arg arg ... closure (app) (app) ...
(complis (reverse (cdr exp))
(compile-
(car exp)
(append (map (lambda (arg) `(,app)) (cdr exp)) code)))
]))
| null | https://raw.githubusercontent.com/ympbyc/Carrot/5ce3969b3833bcf1b466d808a74d0a03653ef6ab/old/Compiler.scm | scheme | ; ; ;
; add your name here
reference:
Helpers ;;;
uncurry function applications
stack all the arguments to the primitive procedure
and apply the procedure
compile :: Lisp -> SECD
compile- :: Lisp -> code -> code
(print (format "exp : ~S" exp))
(print (format "code: ~S" code))
(newline)
(stack-constant const)
(ref-arg symbol) (thaw)
(stack-constant symbol)
call primitive procedures
(:= (foo bar baz) (bar baz))
bound (def symbol)
no param
(-> (x y z) (x y z)) = (-> (x) (-> (y) (-> (z) (x y z)))) ;auto-currying
(stack-closure symbol ((code) (restore)))
(freeze ((code) (restore)))
arg arg ... closure (app) (app) ... |
(load "./SECD.scm")
(define (atom? x)
(cond
[(string? x) #t]
[(number? x) #t]
[(boolean? x) #t]
[(char? x) #t]
[else #f]))
(define (complis exp code)
(if (null? exp)
code
(compile- `(delay ,(car exp)) (complis (cdr exp) code))))
(define (primitive-compile args prim)
(if (null? args)
prim
(compile- (car args) (primitive-compile (cdr args) prim))))
(define (compile program)
(fold-right compile- `((,stop)) program))
(define (compile- exp code)
(cond
[(atom? exp)
(cons `(,stack-constant ,exp) code)]
[(symbol? exp)
(cons `(,ref-arg ,exp) (cons `(,thaw) code))]
[(eq? (car exp) 'quote)
(cons `(,stack-constant ,(cadr exp)) code)]
[(eq? (car exp) '**)
(append (primitive-compile (cddr exp) `((,primitive ,(cadr exp)))) code)]
[(eq? (car exp) ':=)
(if (< (length (cadr exp)) 2)
(compile- `(delay (-> ,(cdadr exp) ,(caddr exp))) (cons `(,def ,(caadr exp)) code)))]
[(eq? (car exp) '->)
(let ((params (cadr exp))
(body (caddr exp)))
(if (null? (cdr params))
(cons `(,stack-closure ,(car params) ,(compile- body `((,restore)))) code)
(cons `(,stack-closure ,(car params) ,(compile- `(-> ,(cdr params) ,body) `((,restore)))) code)))]
[(eq? (car exp) 'delay)
(cons `(,freeze ,(compile- (cadr exp) `((,restore)))) code)]
[else
( foo 1 2 3 ) = ( ( ( foo 1 ) 2 ) 3 )
(complis (reverse (cdr exp))
(compile-
(car exp)
(append (map (lambda (arg) `(,app)) (cdr exp)) code)))
]))
|
740a704e815ec94ba431f6e46978e061f02926e9c568f0a4d23b95f06011b454 | HIPERFIT/accelerate-opencl | Fold_Test.hs | module Fold_Test (tests) where
import Data.Array.Accelerate (Acc, Exp, Elt, Z(..), (:.)(..))
import qualified Data.Array.Accelerate as Acc
import qualified Data.Array.Accelerate.Smart as Acc
import qualified Data.Array.Accelerate.OpenCL as Acc
import Test.Framework (testGroup)
import Test.Framework.Providers.QuickCheck2 (testProperty)
import Test.QuickCheck
-- Convert seconds to milliseconds
seconds n = n * 1000000
milliseconds n = n * 1000
-- Make problems larger, and limit the time used on solving each problem
scale :: Testable a => a -> Property
scale = within (milliseconds 400) . mapSize (*10) . property
tests = testGroup "fold"
[
testProperty "fold sum, empty list" test_fold_nil_tuple
, testProperty "fold sum, empty list" test_fold_nil
, testProperty "fold sum, Int" (scale test_fold_sum)
, testProperty "fold sum, (Int, Int)" (scale test_fold_sumTuple)
, testProperty "fold1 sum, Int" (scale test_fold1_sum)
, testProperty "fold1 sum, (Int, Int)" (scale test_fold1_sumTuple)
]
-- Simultaneous addition of tuples
add_simple (x1, y1) (x2, y2) = (x1 + x2, y1 + y2)
add :: Exp (Int, Int) -> Exp (Int, Int) -> Exp (Int, Int)
add x y = let (x1, y1) = Acc.unlift x :: (Exp Int, Exp Int)
(x2, y2) = Acc.unlift y :: (Exp Int, Exp Int)
in Acc.lift ( x1 + x2, y1 + y2)
fold1 tests --
test_fold1_sum :: [Int] -> Bool
test_fold1_sum = test_fold1 (+) (+)
test_fold1_sumTuple :: [(Int, Int)] -> Bool
test_fold1_sumTuple = test_fold1 add_simple add
-- fold tests --
-- We do not want to test whether fold on empty list here
test_fold_sum :: Int -> [Int] -> Property
test_fold_sum x xs = (not $ null xs) ==> test_fold (+) (+) x xs
test_fold_sumTuple :: (Int, Int) -> [(Int, Int)] -> Property
test_fold_sumTuple x xs = (not $ null xs) ==> test_fold add_simple add x xs
-- Tests the empty list case
test_fold_nil :: Property
test_fold_nil =
mapSize (const 1) $ test_fold (+) (+) (0 :: Int) []
test_fold_nil_tuple :: Property
test_fold_nil_tuple =
mapSize (const 1) $ test_fold add_simple add ((0,0) :: (Int, Int)) []
Generic test functions
-- | Generic fold1 test
--
-- Supply it with a regular function and an Accelerate function that
-- performs the same operations, to create a QuickCheckable property
test_fold1 :: (Eq a, Elt a)
=> (a -> a -> a) -> (Exp a -> Exp a -> Exp a) -> [a] -> Bool
foldl1 errors on empty list
test_fold1 f f_acc xs = Prelude.foldl1 f xs == (head . Acc.toList $ Acc.run (doFold vector))
where
doFold = Acc.fold1 f_acc . Acc.use
vector = Acc.fromList (Z :. length xs) xs
-- | Generic fold test
--
-- Supply it with a regular function and an Accelerate function that
-- performs the same operations, to create a QuickCheckable property
test_fold :: (Eq a, Elt a)
=> (a -> a -> a) -> (Exp a -> Exp a -> Exp a) -> a -> [a] -> Bool
test_fold f f_acc x xs = Prelude.foldl f x xs == (head . Acc.toList $ Acc.run (doFold vector))
where
doFold = Acc.fold f_acc (Acc.constant x) . Acc.use
vector = Acc.fromList (Z :. length xs) xs
| null | https://raw.githubusercontent.com/HIPERFIT/accelerate-opencl/7ec05ba9d4d5461ffcf952bed6d0dcc4b1915099/tests/unit/Fold_Test.hs | haskell | Convert seconds to milliseconds
Make problems larger, and limit the time used on solving each problem
Simultaneous addition of tuples
fold tests --
We do not want to test whether fold on empty list here
Tests the empty list case
| Generic fold1 test
Supply it with a regular function and an Accelerate function that
performs the same operations, to create a QuickCheckable property
| Generic fold test
Supply it with a regular function and an Accelerate function that
performs the same operations, to create a QuickCheckable property | module Fold_Test (tests) where
import Data.Array.Accelerate (Acc, Exp, Elt, Z(..), (:.)(..))
import qualified Data.Array.Accelerate as Acc
import qualified Data.Array.Accelerate.Smart as Acc
import qualified Data.Array.Accelerate.OpenCL as Acc
import Test.Framework (testGroup)
import Test.Framework.Providers.QuickCheck2 (testProperty)
import Test.QuickCheck
seconds n = n * 1000000
milliseconds n = n * 1000
scale :: Testable a => a -> Property
scale = within (milliseconds 400) . mapSize (*10) . property
tests = testGroup "fold"
[
testProperty "fold sum, empty list" test_fold_nil_tuple
, testProperty "fold sum, empty list" test_fold_nil
, testProperty "fold sum, Int" (scale test_fold_sum)
, testProperty "fold sum, (Int, Int)" (scale test_fold_sumTuple)
, testProperty "fold1 sum, Int" (scale test_fold1_sum)
, testProperty "fold1 sum, (Int, Int)" (scale test_fold1_sumTuple)
]
add_simple (x1, y1) (x2, y2) = (x1 + x2, y1 + y2)
add :: Exp (Int, Int) -> Exp (Int, Int) -> Exp (Int, Int)
add x y = let (x1, y1) = Acc.unlift x :: (Exp Int, Exp Int)
(x2, y2) = Acc.unlift y :: (Exp Int, Exp Int)
in Acc.lift ( x1 + x2, y1 + y2)
test_fold1_sum :: [Int] -> Bool
test_fold1_sum = test_fold1 (+) (+)
test_fold1_sumTuple :: [(Int, Int)] -> Bool
test_fold1_sumTuple = test_fold1 add_simple add
test_fold_sum :: Int -> [Int] -> Property
test_fold_sum x xs = (not $ null xs) ==> test_fold (+) (+) x xs
test_fold_sumTuple :: (Int, Int) -> [(Int, Int)] -> Property
test_fold_sumTuple x xs = (not $ null xs) ==> test_fold add_simple add x xs
test_fold_nil :: Property
test_fold_nil =
mapSize (const 1) $ test_fold (+) (+) (0 :: Int) []
test_fold_nil_tuple :: Property
test_fold_nil_tuple =
mapSize (const 1) $ test_fold add_simple add ((0,0) :: (Int, Int)) []
Generic test functions
test_fold1 :: (Eq a, Elt a)
=> (a -> a -> a) -> (Exp a -> Exp a -> Exp a) -> [a] -> Bool
foldl1 errors on empty list
test_fold1 f f_acc xs = Prelude.foldl1 f xs == (head . Acc.toList $ Acc.run (doFold vector))
where
doFold = Acc.fold1 f_acc . Acc.use
vector = Acc.fromList (Z :. length xs) xs
test_fold :: (Eq a, Elt a)
=> (a -> a -> a) -> (Exp a -> Exp a -> Exp a) -> a -> [a] -> Bool
test_fold f f_acc x xs = Prelude.foldl f x xs == (head . Acc.toList $ Acc.run (doFold vector))
where
doFold = Acc.fold f_acc (Acc.constant x) . Acc.use
vector = Acc.fromList (Z :. length xs) xs
|
9f70ec64fabe1cccf4deedd7c2662f0b20c5088c1772ab23adaa3fc45a34c410 | gildor478/ocaml-gettext | bench.ml | (**************************************************************************)
(* ocaml-gettext: a library to translate messages *)
(* *)
Copyright ( C ) 2003 - 2008 < >
(* *)
(* This library is free software; you can redistribute it and/or *)
(* modify it under the terms of the GNU Lesser General Public *)
License as published by the Free Software Foundation ; either
version 2.1 of the License , or ( at your option ) any later version ;
(* 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 *)
(* Lesser General Public License for more details. *)
(* *)
You should have received a copy of the GNU Lesser General Public
License along with this library ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307
USA
(**************************************************************************)
open Benchmark
open Common
open GettextTypes
type benchs = { verbose : bool; search_path : string list; time : int }
(* Different implementation of realize. *)
let realize_data =
[
("Camomile.Map", GettextCamomile.Map.realize);
("Camomile.Hashtbl", GettextCamomile.Hashtbl.realize);
("Camomile.Open", GettextCamomile.Open.realize);
("Stub.Native", GettextStub.Native.realize);
("Stub.Preload", GettextStub.Preload.realize);
]
let parse_arg () =
let benchs = ref { verbose = false; search_path = []; time = 1 } in
Arg.parse
(Arg.align
[
( "--search",
Arg.String
(fun dir ->
benchs :=
{ !benchs with search_path = dir :: !benchs.search_path }),
"dir Search the specified directory for MO file." );
( "--verbose",
Arg.Unit (fun () -> benchs := { !benchs with verbose = true }),
"Processs with a lot of message." );
( "--time",
Arg.Int (fun sec -> benchs := { !benchs with time = sec }),
Printf.sprintf
"second Process each test during the specified number of second. \
Default : %d."
!benchs.time );
])
(fun _str -> ())
( "Benchmark utility for ocaml-gettext v" ^ GettextConfig.version
^ " by Sylvain Le Gall\n"
^ "Copyright (C) 2004-2008 Sylvain Le Gall <>\n"
^ "Licensed under LGPL v2.1 with Ocaml exception." );
!benchs
let print_debug benchs str =
if benchs.verbose then (
print_string str;
print_newline () )
else ()
let make_buffer lst = (lst, [])
let get_buffer (lst1, lst2) =
match (lst1, lst2) with
| hd :: tl, lst2 -> (hd, (tl, hd :: lst2))
| [], hd :: tl -> (hd, (tl, [ hd ]))
| [], [] -> failwith "Buffer is empty"
Generic function to benchmark gettextCompat function
let gettext_bench benchs str_gettext fun_gettext =
let f ref_translations =
let (debug_str, t', textdomain, tr), buffer =
get_buffer !ref_translations
in
print_debug benchs
(Printf.sprintf "Translation of %S from %s" (string_of_translation tr)
debug_str);
ignore (fun_gettext t' textdomain tr);
ref_translations := buffer
in
let parameters_lst = List.map parameters_of_filename mo_files_data in
let create_translation (str_realize, realize) =
let rec create_one_translation accu lst =
match lst with
| parameters :: tl ->
let t = t_of_parameters parameters in
let t' = realize t in
let new_accu =
List.fold_left
(fun lst tr ->
( str_realize ^ " with textdomain " ^ parameters.textdomain,
t',
parameters.textdomain,
tr )
:: lst)
accu parameters.translations
in
create_one_translation new_accu tl
| [] -> make_buffer accu
in
ref (create_one_translation [] parameters_lst)
in
let bench_lst =
List.map
(fun (str_realize, realize) ->
(str_realize, f, create_translation (str_realize, realize)))
realize_data
in
print_debug benchs ("Benchmarking " ^ str_gettext ^ ":");
(str_gettext ^ " benchmark", throughputN benchs.time bench_lst)
(*******************************)
(* Performance of check_format *)
(*******************************)
let format_bench benchs =
let f ref_buffer =
let elem, buffer = get_buffer !ref_buffer in
let translation =
print_debug benchs ("Checking format of : " ^ string_of_translation elem);
GettextFormat.check_format Ignore elem
in
print_debug benchs
("Result of the check : " ^ string_of_translation translation);
ref_buffer := buffer
in
print_debug benchs "Benchmarking format :";
( "Format benchmark",
throughputN benchs.time
[
("Singular", f, ref (make_buffer format_translation_singular_data));
("Plural", f, ref (make_buffer format_translation_plural_data));
("All", f, ref (make_buffer format_translation_all_data));
] )
(***************************)
(* Performance of realize *)
(***************************)
let realize_bench benchs =
let f (realize, parameters_lst) =
let f_one parameters =
let t =
print_debug benchs ("Creating t for " ^ parameters.fl_mo);
t_of_parameters parameters
in
print_debug benchs ("Realizing t for " ^ parameters.fl_mo);
ignore (realize t)
in
List.iter f_one parameters_lst
in
let parameters_lst = List.map parameters_of_filename mo_files_data in
let bench_lst =
List.map
(fun (str_implementation, realize) ->
(str_implementation, f, (realize, parameters_lst)))
realize_data
in
print_debug benchs "Benchmarking realize:";
("Realize benchmark", throughputN benchs.time bench_lst)
(**********************)
(* Performance of s_ *)
(**********************)
let s_bench benchs =
let fun_gettext t' textdomain translation =
match translation with
| Singular (str, _) -> ignore (GettextCompat.dgettext t' textdomain str)
| _ -> ()
in
gettext_bench benchs "s_" fun_gettext
(*********************)
(* Performance of f_ *)
(*********************)
let f_bench benchs =
let fun_gettext t' textdomain translation =
match translation with
| Singular (str, _) ->
ignore (GettextCompat.fdgettext t' textdomain (Obj.magic str))
| _ -> ()
in
gettext_bench benchs "f_" fun_gettext
(**********************)
(* Performance of sn_ *)
(**********************)
let sn_bench benchs =
let fun_gettext t' textdomain translation =
match translation with
| Plural (str_id, str_plural, _) ->
ignore (GettextCompat.dngettext t' textdomain str_id str_plural 0);
ignore (GettextCompat.dngettext t' textdomain str_id str_plural 1);
ignore (GettextCompat.dngettext t' textdomain str_id str_plural 2);
ignore (GettextCompat.dngettext t' textdomain str_id str_plural 3)
| _ -> ()
in
gettext_bench benchs "sn_" fun_gettext
(**********************)
(* Performance of fn_ *)
(**********************)
let fn_bench benchs =
let fun_gettext t' textdomain translation =
match translation with
| Plural (str_id, str_plural, _) ->
ignore
(GettextCompat.fdngettext t' textdomain (Obj.magic str_id)
(Obj.magic str_plural) 0);
ignore
(GettextCompat.fdngettext t' textdomain (Obj.magic str_id)
(Obj.magic str_plural) 1);
ignore
(GettextCompat.fdngettext t' textdomain (Obj.magic str_id)
(Obj.magic str_plural) 2);
ignore
(GettextCompat.fdngettext t' textdomain (Obj.magic str_id)
(Obj.magic str_plural) 3)
| _ -> ()
in
gettext_bench benchs "fn_" fun_gettext
(**************************)
(* Main benchmark routine *)
(**************************)
;;
let benchs = parse_arg () in
let all_bench =
[ format_bench; realize_bench; s_bench; f_bench; sn_bench; fn_bench ]
in
print_env "benchmarks";
(* Running *)
let all_results = List.map (fun x -> x benchs) all_bench in
List.iter
(fun (str, results) ->
print_newline ();
print_newline ();
print_endline str;
tabulate results)
all_results
| null | https://raw.githubusercontent.com/gildor478/ocaml-gettext/9b7afc702bccace9a544b8efa2a28bc2b13371ed/test/bench/bench.ml | ocaml | ************************************************************************
ocaml-gettext: a library to translate messages
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
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
Lesser General Public License for more details.
************************************************************************
Different implementation of realize.
*****************************
Performance of check_format
*****************************
*************************
Performance of realize
*************************
********************
Performance of s_
********************
*******************
Performance of f_
*******************
********************
Performance of sn_
********************
********************
Performance of fn_
********************
************************
Main benchmark routine
************************
Running | Copyright ( C ) 2003 - 2008 < >
License as published by the Free Software Foundation ; either
version 2.1 of the License , or ( at your option ) any later version ;
You should have received a copy of the GNU Lesser General Public
License along with this library ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307
USA
open Benchmark
open Common
open GettextTypes
type benchs = { verbose : bool; search_path : string list; time : int }
let realize_data =
[
("Camomile.Map", GettextCamomile.Map.realize);
("Camomile.Hashtbl", GettextCamomile.Hashtbl.realize);
("Camomile.Open", GettextCamomile.Open.realize);
("Stub.Native", GettextStub.Native.realize);
("Stub.Preload", GettextStub.Preload.realize);
]
let parse_arg () =
let benchs = ref { verbose = false; search_path = []; time = 1 } in
Arg.parse
(Arg.align
[
( "--search",
Arg.String
(fun dir ->
benchs :=
{ !benchs with search_path = dir :: !benchs.search_path }),
"dir Search the specified directory for MO file." );
( "--verbose",
Arg.Unit (fun () -> benchs := { !benchs with verbose = true }),
"Processs with a lot of message." );
( "--time",
Arg.Int (fun sec -> benchs := { !benchs with time = sec }),
Printf.sprintf
"second Process each test during the specified number of second. \
Default : %d."
!benchs.time );
])
(fun _str -> ())
( "Benchmark utility for ocaml-gettext v" ^ GettextConfig.version
^ " by Sylvain Le Gall\n"
^ "Copyright (C) 2004-2008 Sylvain Le Gall <>\n"
^ "Licensed under LGPL v2.1 with Ocaml exception." );
!benchs
let print_debug benchs str =
if benchs.verbose then (
print_string str;
print_newline () )
else ()
let make_buffer lst = (lst, [])
let get_buffer (lst1, lst2) =
match (lst1, lst2) with
| hd :: tl, lst2 -> (hd, (tl, hd :: lst2))
| [], hd :: tl -> (hd, (tl, [ hd ]))
| [], [] -> failwith "Buffer is empty"
Generic function to benchmark gettextCompat function
let gettext_bench benchs str_gettext fun_gettext =
let f ref_translations =
let (debug_str, t', textdomain, tr), buffer =
get_buffer !ref_translations
in
print_debug benchs
(Printf.sprintf "Translation of %S from %s" (string_of_translation tr)
debug_str);
ignore (fun_gettext t' textdomain tr);
ref_translations := buffer
in
let parameters_lst = List.map parameters_of_filename mo_files_data in
let create_translation (str_realize, realize) =
let rec create_one_translation accu lst =
match lst with
| parameters :: tl ->
let t = t_of_parameters parameters in
let t' = realize t in
let new_accu =
List.fold_left
(fun lst tr ->
( str_realize ^ " with textdomain " ^ parameters.textdomain,
t',
parameters.textdomain,
tr )
:: lst)
accu parameters.translations
in
create_one_translation new_accu tl
| [] -> make_buffer accu
in
ref (create_one_translation [] parameters_lst)
in
let bench_lst =
List.map
(fun (str_realize, realize) ->
(str_realize, f, create_translation (str_realize, realize)))
realize_data
in
print_debug benchs ("Benchmarking " ^ str_gettext ^ ":");
(str_gettext ^ " benchmark", throughputN benchs.time bench_lst)
let format_bench benchs =
let f ref_buffer =
let elem, buffer = get_buffer !ref_buffer in
let translation =
print_debug benchs ("Checking format of : " ^ string_of_translation elem);
GettextFormat.check_format Ignore elem
in
print_debug benchs
("Result of the check : " ^ string_of_translation translation);
ref_buffer := buffer
in
print_debug benchs "Benchmarking format :";
( "Format benchmark",
throughputN benchs.time
[
("Singular", f, ref (make_buffer format_translation_singular_data));
("Plural", f, ref (make_buffer format_translation_plural_data));
("All", f, ref (make_buffer format_translation_all_data));
] )
let realize_bench benchs =
let f (realize, parameters_lst) =
let f_one parameters =
let t =
print_debug benchs ("Creating t for " ^ parameters.fl_mo);
t_of_parameters parameters
in
print_debug benchs ("Realizing t for " ^ parameters.fl_mo);
ignore (realize t)
in
List.iter f_one parameters_lst
in
let parameters_lst = List.map parameters_of_filename mo_files_data in
let bench_lst =
List.map
(fun (str_implementation, realize) ->
(str_implementation, f, (realize, parameters_lst)))
realize_data
in
print_debug benchs "Benchmarking realize:";
("Realize benchmark", throughputN benchs.time bench_lst)
let s_bench benchs =
let fun_gettext t' textdomain translation =
match translation with
| Singular (str, _) -> ignore (GettextCompat.dgettext t' textdomain str)
| _ -> ()
in
gettext_bench benchs "s_" fun_gettext
let f_bench benchs =
let fun_gettext t' textdomain translation =
match translation with
| Singular (str, _) ->
ignore (GettextCompat.fdgettext t' textdomain (Obj.magic str))
| _ -> ()
in
gettext_bench benchs "f_" fun_gettext
let sn_bench benchs =
let fun_gettext t' textdomain translation =
match translation with
| Plural (str_id, str_plural, _) ->
ignore (GettextCompat.dngettext t' textdomain str_id str_plural 0);
ignore (GettextCompat.dngettext t' textdomain str_id str_plural 1);
ignore (GettextCompat.dngettext t' textdomain str_id str_plural 2);
ignore (GettextCompat.dngettext t' textdomain str_id str_plural 3)
| _ -> ()
in
gettext_bench benchs "sn_" fun_gettext
let fn_bench benchs =
let fun_gettext t' textdomain translation =
match translation with
| Plural (str_id, str_plural, _) ->
ignore
(GettextCompat.fdngettext t' textdomain (Obj.magic str_id)
(Obj.magic str_plural) 0);
ignore
(GettextCompat.fdngettext t' textdomain (Obj.magic str_id)
(Obj.magic str_plural) 1);
ignore
(GettextCompat.fdngettext t' textdomain (Obj.magic str_id)
(Obj.magic str_plural) 2);
ignore
(GettextCompat.fdngettext t' textdomain (Obj.magic str_id)
(Obj.magic str_plural) 3)
| _ -> ()
in
gettext_bench benchs "fn_" fun_gettext
;;
let benchs = parse_arg () in
let all_bench =
[ format_bench; realize_bench; s_bench; f_bench; sn_bench; fn_bench ]
in
print_env "benchmarks";
let all_results = List.map (fun x -> x benchs) all_bench in
List.iter
(fun (str, results) ->
print_newline ();
print_newline ();
print_endline str;
tabulate results)
all_results
|
26e5c8d0fb1ccfc2d67ef6ab8fbc9776781bc9a65e7a3adbcb71c7ceff768692 | caradoc-org/caradoc | mapkey.ml | (*****************************************************************************)
(* Caradoc: a PDF parser and validator *)
Copyright ( C ) 2015 ANSSI
Copyright ( C ) 2015 - 2017
(* *)
(* This program is free software; you can redistribute it and/or modify *)
it under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation .
(* *)
(* This program is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)
(* GNU General Public License for more details. *)
(* *)
You should have received a copy of the GNU General Public License along
with this program ; if not , write to the Free Software Foundation , Inc. ,
51 Franklin Street , Fifth Floor , Boston , USA .
(*****************************************************************************)
open Key
module MapKey = Map.Make(Key)
| null | https://raw.githubusercontent.com/caradoc-org/caradoc/100f53bc55ef682049e10fabf24869bc019dc6ce/src/util/mapkey.ml | ocaml | ***************************************************************************
Caradoc: a PDF parser and validator
This program is free software; you can redistribute it and/or modify
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 ) 2015 ANSSI
Copyright ( C ) 2015 - 2017
it under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation .
You should have received a copy of the GNU General Public License along
with this program ; if not , write to the Free Software Foundation , Inc. ,
51 Franklin Street , Fifth Floor , Boston , USA .
open Key
module MapKey = Map.Make(Key)
|
5348156b0532c3b6661d1589597baaf853ea1671ca23c14447e03c8634b95ff7 | sicmutils/sicmutils | pendulum_test.cljc | #_"SPDX-License-Identifier: GPL-3.0"
(ns sicmutils.examples.pendulum-test
(:require [clojure.test :refer [is deftest use-fixtures]]
[sicmutils.env :refer [up simplify]]
[sicmutils.examples.pendulum :as p]
[sicmutils.simplify :refer [hermetic-simplify-fixture]]
[sicmutils.value :as v]))
(use-fixtures :each hermetic-simplify-fixture)
(deftest simple-pendulum
(is (= '(+ (* (/ 1 2) (expt l 2) m (expt thetadot 2))
(* g l m (cos theta)))
(v/freeze
(simplify
((p/L 'm 'l 'g (fn [_t] (up 0 0)))
(up 't 'theta 'thetadot)))))))
| null | https://raw.githubusercontent.com/sicmutils/sicmutils/ce763b31153eb9253f165bd5b4e4e6a6087bf730/test/sicmutils/examples/pendulum_test.cljc | clojure | #_"SPDX-License-Identifier: GPL-3.0"
(ns sicmutils.examples.pendulum-test
(:require [clojure.test :refer [is deftest use-fixtures]]
[sicmutils.env :refer [up simplify]]
[sicmutils.examples.pendulum :as p]
[sicmutils.simplify :refer [hermetic-simplify-fixture]]
[sicmutils.value :as v]))
(use-fixtures :each hermetic-simplify-fixture)
(deftest simple-pendulum
(is (= '(+ (* (/ 1 2) (expt l 2) m (expt thetadot 2))
(* g l m (cos theta)))
(v/freeze
(simplify
((p/L 'm 'l 'g (fn [_t] (up 0 0)))
(up 't 'theta 'thetadot)))))))
| |
5a39b5d9233ea76d69108765ab8743467d80aa0bb33dfb3f5ca66d4966d8d97a | axelarge/advent-of-code | day10_test.clj | (ns advent-of-code.y2015.day10-test
(:require [clojure.test :refer :all]
[advent-of-code.y2015.day10 :refer :all]))
(deftest test-solve1
(is (= (solve1 input) 329356)))
(deftest ^:slow test-solve2
(is (= (solve2 input) 4666278)))
| null | https://raw.githubusercontent.com/axelarge/advent-of-code/4c62a53ef71605780a22cf8219029453d8e1b977/test/advent_of_code/y2015/day10_test.clj | clojure | (ns advent-of-code.y2015.day10-test
(:require [clojure.test :refer :all]
[advent-of-code.y2015.day10 :refer :all]))
(deftest test-solve1
(is (= (solve1 input) 329356)))
(deftest ^:slow test-solve2
(is (= (solve2 input) 4666278)))
| |
4438b639d1419e3537d59fdb3062d3fa3084987ced40a61d31d5d338b9ea1c6e | davidhmartin/mcache | spy.clj | (ns mcache.spy
"Memcache protocol implementation extending net.spy.memcached.MemcachedClient"
(:use [mcache.core]
[mcache.util :only (cache-update-multi)]))
(extend-type net.spy.memcached.MemcachedClient
Memcache
(default-exp [mc] DEFAULT-EXP)
(put-if-absent
([mc key value]
(put-if-absent mc key value DEFAULT-EXP))
([mc key value exp]
(.. mc (add key exp value))))
(put-all-if-absent
([mc key-val-map]
(put-all-if-absent mc key-val-map DEFAULT-EXP))
([mc key-val-map exp]
(cache-update-multi put-if-absent mc key-val-map exp)))
(put
([mc key value]
(.. mc (set key DEFAULT-EXP value)))
([mc key value exp]
(.. mc (set key exp value))))
(put-all
([mc key-val-map] (put-all mc key-val-map DEFAULT-EXP))
([mc key-val-map exp]
(cache-update-multi put mc key-val-map exp)))
(put-if-present
([mc key value] (put-if-present mc key value DEFAULT-EXP))
([mc key value exp]
(.. mc (replace key exp value))))
(put-all-if-present
([mc key-val-map] (put-all-if-present mc key-val-map DEFAULT-EXP))
([mc key-val-map exp]
(cache-update-multi put-if-present mc key-val-map exp)))
(delete [mc key]
(.. mc (delete key)))
(delete-all [mc keys]
(doall (map #(delete mc %) keys)))
(fetch [mc key]
(.. mc (get key)))
(fetch-all [mc keys]
(into {} (.. mc (getBulk keys))))
(clear [mc] (.. mc (flush)))
)
| null | https://raw.githubusercontent.com/davidhmartin/mcache/0df952207cef1ed10b5d81c58edc94873a11fdeb/src/mcache/spy.clj | clojure | (ns mcache.spy
"Memcache protocol implementation extending net.spy.memcached.MemcachedClient"
(:use [mcache.core]
[mcache.util :only (cache-update-multi)]))
(extend-type net.spy.memcached.MemcachedClient
Memcache
(default-exp [mc] DEFAULT-EXP)
(put-if-absent
([mc key value]
(put-if-absent mc key value DEFAULT-EXP))
([mc key value exp]
(.. mc (add key exp value))))
(put-all-if-absent
([mc key-val-map]
(put-all-if-absent mc key-val-map DEFAULT-EXP))
([mc key-val-map exp]
(cache-update-multi put-if-absent mc key-val-map exp)))
(put
([mc key value]
(.. mc (set key DEFAULT-EXP value)))
([mc key value exp]
(.. mc (set key exp value))))
(put-all
([mc key-val-map] (put-all mc key-val-map DEFAULT-EXP))
([mc key-val-map exp]
(cache-update-multi put mc key-val-map exp)))
(put-if-present
([mc key value] (put-if-present mc key value DEFAULT-EXP))
([mc key value exp]
(.. mc (replace key exp value))))
(put-all-if-present
([mc key-val-map] (put-all-if-present mc key-val-map DEFAULT-EXP))
([mc key-val-map exp]
(cache-update-multi put-if-present mc key-val-map exp)))
(delete [mc key]
(.. mc (delete key)))
(delete-all [mc keys]
(doall (map #(delete mc %) keys)))
(fetch [mc key]
(.. mc (get key)))
(fetch-all [mc keys]
(into {} (.. mc (getBulk keys))))
(clear [mc] (.. mc (flush)))
)
| |
8ce7032a750f4bc19fc7bca20c2f2094449430141a22500d6dfc7a39215ccf70 | janestreet/core_profiler | offline.ml | open Core
open Core_profiler_disabled
module Profiler = struct
let is_enabled = true
let safe_to_delay () =
Common.maybe_do_slow_tasks Common.Offline_profiler ~reluctance:1;
Protocol.Buffer.ensure_free 2048
let dump_stats () =
Protocol.Writer.dump_stats ()
let configure
?don't_require_core_profiler_env
?offline_profiler_data_file
?online_print_time_interval_secs:_
?online_print_by_default:_
() =
Option.iter don't_require_core_profiler_env ~f:(fun () ->
Check_environment.don't_require_core_profiler_env ());
Option.iter offline_profiler_data_file ~f:(fun file ->
Protocol.set_current_output_filename file);
;;
end
module Timer = struct
type timer = Probe_id.t
type t = timer
type probe = t
let create ~name =
Check_environment.check_safety_exn ();
let id = Probe_id.create () in
Protocol.Writer.write_new_single id name Probe_type.Timer;
id
let record id =
let n = Common.now Common.Offline_profiler ~reluctance:3 () in
Protocol.Writer.write_timer_at id n
module Group = struct
type t = Probe_id.t
let create ~name =
Check_environment.check_safety_exn ();
let id = Probe_id.create () in
Protocol.Writer.write_new_group id name Probe_type.Timer;
id
let add_probe group ?(sources=[||]) ~name () =
let id = Probe_id.create () in
(* Note! sources : Point.t array = Point_id.t array *)
Protocol.Writer.write_new_group_point ~group_id:group ~id name sources;
id
let reset group =
let n = Common.now Common.Offline_profiler ~reluctance:2 () in
Protocol.Writer.write_group_reset group n
end
end
let%bench_module "Timer" = (module struct
let () = Profiler.configure ()
~don't_require_core_profiler_env:()
let timer = Timer.create ~name:"bench_timer"
let group = Timer.Group.create " bench_timer_group " ( )
* let group_probe = Timer . Group.add_probe group " bench_timer_group_probe "
* let group_probe = Timer.Group.add_probe group "bench_timer_group_probe" *)
let%bench "at" = Timer.record timer
BENCH " group_probe_at " = Timer.Group.Probe.at group_probe
*
* BENCH " group_reset " = Timer.Group.reset group
*
* BENCH "group_reset" = Timer.Group.reset group *)
let () = Protocol.Writer.set_at_exit_handler `Disable
end)
module Probe = struct
type probe = Probe_id.t
type t = probe
let create ~name ~units =
Check_environment.check_safety_exn ();
let id = Probe_id.create () in
Protocol.Writer.write_new_single id name (Probe_type.Probe units);
id
let record id value =
let n = Common.now Common.Offline_profiler ~reluctance:3 () in
Protocol.Writer.write_probe_at id n value
module Group = struct
type t = Probe_id.t
let create ~name ~units =
Check_environment.check_safety_exn ();
let id = Probe_id.create () in
Protocol.Writer.write_new_group id name (Probe_type.Probe units);
id
let add_probe group ?(sources=[||]) ~name () =
let id = Probe_id.create () in
Protocol.Writer.write_new_group_point ~group_id:group ~id name sources;
id
let reset group =
let n = Common.now Common.Offline_profiler ~reluctance:2 () in
Protocol.Writer.write_group_reset group n
end
end
let%bench_module "Probe" = (module struct
let () = Profiler.configure ()
~don't_require_core_profiler_env:()
let timer = Probe.create ~name:"bench_probe" ~units:Profiler_units.Seconds
let group = Probe.Group.create " bench_probe_group " Profiler_units . Int
* let group_probe = Probe . Group.add_probe group " bench_probe_group_probe "
* let group_probe = Probe.Group.add_probe group "bench_probe_group_probe" *)
let%bench "at" = Probe.record timer 19827312
BENCH " group_probe_at " = Probe.Group.Probe.at group_probe 123812
*
* BENCH " group_reset " = Probe.Group.reset group
*
* BENCH "group_reset" = Probe.Group.reset group *)
let () = Protocol.Writer.set_at_exit_handler `Disable
end)
module Delta_timer = struct
type state = Time_ns.t
type t =
{ probe : Probe.t
; mutable state : state
; mutable accum : int
}
let create ~name =
{ probe = Probe.create ~name ~units:Profiler_units.Nanoseconds
; state = Time_ns.epoch
; accum = 0
}
let diff n state =
Time_ns.diff n state
|> Time_ns.Span.to_int_ns
If we calibrate on start , we get back the time before we started calibrating ,
and those will be included in the delta .
and those 300ns will be included in the delta. *)
let stateless_start _t = Common.now Common.Offline_profiler ~reluctance:4 ()
let stateless_stop t state =
Avoid calling Common.now ( ) twice :
let n = Common.now Common.Offline_profiler ~reluctance:2 () in
let d = diff n state in
Protocol.Writer.write_probe_at t.probe n d
let start t =
let n = Common.now Common.Offline_profiler ~reluctance:4 () in
t.state <- n
let accumulate t n =
t.accum <- t.accum + (diff n t.state);
t.state <- n
let write_probe_at t n =
Protocol.Writer.write_probe_at t.probe n t.accum;
t.accum <- 0;
t.state <- n
let pause t =
let n = Common.now Common.Offline_profiler ~reluctance:4 () in
accumulate t n
let record t =
let n = Common.now Common.Offline_profiler ~reluctance:2 () in
write_probe_at t n
let stop t =
let n = Common.now Common.Offline_profiler ~reluctance:2 () in
accumulate t n;
write_probe_at t n
let wrap_sync t f x =
let state = stateless_start t in
let r =
try
f x
with ex ->
stateless_stop t state;
Exn.reraise ex "Core_profiler Delta_timer.wrap_sync"
in
stateless_stop t state;
r
let wrap_sync2 t f x y =
let state = stateless_start t in
let r =
try
f x y
with ex ->
stateless_stop t state;
Exn.reraise ex "Core_profiler Delta_timer.wrap_sync2"
in
stateless_stop t state;
r
let wrap_sync3 t f x y z =
let state = stateless_start t in
let r =
try
f x y z
with ex ->
stateless_stop t state;
Exn.reraise ex "Core_profiler Delta_timer.wrap_sync3"
in
stateless_stop t state;
r
let wrap_sync4 t f x y z w =
let state = stateless_start t in
let r =
try
f x y z w
with ex ->
stateless_stop t state;
Exn.reraise ex "Core_profiler Delta_timer.wrap_sync4"
in
stateless_stop t state;
r
let wrap_async t f x =
* let open Async in
* let state = start_async t in
* try_with ~run:`Now ( fun ( ) - > f x ) > > = fun res - >
* stop_async t state ;
* match res with
* | Ok x - > return x
* | Error ex - > Exn.reraise ex " Core_profiler "
* let open Async in
* let state = start_async t in
* try_with ~run:`Now (fun () -> f x) >>= fun res ->
* stop_async t state;
* match res with
* | Ok x -> return x
* | Error ex -> Exn.reraise ex "Core_profiler Delta_timer.wrap_async" *)
end
let%bench_module "Delta_timer" = (module struct
let () = Profiler.configure ()
~don't_require_core_profiler_env:()
let delta = Delta_timer.create ~name:"unittest"
let started = Delta_timer.stateless_start delta
let%bench "start_async" = Delta_timer.stateless_start delta
let%bench "stop_async" = Delta_timer.stateless_stop delta started
let%bench "start" = Delta_timer.start delta
let%bench "stop" = Delta_timer.stop delta
end)
let%bench_module "Delta_timer.wrap_sync" = (module struct
let () = Profiler.configure ()
~don't_require_core_profiler_env:()
let nop () = ()
let wrapped_nop =
let delta = Delta_timer.create ~name:"nop" in
Delta_timer.wrap_sync delta nop
let count_256 () =
for _ = 1 to 256 do
()
done
let wrapped_count_256 =
let delta = Delta_timer.create ~name:"count_256" in
Delta_timer.wrap_sync delta count_256
let%bench "nop" = nop ()
let%bench "wrapped_nop" = wrapped_nop ()
let%bench "count_256" = count_256 ()
let%bench "wrapped_count_256" = wrapped_count_256 ()
end)
(* stateless Delta_probe does not support pausing *)
module Delta_probe = struct
type state = int
type t =
{ probe : Probe.t
; mutable state : state
; mutable accum : state
}
let create ~name ~units =
{ probe = Probe.create ~name ~units
; state = 0
; accum = 0
}
let stateless_start _t value = value
let stateless_stop t state value = Probe.record t.probe (value - state)
let start t value =
t.state <- value
let record t =
Probe.record t.probe t.accum;
t.accum <- 0
let pause t value =
t.accum <- t.accum + (value - t.state)
let stop t value =
pause t value;
record t;
end
let%bench_module "Delta_probe" = (module struct
let () = Profiler.configure ()
~don't_require_core_profiler_env:()
let delta = Delta_probe.create ~name:"unittest" ~units:Profiler_units.Int
let started = Delta_probe.stateless_start delta 123
let%bench "start" = Delta_probe.start delta 123
let%bench "stop" = Delta_probe.stop delta 456
let%bench "start_async" = Delta_probe.stateless_start delta 123
let%bench "stop_async" = Delta_probe.stateless_stop delta started 456
end)
| null | https://raw.githubusercontent.com/janestreet/core_profiler/3d1c0e61df848f5f25f78d64beea92b619b6d5d9/src/offline.ml | ocaml | Note! sources : Point.t array = Point_id.t array
stateless Delta_probe does not support pausing | open Core
open Core_profiler_disabled
module Profiler = struct
let is_enabled = true
let safe_to_delay () =
Common.maybe_do_slow_tasks Common.Offline_profiler ~reluctance:1;
Protocol.Buffer.ensure_free 2048
let dump_stats () =
Protocol.Writer.dump_stats ()
let configure
?don't_require_core_profiler_env
?offline_profiler_data_file
?online_print_time_interval_secs:_
?online_print_by_default:_
() =
Option.iter don't_require_core_profiler_env ~f:(fun () ->
Check_environment.don't_require_core_profiler_env ());
Option.iter offline_profiler_data_file ~f:(fun file ->
Protocol.set_current_output_filename file);
;;
end
module Timer = struct
type timer = Probe_id.t
type t = timer
type probe = t
let create ~name =
Check_environment.check_safety_exn ();
let id = Probe_id.create () in
Protocol.Writer.write_new_single id name Probe_type.Timer;
id
let record id =
let n = Common.now Common.Offline_profiler ~reluctance:3 () in
Protocol.Writer.write_timer_at id n
module Group = struct
type t = Probe_id.t
let create ~name =
Check_environment.check_safety_exn ();
let id = Probe_id.create () in
Protocol.Writer.write_new_group id name Probe_type.Timer;
id
let add_probe group ?(sources=[||]) ~name () =
let id = Probe_id.create () in
Protocol.Writer.write_new_group_point ~group_id:group ~id name sources;
id
let reset group =
let n = Common.now Common.Offline_profiler ~reluctance:2 () in
Protocol.Writer.write_group_reset group n
end
end
let%bench_module "Timer" = (module struct
let () = Profiler.configure ()
~don't_require_core_profiler_env:()
let timer = Timer.create ~name:"bench_timer"
let group = Timer.Group.create " bench_timer_group " ( )
* let group_probe = Timer . Group.add_probe group " bench_timer_group_probe "
* let group_probe = Timer.Group.add_probe group "bench_timer_group_probe" *)
let%bench "at" = Timer.record timer
BENCH " group_probe_at " = Timer.Group.Probe.at group_probe
*
* BENCH " group_reset " = Timer.Group.reset group
*
* BENCH "group_reset" = Timer.Group.reset group *)
let () = Protocol.Writer.set_at_exit_handler `Disable
end)
module Probe = struct
type probe = Probe_id.t
type t = probe
let create ~name ~units =
Check_environment.check_safety_exn ();
let id = Probe_id.create () in
Protocol.Writer.write_new_single id name (Probe_type.Probe units);
id
let record id value =
let n = Common.now Common.Offline_profiler ~reluctance:3 () in
Protocol.Writer.write_probe_at id n value
module Group = struct
type t = Probe_id.t
let create ~name ~units =
Check_environment.check_safety_exn ();
let id = Probe_id.create () in
Protocol.Writer.write_new_group id name (Probe_type.Probe units);
id
let add_probe group ?(sources=[||]) ~name () =
let id = Probe_id.create () in
Protocol.Writer.write_new_group_point ~group_id:group ~id name sources;
id
let reset group =
let n = Common.now Common.Offline_profiler ~reluctance:2 () in
Protocol.Writer.write_group_reset group n
end
end
let%bench_module "Probe" = (module struct
let () = Profiler.configure ()
~don't_require_core_profiler_env:()
let timer = Probe.create ~name:"bench_probe" ~units:Profiler_units.Seconds
let group = Probe.Group.create " bench_probe_group " Profiler_units . Int
* let group_probe = Probe . Group.add_probe group " bench_probe_group_probe "
* let group_probe = Probe.Group.add_probe group "bench_probe_group_probe" *)
let%bench "at" = Probe.record timer 19827312
BENCH " group_probe_at " = Probe.Group.Probe.at group_probe 123812
*
* BENCH " group_reset " = Probe.Group.reset group
*
* BENCH "group_reset" = Probe.Group.reset group *)
let () = Protocol.Writer.set_at_exit_handler `Disable
end)
module Delta_timer = struct
type state = Time_ns.t
type t =
{ probe : Probe.t
; mutable state : state
; mutable accum : int
}
let create ~name =
{ probe = Probe.create ~name ~units:Profiler_units.Nanoseconds
; state = Time_ns.epoch
; accum = 0
}
let diff n state =
Time_ns.diff n state
|> Time_ns.Span.to_int_ns
If we calibrate on start , we get back the time before we started calibrating ,
and those will be included in the delta .
and those 300ns will be included in the delta. *)
let stateless_start _t = Common.now Common.Offline_profiler ~reluctance:4 ()
let stateless_stop t state =
Avoid calling Common.now ( ) twice :
let n = Common.now Common.Offline_profiler ~reluctance:2 () in
let d = diff n state in
Protocol.Writer.write_probe_at t.probe n d
let start t =
let n = Common.now Common.Offline_profiler ~reluctance:4 () in
t.state <- n
let accumulate t n =
t.accum <- t.accum + (diff n t.state);
t.state <- n
let write_probe_at t n =
Protocol.Writer.write_probe_at t.probe n t.accum;
t.accum <- 0;
t.state <- n
let pause t =
let n = Common.now Common.Offline_profiler ~reluctance:4 () in
accumulate t n
let record t =
let n = Common.now Common.Offline_profiler ~reluctance:2 () in
write_probe_at t n
let stop t =
let n = Common.now Common.Offline_profiler ~reluctance:2 () in
accumulate t n;
write_probe_at t n
let wrap_sync t f x =
let state = stateless_start t in
let r =
try
f x
with ex ->
stateless_stop t state;
Exn.reraise ex "Core_profiler Delta_timer.wrap_sync"
in
stateless_stop t state;
r
let wrap_sync2 t f x y =
let state = stateless_start t in
let r =
try
f x y
with ex ->
stateless_stop t state;
Exn.reraise ex "Core_profiler Delta_timer.wrap_sync2"
in
stateless_stop t state;
r
let wrap_sync3 t f x y z =
let state = stateless_start t in
let r =
try
f x y z
with ex ->
stateless_stop t state;
Exn.reraise ex "Core_profiler Delta_timer.wrap_sync3"
in
stateless_stop t state;
r
let wrap_sync4 t f x y z w =
let state = stateless_start t in
let r =
try
f x y z w
with ex ->
stateless_stop t state;
Exn.reraise ex "Core_profiler Delta_timer.wrap_sync4"
in
stateless_stop t state;
r
let wrap_async t f x =
* let open Async in
* let state = start_async t in
* try_with ~run:`Now ( fun ( ) - > f x ) > > = fun res - >
* stop_async t state ;
* match res with
* | Ok x - > return x
* | Error ex - > Exn.reraise ex " Core_profiler "
* let open Async in
* let state = start_async t in
* try_with ~run:`Now (fun () -> f x) >>= fun res ->
* stop_async t state;
* match res with
* | Ok x -> return x
* | Error ex -> Exn.reraise ex "Core_profiler Delta_timer.wrap_async" *)
end
let%bench_module "Delta_timer" = (module struct
let () = Profiler.configure ()
~don't_require_core_profiler_env:()
let delta = Delta_timer.create ~name:"unittest"
let started = Delta_timer.stateless_start delta
let%bench "start_async" = Delta_timer.stateless_start delta
let%bench "stop_async" = Delta_timer.stateless_stop delta started
let%bench "start" = Delta_timer.start delta
let%bench "stop" = Delta_timer.stop delta
end)
let%bench_module "Delta_timer.wrap_sync" = (module struct
let () = Profiler.configure ()
~don't_require_core_profiler_env:()
let nop () = ()
let wrapped_nop =
let delta = Delta_timer.create ~name:"nop" in
Delta_timer.wrap_sync delta nop
let count_256 () =
for _ = 1 to 256 do
()
done
let wrapped_count_256 =
let delta = Delta_timer.create ~name:"count_256" in
Delta_timer.wrap_sync delta count_256
let%bench "nop" = nop ()
let%bench "wrapped_nop" = wrapped_nop ()
let%bench "count_256" = count_256 ()
let%bench "wrapped_count_256" = wrapped_count_256 ()
end)
module Delta_probe = struct
type state = int
type t =
{ probe : Probe.t
; mutable state : state
; mutable accum : state
}
let create ~name ~units =
{ probe = Probe.create ~name ~units
; state = 0
; accum = 0
}
let stateless_start _t value = value
let stateless_stop t state value = Probe.record t.probe (value - state)
let start t value =
t.state <- value
let record t =
Probe.record t.probe t.accum;
t.accum <- 0
let pause t value =
t.accum <- t.accum + (value - t.state)
let stop t value =
pause t value;
record t;
end
let%bench_module "Delta_probe" = (module struct
let () = Profiler.configure ()
~don't_require_core_profiler_env:()
let delta = Delta_probe.create ~name:"unittest" ~units:Profiler_units.Int
let started = Delta_probe.stateless_start delta 123
let%bench "start" = Delta_probe.start delta 123
let%bench "stop" = Delta_probe.stop delta 456
let%bench "start_async" = Delta_probe.stateless_start delta 123
let%bench "stop_async" = Delta_probe.stateless_stop delta started 456
end)
|
558d87680a973aef630b01a177ec4c273ab7193a6d0e9b8f7d149634ac8e1c0a | tschady/advent-of-code | d15_test.clj | (ns aoc.2021.d15-test
(:require [aoc.2021.d15 :as sut]
[clojure.test :refer :all]))
(def ex ["1163751742"
"1381373672"
"2136511328"
"3694931569"
"7463417111"
"1319128137"
"1359912421"
"3125421639"
"1293138521"
"2311944581"])
(deftest challenges
(is (= 824 (sut/part-1 sut/input)))
(is (= 3063 (sut/part-2 sut/input))))
| null | https://raw.githubusercontent.com/tschady/advent-of-code/72ee3771da0bab9b5c590268b92fed3d137a6c99/test/aoc/2021/d15_test.clj | clojure | (ns aoc.2021.d15-test
(:require [aoc.2021.d15 :as sut]
[clojure.test :refer :all]))
(def ex ["1163751742"
"1381373672"
"2136511328"
"3694931569"
"7463417111"
"1319128137"
"1359912421"
"3125421639"
"1293138521"
"2311944581"])
(deftest challenges
(is (= 824 (sut/part-1 sut/input)))
(is (= 3063 (sut/part-2 sut/input))))
| |
8061acee6b0081802d879c6a2b0b6a6141db4fa5e1e626394ef98fb97612e220 | obsidiansystems/obelisk | Deploy.hs | # LANGUAGE DeriveGeneric #
# LANGUAGE FlexibleContexts #
# LANGUAGE LambdaCase #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE QuasiQuotes #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE ViewPatterns #
module Obelisk.Command.Deploy where
import Control.Applicative (liftA2)
import Control.Lens
import Control.Monad
import Control.Monad.Catch (Exception (displayException), MonadThrow, bracket, throwM, try)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Data.Aeson (FromJSON, ToJSON, encode, eitherDecode)
import Data.Bits
import qualified Data.ByteString.Lazy as BSL
import Data.Default
import qualified Data.Map as Map
import qualified Data.Set as Set
import Data.String.Here.Interpolated (i)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import GHC.Generics
import System.Directory
import System.FilePath
import System.IO
import System.PosixCompat.Files
import Text.URI (URI)
import qualified Text.URI as URI
import Text.URI.Lens
import Obelisk.App (MonadObelisk)
import Obelisk.CliApp (
Severity (..), callProcessAndLogOutput, failWith, proc, putLog,
setCwd, setDelegateCtlc, setEnvOverride, withSpinner)
import Obelisk.Command.Nix
import Obelisk.Command.Project
import Obelisk.Command.Thunk
import Obelisk.Command.Utils
data DeployInitOpts = DeployInitOpts
{ _deployInitOpts_outputDir :: FilePath
, _deployInitOpts_sshKey :: FilePath
, _deployInitOpts_hostname :: [String]
, _deployInitOpts_route :: String
, _deployInitOpts_adminEmail :: String
, _deployInitOpts_enableHttps :: Bool
} deriving Show
deployInit :: MonadObelisk m => DeployInitOpts -> FilePath -> m ()
deployInit deployOpts root = do
let deployDir = _deployInitOpts_outputDir deployOpts
rootEqualsTarget <- liftIO $ liftA2 equalFilePath (canonicalizePath root) (canonicalizePath deployDir)
when rootEqualsTarget $
failWith [i|Deploy directory ${deployDir} should not be the same as project root.|]
thunkPtr <- readThunk root >>= \case
Right (ThunkData_Packed _ ptr) -> return ptr
_ -> getThunkPtr CheckClean_NotIgnored root Nothing
deployInit' thunkPtr deployOpts
deployInit'
:: MonadObelisk m
=> ThunkPtr
-> DeployInitOpts
-> m ()
deployInit' thunkPtr (DeployInitOpts deployDir sshKeyPath hostnames route adminEmail enableHttps) = do
liftIO $ createDirectoryIfMissing True deployDir
localKey <- withSpinner ("Preparing " <> T.pack deployDir) $ do
localKey <- liftIO (doesFileExist sshKeyPath) >>= \case
False -> failWith $ T.pack $ "ob deploy init: file does not exist: " <> sshKeyPath
True -> pure $ deployDir </> "ssh_key"
callProcessAndLogOutput (Notice, Error) $
proc cp [sshKeyPath, localKey]
liftIO $ setFileMode localKey $ ownerReadMode .|. ownerWriteMode
return localKey
withSpinner "Validating configuration" $ do
void $ getHostFromRoute enableHttps route -- make sure that hostname is present
forM_ hostnames $ \hostname -> do
putLog Notice $ "Verifying host keys (" <> T.pack hostname <> ")"
-- Note: we can't use a spinner here as this function will prompt the user.
verifyHostKey (deployDir </> "backend_known_hosts") localKey hostname
--IMPORTANT: We cannot copy config directory from the development project to
--the deployment directory. If we do, it's very likely someone will
--accidentally create a production deployment that uses development
--credentials to connect to some resources. This could result in, e.g.,
--production data backed up to a dev environment.
withSpinner "Creating project configuration directories" $ liftIO $ do
mapM_ (createDirectoryIfMissing True)
[ deployDir </> "config" </> "backend"
, deployDir </> "config" </> "common"
, deployDir </> "config" </> "frontend"
]
let srcDir = deployDir </> "src"
withSpinner ("Creating source thunk (" <> T.pack (makeRelative deployDir srcDir) <> ")") $ do
createThunk srcDir $ Right thunkPtr
setupObeliskImpl deployDir
withSpinner "Writing deployment configuration" $ do
writeDeployConfig deployDir "backend_hosts" $ unlines hostnames
writeDeployConfig deployDir "enable_https" $ show enableHttps
writeDeployConfig deployDir "admin_email" adminEmail
writeDeployConfig deployDir ("config" </> "common" </> "route") route
writeDeployConfig deployDir "module.nix" $
"(import " <> toNixPath (makeRelative deployDir srcDir) <> " {}).obelisk.serverModules.mkBaseEc2"
withSpinner ("Initializing git repository (" <> T.pack deployDir <> ")") $
initGit deployDir
setupObeliskImpl :: MonadIO m => FilePath -> m ()
setupObeliskImpl deployDir = liftIO $ do
let
implDir = toImplDir deployDir
goBackUp = foldr (</>) "" $ (".." <$) $ splitPath $ makeRelative deployDir implDir
createDirectoryIfMissing True implDir
writeFile (implDir </> "default.nix") $ "(import " <> toNixPath (goBackUp </> "src") <> " {}).obelisk"
deployPush :: MonadObelisk m => FilePath -> m [String] -> m ()
deployPush deployPath getNixBuilders = do
hosts <- Set.fromList . filter (/= mempty) . lines <$> readDeployConfig deployPath "backend_hosts"
adminEmail <- readDeployConfig deployPath "admin_email"
enableHttps <- read <$> readDeployConfig deployPath "enable_https"
route <- readDeployConfig deployPath $ "config" </> "common" </> "route"
routeHost <- getHostFromRoute enableHttps route
let srcPath = deployPath </> "src"
thunkPtr <- readThunk srcPath >>= \case
Right (ThunkData_Packed _ ptr) -> return ptr
Right ThunkData_Checkout -> do
checkGitCleanStatus srcPath True >>= \case
True -> packThunk (ThunkPackConfig False (ThunkConfig Nothing)) srcPath
False -> failWith $ T.pack $ "ob deploy push: ensure " <> srcPath <> " has no pending changes and latest is pushed upstream."
Left err -> failWith $ "ob deploy push: couldn't read src thunk: " <> T.pack (show err)
let version = show . _thunkRev_commit $ _thunkPtr_rev thunkPtr
builders <- getNixBuilders
let moduleFile = deployPath </> "module.nix"
moduleFileExists <- liftIO $ doesFileExist moduleFile
buildOutputByHost <- ifor (Map.fromSet (const ()) hosts) $ \host () -> do
TODO : What does it mean if this returns more or less than 1 line of output ?
[result] <- fmap lines $ nixCmd $ NixCmd_Build $ def
& nixCmdConfig_target .~ Target
{ _target_path = Just srcPath
, _target_attr = Just "server.system"
, _target_expr = Nothing
}
& nixBuildConfig_outLink .~ OutLink_None
& nixCmdConfig_args .~ (
[ strArg "hostName" host
, strArg "adminEmail" adminEmail
, strArg "routeHost" routeHost
, strArg "version" version
, boolArg "enableHttps" enableHttps
] <> [rawArg "module" ("import " <> toNixPath moduleFile) | moduleFileExists ])
& nixCmdConfig_builders .~ builders
pure result
let knownHostsPath = deployPath </> "backend_known_hosts"
sshOpts = sshArgs knownHostsPath (deployPath </> "ssh_key") False
withSpinner "Uploading closures" $ ifor_ buildOutputByHost $ \host outputPath -> do
callProcess'
(Map.fromList [("NIX_SSHOPTS", unwords sshOpts)])
"nix-copy-closure" ["-v", "--to", "--use-substitutes", "root@" <> host, "--gzip", outputPath]
withSpinner "Uploading config" $ ifor_ buildOutputByHost $ \host _ -> do
callProcessAndLogOutput (Notice, Warning) $
proc rsyncPath
[ "-e " <> sshPath <> " " <> unwords sshOpts
, "-qarvz"
, deployPath </> "config"
, "root@" <> host <> ":/var/lib/backend"
]
--TODO: Create GC root so we're sure our closure won't go away during this time period
withSpinner "Switching to new configuration" $ ifor_ buildOutputByHost $ \host outputPath -> do
callProcessAndLogOutput (Notice, Warning) $
proc sshPath $ sshOpts <>
[ "root@" <> host
, unwords
-- Note that we don't want to $(staticWhich "nix-env") here, because this is executing on a remote machine
[ "nix-env -p /nix/var/nix/profiles/system --set " <> outputPath
, "&&"
, "/nix/var/nix/profiles/system/bin/switch-to-configuration switch"
]
]
isClean <- checkGitCleanStatus deployPath True
when (not isClean) $ do
withSpinner "Committing changes to Git" $ do
callProcessAndLogOutput (Debug, Error) $
gitProc deployPath ["add", "."]
callProcessAndLogOutput (Debug, Error) $
gitProc deployPath ["commit", "-m", "New deployment"]
putLog Notice $ "Deployed => " <> T.pack route
where
callProcess' envMap cmd args = do
let p = setEnvOverride (envMap <>) $ setDelegateCtlc True $ proc cmd args
callProcessAndLogOutput (Notice, Notice) p
deployUpdate :: MonadObelisk m => FilePath -> m ()
deployUpdate deployPath = updateThunkToLatest (ThunkUpdateConfig Nothing (ThunkConfig Nothing)) (deployPath </> "src")
data PlatformDeployment = Android | IOS
deriving (Show, Eq)
renderPlatformDeployment :: PlatformDeployment -> String
renderPlatformDeployment = \case
Android -> "android"
IOS -> "ios"
deployMobile :: forall m. MonadObelisk m => PlatformDeployment -> [String] -> m ()
deployMobile platform mobileArgs = withProjectRoot "." $ \root -> do
let srcDir = root </> "src"
configDir = root </> "config"
exists <- liftIO $ doesDirectoryExist srcDir
unless exists $ failWith "ob test should be run inside of a deploy directory"
(nixBuildTarget, extraArgs) <- case platform of
Android -> do
let keystorePath = root </> "android_keystore.jks"
keytoolConfPath = root </> "android_keytool_config.json"
hasKeystore <- liftIO $ doesFileExist keystorePath
when (not hasKeystore) $ do
TODO log instructions for how to modify the keystore
putLog Notice $ "Creating keystore: " <> T.pack keystorePath
putLog Notice "Enter a keystore password: "
keyStorePassword <- liftIO $ withEcho False getLine
putLog Notice "Re-enter the keystore password: "
keyStorePassword' <- liftIO $ withEcho False getLine
unless (keyStorePassword' == keyStorePassword) $ failWith "passwords do not match"
let keyToolConf = KeytoolConfig
{ _keytoolConfig_keystore = keystorePath
, _keytoolConfig_alias = "obelisk"
, _keytoolConfig_storepass = keyStorePassword
, _keytoolConfig_keypass = keyStorePassword
}
createKeystore root keyToolConf
liftIO $ BSL.writeFile keytoolConfPath $ encode keyToolConf
checkKeytoolConfExist <- liftIO $ doesFileExist keytoolConfPath
unless checkKeytoolConfExist $ failWith "Missing android KeytoolConfig"
keytoolConfContents <- liftIO $ BSL.readFile keytoolConfPath
keyArgs <- case eitherDecode keytoolConfContents :: Either String KeytoolConfig of
Left err -> failWith $ T.pack err
Right conf -> pure
[ "--sign"
, "--store-file", _keytoolConfig_keystore conf
, "--store-password", _keytoolConfig_storepass conf
, "--key-alias", _keytoolConfig_alias conf
, "--key-password", _keytoolConfig_keypass conf
]
let expr = mconcat
[ "with (import ", toNixPath srcDir, " {});"
, "android.frontend.override (drv: {"
, "isRelease = true;"
, "staticSrc = (passthru.__androidWithConfig ", configDir, ").frontend.staticSrc;"
, "assets = (passthru.__androidWithConfig ", configDir, ").frontend.assets;"
, "})"
]
return (Target
{ _target_path = Nothing
, _target_attr = Nothing
, _target_expr = Just expr
}, keyArgs)
IOS -> do
let expr = mconcat
[ "with (import ", toNixPath srcDir, " {});"
, "ios.frontend.override (_: { staticSrc = (passthru.__iosWithConfig ", toNixPath configDir, ").frontend.staticSrc; })"
]
return (Target
{ _target_path = Nothing
, _target_attr = Nothing
, _target_expr = Just expr
}, [])
result <- nixCmd $ NixCmd_Build $ def
& nixBuildConfig_outLink .~ OutLink_None
& nixCmdConfig_target .~ nixBuildTarget
let mobileArtifact = case platform of
IOS -> "iOS App"
Android -> "Android APK"
putLog Notice $ T.pack $ unwords ["Your recently built", mobileArtifact, "can be found at the following path:", show result]
callProcessAndLogOutput (Notice, Error) $ proc (result </> "bin" </> "deploy") (mobileArgs ++ extraArgs)
where
withEcho showEcho f = bracket
(do
prevEcho <- hGetEcho stdin
hSetEcho stdin showEcho
pure prevEcho
)
(hSetEcho stdin)
(const f)
data KeytoolConfig = KeytoolConfig
{ _keytoolConfig_keystore :: FilePath
, _keytoolConfig_alias :: String
, _keytoolConfig_storepass :: String
, _keytoolConfig_keypass :: String
} deriving (Show, Generic)
instance FromJSON KeytoolConfig
instance ToJSON KeytoolConfig
createKeystore :: MonadObelisk m => FilePath -> KeytoolConfig -> m ()
createKeystore root config =
callProcessAndLogOutput (Notice, Notice) $ setCwd (Just root) $ proc jreKeyToolPath
[ "-genkeypair", "-noprompt"
, "-keystore", _keytoolConfig_keystore config
, "-keyalg", "RSA", "-keysize", "2048"
, "-validity", "1000000"
, "-storepass", _keytoolConfig_storepass config
, "-alias", _keytoolConfig_alias config
, "-keypass", _keytoolConfig_keypass config
]
| Simplified deployment configuration mechanism . At one point we may revisit this .
writeDeployConfig :: MonadObelisk m => FilePath -> FilePath -> String -> m ()
writeDeployConfig deployDir fname = liftIO . writeFile (deployDir </> fname)
readDeployConfig :: MonadObelisk m => FilePath -> FilePath -> m String
readDeployConfig deployDir fname = liftIO $ do
fmap (T.unpack . T.strip) $ T.readFile $ deployDir </> fname
verifyHostKey :: MonadObelisk m => FilePath -> FilePath -> String -> m ()
verifyHostKey knownHostsPath keyPath hostName =
callProcessAndLogOutput (Notice, Warning) $ proc sshPath $
sshArgs knownHostsPath keyPath True <>
[ "root@" <> hostName
, "-o", "NumberOfPasswordPrompts=0"
, "exit"
]
sshArgs :: FilePath -> FilePath -> Bool -> [String]
sshArgs knownHostsPath keyPath askHostKeyCheck =
[ "-o", "UserKnownHostsFile=" <> knownHostsPath
, "-o", "StrictHostKeyChecking=" <> if askHostKeyCheck then "ask" else "yes"
, "-i", keyPath
]
-- common/route validation
-- TODO: move these to executable-config once the typed-config stuff is done.
data InvalidRoute
= InvalidRoute_NotHttps URI
| InvalidRoute_MissingScheme URI
| InvalidRoute_MissingHost URI
| InvalidRoute_HasPort URI
| InvalidRoute_HasPath URI
deriving Show
instance Exception InvalidRoute where
displayException = \case
InvalidRoute_MissingScheme uri -> route uri "must have an URI scheme"
InvalidRoute_NotHttps uri -> route uri "must be HTTPS"
InvalidRoute_MissingHost uri -> route uri "must contain a hostname"
InvalidRoute_HasPort uri -> route uri "cannot specify port"
InvalidRoute_HasPath uri -> route uri "cannot contain path"
where
route uri err = T.unpack $ "Route (" <> URI.render uri <> ") " <> err
-- | Get the hostname from a https route
--
-- Fail if the route is invalid (i.e, no host present or scheme is not https)
getHostFromRoute
:: MonadObelisk m
=> Bool -- ^ Ensure https?
-> String
-> m String
getHostFromRoute mustBeHttps route = do
result :: Either InvalidRoute String <- try $ do
validateCommonRouteAndGetHost mustBeHttps =<< URI.mkURI (T.strip $ T.pack route)
either (failWith . T.pack . displayException) pure result
validateCommonRouteAndGetHost
:: (MonadThrow m, MonadObelisk m)
=> Bool -- ^ Ensure https?
-> URI
-> m String
validateCommonRouteAndGetHost mustBeHttps uri = do
case uri ^? uriScheme of
Just (Just (URI.unRText -> s)) -> case (mustBeHttps, s) of
(False, _) -> pure ()
(True, "https") -> pure ()
_ -> throwM $ InvalidRoute_NotHttps uri
_ -> throwM $ InvalidRoute_MissingScheme uri
case uri ^. uriPath of
[] -> pure ()
_path -> throwM $ InvalidRoute_HasPath uri
case uri ^? uriAuthority . _Right . authPort of
Just (Just _port) -> throwM $ InvalidRoute_HasPort uri
_ -> pure ()
case uri ^? uriAuthority . _Right . authHost of
Nothing -> throwM $ InvalidRoute_MissingHost uri
Just sslHost -> return $ T.unpack $ URI.unRText sslHost
| null | https://raw.githubusercontent.com/obsidiansystems/obelisk/d779d5ab007d8ee5c3cd3400473453e1d106f5f1/lib/command/src/Obelisk/Command/Deploy.hs | haskell | # LANGUAGE OverloadedStrings #
make sure that hostname is present
Note: we can't use a spinner here as this function will prompt the user.
IMPORTANT: We cannot copy config directory from the development project to
the deployment directory. If we do, it's very likely someone will
accidentally create a production deployment that uses development
credentials to connect to some resources. This could result in, e.g.,
production data backed up to a dev environment.
TODO: Create GC root so we're sure our closure won't go away during this time period
Note that we don't want to $(staticWhich "nix-env") here, because this is executing on a remote machine
common/route validation
TODO: move these to executable-config once the typed-config stuff is done.
| Get the hostname from a https route
Fail if the route is invalid (i.e, no host present or scheme is not https)
^ Ensure https?
^ Ensure https? | # LANGUAGE DeriveGeneric #
# LANGUAGE FlexibleContexts #
# LANGUAGE LambdaCase #
# LANGUAGE QuasiQuotes #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE ViewPatterns #
module Obelisk.Command.Deploy where
import Control.Applicative (liftA2)
import Control.Lens
import Control.Monad
import Control.Monad.Catch (Exception (displayException), MonadThrow, bracket, throwM, try)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Data.Aeson (FromJSON, ToJSON, encode, eitherDecode)
import Data.Bits
import qualified Data.ByteString.Lazy as BSL
import Data.Default
import qualified Data.Map as Map
import qualified Data.Set as Set
import Data.String.Here.Interpolated (i)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import GHC.Generics
import System.Directory
import System.FilePath
import System.IO
import System.PosixCompat.Files
import Text.URI (URI)
import qualified Text.URI as URI
import Text.URI.Lens
import Obelisk.App (MonadObelisk)
import Obelisk.CliApp (
Severity (..), callProcessAndLogOutput, failWith, proc, putLog,
setCwd, setDelegateCtlc, setEnvOverride, withSpinner)
import Obelisk.Command.Nix
import Obelisk.Command.Project
import Obelisk.Command.Thunk
import Obelisk.Command.Utils
data DeployInitOpts = DeployInitOpts
{ _deployInitOpts_outputDir :: FilePath
, _deployInitOpts_sshKey :: FilePath
, _deployInitOpts_hostname :: [String]
, _deployInitOpts_route :: String
, _deployInitOpts_adminEmail :: String
, _deployInitOpts_enableHttps :: Bool
} deriving Show
deployInit :: MonadObelisk m => DeployInitOpts -> FilePath -> m ()
deployInit deployOpts root = do
let deployDir = _deployInitOpts_outputDir deployOpts
rootEqualsTarget <- liftIO $ liftA2 equalFilePath (canonicalizePath root) (canonicalizePath deployDir)
when rootEqualsTarget $
failWith [i|Deploy directory ${deployDir} should not be the same as project root.|]
thunkPtr <- readThunk root >>= \case
Right (ThunkData_Packed _ ptr) -> return ptr
_ -> getThunkPtr CheckClean_NotIgnored root Nothing
deployInit' thunkPtr deployOpts
deployInit'
:: MonadObelisk m
=> ThunkPtr
-> DeployInitOpts
-> m ()
deployInit' thunkPtr (DeployInitOpts deployDir sshKeyPath hostnames route adminEmail enableHttps) = do
liftIO $ createDirectoryIfMissing True deployDir
localKey <- withSpinner ("Preparing " <> T.pack deployDir) $ do
localKey <- liftIO (doesFileExist sshKeyPath) >>= \case
False -> failWith $ T.pack $ "ob deploy init: file does not exist: " <> sshKeyPath
True -> pure $ deployDir </> "ssh_key"
callProcessAndLogOutput (Notice, Error) $
proc cp [sshKeyPath, localKey]
liftIO $ setFileMode localKey $ ownerReadMode .|. ownerWriteMode
return localKey
withSpinner "Validating configuration" $ do
forM_ hostnames $ \hostname -> do
putLog Notice $ "Verifying host keys (" <> T.pack hostname <> ")"
verifyHostKey (deployDir </> "backend_known_hosts") localKey hostname
withSpinner "Creating project configuration directories" $ liftIO $ do
mapM_ (createDirectoryIfMissing True)
[ deployDir </> "config" </> "backend"
, deployDir </> "config" </> "common"
, deployDir </> "config" </> "frontend"
]
let srcDir = deployDir </> "src"
withSpinner ("Creating source thunk (" <> T.pack (makeRelative deployDir srcDir) <> ")") $ do
createThunk srcDir $ Right thunkPtr
setupObeliskImpl deployDir
withSpinner "Writing deployment configuration" $ do
writeDeployConfig deployDir "backend_hosts" $ unlines hostnames
writeDeployConfig deployDir "enable_https" $ show enableHttps
writeDeployConfig deployDir "admin_email" adminEmail
writeDeployConfig deployDir ("config" </> "common" </> "route") route
writeDeployConfig deployDir "module.nix" $
"(import " <> toNixPath (makeRelative deployDir srcDir) <> " {}).obelisk.serverModules.mkBaseEc2"
withSpinner ("Initializing git repository (" <> T.pack deployDir <> ")") $
initGit deployDir
setupObeliskImpl :: MonadIO m => FilePath -> m ()
setupObeliskImpl deployDir = liftIO $ do
let
implDir = toImplDir deployDir
goBackUp = foldr (</>) "" $ (".." <$) $ splitPath $ makeRelative deployDir implDir
createDirectoryIfMissing True implDir
writeFile (implDir </> "default.nix") $ "(import " <> toNixPath (goBackUp </> "src") <> " {}).obelisk"
deployPush :: MonadObelisk m => FilePath -> m [String] -> m ()
deployPush deployPath getNixBuilders = do
hosts <- Set.fromList . filter (/= mempty) . lines <$> readDeployConfig deployPath "backend_hosts"
adminEmail <- readDeployConfig deployPath "admin_email"
enableHttps <- read <$> readDeployConfig deployPath "enable_https"
route <- readDeployConfig deployPath $ "config" </> "common" </> "route"
routeHost <- getHostFromRoute enableHttps route
let srcPath = deployPath </> "src"
thunkPtr <- readThunk srcPath >>= \case
Right (ThunkData_Packed _ ptr) -> return ptr
Right ThunkData_Checkout -> do
checkGitCleanStatus srcPath True >>= \case
True -> packThunk (ThunkPackConfig False (ThunkConfig Nothing)) srcPath
False -> failWith $ T.pack $ "ob deploy push: ensure " <> srcPath <> " has no pending changes and latest is pushed upstream."
Left err -> failWith $ "ob deploy push: couldn't read src thunk: " <> T.pack (show err)
let version = show . _thunkRev_commit $ _thunkPtr_rev thunkPtr
builders <- getNixBuilders
let moduleFile = deployPath </> "module.nix"
moduleFileExists <- liftIO $ doesFileExist moduleFile
buildOutputByHost <- ifor (Map.fromSet (const ()) hosts) $ \host () -> do
TODO : What does it mean if this returns more or less than 1 line of output ?
[result] <- fmap lines $ nixCmd $ NixCmd_Build $ def
& nixCmdConfig_target .~ Target
{ _target_path = Just srcPath
, _target_attr = Just "server.system"
, _target_expr = Nothing
}
& nixBuildConfig_outLink .~ OutLink_None
& nixCmdConfig_args .~ (
[ strArg "hostName" host
, strArg "adminEmail" adminEmail
, strArg "routeHost" routeHost
, strArg "version" version
, boolArg "enableHttps" enableHttps
] <> [rawArg "module" ("import " <> toNixPath moduleFile) | moduleFileExists ])
& nixCmdConfig_builders .~ builders
pure result
let knownHostsPath = deployPath </> "backend_known_hosts"
sshOpts = sshArgs knownHostsPath (deployPath </> "ssh_key") False
withSpinner "Uploading closures" $ ifor_ buildOutputByHost $ \host outputPath -> do
callProcess'
(Map.fromList [("NIX_SSHOPTS", unwords sshOpts)])
"nix-copy-closure" ["-v", "--to", "--use-substitutes", "root@" <> host, "--gzip", outputPath]
withSpinner "Uploading config" $ ifor_ buildOutputByHost $ \host _ -> do
callProcessAndLogOutput (Notice, Warning) $
proc rsyncPath
[ "-e " <> sshPath <> " " <> unwords sshOpts
, "-qarvz"
, deployPath </> "config"
, "root@" <> host <> ":/var/lib/backend"
]
withSpinner "Switching to new configuration" $ ifor_ buildOutputByHost $ \host outputPath -> do
callProcessAndLogOutput (Notice, Warning) $
proc sshPath $ sshOpts <>
[ "root@" <> host
, unwords
[ "nix-env -p /nix/var/nix/profiles/system --set " <> outputPath
, "&&"
, "/nix/var/nix/profiles/system/bin/switch-to-configuration switch"
]
]
isClean <- checkGitCleanStatus deployPath True
when (not isClean) $ do
withSpinner "Committing changes to Git" $ do
callProcessAndLogOutput (Debug, Error) $
gitProc deployPath ["add", "."]
callProcessAndLogOutput (Debug, Error) $
gitProc deployPath ["commit", "-m", "New deployment"]
putLog Notice $ "Deployed => " <> T.pack route
where
callProcess' envMap cmd args = do
let p = setEnvOverride (envMap <>) $ setDelegateCtlc True $ proc cmd args
callProcessAndLogOutput (Notice, Notice) p
deployUpdate :: MonadObelisk m => FilePath -> m ()
deployUpdate deployPath = updateThunkToLatest (ThunkUpdateConfig Nothing (ThunkConfig Nothing)) (deployPath </> "src")
data PlatformDeployment = Android | IOS
deriving (Show, Eq)
renderPlatformDeployment :: PlatformDeployment -> String
renderPlatformDeployment = \case
Android -> "android"
IOS -> "ios"
deployMobile :: forall m. MonadObelisk m => PlatformDeployment -> [String] -> m ()
deployMobile platform mobileArgs = withProjectRoot "." $ \root -> do
let srcDir = root </> "src"
configDir = root </> "config"
exists <- liftIO $ doesDirectoryExist srcDir
unless exists $ failWith "ob test should be run inside of a deploy directory"
(nixBuildTarget, extraArgs) <- case platform of
Android -> do
let keystorePath = root </> "android_keystore.jks"
keytoolConfPath = root </> "android_keytool_config.json"
hasKeystore <- liftIO $ doesFileExist keystorePath
when (not hasKeystore) $ do
TODO log instructions for how to modify the keystore
putLog Notice $ "Creating keystore: " <> T.pack keystorePath
putLog Notice "Enter a keystore password: "
keyStorePassword <- liftIO $ withEcho False getLine
putLog Notice "Re-enter the keystore password: "
keyStorePassword' <- liftIO $ withEcho False getLine
unless (keyStorePassword' == keyStorePassword) $ failWith "passwords do not match"
let keyToolConf = KeytoolConfig
{ _keytoolConfig_keystore = keystorePath
, _keytoolConfig_alias = "obelisk"
, _keytoolConfig_storepass = keyStorePassword
, _keytoolConfig_keypass = keyStorePassword
}
createKeystore root keyToolConf
liftIO $ BSL.writeFile keytoolConfPath $ encode keyToolConf
checkKeytoolConfExist <- liftIO $ doesFileExist keytoolConfPath
unless checkKeytoolConfExist $ failWith "Missing android KeytoolConfig"
keytoolConfContents <- liftIO $ BSL.readFile keytoolConfPath
keyArgs <- case eitherDecode keytoolConfContents :: Either String KeytoolConfig of
Left err -> failWith $ T.pack err
Right conf -> pure
[ "--sign"
, "--store-file", _keytoolConfig_keystore conf
, "--store-password", _keytoolConfig_storepass conf
, "--key-alias", _keytoolConfig_alias conf
, "--key-password", _keytoolConfig_keypass conf
]
let expr = mconcat
[ "with (import ", toNixPath srcDir, " {});"
, "android.frontend.override (drv: {"
, "isRelease = true;"
, "staticSrc = (passthru.__androidWithConfig ", configDir, ").frontend.staticSrc;"
, "assets = (passthru.__androidWithConfig ", configDir, ").frontend.assets;"
, "})"
]
return (Target
{ _target_path = Nothing
, _target_attr = Nothing
, _target_expr = Just expr
}, keyArgs)
IOS -> do
let expr = mconcat
[ "with (import ", toNixPath srcDir, " {});"
, "ios.frontend.override (_: { staticSrc = (passthru.__iosWithConfig ", toNixPath configDir, ").frontend.staticSrc; })"
]
return (Target
{ _target_path = Nothing
, _target_attr = Nothing
, _target_expr = Just expr
}, [])
result <- nixCmd $ NixCmd_Build $ def
& nixBuildConfig_outLink .~ OutLink_None
& nixCmdConfig_target .~ nixBuildTarget
let mobileArtifact = case platform of
IOS -> "iOS App"
Android -> "Android APK"
putLog Notice $ T.pack $ unwords ["Your recently built", mobileArtifact, "can be found at the following path:", show result]
callProcessAndLogOutput (Notice, Error) $ proc (result </> "bin" </> "deploy") (mobileArgs ++ extraArgs)
where
withEcho showEcho f = bracket
(do
prevEcho <- hGetEcho stdin
hSetEcho stdin showEcho
pure prevEcho
)
(hSetEcho stdin)
(const f)
data KeytoolConfig = KeytoolConfig
{ _keytoolConfig_keystore :: FilePath
, _keytoolConfig_alias :: String
, _keytoolConfig_storepass :: String
, _keytoolConfig_keypass :: String
} deriving (Show, Generic)
instance FromJSON KeytoolConfig
instance ToJSON KeytoolConfig
createKeystore :: MonadObelisk m => FilePath -> KeytoolConfig -> m ()
createKeystore root config =
callProcessAndLogOutput (Notice, Notice) $ setCwd (Just root) $ proc jreKeyToolPath
[ "-genkeypair", "-noprompt"
, "-keystore", _keytoolConfig_keystore config
, "-keyalg", "RSA", "-keysize", "2048"
, "-validity", "1000000"
, "-storepass", _keytoolConfig_storepass config
, "-alias", _keytoolConfig_alias config
, "-keypass", _keytoolConfig_keypass config
]
| Simplified deployment configuration mechanism . At one point we may revisit this .
writeDeployConfig :: MonadObelisk m => FilePath -> FilePath -> String -> m ()
writeDeployConfig deployDir fname = liftIO . writeFile (deployDir </> fname)
readDeployConfig :: MonadObelisk m => FilePath -> FilePath -> m String
readDeployConfig deployDir fname = liftIO $ do
fmap (T.unpack . T.strip) $ T.readFile $ deployDir </> fname
verifyHostKey :: MonadObelisk m => FilePath -> FilePath -> String -> m ()
verifyHostKey knownHostsPath keyPath hostName =
callProcessAndLogOutput (Notice, Warning) $ proc sshPath $
sshArgs knownHostsPath keyPath True <>
[ "root@" <> hostName
, "-o", "NumberOfPasswordPrompts=0"
, "exit"
]
sshArgs :: FilePath -> FilePath -> Bool -> [String]
sshArgs knownHostsPath keyPath askHostKeyCheck =
[ "-o", "UserKnownHostsFile=" <> knownHostsPath
, "-o", "StrictHostKeyChecking=" <> if askHostKeyCheck then "ask" else "yes"
, "-i", keyPath
]
data InvalidRoute
= InvalidRoute_NotHttps URI
| InvalidRoute_MissingScheme URI
| InvalidRoute_MissingHost URI
| InvalidRoute_HasPort URI
| InvalidRoute_HasPath URI
deriving Show
instance Exception InvalidRoute where
displayException = \case
InvalidRoute_MissingScheme uri -> route uri "must have an URI scheme"
InvalidRoute_NotHttps uri -> route uri "must be HTTPS"
InvalidRoute_MissingHost uri -> route uri "must contain a hostname"
InvalidRoute_HasPort uri -> route uri "cannot specify port"
InvalidRoute_HasPath uri -> route uri "cannot contain path"
where
route uri err = T.unpack $ "Route (" <> URI.render uri <> ") " <> err
getHostFromRoute
:: MonadObelisk m
-> String
-> m String
getHostFromRoute mustBeHttps route = do
result :: Either InvalidRoute String <- try $ do
validateCommonRouteAndGetHost mustBeHttps =<< URI.mkURI (T.strip $ T.pack route)
either (failWith . T.pack . displayException) pure result
validateCommonRouteAndGetHost
:: (MonadThrow m, MonadObelisk m)
-> URI
-> m String
validateCommonRouteAndGetHost mustBeHttps uri = do
case uri ^? uriScheme of
Just (Just (URI.unRText -> s)) -> case (mustBeHttps, s) of
(False, _) -> pure ()
(True, "https") -> pure ()
_ -> throwM $ InvalidRoute_NotHttps uri
_ -> throwM $ InvalidRoute_MissingScheme uri
case uri ^. uriPath of
[] -> pure ()
_path -> throwM $ InvalidRoute_HasPath uri
case uri ^? uriAuthority . _Right . authPort of
Just (Just _port) -> throwM $ InvalidRoute_HasPort uri
_ -> pure ()
case uri ^? uriAuthority . _Right . authHost of
Nothing -> throwM $ InvalidRoute_MissingHost uri
Just sslHost -> return $ T.unpack $ URI.unRText sslHost
|
42afc83497ea5e472e770e19178c99a8ce5c8971e338b516bf114685690df267 | directrix1/DuplicateBridgeTeamSteele | replace.lisp | (include-book "utilities")
; chrs [characters] :: list of characters to be scanned
; so-far string :: string seen so far
; div character :: character to split at
;
; returns a list [string (characters)]
; split at div, return a list where string is the chrs->str of the
; character seen before div and (characters) is the remaining
; characters in [characters] after div
(defun split2 (chrs so-far div)
(if (consp chrs)
(if (equal (first chrs) div)
(list (reverse (chrs->str so-far)) (rest chrs))
(split2 (rest chrs)
(cons (first chrs) so-far)
div))
(list (reverse (chrs->str so-far)) nil)))
; chrs [characters] :: list of characters
;
; returns t or nil
; if chrs contains only aA - zZ or a hyphen, then return true
; else return false
(defun possible-key (chrs)
(if (consp chrs)
(let ((first-char-code (char-code (first chrs))))
(and (or (and (>= first-char-code 65) ; At least A
(<= first-char-code 90)); At most Z
(= first-char-code 45)) ;Hyphen
(possible-key (rest chrs))))
t))
; chunks [string] :: list of strings
replacements [ ( string string ) ] : : list of conspairs of strings
;
; if the string in chunks is found in replacements, replace it with
; another string
; (chunks-replace (list "NO" "FUN") '(("NO" . "GO") ("FUN" . "AWAY")))
; -> (list "GO" "AWAY")
(defun chunks-replace (chunks replacements)
(if (consp chunks)
(let ((lookup (if (possible-key (str->chrs (first chunks)))
(assoc-string-equal (first chunks)
replacements)
nil)))
(cons (if (consp lookup)
(cdr lookup)
(first chunks))
(chunks-replace (rest chunks) replacements)))
nil))
; chrs [characters] :: list of characters
;
; returns [string]
; splits a list of characters at the | symbol
; returns a list consisting of strings, where each string is the
; characters appearing before a |
(defun bar-split (chrs)
(if (endp chrs)
nil
(let ((first-division (split2 chrs nil #\|)))
(cons (first first-division)
(bar-split (second first-division))))))
; line :: string
replacements [ ( string string ) ] : : list of conspairs of strings
;
if line contains a string surrounded by pipes |EXAMPLE| ,
this method looks and sees if |EXAMPLE| exists in the replacements
list , and if it is , |EXAMPLE| is replaced with some other string
(defun line-replace (line replacements)
(string-concat
(chunks-replace (bar-split (str->chrs line)) replacements)))
; template-replace - Performs a replacement on a template list
; of strings.
Any substring of the form |KEY| in the template is replaced by the
; cooresponding value. Keys are mapped to values by an association list.
; Keys must be made up of only capital A-Z and the dash.
;
; template [string] :: list of list of strings
replacements [ ( string . string ) ] : : list of key - value
; of strings
;
; returns [string]
(defun template-replace (template replacements)
(if (endp template)
nil
(cons (line-replace (first template)
replacements)
(template-replace (rest template)
replacements)))) | null | https://raw.githubusercontent.com/directrix1/DuplicateBridgeTeamSteele/0f0d0312569fb1d26d568e2b87d66ac160ac60c3/timpl/dropbox/psp%2B%2B/replace.lisp | lisp | chrs [characters] :: list of characters to be scanned
so-far string :: string seen so far
div character :: character to split at
returns a list [string (characters)]
split at div, return a list where string is the chrs->str of the
character seen before div and (characters) is the remaining
characters in [characters] after div
chrs [characters] :: list of characters
returns t or nil
if chrs contains only aA - zZ or a hyphen, then return true
else return false
At least A
At most Z
Hyphen
chunks [string] :: list of strings
if the string in chunks is found in replacements, replace it with
another string
(chunks-replace (list "NO" "FUN") '(("NO" . "GO") ("FUN" . "AWAY")))
-> (list "GO" "AWAY")
chrs [characters] :: list of characters
returns [string]
splits a list of characters at the | symbol
returns a list consisting of strings, where each string is the
characters appearing before a |
line :: string
template-replace - Performs a replacement on a template list
of strings.
cooresponding value. Keys are mapped to values by an association list.
Keys must be made up of only capital A-Z and the dash.
template [string] :: list of list of strings
of strings
returns [string]
| (include-book "utilities")
(defun split2 (chrs so-far div)
(if (consp chrs)
(if (equal (first chrs) div)
(list (reverse (chrs->str so-far)) (rest chrs))
(split2 (rest chrs)
(cons (first chrs) so-far)
div))
(list (reverse (chrs->str so-far)) nil)))
(defun possible-key (chrs)
(if (consp chrs)
(let ((first-char-code (char-code (first chrs))))
(possible-key (rest chrs))))
t))
replacements [ ( string string ) ] : : list of conspairs of strings
(defun chunks-replace (chunks replacements)
(if (consp chunks)
(let ((lookup (if (possible-key (str->chrs (first chunks)))
(assoc-string-equal (first chunks)
replacements)
nil)))
(cons (if (consp lookup)
(cdr lookup)
(first chunks))
(chunks-replace (rest chunks) replacements)))
nil))
(defun bar-split (chrs)
(if (endp chrs)
nil
(let ((first-division (split2 chrs nil #\|)))
(cons (first first-division)
(bar-split (second first-division))))))
replacements [ ( string string ) ] : : list of conspairs of strings
if line contains a string surrounded by pipes |EXAMPLE| ,
this method looks and sees if |EXAMPLE| exists in the replacements
list , and if it is , |EXAMPLE| is replaced with some other string
(defun line-replace (line replacements)
(string-concat
(chunks-replace (bar-split (str->chrs line)) replacements)))
Any substring of the form |KEY| in the template is replaced by the
replacements [ ( string . string ) ] : : list of key - value
(defun template-replace (template replacements)
(if (endp template)
nil
(cons (line-replace (first template)
replacements)
(template-replace (rest template)
replacements)))) |
50fba6d920e2236feb5c6739b4bdcd0a6de0950d802c58dc1bbfaf4379c4c88c | haskell/time | LocalTime.hs | {-# LANGUAGE Safe #-}
module Data.Time.LocalTime (
-- * Time zones
TimeZone (..),
timeZoneOffsetString,
timeZoneOffsetString',
minutesToTimeZone,
hoursToTimeZone,
utc,
-- getting the locale time zone
getTimeZone,
getCurrentTimeZone,
module Data.Time.LocalTime.Internal.TimeOfDay,
module Data.Time.LocalTime.Internal.CalendarDiffTime,
module Data.Time.LocalTime.Internal.LocalTime,
module Data.Time.LocalTime.Internal.ZonedTime,
) where
import Data.Time.Format ()
import Data.Time.LocalTime.Internal.CalendarDiffTime
import Data.Time.LocalTime.Internal.LocalTime
import Data.Time.LocalTime.Internal.TimeOfDay
import Data.Time.LocalTime.Internal.TimeZone hiding (timeZoneOffsetString'')
import Data.Time.LocalTime.Internal.ZonedTime
| null | https://raw.githubusercontent.com/haskell/time/dba6302b244a7b991ee7cac0d16461fddd222965/lib/Data/Time/LocalTime.hs | haskell | # LANGUAGE Safe #
* Time zones
getting the locale time zone |
module Data.Time.LocalTime (
TimeZone (..),
timeZoneOffsetString,
timeZoneOffsetString',
minutesToTimeZone,
hoursToTimeZone,
utc,
getTimeZone,
getCurrentTimeZone,
module Data.Time.LocalTime.Internal.TimeOfDay,
module Data.Time.LocalTime.Internal.CalendarDiffTime,
module Data.Time.LocalTime.Internal.LocalTime,
module Data.Time.LocalTime.Internal.ZonedTime,
) where
import Data.Time.Format ()
import Data.Time.LocalTime.Internal.CalendarDiffTime
import Data.Time.LocalTime.Internal.LocalTime
import Data.Time.LocalTime.Internal.TimeOfDay
import Data.Time.LocalTime.Internal.TimeZone hiding (timeZoneOffsetString'')
import Data.Time.LocalTime.Internal.ZonedTime
|
bee8dc435d2b01e20c4ab1b0f97f200c0384273b582a6391bcb5f97cf17c10e2 | xvw/preface | freer_monad_print_read_or_fail.mli | val cases : (string * unit Alcotest.test_case list) list
| null | https://raw.githubusercontent.com/xvw/preface/ee5934395476c3e44451e3effffa0fc7db68b83e/test/preface_examples_test/freer_monad_print_read_or_fail.mli | ocaml | val cases : (string * unit Alcotest.test_case list) list
| |
f766caa8f3241fb99e8155cd555b6d9d984b8274c4f2a7e159ec9d06b62cfeab | solomon-b/HowardLang | Typechecker.hs | # LANGUAGE ScopedTypeVariables #
# LANGUAGE TemplateHaskell #
module HowardLang.Typechecker where
import Control.Monad.Except
import Control.Monad.Identity
import Control.Monad.Reader
import Data.Functor.Foldable
import Data.Maybe (mapMaybe)
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as M
import Data.Set (Set)
import qualified Data.Set as S
import Control.Monad.State
import Lens.Micro
import Lens.Micro.TH
import HowardLang.Types
import HowardLang.PrettyPrinter
newtype TypecheckT m a =
TypecheckT { unTypecheckT :: ExceptT Err (ReaderT Context m) a }
deriving (Functor, Applicative, Monad, MonadReader Context, MonadError Err)
type TypecheckM a = TypecheckT Identity a
runTypecheckT :: Context -> TypecheckT m a -> m (Either Err a)
runTypecheckT gamma = flip runReaderT gamma . runExceptT . unTypecheckT
runTypecheckM :: Context -> TypecheckT Identity a -> Either Err a
runTypecheckM gamma = runIdentity . runTypecheckT gamma
typetest :: Term -> Either Err Type
typetest = runTypecheckM [] . typecheck
-- TODO: Make this safer
getBinding :: Context -> Int -> Type
getBinding xs i = snd $ xs !! i
-- TODO: Improve error reporting!!!!
natToInt :: MonadError Err m => Term -> m Int
natToInt Z = pure 0
natToInt (S t) = (+1) <$> natToInt t
natToInt _ = throwTypeError' "Type Error: Excepted Nat"
checkTotal :: MonadError Err m => [a] -> [b] -> m ()
checkTotal xs ys = if length xs /= length ys then throwTypeError' "Error: Pattern Match Non-Total" else pure ()
-- TODO: How would I write this as a recursion scheme?
infixl !!!
(!!!) :: [a] -> Int -> Maybe a
(!!!) [] _ = Nothing
(!!!) (x:_) 0 = Just x
(!!!) (_:xs) i = xs !!! (i - 1)
typecheck :: (MonadError Err m , MonadReader Context m) => Term -> m Type
typecheck = para ralgebra
where
ralgebra :: (MonadError Err m , MonadReader Context m) => TermF (Term, m Type) -> m Type
ralgebra = \case
VarF i -> asks (`getBinding` i)
AppF (t1, mty1) (_, mty2) -> mty1 >>= \case
FuncT ty1 ty2 -> do
ty2' <- mty2
if ty2' == ty1
then pure ty2
else throwTypeError t1 ty1 ty2'
ty -> throwTypeError' $ pretty t1 ++ " :: " ++ show ty ++ " is not a function"
AbsF var ty (_, mty2) -> FuncT ty <$> local (update var ty) mty2
LetF v (_, mty1) (_, mty2) -> mty1 >>= \ty1 -> local (update v ty1) mty2
CaseF (n, mnTy) (z, mzTy) v (_, msTy) -> mnTy >>= \case
NatT -> do
zTy <- mzTy
sTy <- local (update v NatT ) msTy
if zTy == sTy
then pure sTy
else throwTypeError z zTy sTy
nTy -> throwTypeError n nTy NatT
VariantCaseF (_, mty1) cases -> mty1 >>= \case
VariantT casesT -> do
let cases' = mapMaybe (traverseOf _2 id) cases
checkTotal cases casesT
types <- traverse (bindLocalTags' casesT) cases'
if allEqual types
then pure $ head types
else throwTypeError' $ "Type mismatch between cases: " ++ show types
ty -> throwTypeError' $ "Expected a Variant Type but got: " ++ show ty
UnitF -> pure UnitT
TruF -> pure BoolT
FlsF -> pure BoolT
ZF -> pure NatT
IfF (t1, mty1) (t2, mty2) (_, mty3) -> mty1 >>= \case
BoolT -> mty2 >>= \ty2 -> mty3 >>= \ty3 -> if ty2 == ty3 then pure ty2 else throwTypeError t2 ty2 ty3
ty1 -> throwTypeError t1 ty1 BoolT
SF (t1, mty) -> mty >>= \case
NatT -> pure NatT
ty -> throwTypeError t1 ty NatT
AsF (t@(Tag tag _), mtagTy) ty -> mtagTy >>= \ty1 ->
case ty of
VariantT tys ->
case lookup tag tys of
Just ty' | ty' == ty1 -> pure ty
_ -> throwTypeError t ty1 ty -- TODO: Improve this error, it does not reference the sum type.
_ -> throwTypeError t ty1 ty
AsF (t1, mTy) ty -> mTy >>= \ty1' ->
if ty1' == ty
then pure ty
else throwTypeError t1 ty1' ty
TupleF ts -> TupleT . fmap snd <$> traverse (traverse snd) ts
GetF (_, mTys) tag -> mTys >>= \case
TupleT tys -> maybe (throwTypeError' "Type Error: Projection failed") pure (tys !!! read tag)
RecordT tys -> maybe (throwTypeError' "Type Error: Projection failed") pure (lookup tag tys)
_ -> throwTypeError' "Catastrophic failure! This shouldnt be possible."
FixLetF (t1, mTy) -> mTy >>= \case
FuncT ty1 ty2 | ty1 == ty2 -> pure ty2
FuncT ty1 ty2 -> throwTypeError t1 ty2 ty1
ty -> throwTypeError' $ "Type Error: " ++ show ty ++ " is not a function type"
UnrollF u (_, mTy1) ->
case u of
FixT _ ty -> do
let u' = typeSubstTop u ty
ty1 <- mTy1
if ty1 == u
then pure u'
else throwTypeError' "Type Error: Temp Error bad Unroll"
_ -> mTy1
RollF u (_, mTy1) ->
case u of
FixT _ ty -> do
let u' = typeSubstTop u ty
ty1 <- mTy1
if ty1 == u'
then pure u
else throwTypeError' $ "Type Error: " ++ show u' ++ " != " ++ show ty1
_ -> mTy1
FstF (t, mTy) ->
case t of
Pair{} -> mTy
_ -> mTy >>= \case
PairT ty1 _ -> pure ty1
ty -> throwTypeError' $ "Expected a Pair but got: " ++ show ty
SndF (t, mTy) ->
case t of
Pair{} -> mTy
_ -> mTy >>= \case
PairT _ ty2 -> pure ty2
ty -> throwTypeError' $ "Expected a Pair but got: " ++ show ty
PairF (_, mTy1) (_, mTy2) -> PairT <$> mTy1 <*> mTy2
RecordF ts -> RecordT <$> traverse (traverse snd) ts
TagF _ (_, mTy) -> mTy
update :: Varname -> Type -> Context -> Context
update var ty = (:) (var, ty)
bindLocalTags' ty1 (tag, bndr, (_, mTy)) = case lookup tag ty1 of
Just tyC -> local (update bndr tyC) mTy
Nothing -> throwTypeError' $ "Expected type: " ++ show (VariantT ty1)
-------------------------
--- Type Substitution ---
-------------------------
typeShift :: DeBruijn -> Type -> Type
typeShift target t = runReader (cataA algebra t) 0
where
algebra :: TypeF (Reader Int Type) -> Reader Int Type
algebra = \case
VarTF j -> ask >>= \i -> if j >= i then pure (VarT $ j + target) else pure (VarT j)
FixTF b t1 -> FixT b <$> local (+1) t1
t' -> fmap embed (sequenceA t')
typeSubst :: DeBruijn -> Type -> Type -> Type
typeSubst target s t = runReader (cataA algebra t) (s, 0)
where
algebra :: TypeF (Reader (Type, Int) Type) -> Reader (Type, Int) Type
algebra = \case
VarTF x -> ask >>= \ctx -> if x == target + snd ctx then pure (fst ctx) else pure (VarT x)
FixTF b ty -> FixT b <$> local update ty
t' -> fmap embed (sequenceA t')
update :: (Type, Int) -> (Type, Int)
update (ty, i) = (ty, i + 1)
typeSubstTop :: Type -> Type -> Type
typeSubstTop s t = typeShift (-1) (typeSubst 0 (typeShift 1 s) t)
------------------------------------------------------------
------ TODO: IMPROVE ERROR MESSAGING MASSIVELY !!!!!! ------
------------------------------------------------------------
{-
Does this form encapsulate all type errors?
"Type Error: Term {t} of type `{T1}` does not match expected type {T2} in expression: {TERM}."
-}
throwTypeError :: MonadError Err m => Term -> Type -> Type -> m a
throwTypeError t1 ty1 ty2 = throwError . T . TypeError $
"Type Error:\n\r" ++
"Expected Type: " ++ show ty2 ++ "\n\r" ++
"Actual Type: " ++ show ty1 ++ "\n\r" ++
"For Term: " ++ pretty t1
throwTypeError' :: MonadError Err m => String -> m a
throwTypeError' = throwError . T . TypeError
----------------------------
--- Constraint Generator ---
----------------------------
Blatently stolen from Candor
genFresh :: [String]
genFresh = ((: []) <$> ['a'..'z']) ++
do
n <- [1..] :: [Int]
a <- ['a'..'z']
pure (a : show n)
type Constraint = (Type, Type)
data InferCtx = InferCtx { _freshNames :: [String], _constraints :: [Constraint] }
makeLenses ''InferCtx
type InferM a = ReaderT Context (State InferCtx) a
evalInferM :: Context -> InferM a -> a
evalInferM gamma = flip evalState ctx . flip runReaderT gamma
where
ctx :: InferCtx
ctx = InferCtx { _freshNames = genFresh, _constraints = [] }
execInferM :: Context -> InferM a -> InferCtx
execInferM gamma = flip execState ctx . flip runReaderT gamma
where
ctx :: InferCtx
ctx = InferCtx { _freshNames = genFresh, _constraints = [] }
evalInferM' :: [Constraint] -> InferM a -> a
evalInferM' cstrs = flip evalState ctx . flip runReaderT []
where
ctx :: InferCtx
ctx = InferCtx { _freshNames = genFresh, _constraints = cstrs }
fresh :: InferM Type
fresh = do
name <- gets (head . _freshNames)
modify (over freshNames tail)
pure (TVar name)
recon :: Term -> InferM Type
recon = \case
Var i -> do
ty <- asks (`getBinding` i)
modify $ over constraints id
pure ty
Abs v ty term -> do
ty2 <- local ((:) (v, ty)) (recon term)
pure $ FuncT ty ty2
App t1 t2 -> do
ty1 <- recon t1
ty2 <- recon t2
names <- gets _freshNames
cnstrs <- gets _constraints
let freshName = head names
put $ InferCtx (tail names) $ (ty1, FuncT ty2 (TVar freshName)):cnstrs
pure $ TVar freshName
Tru -> pure BoolT
Fls -> pure BoolT
Z -> pure NatT
S t -> do
ty <- recon t
modify $ over constraints ((:) (ty, NatT))
pure NatT
If t1 t2 t3 -> do
ty1 <- recon t1
ty2 <- recon t2
ty3 <- recon t3
modify $ over constraints ([(ty1, BoolT), (ty2, ty3)] ++)
pure ty3
Pair t1 t2 -> do
ty1 <- recon t1
ty2 <- recon t2
tva <- fresh
tvb <- fresh
modify $ over constraints ([(ty1, tva),(ty2, tvb)] ++)
pure $ PairT ty1 ty2
Fst term -> do
ty <- recon term
tva <- fresh
tvb <- fresh
modify $ over constraints ((:) (ty, PairT tva tvb))
pure tva
Snd term -> do
ty <- recon term
tva <- fresh
tvb <- fresh
modify $ over constraints ((:) (ty, PairT tva tvb))
pure tvb
Tuple terms -> do
let f (_, term) = do
ty <- recon term
tv <- fresh
modify $ over constraints ((:) (ty, tv))
pure tv
TupleT <$> traverse f terms
--Get term _ -> do
-- ty <- recon term
-- tv <- fresh
modify $ over constraints ( (: ) ( ty , TupleT [ tv ] ) )
-- pure tv
substinty :: Varname -> Type -> Type -> Type
substinty tyX tyT tyS = f tyS
where
f tyS' = case tyS' of
FuncT ty1 ty2 -> FuncT (f ty1) (f ty2)
NatT -> NatT
BoolT -> BoolT
TVar v -> if v == tyX then tyT else TVar v
PairT ty1 ty2 -> PairT (f ty1) (f ty2)
TupleT types -> TupleT $ f <$> types
applysubst :: Type -> InferM Type
applysubst tyT = do
cnstrs <- gets _constraints
pure $ foldl (\tyS (TVar tyX, tyC2) -> substinty tyX tyC2 tyS) tyT cnstrs
substinconstr :: Varname -> Type -> [Constraint] -> [Constraint]
substinconstr tyX tyT cnstrs =
fmap (\(tyS1, tyS2) -> (substinty tyX tyT tyS1, substinty tyX tyT tyS2)) cnstrs
unify :: [Constraint] -> [Constraint]
unify = \case
[] -> []
(tyS, TVar tyX) : rest ->
if tyS == TVar tyX
then unify rest
else unify (substinconstr tyX tyS rest) ++ [(TVar tyX, tyS)]
(TVar tyX, tyT) : rest ->
if tyT == TVar tyX
then unify rest
else unify (substinconstr tyX tyT rest) ++ [(TVar tyX, tyT)]
(NatT, NatT) : rest -> unify rest
(BoolT, BoolT) : rest -> unify rest
(FuncT tyS1 tyS2, FuncT tyT1 tyT2) : rest -> unify $ (tyS1, tyT1) : (tyS2, tyT2) : rest
(PairT tyS1 tyS2, PairT tyT1 tyT2) : rest -> unify $ (tyS1, tyT1) : (tyS2, tyT2) : rest
(TupleT tyS, TupleT tyT) : rest -> unify $ zip tyS tyT ++ rest
(tyS, tyT) : rest -> error $ "unsolvable constraint: " ++ show tyS ++ show tyT
substitute :: Constraint -> Type -> Type
substitute c@(TVar a, ty) = \case
TVar b | a == b -> ty
ty1 `FuncT` ty2 -> substitute c ty1 `FuncT` substitute c ty2
ty1 `PairT` ty2 -> substitute c ty1 `PairT` substitute c ty2
TupleT terms -> TupleT $ substitute c <$> terms
t -> t
substitutes :: [Constraint] -> Type -> Type
substitutes cs ty = foldl (flip substitute) ty cs
inferType :: Term -> Type
inferType term = evalInferM [] $ do
ty <- recon term
cs <- gets _constraints
let cs' = unify cs
pure $ substitutes cs' ty
type Subst = Map String Type
--
: : Subst
nullSubst = M.empty
--
compose : : Subst - > Subst - > Subst
--compose s1 s2 = M.map (apply s1) s2 `M.union` s1
--
--class Substitutable a where
-- apply :: Subst -> a -> a
-- ftv :: a -> S.Set String
--
instance where
apply _ BoolT = BoolT
apply _ NatT = NatT
apply _ UnitT = UnitT
apply a ) = t a s
apply s ( t1 ` FuncT ` t2 ) = apply s t1 ` FuncT ` apply s t2
--
-- ftv BoolT = S.empty
-- ftv NatT = S.empty
ftv UnitT = S.empty
ftv ( TVar a ) = S.singleton a
ftv ( t1 ` FuncT ` t2 ) = ftv t1 ` S.union ` ftv t2
--
--instance Substitutable a => Substitutable [a] where
-- apply = fmap . apply
-- ftv = foldr (S.union . ftv) S.empty
--
unify : : Type - > Type - > InferM Subst
unify ( t1 ` FuncT ` t2 ) ( t1 ' ` FuncT ` t2 ' ) = do
-- s1 <- unify t1 t1'
-- s2 <- unify (apply s1 t2) (apply s1 t2')
-- pure $ s2 `compose` s1
unify ( TVar a ) t = bind a t
unify t ( TVar a ) = bind a t
unify t1 t2 | t1 = = t2 = pure nullSubst
--unify t1 t2 = error $ "Unification failed: " ++ show t1 ++ " ~ " ++ show t2
--
bind : : String - > Type - > InferM Subst
bind a t | t = = TVar a = return nullSubst
-- -- | occursCheck ...
| otherwise = return $ M.singleton a t
| null | https://raw.githubusercontent.com/solomon-b/HowardLang/b7af7ea2e47d7477d33637406ebb04f6e9b55f9d/src/HowardLang/Typechecker.hs | haskell | TODO: Make this safer
TODO: Improve error reporting!!!!
TODO: How would I write this as a recursion scheme?
TODO: Improve this error, it does not reference the sum type.
-----------------------
- Type Substitution ---
-----------------------
----------------------------------------------------------
---- TODO: IMPROVE ERROR MESSAGING MASSIVELY !!!!!! ------
----------------------------------------------------------
Does this form encapsulate all type errors?
"Type Error: Term {t} of type `{T1}` does not match expected type {T2} in expression: {TERM}."
--------------------------
- Constraint Generator ---
--------------------------
Get term _ -> do
ty <- recon term
tv <- fresh
pure tv
compose s1 s2 = M.map (apply s1) s2 `M.union` s1
class Substitutable a where
apply :: Subst -> a -> a
ftv :: a -> S.Set String
ftv BoolT = S.empty
ftv NatT = S.empty
instance Substitutable a => Substitutable [a] where
apply = fmap . apply
ftv = foldr (S.union . ftv) S.empty
s1 <- unify t1 t1'
s2 <- unify (apply s1 t2) (apply s1 t2')
pure $ s2 `compose` s1
unify t1 t2 = error $ "Unification failed: " ++ show t1 ++ " ~ " ++ show t2
-- | occursCheck ... | # LANGUAGE ScopedTypeVariables #
# LANGUAGE TemplateHaskell #
module HowardLang.Typechecker where
import Control.Monad.Except
import Control.Monad.Identity
import Control.Monad.Reader
import Data.Functor.Foldable
import Data.Maybe (mapMaybe)
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as M
import Data.Set (Set)
import qualified Data.Set as S
import Control.Monad.State
import Lens.Micro
import Lens.Micro.TH
import HowardLang.Types
import HowardLang.PrettyPrinter
newtype TypecheckT m a =
TypecheckT { unTypecheckT :: ExceptT Err (ReaderT Context m) a }
deriving (Functor, Applicative, Monad, MonadReader Context, MonadError Err)
type TypecheckM a = TypecheckT Identity a
runTypecheckT :: Context -> TypecheckT m a -> m (Either Err a)
runTypecheckT gamma = flip runReaderT gamma . runExceptT . unTypecheckT
runTypecheckM :: Context -> TypecheckT Identity a -> Either Err a
runTypecheckM gamma = runIdentity . runTypecheckT gamma
typetest :: Term -> Either Err Type
typetest = runTypecheckM [] . typecheck
getBinding :: Context -> Int -> Type
getBinding xs i = snd $ xs !! i
natToInt :: MonadError Err m => Term -> m Int
natToInt Z = pure 0
natToInt (S t) = (+1) <$> natToInt t
natToInt _ = throwTypeError' "Type Error: Excepted Nat"
checkTotal :: MonadError Err m => [a] -> [b] -> m ()
checkTotal xs ys = if length xs /= length ys then throwTypeError' "Error: Pattern Match Non-Total" else pure ()
infixl !!!
(!!!) :: [a] -> Int -> Maybe a
(!!!) [] _ = Nothing
(!!!) (x:_) 0 = Just x
(!!!) (_:xs) i = xs !!! (i - 1)
typecheck :: (MonadError Err m , MonadReader Context m) => Term -> m Type
typecheck = para ralgebra
where
ralgebra :: (MonadError Err m , MonadReader Context m) => TermF (Term, m Type) -> m Type
ralgebra = \case
VarF i -> asks (`getBinding` i)
AppF (t1, mty1) (_, mty2) -> mty1 >>= \case
FuncT ty1 ty2 -> do
ty2' <- mty2
if ty2' == ty1
then pure ty2
else throwTypeError t1 ty1 ty2'
ty -> throwTypeError' $ pretty t1 ++ " :: " ++ show ty ++ " is not a function"
AbsF var ty (_, mty2) -> FuncT ty <$> local (update var ty) mty2
LetF v (_, mty1) (_, mty2) -> mty1 >>= \ty1 -> local (update v ty1) mty2
CaseF (n, mnTy) (z, mzTy) v (_, msTy) -> mnTy >>= \case
NatT -> do
zTy <- mzTy
sTy <- local (update v NatT ) msTy
if zTy == sTy
then pure sTy
else throwTypeError z zTy sTy
nTy -> throwTypeError n nTy NatT
VariantCaseF (_, mty1) cases -> mty1 >>= \case
VariantT casesT -> do
let cases' = mapMaybe (traverseOf _2 id) cases
checkTotal cases casesT
types <- traverse (bindLocalTags' casesT) cases'
if allEqual types
then pure $ head types
else throwTypeError' $ "Type mismatch between cases: " ++ show types
ty -> throwTypeError' $ "Expected a Variant Type but got: " ++ show ty
UnitF -> pure UnitT
TruF -> pure BoolT
FlsF -> pure BoolT
ZF -> pure NatT
IfF (t1, mty1) (t2, mty2) (_, mty3) -> mty1 >>= \case
BoolT -> mty2 >>= \ty2 -> mty3 >>= \ty3 -> if ty2 == ty3 then pure ty2 else throwTypeError t2 ty2 ty3
ty1 -> throwTypeError t1 ty1 BoolT
SF (t1, mty) -> mty >>= \case
NatT -> pure NatT
ty -> throwTypeError t1 ty NatT
AsF (t@(Tag tag _), mtagTy) ty -> mtagTy >>= \ty1 ->
case ty of
VariantT tys ->
case lookup tag tys of
Just ty' | ty' == ty1 -> pure ty
_ -> throwTypeError t ty1 ty
AsF (t1, mTy) ty -> mTy >>= \ty1' ->
if ty1' == ty
then pure ty
else throwTypeError t1 ty1' ty
TupleF ts -> TupleT . fmap snd <$> traverse (traverse snd) ts
GetF (_, mTys) tag -> mTys >>= \case
TupleT tys -> maybe (throwTypeError' "Type Error: Projection failed") pure (tys !!! read tag)
RecordT tys -> maybe (throwTypeError' "Type Error: Projection failed") pure (lookup tag tys)
_ -> throwTypeError' "Catastrophic failure! This shouldnt be possible."
FixLetF (t1, mTy) -> mTy >>= \case
FuncT ty1 ty2 | ty1 == ty2 -> pure ty2
FuncT ty1 ty2 -> throwTypeError t1 ty2 ty1
ty -> throwTypeError' $ "Type Error: " ++ show ty ++ " is not a function type"
UnrollF u (_, mTy1) ->
case u of
FixT _ ty -> do
let u' = typeSubstTop u ty
ty1 <- mTy1
if ty1 == u
then pure u'
else throwTypeError' "Type Error: Temp Error bad Unroll"
_ -> mTy1
RollF u (_, mTy1) ->
case u of
FixT _ ty -> do
let u' = typeSubstTop u ty
ty1 <- mTy1
if ty1 == u'
then pure u
else throwTypeError' $ "Type Error: " ++ show u' ++ " != " ++ show ty1
_ -> mTy1
FstF (t, mTy) ->
case t of
Pair{} -> mTy
_ -> mTy >>= \case
PairT ty1 _ -> pure ty1
ty -> throwTypeError' $ "Expected a Pair but got: " ++ show ty
SndF (t, mTy) ->
case t of
Pair{} -> mTy
_ -> mTy >>= \case
PairT _ ty2 -> pure ty2
ty -> throwTypeError' $ "Expected a Pair but got: " ++ show ty
PairF (_, mTy1) (_, mTy2) -> PairT <$> mTy1 <*> mTy2
RecordF ts -> RecordT <$> traverse (traverse snd) ts
TagF _ (_, mTy) -> mTy
update :: Varname -> Type -> Context -> Context
update var ty = (:) (var, ty)
bindLocalTags' ty1 (tag, bndr, (_, mTy)) = case lookup tag ty1 of
Just tyC -> local (update bndr tyC) mTy
Nothing -> throwTypeError' $ "Expected type: " ++ show (VariantT ty1)
typeShift :: DeBruijn -> Type -> Type
typeShift target t = runReader (cataA algebra t) 0
where
algebra :: TypeF (Reader Int Type) -> Reader Int Type
algebra = \case
VarTF j -> ask >>= \i -> if j >= i then pure (VarT $ j + target) else pure (VarT j)
FixTF b t1 -> FixT b <$> local (+1) t1
t' -> fmap embed (sequenceA t')
typeSubst :: DeBruijn -> Type -> Type -> Type
typeSubst target s t = runReader (cataA algebra t) (s, 0)
where
algebra :: TypeF (Reader (Type, Int) Type) -> Reader (Type, Int) Type
algebra = \case
VarTF x -> ask >>= \ctx -> if x == target + snd ctx then pure (fst ctx) else pure (VarT x)
FixTF b ty -> FixT b <$> local update ty
t' -> fmap embed (sequenceA t')
update :: (Type, Int) -> (Type, Int)
update (ty, i) = (ty, i + 1)
typeSubstTop :: Type -> Type -> Type
typeSubstTop s t = typeShift (-1) (typeSubst 0 (typeShift 1 s) t)
throwTypeError :: MonadError Err m => Term -> Type -> Type -> m a
throwTypeError t1 ty1 ty2 = throwError . T . TypeError $
"Type Error:\n\r" ++
"Expected Type: " ++ show ty2 ++ "\n\r" ++
"Actual Type: " ++ show ty1 ++ "\n\r" ++
"For Term: " ++ pretty t1
throwTypeError' :: MonadError Err m => String -> m a
throwTypeError' = throwError . T . TypeError
Blatently stolen from Candor
genFresh :: [String]
genFresh = ((: []) <$> ['a'..'z']) ++
do
n <- [1..] :: [Int]
a <- ['a'..'z']
pure (a : show n)
type Constraint = (Type, Type)
data InferCtx = InferCtx { _freshNames :: [String], _constraints :: [Constraint] }
makeLenses ''InferCtx
type InferM a = ReaderT Context (State InferCtx) a
evalInferM :: Context -> InferM a -> a
evalInferM gamma = flip evalState ctx . flip runReaderT gamma
where
ctx :: InferCtx
ctx = InferCtx { _freshNames = genFresh, _constraints = [] }
execInferM :: Context -> InferM a -> InferCtx
execInferM gamma = flip execState ctx . flip runReaderT gamma
where
ctx :: InferCtx
ctx = InferCtx { _freshNames = genFresh, _constraints = [] }
evalInferM' :: [Constraint] -> InferM a -> a
evalInferM' cstrs = flip evalState ctx . flip runReaderT []
where
ctx :: InferCtx
ctx = InferCtx { _freshNames = genFresh, _constraints = cstrs }
fresh :: InferM Type
fresh = do
name <- gets (head . _freshNames)
modify (over freshNames tail)
pure (TVar name)
recon :: Term -> InferM Type
recon = \case
Var i -> do
ty <- asks (`getBinding` i)
modify $ over constraints id
pure ty
Abs v ty term -> do
ty2 <- local ((:) (v, ty)) (recon term)
pure $ FuncT ty ty2
App t1 t2 -> do
ty1 <- recon t1
ty2 <- recon t2
names <- gets _freshNames
cnstrs <- gets _constraints
let freshName = head names
put $ InferCtx (tail names) $ (ty1, FuncT ty2 (TVar freshName)):cnstrs
pure $ TVar freshName
Tru -> pure BoolT
Fls -> pure BoolT
Z -> pure NatT
S t -> do
ty <- recon t
modify $ over constraints ((:) (ty, NatT))
pure NatT
If t1 t2 t3 -> do
ty1 <- recon t1
ty2 <- recon t2
ty3 <- recon t3
modify $ over constraints ([(ty1, BoolT), (ty2, ty3)] ++)
pure ty3
Pair t1 t2 -> do
ty1 <- recon t1
ty2 <- recon t2
tva <- fresh
tvb <- fresh
modify $ over constraints ([(ty1, tva),(ty2, tvb)] ++)
pure $ PairT ty1 ty2
Fst term -> do
ty <- recon term
tva <- fresh
tvb <- fresh
modify $ over constraints ((:) (ty, PairT tva tvb))
pure tva
Snd term -> do
ty <- recon term
tva <- fresh
tvb <- fresh
modify $ over constraints ((:) (ty, PairT tva tvb))
pure tvb
Tuple terms -> do
let f (_, term) = do
ty <- recon term
tv <- fresh
modify $ over constraints ((:) (ty, tv))
pure tv
TupleT <$> traverse f terms
modify $ over constraints ( (: ) ( ty , TupleT [ tv ] ) )
substinty :: Varname -> Type -> Type -> Type
substinty tyX tyT tyS = f tyS
where
f tyS' = case tyS' of
FuncT ty1 ty2 -> FuncT (f ty1) (f ty2)
NatT -> NatT
BoolT -> BoolT
TVar v -> if v == tyX then tyT else TVar v
PairT ty1 ty2 -> PairT (f ty1) (f ty2)
TupleT types -> TupleT $ f <$> types
applysubst :: Type -> InferM Type
applysubst tyT = do
cnstrs <- gets _constraints
pure $ foldl (\tyS (TVar tyX, tyC2) -> substinty tyX tyC2 tyS) tyT cnstrs
substinconstr :: Varname -> Type -> [Constraint] -> [Constraint]
substinconstr tyX tyT cnstrs =
fmap (\(tyS1, tyS2) -> (substinty tyX tyT tyS1, substinty tyX tyT tyS2)) cnstrs
unify :: [Constraint] -> [Constraint]
unify = \case
[] -> []
(tyS, TVar tyX) : rest ->
if tyS == TVar tyX
then unify rest
else unify (substinconstr tyX tyS rest) ++ [(TVar tyX, tyS)]
(TVar tyX, tyT) : rest ->
if tyT == TVar tyX
then unify rest
else unify (substinconstr tyX tyT rest) ++ [(TVar tyX, tyT)]
(NatT, NatT) : rest -> unify rest
(BoolT, BoolT) : rest -> unify rest
(FuncT tyS1 tyS2, FuncT tyT1 tyT2) : rest -> unify $ (tyS1, tyT1) : (tyS2, tyT2) : rest
(PairT tyS1 tyS2, PairT tyT1 tyT2) : rest -> unify $ (tyS1, tyT1) : (tyS2, tyT2) : rest
(TupleT tyS, TupleT tyT) : rest -> unify $ zip tyS tyT ++ rest
(tyS, tyT) : rest -> error $ "unsolvable constraint: " ++ show tyS ++ show tyT
substitute :: Constraint -> Type -> Type
substitute c@(TVar a, ty) = \case
TVar b | a == b -> ty
ty1 `FuncT` ty2 -> substitute c ty1 `FuncT` substitute c ty2
ty1 `PairT` ty2 -> substitute c ty1 `PairT` substitute c ty2
TupleT terms -> TupleT $ substitute c <$> terms
t -> t
substitutes :: [Constraint] -> Type -> Type
substitutes cs ty = foldl (flip substitute) ty cs
inferType :: Term -> Type
inferType term = evalInferM [] $ do
ty <- recon term
cs <- gets _constraints
let cs' = unify cs
pure $ substitutes cs' ty
type Subst = Map String Type
: : Subst
nullSubst = M.empty
compose : : Subst - > Subst - > Subst
instance where
apply _ BoolT = BoolT
apply _ NatT = NatT
apply _ UnitT = UnitT
apply a ) = t a s
apply s ( t1 ` FuncT ` t2 ) = apply s t1 ` FuncT ` apply s t2
ftv UnitT = S.empty
ftv ( TVar a ) = S.singleton a
ftv ( t1 ` FuncT ` t2 ) = ftv t1 ` S.union ` ftv t2
unify : : Type - > Type - > InferM Subst
unify ( t1 ` FuncT ` t2 ) ( t1 ' ` FuncT ` t2 ' ) = do
unify ( TVar a ) t = bind a t
unify t ( TVar a ) = bind a t
unify t1 t2 | t1 = = t2 = pure nullSubst
bind : : String - > Type - > InferM Subst
bind a t | t = = TVar a = return nullSubst
| otherwise = return $ M.singleton a t
|
dcebf5b23eef4e1bbaad1942e0f21c44810fe64b34d80f36309654f5bc45489a | open-telemetry/opentelemetry-erlang | otel_simple_processor.erl | %%%------------------------------------------------------------------------
Copyright 2021 , OpenTelemetry Authors
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
@doc This Span Processor synchronously exports each ended Span .
%%
Use this processor if ending a Span should block until it has been
%% exported. This is useful for cases like a serverless environment where
%% the application will possibly be suspended after handling a request.
%%
%% @end
%%%-----------------------------------------------------------------------
-module(otel_simple_processor).
-behaviour(gen_statem).
-behaviour(otel_span_processor).
-export([start_link/1,
on_start/3,
on_end/2,
force_flush/1,
report_cb/1,
%% deprecated
set_exporter/1,
set_exporter/2,
set_exporter/3]).
-export([init/1,
callback_mode/0,
idle/3,
exporting/3,
terminate/3]).
-deprecated({set_exporter, 1, "set through the otel_tracer_provider instead"}).
-deprecated({set_exporter, 2, "set through the otel_tracer_provider instead"}).
-deprecated({set_exporter, 3, "set through the otel_tracer_provider instead"}).
-include_lib("opentelemetry_api/include/opentelemetry.hrl").
-include_lib("kernel/include/logger.hrl").
-include("otel_span.hrl").
-record(data, {exporter :: {module(), term()} | undefined,
exporter_config :: {module(), term()} | undefined,
current_from :: gen_statem:from() | undefined,
resource :: otel_resource:t(),
handed_off_table :: atom() | undefined,
runner_pid :: pid() | undefined,
exporting_timeout_ms :: integer()}).
-define(DEFAULT_EXPORTER_TIMEOUT_MS, timer:minutes(5)).
-define(NAME_TO_ATOM(Name, Unique), list_to_atom(lists:concat([Name, "_", Unique]))).
start_link(Config) ->
Name = case maps:find(name, Config) of
{ok, N} ->
N;
error ->
%% use a unique reference to distiguish multiple batch processors while
%% still having a single name, instead of a possibly changing pid, to
%% communicate with the processor
erlang:ref_to_list(erlang:make_ref())
end,
RegisterName = ?NAME_TO_ATOM(?MODULE, Name),
Config1 = Config#{reg_name => RegisterName},
{ok, Pid} = gen_statem:start_link({local, RegisterName}, ?MODULE, [Config1], []),
{ok, Pid, Config1}.
%% @deprecated Please use {@link otel_tracer_provider}
set_exporter(Exporter) ->
set_exporter(global, Exporter, []).
%% @deprecated Please use {@link otel_tracer_provider}
-spec set_exporter(module(), term()) -> ok.
set_exporter(Exporter, Options) ->
gen_statem:call(?REG_NAME(global), {set_exporter, {Exporter, Options}}).
%% @deprecated Please use {@link otel_tracer_provider}
-spec set_exporter(atom(), module(), term()) -> ok.
set_exporter(Name, Exporter, Options) ->
gen_statem:call(?REG_NAME(Name), {set_exporter, {Exporter, Options}}).
-spec on_start(otel_ctx:t(), opentelemetry:span(), otel_span_processor:processor_config())
-> opentelemetry:span().
on_start(_Ctx, Span, _) ->
Span.
-spec on_end(opentelemetry:span(), otel_span_processor:processor_config())
-> true | dropped | {error, invalid_span} | {error, no_export_buffer}.
on_end(#span{trace_flags=TraceFlags}, _) when not(?IS_SAMPLED(TraceFlags)) ->
dropped;
on_end(Span=#span{}, #{reg_name := RegName}) ->
gen_statem:call(RegName, {export, Span});
on_end(_Span, _) ->
{error, invalid_span}.
-spec force_flush(otel_span_processor:processor_config()) -> ok.
force_flush(#{reg_name := RegName}) ->
gen_statem:cast(RegName, force_flush).
init([Args]) ->
process_flag(trap_exit, true),
ExportingTimeout = maps:get(exporting_timeout_ms, Args, ?DEFAULT_EXPORTER_TIMEOUT_MS),
%% TODO: this should be passed in from the tracer server
Resource = case maps:find(resource, Args) of
{ok, R} ->
R;
error ->
otel_resource_detector:get_resource()
end,
%% Resource = otel_tracer_provider:resource(),
{ok, idle, #data{exporter=undefined,
exporter_config=maps:get(exporter, Args, none),
resource = Resource,
handed_off_table=undefined,
exporting_timeout_ms=ExportingTimeout},
[{next_event, internal, init_exporter}]}.
callback_mode() ->
state_functions.
idle({call, From}, {export, _Span}, #data{exporter=undefined}) ->
{keep_state_and_data, [{reply, From, dropped}]};
idle({call, From}, {export, Span}, Data) ->
{next_state, exporting, Data, [{next_event, internal, {export, From, Span}}]};
idle(EventType, Event, Data) ->
handle_event_(idle, EventType, Event, Data).
exporting({call, _From}, {export, _}, _) ->
{keep_state_and_data, [postpone]};
exporting(internal, {export, From, Span}, Data=#data{exporting_timeout_ms=ExportingTimeout}) ->
{OldTableName, RunnerPid} = export_span(Span, Data),
{keep_state, Data#data{runner_pid=RunnerPid,
current_from=From,
handed_off_table=OldTableName},
[{state_timeout, ExportingTimeout, exporting_timeout}]};
exporting(state_timeout, exporting_timeout, Data=#data{current_from=From,
handed_off_table=_ExportingTable}) ->
%% kill current exporting process because it is taking too long
%% which deletes the exporting table, so create a new one and
%% repeat the state to force another span exporting immediately
Data1 = kill_runner(Data),
{next_state, idle, Data1, [{reply, From, {error, timeout}}]};
important to verify runner_pid and FromPid are the same in case it was sent
after kill_runner was called but before it had done the unlink
exporting(info, {'EXIT', FromPid, _}, Data=#data{runner_pid=FromPid}) ->
complete_exporting(Data);
important to verify runner_pid and FromPid are the same in case it was sent
after kill_runner was called but before it had done the unlink
exporting(info, {completed, FromPid}, Data=#data{runner_pid=FromPid}) ->
complete_exporting(Data);
exporting(EventType, Event, Data) ->
handle_event_(exporting, EventType, Event, Data).
handle_event_(_, internal, init_exporter, Data=#data{exporter=undefined,
exporter_config=ExporterConfig}) ->
Exporter = otel_exporter:init(ExporterConfig),
{keep_state, Data#data{exporter=Exporter}};
handle_event_(_, {call, From}, {set_exporter, Exporter}, Data=#data{exporter=OldExporter}) ->
otel_exporter:shutdown(OldExporter),
{keep_state, Data#data{exporter=otel_exporter:init(Exporter)}, [{reply, From, ok}]};
handle_event_(_, _, _, _) ->
keep_state_and_data.
terminate(_, _, _Data) ->
ok.
%%
complete_exporting(Data=#data{current_from=From,
handed_off_table=ExportingTable})
when ExportingTable =/= undefined ->
{next_state, idle, Data#data{current_from=undefined,
runner_pid=undefined,
handed_off_table=undefined},
[{reply, From, ok}]}.
kill_runner(Data=#data{runner_pid=RunnerPid}) ->
erlang:unlink(RunnerPid),
erlang:exit(RunnerPid, kill),
Data#data{runner_pid=undefined,
handed_off_table=undefined}.
new_export_table(Name) ->
ets:new(Name, [public,
{write_concurrency, true},
duplicate_bag,
OpenTelemetry exporter protos group by the
%% instrumentation_scope. So using instrumentation_scope
%% as the key means we can easily lookup all spans for
for each instrumentation_scope and export together .
{keypos, #span.instrumentation_scope}]).
export_span(Span, #data{exporter=Exporter,
resource=Resource}) ->
Table = new_export_table(otel_simple_processor_table),
_ = ets:insert(Table, Span),
Self = self(),
RunnerPid = erlang:spawn_link(fun() -> send_spans(Self, Resource, Exporter) end),
ets:give_away(Table, RunnerPid, export),
{Table, RunnerPid}.
%% Additional benefit of using a separate process is calls to `register` won't
%% timeout if the actual exporting takes longer than the call timeout
send_spans(FromPid, Resource, Exporter) ->
receive
{'ETS-TRANSFER', Table, FromPid, export} ->
export(Exporter, Resource, Table),
ets:delete(Table),
completed(FromPid)
end.
completed(FromPid) ->
FromPid ! {completed, self()}.
export(undefined, _, _) ->
true;
export({ExporterModule, Config}, Resource, SpansTid) ->
%% don't let a exporter exception crash us
%% and return true if exporter failed
try
otel_exporter:export_traces(ExporterModule, SpansTid, Resource, Config) =:= failed_not_retryable
catch
Kind:Reason:StackTrace ->
?LOG_INFO(#{source => exporter,
during => export,
kind => Kind,
reason => Reason,
exporter => ExporterModule,
stacktrace => StackTrace}, #{report_cb => fun ?MODULE:report_cb/1}),
true
end.
%% logger format functions
report_cb(#{source := exporter,
during := export,
kind := Kind,
reason := Reason,
exporter := ExporterModule,
stacktrace := StackTrace}) ->
{"exporter threw exception: exporter=~p ~ts",
[ExporterModule, format_exception(Kind, Reason, StackTrace)]}.
-if(?OTP_RELEASE >= 24).
format_exception(Kind, Reason, StackTrace) ->
erl_error:format_exception(Kind, Reason, StackTrace).
-else.
format_exception(Kind, Reason, StackTrace) ->
io_lib:format("~p:~p ~p", [Kind, Reason, StackTrace]).
-endif.
| null | https://raw.githubusercontent.com/open-telemetry/opentelemetry-erlang/2ff5849d01f77fc143c83aa13f1d64fe2a7e5c48/apps/opentelemetry/src/otel_simple_processor.erl | erlang | ------------------------------------------------------------------------
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
exported. This is useful for cases like a serverless environment where
the application will possibly be suspended after handling a request.
@end
-----------------------------------------------------------------------
deprecated
use a unique reference to distiguish multiple batch processors while
still having a single name, instead of a possibly changing pid, to
communicate with the processor
@deprecated Please use {@link otel_tracer_provider}
@deprecated Please use {@link otel_tracer_provider}
@deprecated Please use {@link otel_tracer_provider}
TODO: this should be passed in from the tracer server
Resource = otel_tracer_provider:resource(),
kill current exporting process because it is taking too long
which deletes the exporting table, so create a new one and
repeat the state to force another span exporting immediately
instrumentation_scope. So using instrumentation_scope
as the key means we can easily lookup all spans for
Additional benefit of using a separate process is calls to `register` won't
timeout if the actual exporting takes longer than the call timeout
don't let a exporter exception crash us
and return true if exporter failed
logger format functions | Copyright 2021 , OpenTelemetry Authors
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
@doc This Span Processor synchronously exports each ended Span .
Use this processor if ending a Span should block until it has been
-module(otel_simple_processor).
-behaviour(gen_statem).
-behaviour(otel_span_processor).
-export([start_link/1,
on_start/3,
on_end/2,
force_flush/1,
report_cb/1,
set_exporter/1,
set_exporter/2,
set_exporter/3]).
-export([init/1,
callback_mode/0,
idle/3,
exporting/3,
terminate/3]).
-deprecated({set_exporter, 1, "set through the otel_tracer_provider instead"}).
-deprecated({set_exporter, 2, "set through the otel_tracer_provider instead"}).
-deprecated({set_exporter, 3, "set through the otel_tracer_provider instead"}).
-include_lib("opentelemetry_api/include/opentelemetry.hrl").
-include_lib("kernel/include/logger.hrl").
-include("otel_span.hrl").
-record(data, {exporter :: {module(), term()} | undefined,
exporter_config :: {module(), term()} | undefined,
current_from :: gen_statem:from() | undefined,
resource :: otel_resource:t(),
handed_off_table :: atom() | undefined,
runner_pid :: pid() | undefined,
exporting_timeout_ms :: integer()}).
-define(DEFAULT_EXPORTER_TIMEOUT_MS, timer:minutes(5)).
-define(NAME_TO_ATOM(Name, Unique), list_to_atom(lists:concat([Name, "_", Unique]))).
start_link(Config) ->
Name = case maps:find(name, Config) of
{ok, N} ->
N;
error ->
erlang:ref_to_list(erlang:make_ref())
end,
RegisterName = ?NAME_TO_ATOM(?MODULE, Name),
Config1 = Config#{reg_name => RegisterName},
{ok, Pid} = gen_statem:start_link({local, RegisterName}, ?MODULE, [Config1], []),
{ok, Pid, Config1}.
set_exporter(Exporter) ->
set_exporter(global, Exporter, []).
-spec set_exporter(module(), term()) -> ok.
set_exporter(Exporter, Options) ->
gen_statem:call(?REG_NAME(global), {set_exporter, {Exporter, Options}}).
-spec set_exporter(atom(), module(), term()) -> ok.
set_exporter(Name, Exporter, Options) ->
gen_statem:call(?REG_NAME(Name), {set_exporter, {Exporter, Options}}).
-spec on_start(otel_ctx:t(), opentelemetry:span(), otel_span_processor:processor_config())
-> opentelemetry:span().
on_start(_Ctx, Span, _) ->
Span.
-spec on_end(opentelemetry:span(), otel_span_processor:processor_config())
-> true | dropped | {error, invalid_span} | {error, no_export_buffer}.
on_end(#span{trace_flags=TraceFlags}, _) when not(?IS_SAMPLED(TraceFlags)) ->
dropped;
on_end(Span=#span{}, #{reg_name := RegName}) ->
gen_statem:call(RegName, {export, Span});
on_end(_Span, _) ->
{error, invalid_span}.
-spec force_flush(otel_span_processor:processor_config()) -> ok.
force_flush(#{reg_name := RegName}) ->
gen_statem:cast(RegName, force_flush).
init([Args]) ->
process_flag(trap_exit, true),
ExportingTimeout = maps:get(exporting_timeout_ms, Args, ?DEFAULT_EXPORTER_TIMEOUT_MS),
Resource = case maps:find(resource, Args) of
{ok, R} ->
R;
error ->
otel_resource_detector:get_resource()
end,
{ok, idle, #data{exporter=undefined,
exporter_config=maps:get(exporter, Args, none),
resource = Resource,
handed_off_table=undefined,
exporting_timeout_ms=ExportingTimeout},
[{next_event, internal, init_exporter}]}.
callback_mode() ->
state_functions.
idle({call, From}, {export, _Span}, #data{exporter=undefined}) ->
{keep_state_and_data, [{reply, From, dropped}]};
idle({call, From}, {export, Span}, Data) ->
{next_state, exporting, Data, [{next_event, internal, {export, From, Span}}]};
idle(EventType, Event, Data) ->
handle_event_(idle, EventType, Event, Data).
exporting({call, _From}, {export, _}, _) ->
{keep_state_and_data, [postpone]};
exporting(internal, {export, From, Span}, Data=#data{exporting_timeout_ms=ExportingTimeout}) ->
{OldTableName, RunnerPid} = export_span(Span, Data),
{keep_state, Data#data{runner_pid=RunnerPid,
current_from=From,
handed_off_table=OldTableName},
[{state_timeout, ExportingTimeout, exporting_timeout}]};
exporting(state_timeout, exporting_timeout, Data=#data{current_from=From,
handed_off_table=_ExportingTable}) ->
Data1 = kill_runner(Data),
{next_state, idle, Data1, [{reply, From, {error, timeout}}]};
important to verify runner_pid and FromPid are the same in case it was sent
after kill_runner was called but before it had done the unlink
exporting(info, {'EXIT', FromPid, _}, Data=#data{runner_pid=FromPid}) ->
complete_exporting(Data);
important to verify runner_pid and FromPid are the same in case it was sent
after kill_runner was called but before it had done the unlink
exporting(info, {completed, FromPid}, Data=#data{runner_pid=FromPid}) ->
complete_exporting(Data);
exporting(EventType, Event, Data) ->
handle_event_(exporting, EventType, Event, Data).
handle_event_(_, internal, init_exporter, Data=#data{exporter=undefined,
exporter_config=ExporterConfig}) ->
Exporter = otel_exporter:init(ExporterConfig),
{keep_state, Data#data{exporter=Exporter}};
handle_event_(_, {call, From}, {set_exporter, Exporter}, Data=#data{exporter=OldExporter}) ->
otel_exporter:shutdown(OldExporter),
{keep_state, Data#data{exporter=otel_exporter:init(Exporter)}, [{reply, From, ok}]};
handle_event_(_, _, _, _) ->
keep_state_and_data.
terminate(_, _, _Data) ->
ok.
complete_exporting(Data=#data{current_from=From,
handed_off_table=ExportingTable})
when ExportingTable =/= undefined ->
{next_state, idle, Data#data{current_from=undefined,
runner_pid=undefined,
handed_off_table=undefined},
[{reply, From, ok}]}.
kill_runner(Data=#data{runner_pid=RunnerPid}) ->
erlang:unlink(RunnerPid),
erlang:exit(RunnerPid, kill),
Data#data{runner_pid=undefined,
handed_off_table=undefined}.
new_export_table(Name) ->
ets:new(Name, [public,
{write_concurrency, true},
duplicate_bag,
OpenTelemetry exporter protos group by the
for each instrumentation_scope and export together .
{keypos, #span.instrumentation_scope}]).
export_span(Span, #data{exporter=Exporter,
resource=Resource}) ->
Table = new_export_table(otel_simple_processor_table),
_ = ets:insert(Table, Span),
Self = self(),
RunnerPid = erlang:spawn_link(fun() -> send_spans(Self, Resource, Exporter) end),
ets:give_away(Table, RunnerPid, export),
{Table, RunnerPid}.
send_spans(FromPid, Resource, Exporter) ->
receive
{'ETS-TRANSFER', Table, FromPid, export} ->
export(Exporter, Resource, Table),
ets:delete(Table),
completed(FromPid)
end.
completed(FromPid) ->
FromPid ! {completed, self()}.
export(undefined, _, _) ->
true;
export({ExporterModule, Config}, Resource, SpansTid) ->
try
otel_exporter:export_traces(ExporterModule, SpansTid, Resource, Config) =:= failed_not_retryable
catch
Kind:Reason:StackTrace ->
?LOG_INFO(#{source => exporter,
during => export,
kind => Kind,
reason => Reason,
exporter => ExporterModule,
stacktrace => StackTrace}, #{report_cb => fun ?MODULE:report_cb/1}),
true
end.
report_cb(#{source := exporter,
during := export,
kind := Kind,
reason := Reason,
exporter := ExporterModule,
stacktrace := StackTrace}) ->
{"exporter threw exception: exporter=~p ~ts",
[ExporterModule, format_exception(Kind, Reason, StackTrace)]}.
-if(?OTP_RELEASE >= 24).
format_exception(Kind, Reason, StackTrace) ->
erl_error:format_exception(Kind, Reason, StackTrace).
-else.
format_exception(Kind, Reason, StackTrace) ->
io_lib:format("~p:~p ~p", [Kind, Reason, StackTrace]).
-endif.
|
b88af5a89a9ff08077050a8272b535e9cab60a21b4a19eb5309e22aa0822fb3f | facebook/pyre-check | sharedMemoryKeys.ml |
* Copyright ( c ) Meta Platforms , Inc. and affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
(* TODO(T132410158) Add a module-level doc comment. *)
open Core
open Ast
open Pyre
module IntKey = struct
type t = int
let to_string = Int.to_string
let compare = Int.compare
let from_string = Core.Int.of_string
end
module StringKey = struct
type t = string
let to_string = Fn.id
let compare = String.compare
let from_string x = x
end
module ReferenceKey = struct
type t = Reference.t [@@deriving compare, sexp]
let to_string = Reference.show
let from_string name = Reference.create name
end
module AttributeTableKey = struct
module T = struct
type t = {
include_generated_attributes: bool;
accessed_via_metaclass: bool;
name: Type.Primitive.t;
}
[@@deriving compare, sexp, hash, show]
end
include T
module Set = Set.Make (T)
include Hashable.Make (T)
let to_string key = sexp_of_t key |> Sexp.to_string
let from_string sexp = Sexp.of_string sexp |> t_of_sexp
end
module ParseAnnotationKey = struct
type type_validation_policy =
| NoValidation
| ValidatePrimitives
| ValidatePrimitivesAndTypeParameters
[@@deriving compare, sexp, hash, show]
module T = struct
type t = {
validation: type_validation_policy;
expression: Expression.t;
}
[@@deriving compare, sexp, hash, show]
end
include T
module Set = Set.Make (T)
include Hashable.Make (T)
let to_string key = sexp_of_t key |> Sexp.to_string
let from_string sexp = Sexp.of_string sexp |> t_of_sexp
end
type dependency =
| CreateModuleErrors of Reference.t
| TypeCheckDefine of Reference.t
| AliasRegister of Reference.t
| ClassConnect of Type.Primitive.t
| RegisterClassMetadata of Type.Primitive.t
| UndecoratedFunction of Reference.t
| AnnotateGlobal of Reference.t
| AnnotateGlobalLocation of Reference.t
| FromEmptyStub of Reference.t
| AttributeTable of AttributeTableKey.t
| ParseAnnotation of ParseAnnotationKey.t
| Metaclass of Type.Primitive.t
| WildcardImport of Reference.t
[@@deriving show, compare, sexp, hash]
module In = struct
type key = dependency [@@deriving compare, sexp]
module KeySet = Caml.Set.Make (struct
type t = dependency [@@deriving compare, sexp]
end)
type registered = {
hash: DependencyTrackedMemory.EncodedDependency.t;
key: key;
}
[@@deriving compare, sexp]
module RegisteredSet = Caml.Set.Make (struct
type t = registered [@@deriving compare, sexp]
end)
let get_key { key; _ } = key
module Table = DependencyTrackedMemory.EncodedDependency.Table
module Registry = struct
type table = key list Table.t
let add_to_table table ~hash ~key =
let append dependency = function
| Some existing ->
let equal left right = Int.equal (compare_key left right) 0 in
if List.mem existing dependency ~equal then
existing
else
dependency :: existing
| None -> [dependency]
in
Table.update table hash ~f:(append key)
type t =
| Master of table
| Worker of key list
module Serializable = struct
module Serialized = struct
type nonrec t = key list
let prefix = Prefix.make ()
let description = "Decoder storage"
end
type t = table
let serialize table = Table.data table |> List.concat_no_order
let deserialize keys =
let table = Table.create ~size:(List.length keys) () in
let add key =
add_to_table
table
~hash:(DependencyTrackedMemory.EncodedDependency.make ~hash:hash_dependency key)
~key
in
List.iter keys ~f:add;
table
end
module Storage = Memory.Serializer (Serializable)
let global : t ref = ref (Master (Table.create ()))
let store () =
match !global with
| Master table -> Storage.store table
| Worker _ -> failwith "trying to store from worker"
let load () = global := Master (Storage.load ())
let register key =
let hash = DependencyTrackedMemory.EncodedDependency.make ~hash:hash_dependency key in
let () =
match !global with
| Master table -> add_to_table table ~key ~hash
| Worker keys -> global := Worker (key :: keys)
in
{ hash; key }
type serialized = Serializable.Serialized.t
let encode { hash; _ } = hash
let decode hash =
match !global with
| Master table -> Table.find table hash >>| List.map ~f:(fun key -> { hash; key })
| Worker _ -> failwith "Can only decode from master"
let collected_map_reduce scheduler ~policy ~initial ~map ~reduce ~inputs () =
let map sofar inputs =
if Scheduler.is_master () then
map sofar inputs, []
else (
global := Worker [];
let payload = map sofar inputs in
match !global with
| Worker keys -> payload, keys
| Master _ -> failwith "can't set worker back to master")
in
let reduce (payload, keys) sofar =
let register key =
let (_ : registered) = register key in
()
in
List.iter keys ~f:register;
reduce payload sofar
in
Scheduler.map_reduce scheduler ~policy ~initial ~map ~reduce ~inputs ()
let collected_iter scheduler ~policy ~f ~inputs =
collected_map_reduce
scheduler
~policy
~initial:()
~map:(fun _ inputs -> f inputs)
~reduce:(fun _ _ -> ())
~inputs
()
end
end
module DependencyKey = struct
include In
include DependencyTrackedMemory.DependencyKey.Make (In)
end
module LocationKey = struct
type t = Location.t
let to_string key = Location.sexp_of_t key |> Sexp.to_string
let compare = Location.compare
let from_string sexp_string = Sexp.of_string sexp_string |> Location.t_of_sexp
end
| null | https://raw.githubusercontent.com/facebook/pyre-check/98b8362ffa5c715c708676c1a37a52647ce79fe0/source/analysis/sharedMemoryKeys.ml | ocaml | TODO(T132410158) Add a module-level doc comment. |
* Copyright ( c ) Meta Platforms , Inc. and affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open Core
open Ast
open Pyre
module IntKey = struct
type t = int
let to_string = Int.to_string
let compare = Int.compare
let from_string = Core.Int.of_string
end
module StringKey = struct
type t = string
let to_string = Fn.id
let compare = String.compare
let from_string x = x
end
module ReferenceKey = struct
type t = Reference.t [@@deriving compare, sexp]
let to_string = Reference.show
let from_string name = Reference.create name
end
module AttributeTableKey = struct
module T = struct
type t = {
include_generated_attributes: bool;
accessed_via_metaclass: bool;
name: Type.Primitive.t;
}
[@@deriving compare, sexp, hash, show]
end
include T
module Set = Set.Make (T)
include Hashable.Make (T)
let to_string key = sexp_of_t key |> Sexp.to_string
let from_string sexp = Sexp.of_string sexp |> t_of_sexp
end
module ParseAnnotationKey = struct
type type_validation_policy =
| NoValidation
| ValidatePrimitives
| ValidatePrimitivesAndTypeParameters
[@@deriving compare, sexp, hash, show]
module T = struct
type t = {
validation: type_validation_policy;
expression: Expression.t;
}
[@@deriving compare, sexp, hash, show]
end
include T
module Set = Set.Make (T)
include Hashable.Make (T)
let to_string key = sexp_of_t key |> Sexp.to_string
let from_string sexp = Sexp.of_string sexp |> t_of_sexp
end
type dependency =
| CreateModuleErrors of Reference.t
| TypeCheckDefine of Reference.t
| AliasRegister of Reference.t
| ClassConnect of Type.Primitive.t
| RegisterClassMetadata of Type.Primitive.t
| UndecoratedFunction of Reference.t
| AnnotateGlobal of Reference.t
| AnnotateGlobalLocation of Reference.t
| FromEmptyStub of Reference.t
| AttributeTable of AttributeTableKey.t
| ParseAnnotation of ParseAnnotationKey.t
| Metaclass of Type.Primitive.t
| WildcardImport of Reference.t
[@@deriving show, compare, sexp, hash]
module In = struct
type key = dependency [@@deriving compare, sexp]
module KeySet = Caml.Set.Make (struct
type t = dependency [@@deriving compare, sexp]
end)
type registered = {
hash: DependencyTrackedMemory.EncodedDependency.t;
key: key;
}
[@@deriving compare, sexp]
module RegisteredSet = Caml.Set.Make (struct
type t = registered [@@deriving compare, sexp]
end)
let get_key { key; _ } = key
module Table = DependencyTrackedMemory.EncodedDependency.Table
module Registry = struct
type table = key list Table.t
let add_to_table table ~hash ~key =
let append dependency = function
| Some existing ->
let equal left right = Int.equal (compare_key left right) 0 in
if List.mem existing dependency ~equal then
existing
else
dependency :: existing
| None -> [dependency]
in
Table.update table hash ~f:(append key)
type t =
| Master of table
| Worker of key list
module Serializable = struct
module Serialized = struct
type nonrec t = key list
let prefix = Prefix.make ()
let description = "Decoder storage"
end
type t = table
let serialize table = Table.data table |> List.concat_no_order
let deserialize keys =
let table = Table.create ~size:(List.length keys) () in
let add key =
add_to_table
table
~hash:(DependencyTrackedMemory.EncodedDependency.make ~hash:hash_dependency key)
~key
in
List.iter keys ~f:add;
table
end
module Storage = Memory.Serializer (Serializable)
let global : t ref = ref (Master (Table.create ()))
let store () =
match !global with
| Master table -> Storage.store table
| Worker _ -> failwith "trying to store from worker"
let load () = global := Master (Storage.load ())
let register key =
let hash = DependencyTrackedMemory.EncodedDependency.make ~hash:hash_dependency key in
let () =
match !global with
| Master table -> add_to_table table ~key ~hash
| Worker keys -> global := Worker (key :: keys)
in
{ hash; key }
type serialized = Serializable.Serialized.t
let encode { hash; _ } = hash
let decode hash =
match !global with
| Master table -> Table.find table hash >>| List.map ~f:(fun key -> { hash; key })
| Worker _ -> failwith "Can only decode from master"
let collected_map_reduce scheduler ~policy ~initial ~map ~reduce ~inputs () =
let map sofar inputs =
if Scheduler.is_master () then
map sofar inputs, []
else (
global := Worker [];
let payload = map sofar inputs in
match !global with
| Worker keys -> payload, keys
| Master _ -> failwith "can't set worker back to master")
in
let reduce (payload, keys) sofar =
let register key =
let (_ : registered) = register key in
()
in
List.iter keys ~f:register;
reduce payload sofar
in
Scheduler.map_reduce scheduler ~policy ~initial ~map ~reduce ~inputs ()
let collected_iter scheduler ~policy ~f ~inputs =
collected_map_reduce
scheduler
~policy
~initial:()
~map:(fun _ inputs -> f inputs)
~reduce:(fun _ _ -> ())
~inputs
()
end
end
module DependencyKey = struct
include In
include DependencyTrackedMemory.DependencyKey.Make (In)
end
module LocationKey = struct
type t = Location.t
let to_string key = Location.sexp_of_t key |> Sexp.to_string
let compare = Location.compare
let from_string sexp_string = Sexp.of_string sexp_string |> Location.t_of_sexp
end
|
e093f23d78e7aeb6f736c60c252cb76d0c38384a2030032681bf60fd4569e53b | crategus/cl-cffi-gtk | text-view-attributes.lisp | Text View Attributes ( 2021 - 6 - 4 )
(in-package :gtk-example)
(defun example-text-view-attributes ()
(within-main-loop
(let* ((window (make-instance 'gtk-window
:type :toplevel
:title "Example Text View Attributes"
:default-width 350
:default-height 200))
(provider (gtk-css-provider-new))
(textview (make-instance 'gtk-text-view
;; Change left margin throughout the widget
:left-margin 24
;; Change top margin
:top-margin 12))
(buffer (gtk-text-view-buffer textview)))
(g-signal-connect window "destroy"
(lambda (widget)
(declare (ignore widget))
(leave-gtk-main)))
(setf (gtk-text-buffer-text buffer) "Hello, this is some text.")
;; Change default font and color throughout the widget
(gtk-css-provider-load-from-data provider
"textview, text {
color : Green;
font : 20px Purisa; }")
(gtk-style-context-add-provider (gtk-widget-style-context textview)
provider
+gtk-style-provider-priority-application+)
;; Use a tag to change the color for just one part of the widget
(let ((tag (gtk-text-buffer-create-tag buffer
"blue_foreground"
:foreground "blue"))
(start (gtk-text-buffer-iter-at-offset buffer 7))
(end (gtk-text-buffer-iter-at-offset buffer 12)))
;; Apply the tag to a region of the text in the buffer
(gtk-text-buffer-apply-tag buffer tag start end))
;; Add the text view to the window and show all
(gtk-container-add window textview)
(gtk-widget-show-all window))))
| null | https://raw.githubusercontent.com/crategus/cl-cffi-gtk/b613a266a5f8e7f477b66a33d4df84fbed3dc7bc/demo/gtk-example/text-view-attributes.lisp | lisp | Change left margin throughout the widget
Change top margin
Change default font and color throughout the widget
}")
Use a tag to change the color for just one part of the widget
Apply the tag to a region of the text in the buffer
Add the text view to the window and show all | Text View Attributes ( 2021 - 6 - 4 )
(in-package :gtk-example)
(defun example-text-view-attributes ()
(within-main-loop
(let* ((window (make-instance 'gtk-window
:type :toplevel
:title "Example Text View Attributes"
:default-width 350
:default-height 200))
(provider (gtk-css-provider-new))
(textview (make-instance 'gtk-text-view
:left-margin 24
:top-margin 12))
(buffer (gtk-text-view-buffer textview)))
(g-signal-connect window "destroy"
(lambda (widget)
(declare (ignore widget))
(leave-gtk-main)))
(setf (gtk-text-buffer-text buffer) "Hello, this is some text.")
(gtk-css-provider-load-from-data provider
"textview, text {
(gtk-style-context-add-provider (gtk-widget-style-context textview)
provider
+gtk-style-provider-priority-application+)
(let ((tag (gtk-text-buffer-create-tag buffer
"blue_foreground"
:foreground "blue"))
(start (gtk-text-buffer-iter-at-offset buffer 7))
(end (gtk-text-buffer-iter-at-offset buffer 12)))
(gtk-text-buffer-apply-tag buffer tag start end))
(gtk-container-add window textview)
(gtk-widget-show-all window))))
|
ee8d51f58326aa9aa290461c5b6ff32d692f21ff9ce7f8f602855d30785c7fed | tdammers/ginger | AST.hs | # LANGUAGE DeriveFunctor #
-- | Implements Ginger's Abstract Syntax Tree.
module Text.Ginger.AST
where
import Data.Text (Text)
import qualified Data.Text as Text
import Text.Ginger.Html
import Data.Scientific (Scientific)
import Data.HashMap.Strict (HashMap)
import qualified Data.HashMap.Strict as HashMap
-- | A context variable name.
type VarName = Text
-- | Top-level data structure, representing a fully parsed template.
data Template a
= Template
{ templateBody :: Statement a
, templateBlocks :: HashMap VarName (Block a)
, templateParent :: Maybe (Template a)
}
deriving (Show, Functor)
-- | A macro definition ( @{% macro %}@ )
data Macro a
= Macro { macroArgs :: [VarName], macroBody :: Statement a }
deriving (Show, Functor)
-- | A block definition ( @{% block %}@ )
data Block a
= Block { blockBody :: Statement a } -- TODO: scoped blocks
deriving (Show, Functor)
-- | Ginger statements.
data Statement a
= MultiS a [Statement a] -- ^ A sequence of multiple statements
| ScopedS a (Statement a) -- ^ Run wrapped statement in a local scope
| IndentS a (Expression a) (Statement a) -- ^ Establish an indented context around the wrapped statement
| LiteralS a Html -- ^ Literal output (anything outside of any tag)
| InterpolationS a (Expression a) -- ^ {{ expression }}
| ExpressionS a (Expression a) -- ^ Evaluate expression
^ { % if expression % } statement{% else % } statement{% endif % }
^ { % switch expression % } { % case expression % } statement{% endcase % } ... { % default % } statement{% enddefault % } { % endswitch % }
^ { % for index , varname in expression % } statement{% endfor % }
^ { % set varname = expr % }
| DefMacroS a VarName (Macro a) -- ^ {% macro varname %}statements{% endmacro %}
| BlockRefS a VarName
^ { % include " template " % }
^ The do - nothing statement ( NOP )
| TryCatchS a (Statement a) [CatchBlock a] (Statement a) -- ^ Try / catch / finally
deriving (Show, Functor)
stmtAnnotation (MultiS a _) = a
stmtAnnotation (ScopedS a _) = a
stmtAnnotation (IndentS a _ _) = a
stmtAnnotation (LiteralS a _) = a
stmtAnnotation (InterpolationS a _) = a
stmtAnnotation (ExpressionS a _) = a
stmtAnnotation (IfS a _ _ _) = a
stmtAnnotation (SwitchS a _ _ _) = a
stmtAnnotation (ForS a _ _ _ _) = a
stmtAnnotation (SetVarS a _ _) = a
stmtAnnotation (DefMacroS a _ _) = a
stmtAnnotation (BlockRefS a _) = a
stmtAnnotation (PreprocessedIncludeS a _) = a
stmtAnnotation (NullS a) = a
stmtAnnotation (TryCatchS a _ _ _) = a
-- | A @catch@ block
data CatchBlock a =
Catch
{ catchWhat :: Maybe Text
, catchCaptureAs :: Maybe VarName
, catchBody :: Statement a
}
deriving (Show, Functor)
-- | Expressions, building blocks for the expression minilanguage.
data Expression a
^ String literal expression : " foobar "
^ Numeric literal expression : 123.4
| BoolLiteralE a Bool -- ^ Boolean literal expression: true
| NullLiteralE a -- ^ Literal null
| VarE a VarName -- ^ Variable reference: foobar
| ListE a [(Expression a)] -- ^ List construct: [ expr, expr, expr ]
| ObjectE a [((Expression a), (Expression a))] -- ^ Object construct: { expr: expr, expr: expr, ... }
| MemberLookupE a (Expression a) (Expression a) -- ^ foo[bar] (also dot access)
^ foo(bar = baz , quux )
| LambdaE a [Text] (Expression a) -- ^ (foo, bar) -> expr
| TernaryE a (Expression a) (Expression a) (Expression a) -- ^ expr ? expr : expr
| DoE a (Statement a) -- ^ do { statement; }
deriving (Show, Functor)
exprAnnotation (StringLiteralE a _) = a
exprAnnotation (NumberLiteralE a _) = a
exprAnnotation (BoolLiteralE a _) = a
exprAnnotation (NullLiteralE a) = a
exprAnnotation (VarE a _) = a
exprAnnotation (ListE a _) = a
exprAnnotation (ObjectE a _) = a
exprAnnotation (MemberLookupE a _ _) = a
exprAnnotation (CallE a _ _) = a
exprAnnotation (LambdaE a _ _) = a
exprAnnotation (TernaryE a _ _ _) = a
exprAnnotation (DoE a _) = a
class Annotated f where
annotation :: f p -> p
instance Annotated Expression where
annotation = exprAnnotation
instance Annotated Statement where
annotation = stmtAnnotation
instance Annotated Block where
annotation = annotation . blockBody
instance Annotated Macro where
annotation = annotation . macroBody
instance Annotated Template where
annotation = annotation . templateBody
| null | https://raw.githubusercontent.com/tdammers/ginger/bd8cb39c1853d4fb4f663c4c201884575906acea/src/Text/Ginger/AST.hs | haskell | | Implements Ginger's Abstract Syntax Tree.
| A context variable name.
| Top-level data structure, representing a fully parsed template.
| A macro definition ( @{% macro %}@ )
| A block definition ( @{% block %}@ )
TODO: scoped blocks
| Ginger statements.
^ A sequence of multiple statements
^ Run wrapped statement in a local scope
^ Establish an indented context around the wrapped statement
^ Literal output (anything outside of any tag)
^ {{ expression }}
^ Evaluate expression
^ {% macro varname %}statements{% endmacro %}
^ Try / catch / finally
| A @catch@ block
| Expressions, building blocks for the expression minilanguage.
^ Boolean literal expression: true
^ Literal null
^ Variable reference: foobar
^ List construct: [ expr, expr, expr ]
^ Object construct: { expr: expr, expr: expr, ... }
^ foo[bar] (also dot access)
^ (foo, bar) -> expr
^ expr ? expr : expr
^ do { statement; } | # LANGUAGE DeriveFunctor #
module Text.Ginger.AST
where
import Data.Text (Text)
import qualified Data.Text as Text
import Text.Ginger.Html
import Data.Scientific (Scientific)
import Data.HashMap.Strict (HashMap)
import qualified Data.HashMap.Strict as HashMap
type VarName = Text
data Template a
= Template
{ templateBody :: Statement a
, templateBlocks :: HashMap VarName (Block a)
, templateParent :: Maybe (Template a)
}
deriving (Show, Functor)
data Macro a
= Macro { macroArgs :: [VarName], macroBody :: Statement a }
deriving (Show, Functor)
data Block a
deriving (Show, Functor)
data Statement a
^ { % if expression % } statement{% else % } statement{% endif % }
^ { % switch expression % } { % case expression % } statement{% endcase % } ... { % default % } statement{% enddefault % } { % endswitch % }
^ { % for index , varname in expression % } statement{% endfor % }
^ { % set varname = expr % }
| BlockRefS a VarName
^ { % include " template " % }
^ The do - nothing statement ( NOP )
deriving (Show, Functor)
stmtAnnotation (MultiS a _) = a
stmtAnnotation (ScopedS a _) = a
stmtAnnotation (IndentS a _ _) = a
stmtAnnotation (LiteralS a _) = a
stmtAnnotation (InterpolationS a _) = a
stmtAnnotation (ExpressionS a _) = a
stmtAnnotation (IfS a _ _ _) = a
stmtAnnotation (SwitchS a _ _ _) = a
stmtAnnotation (ForS a _ _ _ _) = a
stmtAnnotation (SetVarS a _ _) = a
stmtAnnotation (DefMacroS a _ _) = a
stmtAnnotation (BlockRefS a _) = a
stmtAnnotation (PreprocessedIncludeS a _) = a
stmtAnnotation (NullS a) = a
stmtAnnotation (TryCatchS a _ _ _) = a
data CatchBlock a =
Catch
{ catchWhat :: Maybe Text
, catchCaptureAs :: Maybe VarName
, catchBody :: Statement a
}
deriving (Show, Functor)
data Expression a
^ String literal expression : " foobar "
^ Numeric literal expression : 123.4
^ foo(bar = baz , quux )
deriving (Show, Functor)
exprAnnotation (StringLiteralE a _) = a
exprAnnotation (NumberLiteralE a _) = a
exprAnnotation (BoolLiteralE a _) = a
exprAnnotation (NullLiteralE a) = a
exprAnnotation (VarE a _) = a
exprAnnotation (ListE a _) = a
exprAnnotation (ObjectE a _) = a
exprAnnotation (MemberLookupE a _ _) = a
exprAnnotation (CallE a _ _) = a
exprAnnotation (LambdaE a _ _) = a
exprAnnotation (TernaryE a _ _ _) = a
exprAnnotation (DoE a _) = a
class Annotated f where
annotation :: f p -> p
instance Annotated Expression where
annotation = exprAnnotation
instance Annotated Statement where
annotation = stmtAnnotation
instance Annotated Block where
annotation = annotation . blockBody
instance Annotated Macro where
annotation = annotation . macroBody
instance Annotated Template where
annotation = annotation . templateBody
|
c7963881c44ef341d3d6cf8f6f1d54bb3fcadad329e65e6904ec4ac1842296df | ocaml-toml/To.ml | types_test.ml | let () =
let key = Toml.Types.Table.Key.of_string "a-b-c" in
assert (String.compare "a-b-c" (Toml.Types.Table.Key.to_string key) = 0)
| null | https://raw.githubusercontent.com/ocaml-toml/To.ml/c0ae79c2589ab4c82f4528b53ad711287140c7dd/tests/types_test.ml | ocaml | let () =
let key = Toml.Types.Table.Key.of_string "a-b-c" in
assert (String.compare "a-b-c" (Toml.Types.Table.Key.to_string key) = 0)
| |
90bc31a8caadeb6507a186603cc1053c9dc9ec9ff9eb9c72f4093c7bf84523f1 | abarbu/schemetex | schemetex-type-inference.scm | (module schemetex-type-inference *
(import chicken scheme srfi-1 extras data-structures ports files foreign)
(begin-for-syntax (require 'traversal))
(import-for-syntax traversal)
(use traversal nondeterminism define-structure linear-algebra irregex AD
srfi-13 srfi-69 shell ssax scheme2c-compatibility nlopt
schemetex-compiler miscmacros)
(define (split-between-every p l)
(let loop ((l l) (r '(())))
(if (null? l)
(map reverse (reverse (if (null? (car r)) (cdr r) r)))
(loop (cdr l)
(if (p (car l))
(cons '() r)
(cons (cons (car l) (car r)) (cdr r)))))))
(define (split-between-everyq e l) (split-between-every (lambda (a) (eq? e a)) l))
(define (type->prefix type)
(if (list? type)
(let ((type (map type->prefix type)))
(let ((t (map car (split-between-everyq '-> type))))
(foldr (lambda (a b) `(-> ,a ,b)) (last t) (but-last t))))
type))
;; n inexact
;; i exact
;; l list
;; v vector
;; m matrix
(define-structure var name type)
(define-structure alt list)
(define op1-types '((bar
(abs (n -> n))
(length (l -> n))
(vector-length (v -> n))
(determinant (m -> n)))
(double-bar
(magnitude (v -> n)))
(neg
(- (n -> n))
(v-neg (v -> v))
(m-neg (m -> m)))
(transpose
(v-transpose (v -> cv))
(v-transpose (cv -> v))
(matrix-transpose (m -> m)))
(log (log (n -> n)))
(lg (log (n -> n)))
(ln (log (n -> n)))
(sin (sin (n -> n)))
(cos (cos (n -> n)))
(tan (tan (n -> n)))
(exp (exp (n -> n)))
(sqrt (sqrt (n -> n)))
(range (range (n -> n -> l)))))
(define op2-types '((+
(+ (n -> n -> n))
(v+ (v -> v -> v))
(cv+ (cv -> cv -> cv))
(m+ (m -> m -> m)))
(-
(- (n -> n -> n))
(v- (v -> v -> v))
(cv- (cv -> cv -> cv))
(m- (m -> m -> m)))
(*
(* (n -> n -> n))
(k*v (n -> v -> v))
((flip2 k*v) (v -> n -> v))
(k*cv (n -> cv -> cv))
((flip2 k*cv) (cv -> n -> cv))
(v*cv (v -> cv -> m))
(cv*v (cv -> v -> m))
(m* (m -> m -> m))
(m*v-new (m -> v -> cv))
(cv*m (cv -> m -> v))
(k*m (n -> m -> m))
((flip2 k*m) (m -> n -> m)))
(/
(/ (n -> n -> n))
(m/ (m -> m -> m))
(m/k (m -> n -> m))
(v/k (v -> n -> v))
(cv/k (cv -> n -> cv)))
(expt
(expt (n -> n -> n))
(v-expt (v -> n -> v))
(m-expt (m -> n -> m)))
(ref
(list-ref (l -> n -> star))
(vector-ref (v -> n -> star))
(cv-vector-ref (cv -> n -> star))
(vector-ref (m -> n -> v))
(v-matrix-ref (m -> v -> star)))
(sum
(sum-n (n -> (n -> n) -> n))
(sum-l (l -> (n -> n) -> n))
(sum-v (v -> (n -> n) -> n)))
(product
(product-n (n -> (n -> n) -> n))
(product-l (l -> (n -> n) -> n))
(product-v (v -> (n -> n) -> n)))
(= (= (n -> n -> b)))
(not-= (not-= (n -> n -> b)))
(> (> (n -> n -> b)))
(< (< (n -> n -> b)))
(>= (>= (n -> n -> b)))
(<= (<= (n -> n -> b)))))
(define builtins (cons
`(if ,(make-alt `((-> b (-> star star)))) (if))
(map (lambda (op) (list (string->symbol (string-append "r-" (symbol->string (first op))))
(make-alt (map (o type->prefix second) (cdr op)))
(map first (cdr op))))
(append op1-types op2-types))))
(define (generate-constraints expr return-type bindings)
;; ground vs generic types
(let ((variables '()) (constraints '()))
(define (mk-variable name domain)
(let ((var (make-var name domain)))
(set! variables (cons var variables))
var))
(define (unifies! a b) (set! constraints (cons `(unify ,a ,b) constraints)) #f)
(define generic-type 'star)
;; handle the return type
(unifies!
(mk-variable 'return-type (if return-type return-type generic-type))
(let loop ((expr expr)
;; arguments
(bindings
(map (lambda (binding)
(cons (car binding)
(mk-variable (car binding) (cdr binding))))
bindings)))
(cond ((list? expr)
(let ((head (first expr)))
(cond ((eq? 'lambda head)
(let ((arguments (map (lambda (variable)
(cons variable (mk-variable variable generic-type)))
(second expr))))
(foldr (lambda (x y) (list '-> x y))
(loop (third expr) (append arguments bindings))
(map cdr arguments))))
((eq? 'cond head)
TODO record the correspondence between the name
;; below and its position in the tree
(let ((return-type (mk-variable (gensym) generic-type)))
(for-each
(lambda (body)
(unless (= (length body) 2)
(error "The optimizer doesn't support cond clauses with multiple statements"))
(unless (eq? (first body) 'else)
(unifies! 'b (loop (first body) bindings)))
(unifies! return-type (loop (second body) bindings)))
(cdr expr))
return-type))
((number? head) (error "Attempt to use a number as a function"))
(else
(let ((variable (loop head bindings))
TODO record the correspondence between the name
;; below and variable above
(return-type (mk-variable (gensym) generic-type)))
(unifies!
variable
(foldr
(lambda (x y) (list '-> x y))
return-type
(map (lambda (argument) (loop argument bindings)) (cdr expr))))
return-type)))))
((symbol? expr)
(cond ((assoc expr bindings)
(cdr (assoc expr bindings)))
(else (error "Unbound variable in" expr))))
((number? expr)
(mk-variable expr 'n))
(else (error "Unknown expression" expr)))))
(list variables constraints)))
(define (unify-types a b)
(define (a-type-of e)
(let ((type (if (var? e) (var-type e) e)))
(if (alt? type)
(a-member-of (alt-list type))
type)))
(let*
((r (remove-duplicatese
(all-values
(let loop ((vars '()))
(let ((previous-vars (map update-var vars)))
(define (type! v t)
(when (var? v)
(set! vars (cons v (remove (lambda (a) (equal? (var-name a) (var-name v))) vars)))
(local-set-var-type! v t))
t)
(let ((type
(let loop ((a a) (b b))
(let ((a-type (a-type-of a))
(b-type (a-type-of b)))
(cond ((equal? a-type 'star) (type! a b-type))
((equal? b-type 'star) (type! b a-type))
((and (symbol? a-type) (symbol? b-type))
(if (equal? a-type b-type)
(type! b (type! a a-type))
(fail)))
((and (list? a-type) (list? b-type))
(if (and (equal? (car a-type) '->)
(equal? (car b-type) '->))
(type! b
(type! a
(list '->
(loop (second a-type) (second b-type))
(loop (third a-type) (third b-type)))))
(fail)))
(else (fail)))))))
(if (equal? vars previous-vars)
(list (remove-duplicatese (map update-var vars)) type)
(loop vars))))))))
(vars (map first r))
(types (map second r)))
(list (map (lambda (l) (make-var (var-name (car l))
(make-alt (remove-duplicatese (map var-type l)))))
(group-by var-name (join vars '())))
(remove-duplicatese types))))
(define (unify? a b) (not (equal? (unify-types a b) '(() ()))))
(define (solve-constraints! variables constraints)
(define (restrict! variable variables)
(var-type-set!
(find-if
(lambda (v) (equal? (var-name variable) (var-name v)))
variables)
(var-type variable)))
(let loop ((variables variables))
(let ((previous-variables (map update-var variables)))
(for-each (lambda (c)
(case (car c)
((unify)
(let ((r (unify-types (second c) (third c))))
(when (null? (second r)) (error "type error" c))
(map (lambda (t) (restrict! t variables))
(first r))))
(else (error "unknown constraint" c))))
constraints)
(unless (equal? previous-variables variables)
(loop variables)))))
(define (polymorphic-types expr variables)
(let* ((bindings '())
(mapping '())
(new-expr (deep-map (lambda (a) (and (symbol? a) (assoc a variables)))
(lambda (a) (let ((name (gensym a)))
(push! (cons name (second (assoc a variables))) bindings)
(push! (cons name a) mapping)
name))
expr)))
(list bindings new-expr mapping)))
(define (variable-the-type v)
(unless (= (length (alt-list (var-type v))) 1)
(error "Variable is polymorphic" v))
(first (alt-list (var-type v))))
(define (variable-polymorphic? v) (not (= (length (alt-list (var-type v))) 1)))
(define (specialize-expression expr mapping builtins allow-polymorphic-variables?)
(deep-map var?
(lambda (v)
(if (assoc (var-name v) mapping)
(if (variable-polymorphic? v)
(if allow-polymorphic-variables?
(car (assoc (cdr (assoc (var-name v) mapping)) builtins))
(error "Not allowed to specialize polymorphic variables" v))
(let ((binding (cdr (assoc (cdr (assoc (var-name v) mapping)) builtins))))
(unless binding
(error "Variable is missing a specialized version for this type"
v (cdr (assoc (var-name v) mapping))))
(list-ref
(second binding)
(position (cut unify? (variable-the-type v) <>) (alt-list (first binding))))))
(var-name v)))
expr))
(define (type-inference expr return-type bindings builtins #!optional (debugging #f))
(let* ((a (polymorphic-types expr builtins))
(variables (append bindings (first a)))
(expr (second a))
(mapping (third a))
(b (generate-constraints expr return-type variables))
(variables (first b))
(constraints (second b))
(expr (begin
(let loop ()
(solve-constraints! variables constraints)
((call/cc
(lambda (k)
(for-each (lambda (v)
(let ((m (assoc (var-name v) mapping)))
(when (and (alt? (var-type v))
(> (length (alt-list (var-type v))) 1)
m
(equal? (cdr m) 'r-ref))
(let ((updated-type
(remove-if (lambda (t)
(and (not (equal? (third (third t)) 'star))
(not (equal? (second t) (third (third t))))))
(alt-list (var-type v)))))
(when (and (not (equal? updated-type (alt-list (var-type v))))
(not (null? updated-type)))
(set-alt-list! (var-type v) updated-type)
(k loop))))))
variables)
(lambda () #f)))))
(deep-map (lambda (a) (and (symbol? a) (find-if (lambda (v) (equal? (var-name v) a)) variables)))
(lambda (a) (find-if (lambda (v) (equal? (var-name v) a)) variables))
expr))))
(for-each (lambda (v)
(when (and (assoc (var-name v) bindings)
(alt? (var-type v))
(> (length (alt-list (var-type v))) 1))
(error (format #f "Type of '~a' cannot be determined. Options are ~a. Provide a type annotation."
(var-name v)
(alt-list (var-type v))))))
variables)
(for-each (lambda (v)
(when (and (alt? (var-type v)) (> (length (alt-list (var-type v))) 1))
;; At the moment there is no way to specify it. This alaways happens when you use multiple references into a matrix.
(format #t "This program cannot be fully specialized becuase the type of '~a' cannot be determined.~%~a~%"
(var-name v) v)))
variables)
;; debugging
(when debugging (pp (list expr variables bindings mapping builtins constraints))(newline))
(list (specialize-expression expr mapping builtins #t)
variables
mapping
(var-type (find (lambda (v) (equal? (var-name v) 'return-type)) variables)))))
(define (specialize expr return-type bindings builtins #!optional (debugging #f))
(first (type-inference expr return-type bindings builtins debugging)))
)
| null | https://raw.githubusercontent.com/abarbu/schemetex/0bc3f5b8e72ede52225a842b6554baafaf370712/schemetex-type-inference.scm | scheme | n inexact
i exact
l list
v vector
m matrix
ground vs generic types
handle the return type
arguments
below and its position in the tree
below and variable above
At the moment there is no way to specify it. This alaways happens when you use multiple references into a matrix.
debugging | (module schemetex-type-inference *
(import chicken scheme srfi-1 extras data-structures ports files foreign)
(begin-for-syntax (require 'traversal))
(import-for-syntax traversal)
(use traversal nondeterminism define-structure linear-algebra irregex AD
srfi-13 srfi-69 shell ssax scheme2c-compatibility nlopt
schemetex-compiler miscmacros)
(define (split-between-every p l)
(let loop ((l l) (r '(())))
(if (null? l)
(map reverse (reverse (if (null? (car r)) (cdr r) r)))
(loop (cdr l)
(if (p (car l))
(cons '() r)
(cons (cons (car l) (car r)) (cdr r)))))))
(define (split-between-everyq e l) (split-between-every (lambda (a) (eq? e a)) l))
(define (type->prefix type)
(if (list? type)
(let ((type (map type->prefix type)))
(let ((t (map car (split-between-everyq '-> type))))
(foldr (lambda (a b) `(-> ,a ,b)) (last t) (but-last t))))
type))
(define-structure var name type)
(define-structure alt list)
(define op1-types '((bar
(abs (n -> n))
(length (l -> n))
(vector-length (v -> n))
(determinant (m -> n)))
(double-bar
(magnitude (v -> n)))
(neg
(- (n -> n))
(v-neg (v -> v))
(m-neg (m -> m)))
(transpose
(v-transpose (v -> cv))
(v-transpose (cv -> v))
(matrix-transpose (m -> m)))
(log (log (n -> n)))
(lg (log (n -> n)))
(ln (log (n -> n)))
(sin (sin (n -> n)))
(cos (cos (n -> n)))
(tan (tan (n -> n)))
(exp (exp (n -> n)))
(sqrt (sqrt (n -> n)))
(range (range (n -> n -> l)))))
(define op2-types '((+
(+ (n -> n -> n))
(v+ (v -> v -> v))
(cv+ (cv -> cv -> cv))
(m+ (m -> m -> m)))
(-
(- (n -> n -> n))
(v- (v -> v -> v))
(cv- (cv -> cv -> cv))
(m- (m -> m -> m)))
(*
(* (n -> n -> n))
(k*v (n -> v -> v))
((flip2 k*v) (v -> n -> v))
(k*cv (n -> cv -> cv))
((flip2 k*cv) (cv -> n -> cv))
(v*cv (v -> cv -> m))
(cv*v (cv -> v -> m))
(m* (m -> m -> m))
(m*v-new (m -> v -> cv))
(cv*m (cv -> m -> v))
(k*m (n -> m -> m))
((flip2 k*m) (m -> n -> m)))
(/
(/ (n -> n -> n))
(m/ (m -> m -> m))
(m/k (m -> n -> m))
(v/k (v -> n -> v))
(cv/k (cv -> n -> cv)))
(expt
(expt (n -> n -> n))
(v-expt (v -> n -> v))
(m-expt (m -> n -> m)))
(ref
(list-ref (l -> n -> star))
(vector-ref (v -> n -> star))
(cv-vector-ref (cv -> n -> star))
(vector-ref (m -> n -> v))
(v-matrix-ref (m -> v -> star)))
(sum
(sum-n (n -> (n -> n) -> n))
(sum-l (l -> (n -> n) -> n))
(sum-v (v -> (n -> n) -> n)))
(product
(product-n (n -> (n -> n) -> n))
(product-l (l -> (n -> n) -> n))
(product-v (v -> (n -> n) -> n)))
(= (= (n -> n -> b)))
(not-= (not-= (n -> n -> b)))
(> (> (n -> n -> b)))
(< (< (n -> n -> b)))
(>= (>= (n -> n -> b)))
(<= (<= (n -> n -> b)))))
(define builtins (cons
`(if ,(make-alt `((-> b (-> star star)))) (if))
(map (lambda (op) (list (string->symbol (string-append "r-" (symbol->string (first op))))
(make-alt (map (o type->prefix second) (cdr op)))
(map first (cdr op))))
(append op1-types op2-types))))
(define (generate-constraints expr return-type bindings)
(let ((variables '()) (constraints '()))
(define (mk-variable name domain)
(let ((var (make-var name domain)))
(set! variables (cons var variables))
var))
(define (unifies! a b) (set! constraints (cons `(unify ,a ,b) constraints)) #f)
(define generic-type 'star)
(unifies!
(mk-variable 'return-type (if return-type return-type generic-type))
(let loop ((expr expr)
(bindings
(map (lambda (binding)
(cons (car binding)
(mk-variable (car binding) (cdr binding))))
bindings)))
(cond ((list? expr)
(let ((head (first expr)))
(cond ((eq? 'lambda head)
(let ((arguments (map (lambda (variable)
(cons variable (mk-variable variable generic-type)))
(second expr))))
(foldr (lambda (x y) (list '-> x y))
(loop (third expr) (append arguments bindings))
(map cdr arguments))))
((eq? 'cond head)
TODO record the correspondence between the name
(let ((return-type (mk-variable (gensym) generic-type)))
(for-each
(lambda (body)
(unless (= (length body) 2)
(error "The optimizer doesn't support cond clauses with multiple statements"))
(unless (eq? (first body) 'else)
(unifies! 'b (loop (first body) bindings)))
(unifies! return-type (loop (second body) bindings)))
(cdr expr))
return-type))
((number? head) (error "Attempt to use a number as a function"))
(else
(let ((variable (loop head bindings))
TODO record the correspondence between the name
(return-type (mk-variable (gensym) generic-type)))
(unifies!
variable
(foldr
(lambda (x y) (list '-> x y))
return-type
(map (lambda (argument) (loop argument bindings)) (cdr expr))))
return-type)))))
((symbol? expr)
(cond ((assoc expr bindings)
(cdr (assoc expr bindings)))
(else (error "Unbound variable in" expr))))
((number? expr)
(mk-variable expr 'n))
(else (error "Unknown expression" expr)))))
(list variables constraints)))
(define (unify-types a b)
(define (a-type-of e)
(let ((type (if (var? e) (var-type e) e)))
(if (alt? type)
(a-member-of (alt-list type))
type)))
(let*
((r (remove-duplicatese
(all-values
(let loop ((vars '()))
(let ((previous-vars (map update-var vars)))
(define (type! v t)
(when (var? v)
(set! vars (cons v (remove (lambda (a) (equal? (var-name a) (var-name v))) vars)))
(local-set-var-type! v t))
t)
(let ((type
(let loop ((a a) (b b))
(let ((a-type (a-type-of a))
(b-type (a-type-of b)))
(cond ((equal? a-type 'star) (type! a b-type))
((equal? b-type 'star) (type! b a-type))
((and (symbol? a-type) (symbol? b-type))
(if (equal? a-type b-type)
(type! b (type! a a-type))
(fail)))
((and (list? a-type) (list? b-type))
(if (and (equal? (car a-type) '->)
(equal? (car b-type) '->))
(type! b
(type! a
(list '->
(loop (second a-type) (second b-type))
(loop (third a-type) (third b-type)))))
(fail)))
(else (fail)))))))
(if (equal? vars previous-vars)
(list (remove-duplicatese (map update-var vars)) type)
(loop vars))))))))
(vars (map first r))
(types (map second r)))
(list (map (lambda (l) (make-var (var-name (car l))
(make-alt (remove-duplicatese (map var-type l)))))
(group-by var-name (join vars '())))
(remove-duplicatese types))))
(define (unify? a b) (not (equal? (unify-types a b) '(() ()))))
(define (solve-constraints! variables constraints)
(define (restrict! variable variables)
(var-type-set!
(find-if
(lambda (v) (equal? (var-name variable) (var-name v)))
variables)
(var-type variable)))
(let loop ((variables variables))
(let ((previous-variables (map update-var variables)))
(for-each (lambda (c)
(case (car c)
((unify)
(let ((r (unify-types (second c) (third c))))
(when (null? (second r)) (error "type error" c))
(map (lambda (t) (restrict! t variables))
(first r))))
(else (error "unknown constraint" c))))
constraints)
(unless (equal? previous-variables variables)
(loop variables)))))
(define (polymorphic-types expr variables)
(let* ((bindings '())
(mapping '())
(new-expr (deep-map (lambda (a) (and (symbol? a) (assoc a variables)))
(lambda (a) (let ((name (gensym a)))
(push! (cons name (second (assoc a variables))) bindings)
(push! (cons name a) mapping)
name))
expr)))
(list bindings new-expr mapping)))
(define (variable-the-type v)
(unless (= (length (alt-list (var-type v))) 1)
(error "Variable is polymorphic" v))
(first (alt-list (var-type v))))
(define (variable-polymorphic? v) (not (= (length (alt-list (var-type v))) 1)))
(define (specialize-expression expr mapping builtins allow-polymorphic-variables?)
(deep-map var?
(lambda (v)
(if (assoc (var-name v) mapping)
(if (variable-polymorphic? v)
(if allow-polymorphic-variables?
(car (assoc (cdr (assoc (var-name v) mapping)) builtins))
(error "Not allowed to specialize polymorphic variables" v))
(let ((binding (cdr (assoc (cdr (assoc (var-name v) mapping)) builtins))))
(unless binding
(error "Variable is missing a specialized version for this type"
v (cdr (assoc (var-name v) mapping))))
(list-ref
(second binding)
(position (cut unify? (variable-the-type v) <>) (alt-list (first binding))))))
(var-name v)))
expr))
(define (type-inference expr return-type bindings builtins #!optional (debugging #f))
(let* ((a (polymorphic-types expr builtins))
(variables (append bindings (first a)))
(expr (second a))
(mapping (third a))
(b (generate-constraints expr return-type variables))
(variables (first b))
(constraints (second b))
(expr (begin
(let loop ()
(solve-constraints! variables constraints)
((call/cc
(lambda (k)
(for-each (lambda (v)
(let ((m (assoc (var-name v) mapping)))
(when (and (alt? (var-type v))
(> (length (alt-list (var-type v))) 1)
m
(equal? (cdr m) 'r-ref))
(let ((updated-type
(remove-if (lambda (t)
(and (not (equal? (third (third t)) 'star))
(not (equal? (second t) (third (third t))))))
(alt-list (var-type v)))))
(when (and (not (equal? updated-type (alt-list (var-type v))))
(not (null? updated-type)))
(set-alt-list! (var-type v) updated-type)
(k loop))))))
variables)
(lambda () #f)))))
(deep-map (lambda (a) (and (symbol? a) (find-if (lambda (v) (equal? (var-name v) a)) variables)))
(lambda (a) (find-if (lambda (v) (equal? (var-name v) a)) variables))
expr))))
(for-each (lambda (v)
(when (and (assoc (var-name v) bindings)
(alt? (var-type v))
(> (length (alt-list (var-type v))) 1))
(error (format #f "Type of '~a' cannot be determined. Options are ~a. Provide a type annotation."
(var-name v)
(alt-list (var-type v))))))
variables)
(for-each (lambda (v)
(when (and (alt? (var-type v)) (> (length (alt-list (var-type v))) 1))
(format #t "This program cannot be fully specialized becuase the type of '~a' cannot be determined.~%~a~%"
(var-name v) v)))
variables)
(when debugging (pp (list expr variables bindings mapping builtins constraints))(newline))
(list (specialize-expression expr mapping builtins #t)
variables
mapping
(var-type (find (lambda (v) (equal? (var-name v) 'return-type)) variables)))))
(define (specialize expr return-type bindings builtins #!optional (debugging #f))
(first (type-inference expr return-type bindings builtins debugging)))
)
|
fe7f22664da2e4920f57c12240a7aac41e2574f9f399714e3acbda678ed99ad3 | backtracking/ocamlgraph | gmap.mli | (**************************************************************************)
(* *)
: a generic graph library for OCaml
Copyright ( C ) 2004 - 2010
, and
(* *)
(* This software is free software; you can redistribute it and/or *)
modify it under the terms of the GNU Library General Public
License version 2.1 , with the special exception on linking
(* described in file LICENSE. *)
(* *)
(* This software 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. *)
(* *)
(**************************************************************************)
(** Graph mapping. Map a graph to another one. *)
* { 2 Mapping of vertices }
(** Signature for the source graph. *)
module type V_SRC = sig
type t
module V : Sig.HASHABLE
val fold_vertex : (V.t -> 'a -> 'a) -> t -> 'a -> 'a
end
(** Signature for the destination graph. *)
module type V_DST = sig
type t
type vertex
val empty : unit -> t
val add_vertex : t -> vertex -> t
end
(** Provide a mapping function from a mapping of vertices. *)
module Vertex(G_Src : V_SRC)(G_Dst : V_DST) : sig
val map : (G_Src.V.t -> G_Dst.vertex) -> G_Src.t -> G_Dst.t
(** [map f g] applies [f] to each vertex of [g] and so builds a new graph
based on [g] *)
val filter_map : (G_Src.V.t -> G_Dst.vertex option) -> G_Src.t -> G_Dst.t
(** [filter_map f g] applies [f] to each vertex of [g] and so
builds a new graph based on [g]; if [None] is returned by [f]
the vertex is omitted in the new graph. *)
end
* { 2 Mapping of edges }
(** Signature for the source graph. *)
module type E_SRC = sig
type t
module E : Sig.ORDERED_TYPE
val fold_edges_e : (E.t -> 'a -> 'a) -> t -> 'a -> 'a
end
(** Signature for the destination graph. *)
module type E_DST = sig
type t
type edge
val empty : unit -> t
val add_edge_e : t -> edge -> t
end
(** Provide a mapping function from a mapping of edges. *)
module Edge(G_Src: E_SRC)(G_Dst: E_DST) : sig
val map : (G_Src.E.t -> G_Dst.edge) -> G_Src.t -> G_Dst.t
(** [map f g] applies [f] to each edge of [g] and so builds a new graph
based on [g] *)
val filter_map : (G_Src.E.t -> G_Dst.edge option) -> G_Src.t -> G_Dst.t
(** [filter_map f g] applies [f] to each edge of [g] and so builds
a new graph based on [g]; if [None] is returned by [f] the
edge is omitted in the new graph. *)
end
| null | https://raw.githubusercontent.com/backtracking/ocamlgraph/1c028af097339ca8bc379436f7bd9477fa3a49cd/src/gmap.mli | ocaml | ************************************************************************
This software is free software; you can redistribute it and/or
described in file LICENSE.
This software 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.
************************************************************************
* Graph mapping. Map a graph to another one.
* Signature for the source graph.
* Signature for the destination graph.
* Provide a mapping function from a mapping of vertices.
* [map f g] applies [f] to each vertex of [g] and so builds a new graph
based on [g]
* [filter_map f g] applies [f] to each vertex of [g] and so
builds a new graph based on [g]; if [None] is returned by [f]
the vertex is omitted in the new graph.
* Signature for the source graph.
* Signature for the destination graph.
* Provide a mapping function from a mapping of edges.
* [map f g] applies [f] to each edge of [g] and so builds a new graph
based on [g]
* [filter_map f g] applies [f] to each edge of [g] and so builds
a new graph based on [g]; if [None] is returned by [f] the
edge is omitted in the new graph. | : a generic graph library for OCaml
Copyright ( C ) 2004 - 2010
, and
modify it under the terms of the GNU Library General Public
License version 2.1 , with the special exception on linking
* { 2 Mapping of vertices }
module type V_SRC = sig
type t
module V : Sig.HASHABLE
val fold_vertex : (V.t -> 'a -> 'a) -> t -> 'a -> 'a
end
module type V_DST = sig
type t
type vertex
val empty : unit -> t
val add_vertex : t -> vertex -> t
end
module Vertex(G_Src : V_SRC)(G_Dst : V_DST) : sig
val map : (G_Src.V.t -> G_Dst.vertex) -> G_Src.t -> G_Dst.t
val filter_map : (G_Src.V.t -> G_Dst.vertex option) -> G_Src.t -> G_Dst.t
end
* { 2 Mapping of edges }
module type E_SRC = sig
type t
module E : Sig.ORDERED_TYPE
val fold_edges_e : (E.t -> 'a -> 'a) -> t -> 'a -> 'a
end
module type E_DST = sig
type t
type edge
val empty : unit -> t
val add_edge_e : t -> edge -> t
end
module Edge(G_Src: E_SRC)(G_Dst: E_DST) : sig
val map : (G_Src.E.t -> G_Dst.edge) -> G_Src.t -> G_Dst.t
val filter_map : (G_Src.E.t -> G_Dst.edge option) -> G_Src.t -> G_Dst.t
end
|
28501d6235523158dc2ba7352eca3f1b06fea196bdb2e3b3c5e6d0fea1c7cf58 | tmfg/mmtis-national-access-point | front_page.cljs | (ns ote.style.front-page
"Front page styles related to hero images and other front page components"
(:require
[stylefy.core :as stylefy :refer [use-style use-sub-style]]
[ote.theme.screen-sizes :refer [width-xxs width-xs width-sm width-md width-l width-xl]]
[ote.theme.colors :as colors]))
(def hero-img {:height "540px"
:margin-top "-20px"
:background "url(/img/hero-2000.png)"
:background-size "cover"
::stylefy/media {{:max-width (str width-xl "px")} {:background "url(/img/hero-2000.png)"}
{:max-width (str width-l "px")} {:background "url(/img/hero-1600.png)"}
{:max-width (str width-sm "px")} {:background "url(/img/hero-1080.png)"
:background-size "cover"
:height "450px"}
{:max-width (str width-xs "px")} {:background "url(/img/hero-800.png)"
:background-size "cover"
:height "400px"}}})
(def hero-btn-container {:padding-top "0.5rem"
::stylefy/media {{:max-width (str width-xl "px")} {:padding-top "0.5rem"}
{:max-width (str width-l "px")} {:padding-top "0.5rem"}
{:max-width (str width-sm "px")} {:padding-top "0.5rem"}
{:max-width (str width-xs "px")} {:padding-top "0"}}})
(def h2 {:font-size "2.25em"
::stylefy/media {{:max-width (str width-xs "px")} {:font-size "1.5em"}}})
(def fp-btn-blue {:box-shadow "3px 3px 8px 0 rgba(0, 0, 0, .2)"
:cursor "pointer"
:background-color colors/primary-button-background-color})
(def fp-btn-hover {::stylefy/mode {:hover {:box-shadow "1px 1px 4px 0 rgba(0, 0, 0, .2)"
:transform "scale(0.98)"}
::stylefy/vendors ["webkit" "moz" "ms"]
::stylefy/auto-prefix #{:transform}}})
(def fp-btn-blue-hover {:background-color colors/primary-button-background-color})
(def fp-btn-gray {:background-image "linear-gradient(90deg, #ccc, #ccc)"})
(def fp-btn {:display "flex"
:padding "20px 20px 20px 10px"
:box-pack "center" ;; Old flex standard
:flex-pack "center" ;; Old flex standard
:justify-content "center"
:backface-visibility "visible"
:transform-origin "50% 50% 0px"
:transition "all 300ms ease"
:font-family "Public Sans, sans-serif"
:font-weight "400"
:font-size "1.1rem"
:text-align "center"
:color "#fff"
:border 0
::stylefy/vendors ["webkit" "moz" "ms"]
::stylefy/auto-prefix #{:box-pack :justify-content :flex-pack :backface-visibility :transform-origin :transition}})
(def front-page-button (merge
fp-btn-blue
fp-btn
fp-btn-hover
fp-btn-blue-hover))
(def hero-btn (merge {:margin-top "1rem"
:margin-left "auto"
:margin-right "auto"
:text-decoration "none"
::stylefy/media {{:max-width (str width-xl "px")} {:margin-top "1rem"}
{:max-width (str width-l "px")} {:margin-top "1rem"}
{:max-width (str width-sm "px")} {:margin-top "0.5rem"}
{:max-width (str width-xs "px")} {:margin-top "0.5rem"}}}
front-page-button))
(def front-page-button-disabled (merge
fp-btn-gray
fp-btn))
(def row-media {:margin-top "20px"
:margin-bottom "20px"
::stylefy/media {{:max-width (str width-xs "px")}
{:display "flex" :flex-direction "column"}}})
(def large-text-container {:padding-left "60px"
::stylefy/media {{:max-width (str width-xs "px")} {:padding-left "10px"
:order 2}}})
(def large-icon-container {:display "flex"
:flex-direction "column"
:align-items "center"
::stylefy/vendors ["webkit" "moz" "ms"]
::stylefy/auto-prefix #{:display :flex-direction :align-items}
::stylefy/media {{:max-width (str width-xs "px")} {:order 1}}})
(def large-font-icon {:font-size "14rem"
:color "#969696"
:text-shadow "0 4px 4px rgba(0, 0, 0, .2)"
::stylefy/media {{:max-width (str width-xs "px")} {:font-size "10rrem"}}})
(def front-page-h1 {:position "static"
:display "flex"
:padding-top "2rem"
:box-orient "vertical" ;; Old flex standard
:box-direction "normal" ;; Old flex standard
:flex-direction "column"
:box-pack "start" ;; Old flex standard
:flex-pack "start" ;; Old flex standard
:justify-content "flex-start"
:box-align "center" ;; Old flex standard
:flex-align "center" ;; Old flex standard
:align-items "center"
:font-family "Public Sans, sans-serif"
:color "#fff"
:font-size "6rem"
:font-weight "200"
:text-shadow "0 2px 10px rgba(0, 0, 0, .5)"
::stylefy/vendors ["webkit" "moz" "ms"]
::stylefy/auto-prefix #{:box-orient :box-direction :flex-direction :box-pack :flex-pack :justify-content :box-align :flex-align}
::stylefy/media {{:max-width (str width-sm "px")} {:padding-top "20px"
:font-size "4rem"
:font-weight "300"}
{:max-width (str width-xs "px")} {:padding-top "20px"
:font-size "3rem"
:font-weight "400"}
{:min-width "0px" :max-width (str width-xxs "px")} {:padding-top "20px"
:font-size "2rem"
:font-weight "400"}}})
(def front-page-hero-text {:display "block"
:margin-top "2.5rem"
:height "100px"
:align-items "cexnter"
:font-family "Public Sans, sans-serif"
:color "#fafafa"
:font-size "2.25rem"
:line-height "3rem"
:font-weight "300"
:text-align "center"
:text-shadow "0 1px 5px rgba(0, 0, 0, .5)"
::stylefy/vendors ["webkit" "moz" "ms"]
::stylefy/media {{:max-width (str width-sm "px")} {:margin-top "2rem"
:line-height "1.6rem"
:font-size "1.6rem"
:font-weight "400"}
{:max-width (str width-xs "px")} {:margin-top "20px"
:line-height "1.4rem"
:font-size "1.4rem"
:font-weight "400"}
{:min-width "0px" :max-width (str width-xxs "px")} {:margin-top "0rem"
:line-height "1.2rem"
:font-size "1.2rem"
:font-weight "400"}}})
(def third-column-text {
:color "#c8c8c8"
:font-size "0.875rem"
:font-weight 300
:box-align "center" ;; Old flex standard
:flex-align "center" ;; Old flex standard
:align-items "flex-start"
::stylefy/vendors ["webkit" "moz" "ms"]
::stylefy/auto-prefix #{:box-align :align-items :flex-align}
::stylefy/media {
{:max-width (str width-xs "px")} {:margin-bottom "20px"}
{:min-width (str width-xs "px")} {:margin-bottom "40px"}}})
(def lower-section {:display "flex"
:padding-top "80px"
:padding-bottom "100px"
:background-image "linear-gradient(45deg, #f1f1f1 0%, #fff 50%, #f1f1f1 100%)"
:box-shadow "0px 4px 40px 0 rgba(0, 0, 0, 0.25)"})
(def media-transport-service {:padding-top "60px"})
(def lower-section-data-container {:display "flex"
:box-orient "vertical" ;; Old flex standard
:box-direction "normal" ;; Old flex standard
:flex-direction "column"
:box-align "center" ;; Old flex standard
:flex-align "center" ;; Old flex standard
:align-items "center"
::stylefy/vendors ["webkit" "moz" "ms"]
::stylefy/auto-prefix #{:box-orient :box-direction :flex-direction :box-align
:align-items :flex-align}})
(def lower-section-title {:font-size "1.5rem"
:font-weight 600
::stylefy/media {{:max-width (str width-xs "px")} {:font-size "1.25rem"
:font-weight 500}}})
(def lower-section-font-icon {:font-size "8rem"
:color "#969696"
:text-shadow "0 4px 4px rgba(0, 0, 0, .2)"
::stylefy/media {{:max-width (str width-xs "px")} {:font-size "6rem"}
{:min-width "0px" :max-width (str width-xxs "px")} {:font-size "5rem"}}})
(def lower-section-text {:text-align "center"
:font-size "1rem"
:font-weight 400
:line-height "1.5rem"
:min-height "95px"
:width "100%" ;; Required by IE11 for some odd reason (here be dragons!).
})
(def footer-logo {:width "160px"
::stylefy/media {{:max-width (str width-xs "px")} {:width "90px"}}})
(def footer-small-icon {:position "relative" :height 22 :width 30 :top 5 :color "#fff" :padding-right "10px"})
(def footer-3-container {:padding-top "60px"
::stylefy/media {{:max-width (str width-xs "px")} {:padding-top "40px"}}})
(def footer-gray-info-text {:color colors/gray550
:margin-left "30px"})
| null | https://raw.githubusercontent.com/tmfg/mmtis-national-access-point/4e3eb5cbdabab58e1b439c90afd4ce35ff57ee6f/ote/src/cljs/ote/style/front_page.cljs | clojure | Old flex standard
Old flex standard
Old flex standard
Old flex standard
Old flex standard
Old flex standard
Old flex standard
Old flex standard
Old flex standard
Old flex standard
Old flex standard
Old flex standard
Old flex standard
Old flex standard
Required by IE11 for some odd reason (here be dragons!). | (ns ote.style.front-page
"Front page styles related to hero images and other front page components"
(:require
[stylefy.core :as stylefy :refer [use-style use-sub-style]]
[ote.theme.screen-sizes :refer [width-xxs width-xs width-sm width-md width-l width-xl]]
[ote.theme.colors :as colors]))
(def hero-img {:height "540px"
:margin-top "-20px"
:background "url(/img/hero-2000.png)"
:background-size "cover"
::stylefy/media {{:max-width (str width-xl "px")} {:background "url(/img/hero-2000.png)"}
{:max-width (str width-l "px")} {:background "url(/img/hero-1600.png)"}
{:max-width (str width-sm "px")} {:background "url(/img/hero-1080.png)"
:background-size "cover"
:height "450px"}
{:max-width (str width-xs "px")} {:background "url(/img/hero-800.png)"
:background-size "cover"
:height "400px"}}})
(def hero-btn-container {:padding-top "0.5rem"
::stylefy/media {{:max-width (str width-xl "px")} {:padding-top "0.5rem"}
{:max-width (str width-l "px")} {:padding-top "0.5rem"}
{:max-width (str width-sm "px")} {:padding-top "0.5rem"}
{:max-width (str width-xs "px")} {:padding-top "0"}}})
(def h2 {:font-size "2.25em"
::stylefy/media {{:max-width (str width-xs "px")} {:font-size "1.5em"}}})
(def fp-btn-blue {:box-shadow "3px 3px 8px 0 rgba(0, 0, 0, .2)"
:cursor "pointer"
:background-color colors/primary-button-background-color})
(def fp-btn-hover {::stylefy/mode {:hover {:box-shadow "1px 1px 4px 0 rgba(0, 0, 0, .2)"
:transform "scale(0.98)"}
::stylefy/vendors ["webkit" "moz" "ms"]
::stylefy/auto-prefix #{:transform}}})
(def fp-btn-blue-hover {:background-color colors/primary-button-background-color})
(def fp-btn-gray {:background-image "linear-gradient(90deg, #ccc, #ccc)"})
(def fp-btn {:display "flex"
:padding "20px 20px 20px 10px"
:justify-content "center"
:backface-visibility "visible"
:transform-origin "50% 50% 0px"
:transition "all 300ms ease"
:font-family "Public Sans, sans-serif"
:font-weight "400"
:font-size "1.1rem"
:text-align "center"
:color "#fff"
:border 0
::stylefy/vendors ["webkit" "moz" "ms"]
::stylefy/auto-prefix #{:box-pack :justify-content :flex-pack :backface-visibility :transform-origin :transition}})
(def front-page-button (merge
fp-btn-blue
fp-btn
fp-btn-hover
fp-btn-blue-hover))
(def hero-btn (merge {:margin-top "1rem"
:margin-left "auto"
:margin-right "auto"
:text-decoration "none"
::stylefy/media {{:max-width (str width-xl "px")} {:margin-top "1rem"}
{:max-width (str width-l "px")} {:margin-top "1rem"}
{:max-width (str width-sm "px")} {:margin-top "0.5rem"}
{:max-width (str width-xs "px")} {:margin-top "0.5rem"}}}
front-page-button))
(def front-page-button-disabled (merge
fp-btn-gray
fp-btn))
(def row-media {:margin-top "20px"
:margin-bottom "20px"
::stylefy/media {{:max-width (str width-xs "px")}
{:display "flex" :flex-direction "column"}}})
(def large-text-container {:padding-left "60px"
::stylefy/media {{:max-width (str width-xs "px")} {:padding-left "10px"
:order 2}}})
(def large-icon-container {:display "flex"
:flex-direction "column"
:align-items "center"
::stylefy/vendors ["webkit" "moz" "ms"]
::stylefy/auto-prefix #{:display :flex-direction :align-items}
::stylefy/media {{:max-width (str width-xs "px")} {:order 1}}})
(def large-font-icon {:font-size "14rem"
:color "#969696"
:text-shadow "0 4px 4px rgba(0, 0, 0, .2)"
::stylefy/media {{:max-width (str width-xs "px")} {:font-size "10rrem"}}})
(def front-page-h1 {:position "static"
:display "flex"
:padding-top "2rem"
:flex-direction "column"
:justify-content "flex-start"
:align-items "center"
:font-family "Public Sans, sans-serif"
:color "#fff"
:font-size "6rem"
:font-weight "200"
:text-shadow "0 2px 10px rgba(0, 0, 0, .5)"
::stylefy/vendors ["webkit" "moz" "ms"]
::stylefy/auto-prefix #{:box-orient :box-direction :flex-direction :box-pack :flex-pack :justify-content :box-align :flex-align}
::stylefy/media {{:max-width (str width-sm "px")} {:padding-top "20px"
:font-size "4rem"
:font-weight "300"}
{:max-width (str width-xs "px")} {:padding-top "20px"
:font-size "3rem"
:font-weight "400"}
{:min-width "0px" :max-width (str width-xxs "px")} {:padding-top "20px"
:font-size "2rem"
:font-weight "400"}}})
(def front-page-hero-text {:display "block"
:margin-top "2.5rem"
:height "100px"
:align-items "cexnter"
:font-family "Public Sans, sans-serif"
:color "#fafafa"
:font-size "2.25rem"
:line-height "3rem"
:font-weight "300"
:text-align "center"
:text-shadow "0 1px 5px rgba(0, 0, 0, .5)"
::stylefy/vendors ["webkit" "moz" "ms"]
::stylefy/media {{:max-width (str width-sm "px")} {:margin-top "2rem"
:line-height "1.6rem"
:font-size "1.6rem"
:font-weight "400"}
{:max-width (str width-xs "px")} {:margin-top "20px"
:line-height "1.4rem"
:font-size "1.4rem"
:font-weight "400"}
{:min-width "0px" :max-width (str width-xxs "px")} {:margin-top "0rem"
:line-height "1.2rem"
:font-size "1.2rem"
:font-weight "400"}}})
(def third-column-text {
:color "#c8c8c8"
:font-size "0.875rem"
:font-weight 300
:align-items "flex-start"
::stylefy/vendors ["webkit" "moz" "ms"]
::stylefy/auto-prefix #{:box-align :align-items :flex-align}
::stylefy/media {
{:max-width (str width-xs "px")} {:margin-bottom "20px"}
{:min-width (str width-xs "px")} {:margin-bottom "40px"}}})
(def lower-section {:display "flex"
:padding-top "80px"
:padding-bottom "100px"
:background-image "linear-gradient(45deg, #f1f1f1 0%, #fff 50%, #f1f1f1 100%)"
:box-shadow "0px 4px 40px 0 rgba(0, 0, 0, 0.25)"})
(def media-transport-service {:padding-top "60px"})
(def lower-section-data-container {:display "flex"
:flex-direction "column"
:align-items "center"
::stylefy/vendors ["webkit" "moz" "ms"]
::stylefy/auto-prefix #{:box-orient :box-direction :flex-direction :box-align
:align-items :flex-align}})
(def lower-section-title {:font-size "1.5rem"
:font-weight 600
::stylefy/media {{:max-width (str width-xs "px")} {:font-size "1.25rem"
:font-weight 500}}})
(def lower-section-font-icon {:font-size "8rem"
:color "#969696"
:text-shadow "0 4px 4px rgba(0, 0, 0, .2)"
::stylefy/media {{:max-width (str width-xs "px")} {:font-size "6rem"}
{:min-width "0px" :max-width (str width-xxs "px")} {:font-size "5rem"}}})
(def lower-section-text {:text-align "center"
:font-size "1rem"
:font-weight 400
:line-height "1.5rem"
:min-height "95px"
})
(def footer-logo {:width "160px"
::stylefy/media {{:max-width (str width-xs "px")} {:width "90px"}}})
(def footer-small-icon {:position "relative" :height 22 :width 30 :top 5 :color "#fff" :padding-right "10px"})
(def footer-3-container {:padding-top "60px"
::stylefy/media {{:max-width (str width-xs "px")} {:padding-top "40px"}}})
(def footer-gray-info-text {:color colors/gray550
:margin-left "30px"})
|
7d6385af09e5f184701e369e93a6fc865dee8d6434ddbee357bc4fc108e44987 | liqd/thentos | SimpleSpec.hs | # LANGUAGE DataKinds #
# LANGUAGE ExistentialQuantification #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
{-# LANGUAGE GADTs #-}
{-# LANGUAGE ImplicitParams #-}
# LANGUAGE InstanceSigs #
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
# LANGUAGE TupleSections #
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE ViewPatterns #-}
# OPTIONS_GHC -fno - warn - orphans #
module Thentos.Adhocracy3.Backend.Api.SimpleSpec
where
import Control.Exception (bracket)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Data.Aeson.Encode.Pretty (encodePretty)
import Data.Aeson (Value(String), object, (.=))
import Data.Configifier (Source(YamlString), Tagged(Tagged), (>>.))
import Data.Foldable (for_)
import Data.Maybe (isJust)
import Data.Monoid ((<>))
import Data.Proxy (Proxy(Proxy))
import Data.String.Conversions (LBS, ST, cs)
import Data.Void (Void)
import GHC.Stack (CallStack)
import LIO.DCLabel (toCNF)
import Network.HTTP.Client (newManager, defaultManagerSettings)
import Network.HTTP.Types (Header, Status, status200, status400)
import Network.Wai (Application)
import Network.Wai.Handler.Warp (defaultSettings, setHost, setPort, runSettings)
import Network.Wai.Test (simpleBody, simpleStatus)
import System.FilePath ((</>))
import System.Process (readProcess)
import Test.Hspec (ActionWith, Spec, around_, around, describe, hspec, it,
shouldBe, shouldContain, shouldSatisfy, pendingWith)
import Test.Hspec.Wai (request, with)
import Test.Hspec.Wai.Internal (WaiSession, runWaiSession)
import Test.QuickCheck (property)
import qualified Data.Aeson as Aeson
import qualified Data.Map as Map
import qualified Data.Text as ST
import qualified Network.HTTP.Types.Status as Status
import Thentos
import Thentos.Action.Core
import Thentos.Action.Types
import Thentos.Adhocracy3.Action.Types
import Thentos.Adhocracy3.Backend.Api.Simple
import Thentos.Config (ThentosConfig)
import Thentos.Types
import Thentos.Test.Arbitrary ()
import Thentos.Test.Config
import Thentos.Test.Core
import Thentos.Test.Network
import Thentos.Test.DefaultSpec
tests :: IO ()
tests = hspec spec
spec :: Spec
spec =
describe "Thentos.Backend.Api.Adhocracy3" $ do
with setupBackend specHasRestDocs
describe "A3UserNoPass" $ do
it "has invertible *JSON instances" . property $
let (===) (Right (A3UserNoPass (UserFormData n _ e)))
(Right (A3UserNoPass (UserFormData n' _ e')))
= n == n' && e == e'
(===) _ _ = False
in \ (A3UserNoPass -> u) -> (Aeson.eitherDecode . Aeson.encode) u === Right u
describe "A3UserWithPassword" $ do
it "has invertible *JSON instances" . property $
\ (A3UserWithPass -> u) -> (Aeson.eitherDecode . Aeson.encode) u == Right u
it "rejects short passwords" $ do
let userdata = mkUserJson "Anna Müller" "" "short"
fromA3UserWithPass <$>
(Aeson.eitherDecode userdata :: Either String A3UserWithPass)
`shouldBe` Left "password too short (less than 6 characters)"
it "rejects long passwords" $ do
let longpass = ST.replicate 26 "long"
userdata = mkUserJson "Anna Müller" "" longpass
fromA3UserWithPass <$>
(Aeson.eitherDecode userdata :: Either String A3UserWithPass)
`shouldBe` Left "password too long (more than 100 characters)"
it "rejects invalid email addresses" $ do
let userdata = mkUserJson "Anna Müller" "anna@" "EckVocUbs3"
fromA3UserWithPass <$>
(Aeson.eitherDecode userdata :: Either String A3UserWithPass)
`shouldBe` Left "expected UserEmail, encountered String \"anna@\""
it "rejects empty user names" $ do
let userdata = mkUserJson "" "" "EckVocUbs3"
fromA3UserWithPass <$>
(Aeson.eitherDecode userdata :: Either String A3UserWithPass)
`shouldBe` Left "user name is empty"
it "rejects user names with @" $ do
let userdata = mkUserJson "Bla@Blub" "" "EckVocUbs3"
fromA3UserWithPass <$>
(Aeson.eitherDecode userdata :: Either String A3UserWithPass)
`shouldBe` Left "'@' in user name is not allowed: \"Bla@Blub\""
it "rejects user names with too much whitespace" $ do
let userdata = mkUserJson " Anna Toll" "" "EckVocUbs3"
fromA3UserWithPass <$>
(Aeson.eitherDecode userdata :: Either String A3UserWithPass)
`shouldBe` Left "Illegal whitespace sequence in user name: \" Anna Toll\""
describe "create user" $ do
let a3userCreated = encodePretty $ object
[ "content_type" .= String "adhocracy_core.resources.principal.IUser"
, "path" .= String ":6541/principals/users/0000111/"
]
smartA3backend = routingReplyServer Nothing $ Map.fromList
[ ("/path/principals/users", (status200, a3userCreated)) ]
around (withTestState smartA3backend) $ do
it "works" . runTestState $ \(_, cfg) -> do
let name = "Anna Müller"
pass = "EckVocUbs3"
reqBody = mkUserJson name "" pass
Appending trailing newline since servant - server < 0.4.1 could n't handle it
rsp <- request "POST" "/principals/users" [ctJson] $ reqBody <> "\n"
shouldBeStatusXWithCustomMessages 200 (simpleStatus rsp) (simpleBody rsp)
-- The returned path is now just a dummy that uses our endpoint prefix
-- (not the one from A3)
[":7118/"]
-- FIXME: we should change Thentos.Test.Config.{back,front}end to so that we
-- can distinguish between bind url and exposed url. i think this here
-- needs to be the exposed url.
-- Find the confirmation token. We use a system call to "grep" it ouf the
-- log file, which is ugly but works, while reading the log file within
-- Haskell doesn't (openFile: resource busy (file is locked)).
let actPrefix = ":7119/activate/"
logPath = cs $ cfg >>. (Proxy :: Proxy '["log", "path"])
actLine <- liftIO $ readProcess "grep" [actPrefix, logPath] ""
let confToken = ST.take 24 . snd $ ST.breakOnEnd (cs actPrefix) (cs actLine)
-- Make sure that we cannot log in since the account isn't yet active
let loginReq = mkLoginRequest name pass
loginRsp <- request "POST" "login_username" [ctJson] loginReq
liftIO $ Status.statusCode (simpleStatus loginRsp) `shouldBe` 400
Activate user
let actReq = encodePretty $ object
[ "path" .= String ("/activate/" <> confToken) ]
actRsp <- request "POST" "activate_account" [ctJson] actReq
liftIO $ Status.statusCode (simpleStatus actRsp) `shouldBe` 200
-- Make sure that we can log in now
loginRsp2 <- request "POST" "login_username" [ctJson] loginReq
liftIO $ Status.statusCode (simpleStatus loginRsp2) `shouldBe` 200
describe "activate_account" $ with setupBackend $ do
let a3errMsg = encodePretty $ A3ErrorMessage
[A3Error "path" "body" "Unknown or expired activation path"]
around_ (withA3fake (Just status400) a3errMsg) $ do
it "rejects bad path mimicking A3" $ do
let reqBody = encodePretty $ object
[ "path" .= String "/activate/no-such-path" ]
rsp <- request "POST" "activate_account" [ctJson] reqBody
shouldBeErr400WithCustomMessage (simpleStatus rsp) (simpleBody rsp)
"\"Unknown or expired activation path\""
describe "login" $ with setupBackend $
it "rejects bad credentials mimicking A3" $ do
let reqBody = mkLoginRequest "Anna Müller" "this-is-wrong"
rsp <- request "POST" "login_username" [ctJson] reqBody
shouldBeErr400WithCustomMessage (simpleStatus rsp) (simpleBody rsp)
"\"User doesn't exist or password is wrong\""
describe "resetPassword" $ with setupBackend $ do
let a3loginSuccess = encodePretty $ object
[ "status" .= String "success"
, "user_path" .= String ":7118/principals/users/0000000/"
, "user_token" .= String "bla-bla-valid-token-blah"
]
around_ (withA3fake Nothing a3loginSuccess) $ do
it "changes the password if A3 signals success" $ do
liftIO $ pendingWith "see BUG #321"
let resetReq = mkPwResetRequestJson "/principals/resets/dummypath" "newpass"
rsp <- request "POST" "password_reset" [ctJson] resetReq
liftIO $ Status.statusCode (simpleStatus rsp) `shouldBe` 200
-- Test that we can log in using the new password
let loginReq = mkLoginRequest "god" "newpass"
loginRsp <- request "POST" "login_username" [ctJson] loginReq
liftIO $ Status.statusCode (simpleStatus loginRsp) `shouldBe` 200
let a3errMsg = encodePretty $ A3ErrorMessage
[A3Error "path" "body" "This resource path does not exist."]
around_ (withA3fake (Just status400) a3errMsg) $ do
it "passes the error on if A3 signals failure" $ do
liftIO $ pendingWith "see BUG #321, too."
let resetReq = mkPwResetRequestJson "/principals/resets/dummypath" "newpass"
rsp <- request "POST" "password_reset" [ctJson] resetReq
shouldBeErr400WithCustomMessage (simpleStatus rsp) (simpleBody rsp)
"resource path does not exist"
describe "an arbitrary request" $ with setupBackend $ do
it "rejects bad session token mimicking A3" $ do
let headers = [("X-User-Token", "invalid-token")]
rsp <- request "POST" "dummy/endpoint" headers ""
shouldBeErr400WithCustomMessage (simpleStatus rsp) (simpleBody rsp)
"\"Invalid user token\""
it "throws an internal error if A3 is unreachable" $ do
rsp <- request "POST" "dummy/endpoint" [ctJson] ""
liftIO $ Status.statusCode (simpleStatus rsp) `shouldBe` 500
Response body should be parseable as JSON
let rspBody = simpleBody rsp
liftIO $ (Aeson.decode rspBody :: Maybe Aeson.Value) `shouldSatisfy` isJust
-- It should contain the quoted string "internal error"
liftIO $ cs rspBody `shouldContain` ("\"internal error\"" :: String)
type TestState = (Application, ThentosConfig)
runTestState :: (TestState -> WaiSession a) -> TestState -> IO a
runTestState session (app, cfg) = runWaiSession (session (app, cfg)) app
withTestState :: Application -> ActionWith TestState -> IO ()
withTestState a3backend action = outsideTempDirectory $ \tmp ->
setupBackend' [ YamlString . cs . unlines $
[ "log:"
, " level: DEBUG"
, " stdout: False"
, " path: " ++ tmp </> "log" ]]
>>= withApp a3backend . action
setupBackend :: IO Application
setupBackend = fst <$> setupBackend' []
setupBackend' :: [Source] -> IO (Application, ThentosConfig)
setupBackend' extraCfg = do
as@(ActionEnv cfg _) <- thentosTestConfig' extraCfg >>= createActionEnv'
mgr <- newManager defaultManagerSettings
createDefaultUser as
((), ()) <- runActionWithPrivs [toCNF GroupAdmin] () as $ (autocreateMissingServices cfg :: ActionStack Void () ())
let Just beConfig = Tagged <$> cfg >>. (Proxy :: Proxy '["backend"])
return (serveApi mgr beConfig as, cfg)
ctJson :: Header
ctJson = ("Content-Type", "application/json")
-- * helper functions
-- | Compare the response status with an expected status code and check that the response
-- body is a JSON object that contains all of the specified custom strings.
shouldBeStatusXWithCustomMessages :: MonadIO m => (?loc :: CallStack) =>
Int -> Status.Status -> LBS -> [String] -> m ()
shouldBeStatusXWithCustomMessages expectedCode rstStatus rspBody customMessages = do
liftIO $ Status.statusCode rstStatus `shouldBe` expectedCode
Response body should be parseable as JSON
liftIO $ (Aeson.decode rspBody :: Maybe Aeson.Value) `shouldSatisfy` isJust
liftIO $ for_ customMessages (cs rspBody `shouldContain`)
| Like ' shouldBeStatusXWithCustomMessage ' , with the expected code set tu 400 .
-- We check the custom messages and the quoted string "error" are present in the JSON body.
shouldBeErr400WithCustomMessage :: MonadIO m => (?loc :: CallStack) =>
Status.Status -> LBS -> String -> m ()
shouldBeErr400WithCustomMessage rstStatus rspBody customMessage =
shouldBeStatusXWithCustomMessages 400 rstStatus rspBody ["\"error\"", customMessage]
-- | Create a JSON object describing an user.
-- Aeson.encode would strip the password, hence we do it by hand.
mkUserJson :: ST -> ST -> ST -> LBS
mkUserJson name email password = encodePretty $ object
[ "data" .= object
[ "adhocracy_core.sheets.principal.IUserBasic" .= object
[ "name" ..= name
]
, "adhocracy_core.sheets.principal.IUserExtended" .= object
[ "email" ..= email
]
, "adhocracy_core.sheets.principal.IPasswordAuthentication" .= object
[ "password" ..= password
]
]
, "content_type" ..= "adhocracy_core.resources.principal.IUser"
]
| Create a JSON object for a login request . Calling the ToJSON instance might be
-- considered cheating, so we do it by hand.
mkLoginRequest :: ST -> ST -> LBS
mkLoginRequest name pass = encodePretty $ object
["name" .= String name, "password" .= String pass]
| Create a JSON object for a PasswordResetRequest . Calling the ToJSON instance might be
-- considered cheating, so we do it by hand.
mkPwResetRequestJson :: ST -> ST -> LBS
mkPwResetRequestJson path pass = encodePretty $ object
["path" .= String path, "password" .= String pass]
| Start a faked A3 backend that always returns the same response , passed in as argument .
The status code defaults to 200 .
withA3fake :: Maybe Status -> LBS -> IO () -> IO ()
withA3fake mStatus respBody = withApp $ staticReplyServer mStatus Nothing respBody
-- | Start an application prior to running the test, stopping it afterwards.
withApp :: Application -> IO () -> IO ()
withApp app test = bracket
(startDaemon $ runSettings settings app)
stopDaemon
(const test)
where
settings = setHost "127.0.0.1" . setPort 8001 $ defaultSettings
| null | https://raw.githubusercontent.com/liqd/thentos/f7d53d8e9d11956d2cc83efb5f5149876109b098/thentos-adhocracy/tests/Thentos/Adhocracy3/Backend/Api/SimpleSpec.hs | haskell | # LANGUAGE GADTs #
# LANGUAGE ImplicitParams #
# LANGUAGE OverloadedStrings #
# LANGUAGE RankNTypes #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeSynonymInstances #
# LANGUAGE ViewPatterns #
The returned path is now just a dummy that uses our endpoint prefix
(not the one from A3)
FIXME: we should change Thentos.Test.Config.{back,front}end to so that we
can distinguish between bind url and exposed url. i think this here
needs to be the exposed url.
Find the confirmation token. We use a system call to "grep" it ouf the
log file, which is ugly but works, while reading the log file within
Haskell doesn't (openFile: resource busy (file is locked)).
Make sure that we cannot log in since the account isn't yet active
Make sure that we can log in now
Test that we can log in using the new password
It should contain the quoted string "internal error"
* helper functions
| Compare the response status with an expected status code and check that the response
body is a JSON object that contains all of the specified custom strings.
We check the custom messages and the quoted string "error" are present in the JSON body.
| Create a JSON object describing an user.
Aeson.encode would strip the password, hence we do it by hand.
considered cheating, so we do it by hand.
considered cheating, so we do it by hand.
| Start an application prior to running the test, stopping it afterwards. | # LANGUAGE DataKinds #
# LANGUAGE ExistentialQuantification #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE InstanceSigs #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE TupleSections #
# OPTIONS_GHC -fno - warn - orphans #
module Thentos.Adhocracy3.Backend.Api.SimpleSpec
where
import Control.Exception (bracket)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Data.Aeson.Encode.Pretty (encodePretty)
import Data.Aeson (Value(String), object, (.=))
import Data.Configifier (Source(YamlString), Tagged(Tagged), (>>.))
import Data.Foldable (for_)
import Data.Maybe (isJust)
import Data.Monoid ((<>))
import Data.Proxy (Proxy(Proxy))
import Data.String.Conversions (LBS, ST, cs)
import Data.Void (Void)
import GHC.Stack (CallStack)
import LIO.DCLabel (toCNF)
import Network.HTTP.Client (newManager, defaultManagerSettings)
import Network.HTTP.Types (Header, Status, status200, status400)
import Network.Wai (Application)
import Network.Wai.Handler.Warp (defaultSettings, setHost, setPort, runSettings)
import Network.Wai.Test (simpleBody, simpleStatus)
import System.FilePath ((</>))
import System.Process (readProcess)
import Test.Hspec (ActionWith, Spec, around_, around, describe, hspec, it,
shouldBe, shouldContain, shouldSatisfy, pendingWith)
import Test.Hspec.Wai (request, with)
import Test.Hspec.Wai.Internal (WaiSession, runWaiSession)
import Test.QuickCheck (property)
import qualified Data.Aeson as Aeson
import qualified Data.Map as Map
import qualified Data.Text as ST
import qualified Network.HTTP.Types.Status as Status
import Thentos
import Thentos.Action.Core
import Thentos.Action.Types
import Thentos.Adhocracy3.Action.Types
import Thentos.Adhocracy3.Backend.Api.Simple
import Thentos.Config (ThentosConfig)
import Thentos.Types
import Thentos.Test.Arbitrary ()
import Thentos.Test.Config
import Thentos.Test.Core
import Thentos.Test.Network
import Thentos.Test.DefaultSpec
tests :: IO ()
tests = hspec spec
spec :: Spec
spec =
describe "Thentos.Backend.Api.Adhocracy3" $ do
with setupBackend specHasRestDocs
describe "A3UserNoPass" $ do
it "has invertible *JSON instances" . property $
let (===) (Right (A3UserNoPass (UserFormData n _ e)))
(Right (A3UserNoPass (UserFormData n' _ e')))
= n == n' && e == e'
(===) _ _ = False
in \ (A3UserNoPass -> u) -> (Aeson.eitherDecode . Aeson.encode) u === Right u
describe "A3UserWithPassword" $ do
it "has invertible *JSON instances" . property $
\ (A3UserWithPass -> u) -> (Aeson.eitherDecode . Aeson.encode) u == Right u
it "rejects short passwords" $ do
let userdata = mkUserJson "Anna Müller" "" "short"
fromA3UserWithPass <$>
(Aeson.eitherDecode userdata :: Either String A3UserWithPass)
`shouldBe` Left "password too short (less than 6 characters)"
it "rejects long passwords" $ do
let longpass = ST.replicate 26 "long"
userdata = mkUserJson "Anna Müller" "" longpass
fromA3UserWithPass <$>
(Aeson.eitherDecode userdata :: Either String A3UserWithPass)
`shouldBe` Left "password too long (more than 100 characters)"
it "rejects invalid email addresses" $ do
let userdata = mkUserJson "Anna Müller" "anna@" "EckVocUbs3"
fromA3UserWithPass <$>
(Aeson.eitherDecode userdata :: Either String A3UserWithPass)
`shouldBe` Left "expected UserEmail, encountered String \"anna@\""
it "rejects empty user names" $ do
let userdata = mkUserJson "" "" "EckVocUbs3"
fromA3UserWithPass <$>
(Aeson.eitherDecode userdata :: Either String A3UserWithPass)
`shouldBe` Left "user name is empty"
it "rejects user names with @" $ do
let userdata = mkUserJson "Bla@Blub" "" "EckVocUbs3"
fromA3UserWithPass <$>
(Aeson.eitherDecode userdata :: Either String A3UserWithPass)
`shouldBe` Left "'@' in user name is not allowed: \"Bla@Blub\""
it "rejects user names with too much whitespace" $ do
let userdata = mkUserJson " Anna Toll" "" "EckVocUbs3"
fromA3UserWithPass <$>
(Aeson.eitherDecode userdata :: Either String A3UserWithPass)
`shouldBe` Left "Illegal whitespace sequence in user name: \" Anna Toll\""
describe "create user" $ do
let a3userCreated = encodePretty $ object
[ "content_type" .= String "adhocracy_core.resources.principal.IUser"
, "path" .= String ":6541/principals/users/0000111/"
]
smartA3backend = routingReplyServer Nothing $ Map.fromList
[ ("/path/principals/users", (status200, a3userCreated)) ]
around (withTestState smartA3backend) $ do
it "works" . runTestState $ \(_, cfg) -> do
let name = "Anna Müller"
pass = "EckVocUbs3"
reqBody = mkUserJson name "" pass
Appending trailing newline since servant - server < 0.4.1 could n't handle it
rsp <- request "POST" "/principals/users" [ctJson] $ reqBody <> "\n"
shouldBeStatusXWithCustomMessages 200 (simpleStatus rsp) (simpleBody rsp)
[":7118/"]
let actPrefix = ":7119/activate/"
logPath = cs $ cfg >>. (Proxy :: Proxy '["log", "path"])
actLine <- liftIO $ readProcess "grep" [actPrefix, logPath] ""
let confToken = ST.take 24 . snd $ ST.breakOnEnd (cs actPrefix) (cs actLine)
let loginReq = mkLoginRequest name pass
loginRsp <- request "POST" "login_username" [ctJson] loginReq
liftIO $ Status.statusCode (simpleStatus loginRsp) `shouldBe` 400
Activate user
let actReq = encodePretty $ object
[ "path" .= String ("/activate/" <> confToken) ]
actRsp <- request "POST" "activate_account" [ctJson] actReq
liftIO $ Status.statusCode (simpleStatus actRsp) `shouldBe` 200
loginRsp2 <- request "POST" "login_username" [ctJson] loginReq
liftIO $ Status.statusCode (simpleStatus loginRsp2) `shouldBe` 200
describe "activate_account" $ with setupBackend $ do
let a3errMsg = encodePretty $ A3ErrorMessage
[A3Error "path" "body" "Unknown or expired activation path"]
around_ (withA3fake (Just status400) a3errMsg) $ do
it "rejects bad path mimicking A3" $ do
let reqBody = encodePretty $ object
[ "path" .= String "/activate/no-such-path" ]
rsp <- request "POST" "activate_account" [ctJson] reqBody
shouldBeErr400WithCustomMessage (simpleStatus rsp) (simpleBody rsp)
"\"Unknown or expired activation path\""
describe "login" $ with setupBackend $
it "rejects bad credentials mimicking A3" $ do
let reqBody = mkLoginRequest "Anna Müller" "this-is-wrong"
rsp <- request "POST" "login_username" [ctJson] reqBody
shouldBeErr400WithCustomMessage (simpleStatus rsp) (simpleBody rsp)
"\"User doesn't exist or password is wrong\""
describe "resetPassword" $ with setupBackend $ do
let a3loginSuccess = encodePretty $ object
[ "status" .= String "success"
, "user_path" .= String ":7118/principals/users/0000000/"
, "user_token" .= String "bla-bla-valid-token-blah"
]
around_ (withA3fake Nothing a3loginSuccess) $ do
it "changes the password if A3 signals success" $ do
liftIO $ pendingWith "see BUG #321"
let resetReq = mkPwResetRequestJson "/principals/resets/dummypath" "newpass"
rsp <- request "POST" "password_reset" [ctJson] resetReq
liftIO $ Status.statusCode (simpleStatus rsp) `shouldBe` 200
let loginReq = mkLoginRequest "god" "newpass"
loginRsp <- request "POST" "login_username" [ctJson] loginReq
liftIO $ Status.statusCode (simpleStatus loginRsp) `shouldBe` 200
let a3errMsg = encodePretty $ A3ErrorMessage
[A3Error "path" "body" "This resource path does not exist."]
around_ (withA3fake (Just status400) a3errMsg) $ do
it "passes the error on if A3 signals failure" $ do
liftIO $ pendingWith "see BUG #321, too."
let resetReq = mkPwResetRequestJson "/principals/resets/dummypath" "newpass"
rsp <- request "POST" "password_reset" [ctJson] resetReq
shouldBeErr400WithCustomMessage (simpleStatus rsp) (simpleBody rsp)
"resource path does not exist"
describe "an arbitrary request" $ with setupBackend $ do
it "rejects bad session token mimicking A3" $ do
let headers = [("X-User-Token", "invalid-token")]
rsp <- request "POST" "dummy/endpoint" headers ""
shouldBeErr400WithCustomMessage (simpleStatus rsp) (simpleBody rsp)
"\"Invalid user token\""
it "throws an internal error if A3 is unreachable" $ do
rsp <- request "POST" "dummy/endpoint" [ctJson] ""
liftIO $ Status.statusCode (simpleStatus rsp) `shouldBe` 500
Response body should be parseable as JSON
let rspBody = simpleBody rsp
liftIO $ (Aeson.decode rspBody :: Maybe Aeson.Value) `shouldSatisfy` isJust
liftIO $ cs rspBody `shouldContain` ("\"internal error\"" :: String)
type TestState = (Application, ThentosConfig)
runTestState :: (TestState -> WaiSession a) -> TestState -> IO a
runTestState session (app, cfg) = runWaiSession (session (app, cfg)) app
withTestState :: Application -> ActionWith TestState -> IO ()
withTestState a3backend action = outsideTempDirectory $ \tmp ->
setupBackend' [ YamlString . cs . unlines $
[ "log:"
, " level: DEBUG"
, " stdout: False"
, " path: " ++ tmp </> "log" ]]
>>= withApp a3backend . action
setupBackend :: IO Application
setupBackend = fst <$> setupBackend' []
setupBackend' :: [Source] -> IO (Application, ThentosConfig)
setupBackend' extraCfg = do
as@(ActionEnv cfg _) <- thentosTestConfig' extraCfg >>= createActionEnv'
mgr <- newManager defaultManagerSettings
createDefaultUser as
((), ()) <- runActionWithPrivs [toCNF GroupAdmin] () as $ (autocreateMissingServices cfg :: ActionStack Void () ())
let Just beConfig = Tagged <$> cfg >>. (Proxy :: Proxy '["backend"])
return (serveApi mgr beConfig as, cfg)
ctJson :: Header
ctJson = ("Content-Type", "application/json")
shouldBeStatusXWithCustomMessages :: MonadIO m => (?loc :: CallStack) =>
Int -> Status.Status -> LBS -> [String] -> m ()
shouldBeStatusXWithCustomMessages expectedCode rstStatus rspBody customMessages = do
liftIO $ Status.statusCode rstStatus `shouldBe` expectedCode
Response body should be parseable as JSON
liftIO $ (Aeson.decode rspBody :: Maybe Aeson.Value) `shouldSatisfy` isJust
liftIO $ for_ customMessages (cs rspBody `shouldContain`)
| Like ' shouldBeStatusXWithCustomMessage ' , with the expected code set tu 400 .
shouldBeErr400WithCustomMessage :: MonadIO m => (?loc :: CallStack) =>
Status.Status -> LBS -> String -> m ()
shouldBeErr400WithCustomMessage rstStatus rspBody customMessage =
shouldBeStatusXWithCustomMessages 400 rstStatus rspBody ["\"error\"", customMessage]
mkUserJson :: ST -> ST -> ST -> LBS
mkUserJson name email password = encodePretty $ object
[ "data" .= object
[ "adhocracy_core.sheets.principal.IUserBasic" .= object
[ "name" ..= name
]
, "adhocracy_core.sheets.principal.IUserExtended" .= object
[ "email" ..= email
]
, "adhocracy_core.sheets.principal.IPasswordAuthentication" .= object
[ "password" ..= password
]
]
, "content_type" ..= "adhocracy_core.resources.principal.IUser"
]
| Create a JSON object for a login request . Calling the ToJSON instance might be
mkLoginRequest :: ST -> ST -> LBS
mkLoginRequest name pass = encodePretty $ object
["name" .= String name, "password" .= String pass]
| Create a JSON object for a PasswordResetRequest . Calling the ToJSON instance might be
mkPwResetRequestJson :: ST -> ST -> LBS
mkPwResetRequestJson path pass = encodePretty $ object
["path" .= String path, "password" .= String pass]
| Start a faked A3 backend that always returns the same response , passed in as argument .
The status code defaults to 200 .
withA3fake :: Maybe Status -> LBS -> IO () -> IO ()
withA3fake mStatus respBody = withApp $ staticReplyServer mStatus Nothing respBody
withApp :: Application -> IO () -> IO ()
withApp app test = bracket
(startDaemon $ runSettings settings app)
stopDaemon
(const test)
where
settings = setHost "127.0.0.1" . setPort 8001 $ defaultSettings
|
a5b715bfe5601636770546eebcd4b228ed6254ee4e3735486576b0c8130ebe1e | yrashk/evfs | evfs_file_server.erl | -module(evfs_file_server).
-behaviour(gen_server).
-include("internal.hrl").
-export([start_link/1]).
%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
-define(EVFS_HANDLERS_TABLE, evfs_handlers).
-type handler() :: {module(), term()}.
-record(state,
{
handlers = [] :: [handler()],
file_server :: pid()
}).
-type state() :: #state{}.
-spec start_link(pid()) -> {ok, state()} | {error, term()}.
start_link(FileServer) ->
gen_server:start({local, ?FILE_SERVER}, ?MODULE, FileServer, []).
-spec init(pid()) -> {ok, state()} | {stop, term()}.
init(FileServer) ->
case ?DEFAULT_HANDLER:init(FileServer) of
{ok, HState} ->
{ok, #state{ handlers = [{?DEFAULT_HANDLER, HState}], file_server = FileServer }};
{stop, _Reason} = Error ->
Error
end.
-type filename_command() :: absname | absname_join | basename |
dirname | extension | join | pathtype |
rootname | split | nativename |
find_src | flatten.
-type file_server_command() ::
original_file_server |
{unregister_handler, module()} |
{register_handler, module(), term()} |
%% Filename API
{filename, filename_command(), [term()]} |
Filesystem API
{open, file:filename(), [file:mode()]} |
{read_file, file:filename()} |
{write_file, file:filename(), binary()} |
{set_cwd, file:filename()} |
{delete, file:filename()} |
{rename, file:filename(), file:filename()} |
{make_dir, file:filename()} |
{del_dir, file:filename()} |
{list_dir, file:filename()} |
get_cwd |
{get_cwd} |
{get_cwd, file:filename()} |
{read_file_info, file:filename()} |
{altname, file:filename()} |
{write_file_info, file:filename(), file:file_info()} |
{read_link_info, file:filename()} |
{read_link, file:filename()} |
{make_link, file:filename(), file:filename()} |
{make_symlink, file:filename(), file:filename()} |
{copy, file:filename(), [file:mode()],
file:filename(), [file:mode()], non_neg_integer()}.
-spec handle_call(file_server_command(), term(), state()) ->
{noreply, state()} |
{reply, eof | ok |
{error, term()} |
{ok, term()}, state()} |
{stop, normal, stopped, state()}.
handle_call({register_handler, Handler, Args}, _From,
#state{ handlers = Handlers } = State) ->
case Handler:init(Args) of
{ok, HState} ->
{reply, ok, State#state{ handlers = [{Handler, HState}|Handlers] } };
{stop, Reason} ->
{reply, {error, Reason}, State}
end;
handle_call({unregister_handler, Handler}, _From,
#state{ handlers = Handlers } = State) ->
{reply, ok, State#state{
handlers = Handlers -- [{Handler,
proplists:get_value(Handler, Handlers)}] } };
handle_call(original_file_server, _From,
#state{ file_server = FileServer } = State) ->
{reply, FileServer, State };
handle_call({filename, absname, [Filename]}, From, State) ->
safe_call_handler(From, Filename, filename_absname, [Filename], State);
handle_call({filename, absname, [Filename, Dir]}, From, State) ->
safe_call_handler(From, Filename, filename_absname, [Filename, Dir], State);
handle_call({filename, absname_join, [Dir, Filename]}, From, State) ->
safe_call_handler(From, Dir, filename_absname_join, [Dir, Filename], State);
handle_call({filename, basename, [Filename]}, From, State) ->
safe_call_handler(From, Filename, filename_basename, [Filename], State);
handle_call({filename, basename, [Filename, Ext]}, From, State) ->
safe_call_handler(From, Filename, filename_basename, [Filename, Ext], State);
handle_call({filename, dirname, [Filename]}, From, State) ->
safe_call_handler(From, Filename, filename_dirname, [Filename], State);
handle_call({filename, extension, [Filename]}, From, State) ->
safe_call_handler(From, Filename, filename_extension, [Filename], State);
handle_call({filename, join, [Components]}, From, State) ->
safe_call_handler(From, hd(Components), filename_join, [Components], State);
handle_call({filename, join, [Name1, Name2]}, From, State) ->
safe_call_handler(From, Name1, filename_join, [Name1, Name2], State);
handle_call({filename, append, [Dir, Name]}, From, State) ->
safe_call_handler(From, Dir, filename_append, [Dir, Name], State);
handle_call({filename, pathtype, [Path]}, From, State) ->
safe_call_handler(From, Path, filename_pathtype, [Path], State);
handle_call({filename, rootname, [Filename]}, From, State) ->
safe_call_handler(From, Filename, filename_rootname, [Filename], State);
handle_call({filename, rootname, [Filename, Ext]}, From, State) ->
safe_call_handler(From, Filename, filename_rootname, [Filename, Ext], State);
handle_call({filename, split, [Filename]}, From, State) ->
safe_call_handler(From, Filename, filename_split, [Filename], State);
handle_call({filename, nativename, [Filename]}, From, State) ->
safe_call_handler(From, Filename, filename_nativename, [Filename], State);
handle_call({filename, find_src, Args}, _From, State) ->
{reply, apply(filename_1,find_src, Args), State};
handle_call({filename, flatten, [Filename]}, From, State) ->
safe_call_handler(From, Filename, filename_flatten, [Filename], State);
%%
handle_call({open, Filename, ModeList}, {Pid, _Tag} = From, State) ->
call_handler(From, Filename, open, [Pid, Filename, ModeList], State);
handle_call({read_file, Filename}, From, State) ->
call_handler(From, Filename, read_file, [Filename], State);
handle_call({write_file, Filename, Bin}, From, State) ->
call_handler(From, Filename, write_file, [Filename, Bin], State);
handle_call({set_cwd, Filename}, From, State) ->
call_handler(From, Filename, set_cwd, [Filename], State);
handle_call({delete, Filename}, From, State) ->
call_handler(From, Filename, delete, [Filename], State);
handle_call({rename, Fr, To}, From, State) ->
call_handler(From, Fr, rename, [Fr, To], State);
handle_call({make_dir, Filename}, From, State) ->
call_handler(From, Filename, make_dir, [Filename], State);
handle_call({del_dir, Filename}, From, State) ->
call_handler(From, Filename, del_dir, [Filename], State);
handle_call({list_dir, Filename}, From, State) ->
call_handler(From, Filename, list_dir, [Filename], State);
handle_call(get_cwd, From, State) ->
call_handler(From, "/", get_cwd, [], State);
handle_call({get_cwd}, From, State) ->
call_handler(From, "/", get_cwd, [], State);
handle_call({get_cwd, Filename}, From, State) ->
call_handler(From, Filename, get_cwd, [Filename], State);
handle_call({read_file_info, Filename}, From, State) ->
call_handler(From, Filename, read_file_info, [Filename], State);
handle_call({altname, Filename}, From, State) ->
call_handler(From, Filename, altname, [Filename], State);
handle_call({write_file_info, Filename, Info}, From, State) ->
call_handler(From, Filename, write_file_info, [Filename, Info], State);
handle_call({read_link_info, Filename}, From, State) ->
call_handler(From, Filename, read_link_info, [Filename], State);
handle_call({read_link, Filename}, From, State) ->
call_handler(From, Filename, read_link, [Filename], State);
handle_call({make_link, Old, New}, From, State) ->
call_handler(From, Old, make_link, [Old, New], State);
handle_call({make_symlink, Old, New}, From, State) ->
call_handler(From, Old, make_symlink, [Old, New], State);
handle_call({copy, SourceName, SourceOpts, DestName, DestOpts, Length},
From, State) ->
call_handler(From, SourceName, copy, [SourceName, SourceOpts, DestName, DestOpts, Length], State);
handle_call(stop, _From, State) ->
{stop, normal, stopped, State};
handle_call(Request, From, State) ->
error_logger:error_msg("handle_call(~p, ~p, _)", [Request, From]),
{noreply, State}.
-spec handle_cast(term(), state()) -> {noreply, state()}.
handle_cast(Msg, State) ->
error_logger:error_msg("handle_cast(~p, _)", [Msg]),
{noreply, State}.
-spec handle_info(term(), state()) ->
{noreply, state()} | {stop, normal, state()}.
handle_info(_Info, State) ->
{noreply, State}.
-spec terminate(term(), state()) -> ok.
terminate(Reason, #state{ handlers = Handlers } = _State) ->
[ Handler:terminate(Reason, HState) || {Handler, HState} <- Handlers ],
ok.
-spec code_change(term(), state(), term()) -> {ok, state()}.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
Internal functions
-spec find_handler([handler()], file:filename()) -> {module(), term(), [handler()]} | {false, [handler()]}.
find_handler(Handlers, Filename) ->
find_handler_1(Handlers, Filename, []).
find_handler_1([], _Filename, NewHandlers) ->
{false, lists:reverse(NewHandlers)};
find_handler_1([{Handler, HState}|Rest], Filename, NewHandlers) ->
{Result, HState1} = Handler:supports(Filename, HState),
NewHandlers1 = [{Handler, HState1}|NewHandlers],
find_handler_2(Result, Rest, Filename, NewHandlers1).
find_handler_2(true, Rest, _Filename, [{Handler, HState}|_] = NewHandlers) ->
{Handler, HState, lists:reverse(NewHandlers) ++ Rest};
find_handler_2(false, Rest, Filename, NewHandlers) ->
find_handler_1(Rest, Filename, NewHandlers).
-spec update_state(module(), term(), [handler()]) -> [handler()].
update_state(Handler, HState, [{Handler, _}|Rest]) ->
[{Handler, HState}|Rest];
update_state(Handler, HState, [OtherHandler|Rest]) ->
[OtherHandler|update_state(Handler, HState, Rest)].
-spec call_handler(file:filename(), atom(), [term()], state()) -> {reply, term(), state()}.
call_handler(Filename, Function, Arguments, #state{ handlers = Handlers } = State) ->
case find_handler(Handlers, Filename) of
{Handler, HState, Handlers1} ->
case apply(Handler, Function, Arguments ++ [HState]) of
{ok, Result, HState1} ->
{reply, Result,
State#state{
handlers = update_state(Handler,
HState1,
Handlers1) }};
{error, Reason, HState1} ->
{reply, {error, Reason},
State#state{
handlers = update_state(Handler,
HState1,
Handlers1) }}
end;
{false, Handlers1} ->
{reply, {error, notsup}, State#state{ handlers = Handlers1 }}
end.
-spec call_handler(term(), file:filename(), atom(), [term()], state()) -> {reply, term(), state()}.
call_handler(From, Filename, Function, Arguments, State) ->
spawn_link(fun () ->
{reply, Result, _State1} = call_handler(Filename, Function, Arguments, State),
gen_server:reply(From, Result)
end),
{noreply, State}.
-spec safe_call_handler(file:filename(), atom(), [term()], state()) -> {reply, term(), state()}.
safe_call_handler(Filename, Function, Arguments,
#state{ handlers = Handlers } = State) ->
case (catch call_handler(Filename, Function, Arguments, State)) of
{'EXIT',{undef, _}} ->
call_handler(Filename, Function, Arguments,
State#state{
handlers = tl(Handlers)
});
Result ->
Result
end.
-spec safe_call_handler(term(), file:filename(), atom(), [term()], state()) -> {reply, term(), state()}.
safe_call_handler(From, Filename, Function, Arguments, State) ->
spawn_link(fun () ->
{reply, Result, _State1} = safe_call_handler(Filename, Function, Arguments, State),
gen_server:reply(From, Result)
end),
{noreply, State}.
| null | https://raw.githubusercontent.com/yrashk/evfs/88ae0bfe2344c8d9a042fc8f787cbf694a027fd5/src/evfs_file_server.erl | erlang | gen_server callbacks
Filename API
| -module(evfs_file_server).
-behaviour(gen_server).
-include("internal.hrl").
-export([start_link/1]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
-define(EVFS_HANDLERS_TABLE, evfs_handlers).
-type handler() :: {module(), term()}.
-record(state,
{
handlers = [] :: [handler()],
file_server :: pid()
}).
-type state() :: #state{}.
-spec start_link(pid()) -> {ok, state()} | {error, term()}.
start_link(FileServer) ->
gen_server:start({local, ?FILE_SERVER}, ?MODULE, FileServer, []).
-spec init(pid()) -> {ok, state()} | {stop, term()}.
init(FileServer) ->
case ?DEFAULT_HANDLER:init(FileServer) of
{ok, HState} ->
{ok, #state{ handlers = [{?DEFAULT_HANDLER, HState}], file_server = FileServer }};
{stop, _Reason} = Error ->
Error
end.
-type filename_command() :: absname | absname_join | basename |
dirname | extension | join | pathtype |
rootname | split | nativename |
find_src | flatten.
-type file_server_command() ::
original_file_server |
{unregister_handler, module()} |
{register_handler, module(), term()} |
{filename, filename_command(), [term()]} |
Filesystem API
{open, file:filename(), [file:mode()]} |
{read_file, file:filename()} |
{write_file, file:filename(), binary()} |
{set_cwd, file:filename()} |
{delete, file:filename()} |
{rename, file:filename(), file:filename()} |
{make_dir, file:filename()} |
{del_dir, file:filename()} |
{list_dir, file:filename()} |
get_cwd |
{get_cwd} |
{get_cwd, file:filename()} |
{read_file_info, file:filename()} |
{altname, file:filename()} |
{write_file_info, file:filename(), file:file_info()} |
{read_link_info, file:filename()} |
{read_link, file:filename()} |
{make_link, file:filename(), file:filename()} |
{make_symlink, file:filename(), file:filename()} |
{copy, file:filename(), [file:mode()],
file:filename(), [file:mode()], non_neg_integer()}.
-spec handle_call(file_server_command(), term(), state()) ->
{noreply, state()} |
{reply, eof | ok |
{error, term()} |
{ok, term()}, state()} |
{stop, normal, stopped, state()}.
handle_call({register_handler, Handler, Args}, _From,
#state{ handlers = Handlers } = State) ->
case Handler:init(Args) of
{ok, HState} ->
{reply, ok, State#state{ handlers = [{Handler, HState}|Handlers] } };
{stop, Reason} ->
{reply, {error, Reason}, State}
end;
handle_call({unregister_handler, Handler}, _From,
#state{ handlers = Handlers } = State) ->
{reply, ok, State#state{
handlers = Handlers -- [{Handler,
proplists:get_value(Handler, Handlers)}] } };
handle_call(original_file_server, _From,
#state{ file_server = FileServer } = State) ->
{reply, FileServer, State };
handle_call({filename, absname, [Filename]}, From, State) ->
safe_call_handler(From, Filename, filename_absname, [Filename], State);
handle_call({filename, absname, [Filename, Dir]}, From, State) ->
safe_call_handler(From, Filename, filename_absname, [Filename, Dir], State);
handle_call({filename, absname_join, [Dir, Filename]}, From, State) ->
safe_call_handler(From, Dir, filename_absname_join, [Dir, Filename], State);
handle_call({filename, basename, [Filename]}, From, State) ->
safe_call_handler(From, Filename, filename_basename, [Filename], State);
handle_call({filename, basename, [Filename, Ext]}, From, State) ->
safe_call_handler(From, Filename, filename_basename, [Filename, Ext], State);
handle_call({filename, dirname, [Filename]}, From, State) ->
safe_call_handler(From, Filename, filename_dirname, [Filename], State);
handle_call({filename, extension, [Filename]}, From, State) ->
safe_call_handler(From, Filename, filename_extension, [Filename], State);
handle_call({filename, join, [Components]}, From, State) ->
safe_call_handler(From, hd(Components), filename_join, [Components], State);
handle_call({filename, join, [Name1, Name2]}, From, State) ->
safe_call_handler(From, Name1, filename_join, [Name1, Name2], State);
handle_call({filename, append, [Dir, Name]}, From, State) ->
safe_call_handler(From, Dir, filename_append, [Dir, Name], State);
handle_call({filename, pathtype, [Path]}, From, State) ->
safe_call_handler(From, Path, filename_pathtype, [Path], State);
handle_call({filename, rootname, [Filename]}, From, State) ->
safe_call_handler(From, Filename, filename_rootname, [Filename], State);
handle_call({filename, rootname, [Filename, Ext]}, From, State) ->
safe_call_handler(From, Filename, filename_rootname, [Filename, Ext], State);
handle_call({filename, split, [Filename]}, From, State) ->
safe_call_handler(From, Filename, filename_split, [Filename], State);
handle_call({filename, nativename, [Filename]}, From, State) ->
safe_call_handler(From, Filename, filename_nativename, [Filename], State);
handle_call({filename, find_src, Args}, _From, State) ->
{reply, apply(filename_1,find_src, Args), State};
handle_call({filename, flatten, [Filename]}, From, State) ->
safe_call_handler(From, Filename, filename_flatten, [Filename], State);
handle_call({open, Filename, ModeList}, {Pid, _Tag} = From, State) ->
call_handler(From, Filename, open, [Pid, Filename, ModeList], State);
handle_call({read_file, Filename}, From, State) ->
call_handler(From, Filename, read_file, [Filename], State);
handle_call({write_file, Filename, Bin}, From, State) ->
call_handler(From, Filename, write_file, [Filename, Bin], State);
handle_call({set_cwd, Filename}, From, State) ->
call_handler(From, Filename, set_cwd, [Filename], State);
handle_call({delete, Filename}, From, State) ->
call_handler(From, Filename, delete, [Filename], State);
handle_call({rename, Fr, To}, From, State) ->
call_handler(From, Fr, rename, [Fr, To], State);
handle_call({make_dir, Filename}, From, State) ->
call_handler(From, Filename, make_dir, [Filename], State);
handle_call({del_dir, Filename}, From, State) ->
call_handler(From, Filename, del_dir, [Filename], State);
handle_call({list_dir, Filename}, From, State) ->
call_handler(From, Filename, list_dir, [Filename], State);
handle_call(get_cwd, From, State) ->
call_handler(From, "/", get_cwd, [], State);
handle_call({get_cwd}, From, State) ->
call_handler(From, "/", get_cwd, [], State);
handle_call({get_cwd, Filename}, From, State) ->
call_handler(From, Filename, get_cwd, [Filename], State);
handle_call({read_file_info, Filename}, From, State) ->
call_handler(From, Filename, read_file_info, [Filename], State);
handle_call({altname, Filename}, From, State) ->
call_handler(From, Filename, altname, [Filename], State);
handle_call({write_file_info, Filename, Info}, From, State) ->
call_handler(From, Filename, write_file_info, [Filename, Info], State);
handle_call({read_link_info, Filename}, From, State) ->
call_handler(From, Filename, read_link_info, [Filename], State);
handle_call({read_link, Filename}, From, State) ->
call_handler(From, Filename, read_link, [Filename], State);
handle_call({make_link, Old, New}, From, State) ->
call_handler(From, Old, make_link, [Old, New], State);
handle_call({make_symlink, Old, New}, From, State) ->
call_handler(From, Old, make_symlink, [Old, New], State);
handle_call({copy, SourceName, SourceOpts, DestName, DestOpts, Length},
From, State) ->
call_handler(From, SourceName, copy, [SourceName, SourceOpts, DestName, DestOpts, Length], State);
handle_call(stop, _From, State) ->
{stop, normal, stopped, State};
handle_call(Request, From, State) ->
error_logger:error_msg("handle_call(~p, ~p, _)", [Request, From]),
{noreply, State}.
-spec handle_cast(term(), state()) -> {noreply, state()}.
handle_cast(Msg, State) ->
error_logger:error_msg("handle_cast(~p, _)", [Msg]),
{noreply, State}.
-spec handle_info(term(), state()) ->
{noreply, state()} | {stop, normal, state()}.
handle_info(_Info, State) ->
{noreply, State}.
-spec terminate(term(), state()) -> ok.
terminate(Reason, #state{ handlers = Handlers } = _State) ->
[ Handler:terminate(Reason, HState) || {Handler, HState} <- Handlers ],
ok.
-spec code_change(term(), state(), term()) -> {ok, state()}.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
Internal functions
-spec find_handler([handler()], file:filename()) -> {module(), term(), [handler()]} | {false, [handler()]}.
find_handler(Handlers, Filename) ->
find_handler_1(Handlers, Filename, []).
find_handler_1([], _Filename, NewHandlers) ->
{false, lists:reverse(NewHandlers)};
find_handler_1([{Handler, HState}|Rest], Filename, NewHandlers) ->
{Result, HState1} = Handler:supports(Filename, HState),
NewHandlers1 = [{Handler, HState1}|NewHandlers],
find_handler_2(Result, Rest, Filename, NewHandlers1).
find_handler_2(true, Rest, _Filename, [{Handler, HState}|_] = NewHandlers) ->
{Handler, HState, lists:reverse(NewHandlers) ++ Rest};
find_handler_2(false, Rest, Filename, NewHandlers) ->
find_handler_1(Rest, Filename, NewHandlers).
-spec update_state(module(), term(), [handler()]) -> [handler()].
update_state(Handler, HState, [{Handler, _}|Rest]) ->
[{Handler, HState}|Rest];
update_state(Handler, HState, [OtherHandler|Rest]) ->
[OtherHandler|update_state(Handler, HState, Rest)].
-spec call_handler(file:filename(), atom(), [term()], state()) -> {reply, term(), state()}.
call_handler(Filename, Function, Arguments, #state{ handlers = Handlers } = State) ->
case find_handler(Handlers, Filename) of
{Handler, HState, Handlers1} ->
case apply(Handler, Function, Arguments ++ [HState]) of
{ok, Result, HState1} ->
{reply, Result,
State#state{
handlers = update_state(Handler,
HState1,
Handlers1) }};
{error, Reason, HState1} ->
{reply, {error, Reason},
State#state{
handlers = update_state(Handler,
HState1,
Handlers1) }}
end;
{false, Handlers1} ->
{reply, {error, notsup}, State#state{ handlers = Handlers1 }}
end.
-spec call_handler(term(), file:filename(), atom(), [term()], state()) -> {reply, term(), state()}.
call_handler(From, Filename, Function, Arguments, State) ->
spawn_link(fun () ->
{reply, Result, _State1} = call_handler(Filename, Function, Arguments, State),
gen_server:reply(From, Result)
end),
{noreply, State}.
-spec safe_call_handler(file:filename(), atom(), [term()], state()) -> {reply, term(), state()}.
safe_call_handler(Filename, Function, Arguments,
#state{ handlers = Handlers } = State) ->
case (catch call_handler(Filename, Function, Arguments, State)) of
{'EXIT',{undef, _}} ->
call_handler(Filename, Function, Arguments,
State#state{
handlers = tl(Handlers)
});
Result ->
Result
end.
-spec safe_call_handler(term(), file:filename(), atom(), [term()], state()) -> {reply, term(), state()}.
safe_call_handler(From, Filename, Function, Arguments, State) ->
spawn_link(fun () ->
{reply, Result, _State1} = safe_call_handler(Filename, Function, Arguments, State),
gen_server:reply(From, Result)
end),
{noreply, State}.
|
b002f70913348698bdb8f16f6c57df99bff0c98766f9f5f8784a59a1eb86aacf | RDTK/generator | analysis.lisp | analysis.lisp ---
;;;;
Copyright ( C ) 2012 - 2019 Jan Moringen
;;;;
Author : < >
(cl:in-package #:build-generator.analysis)
(defun guess-project-natures (directory)
(or (append
(when (or (directory (merge-pathnames "configure" directory))
(directory (merge-pathnames "configure.in" directory))
(directory (merge-pathnames "configure.ac" directory)))
'(:autotools))
(when (directory (merge-pathnames "*.asd" directory))
'(:asdf))
(when (probe-file (merge-pathnames "setup.py" directory))
'(:setuptools))
(when (probe-file (merge-pathnames "pom.xml" directory))
'(:maven))
(when (probe-file (merge-pathnames "build.xml" directory))
'(:ant))
(cond ((probe-file (merge-pathnames "package.xml" directory))
'(:ros-package))
((directory (merge-pathnames "*/package.xml" directory))
'(:ros-packages)))
(when (probe-file (merge-pathnames "CMakeLists.txt" directory))
'(:cmake)))
'(:freestyle)))
;;; URI methods
(defun guess-scm (url scm)
(let+ (((&accessors-r/o (scheme puri:uri-scheme)) url)
(source/string nil)
((&flet source/string ()
(or source/string (setf source/string (princ-to-string url)))))
((&flet source-contains (substring)
(search substring (source/string) :test #'char-equal))))
(cond (scm (make-keyword (string-upcase scm)))
((member scheme '(:git :svn)) scheme)
((source-contains "git") :git)
((source-contains "svn") :svn)
((source-contains "hg") :mercurial)
(t (error "~@<Cannot handle URI ~A.~@:>"
url)))))
(defmethod analyze ((source string) (kind (eql :auto)) &rest args &key)
(let ((uri (with-condition-translation (((error repository-access-error)
:specification source))
(puri:uri source))))
(apply #'analyze uri kind args)))
(defmethod analyze ((source puri:uri) (kind (eql :auto))
&rest args
&key
scm
TODO
(temp-directory #P"/tmp/"))
(let* ((source (puri:copy-uri source :fragment nil))
(kind (guess-scm source scm))
(temp-directory (util:make-temporary-directory
:base temp-directory :hint "project")))
(apply #'analyze source kind
:versions versions
:temp-directory temp-directory
(remove-from-plist args :versions :temp-directory))))
;;; Pathname methods
(defmethod analyze ((source pathname) (kind (eql :auto))
&key
(natures nil natures-supplied?)
branches)
(let ((natures (if natures-supplied?
natures
(guess-project-natures source))))
(log:info "~@<Analyzing ~A ~:[without natures~:;with nature~*~:P ~
~2:*~{~A~^, ~}~]~@:>"
source natures (length natures))
(cond ((emptyp natures)
(mapcar (lambda (branch) (cons branch '())) branches))
((length= 1 natures)
(analyze source (first natures)))
(t
(let ((merged (make-hash-table)))
(dolist (result (analyze source natures))
(loop :for (key value) :on result :by #'cddr
:do (cond ((not (nth-value 1 (gethash key merged)))
(setf (gethash key merged) value))
((listp (gethash key merged))
(appendf (gethash key merged)
(ensure-list value))))))
(hash-table-plist merged))))))
(defmethod analyze :around ((source pathname) (kind (eql :auto)) &key)
(let+ ((cache (make-hash-table :test #'eq))
((&flet+ maybe-augment (result (key function))
(cond
((getf result key)
result)
((when-let ((value (getf (ensure-gethash
function cache
(funcall function source))
key)))
(list* key value result)))
(t
result)))))
(reduce #'maybe-augment
`((:license ,(rcurry #'analyze :license)))
:initial-value (call-next-method))))
(defmethod analyze ((source pathname) (kind cons) &rest args &key)
(mapcan (lambda (kind)
(with-simple-restart (continue "~@<Do not analyze ~A with ~
nature ~A~@:>"
source kind)
(list (apply #'analyze source kind args))))
kind))
(defmethod analyze ((source pathname) (kind (eql :freestyle)) &key)
'())
| null | https://raw.githubusercontent.com/RDTK/generator/8d9e6e47776f2ccb7b5ed934337d2db50ecbe2f5/src/analysis/analysis.lisp | lisp |
URI methods
Pathname methods
with nature~*~:P ~ | analysis.lisp ---
Copyright ( C ) 2012 - 2019 Jan Moringen
Author : < >
(cl:in-package #:build-generator.analysis)
(defun guess-project-natures (directory)
(or (append
(when (or (directory (merge-pathnames "configure" directory))
(directory (merge-pathnames "configure.in" directory))
(directory (merge-pathnames "configure.ac" directory)))
'(:autotools))
(when (directory (merge-pathnames "*.asd" directory))
'(:asdf))
(when (probe-file (merge-pathnames "setup.py" directory))
'(:setuptools))
(when (probe-file (merge-pathnames "pom.xml" directory))
'(:maven))
(when (probe-file (merge-pathnames "build.xml" directory))
'(:ant))
(cond ((probe-file (merge-pathnames "package.xml" directory))
'(:ros-package))
((directory (merge-pathnames "*/package.xml" directory))
'(:ros-packages)))
(when (probe-file (merge-pathnames "CMakeLists.txt" directory))
'(:cmake)))
'(:freestyle)))
(defun guess-scm (url scm)
(let+ (((&accessors-r/o (scheme puri:uri-scheme)) url)
(source/string nil)
((&flet source/string ()
(or source/string (setf source/string (princ-to-string url)))))
((&flet source-contains (substring)
(search substring (source/string) :test #'char-equal))))
(cond (scm (make-keyword (string-upcase scm)))
((member scheme '(:git :svn)) scheme)
((source-contains "git") :git)
((source-contains "svn") :svn)
((source-contains "hg") :mercurial)
(t (error "~@<Cannot handle URI ~A.~@:>"
url)))))
(defmethod analyze ((source string) (kind (eql :auto)) &rest args &key)
(let ((uri (with-condition-translation (((error repository-access-error)
:specification source))
(puri:uri source))))
(apply #'analyze uri kind args)))
(defmethod analyze ((source puri:uri) (kind (eql :auto))
&rest args
&key
scm
TODO
(temp-directory #P"/tmp/"))
(let* ((source (puri:copy-uri source :fragment nil))
(kind (guess-scm source scm))
(temp-directory (util:make-temporary-directory
:base temp-directory :hint "project")))
(apply #'analyze source kind
:versions versions
:temp-directory temp-directory
(remove-from-plist args :versions :temp-directory))))
(defmethod analyze ((source pathname) (kind (eql :auto))
&key
(natures nil natures-supplied?)
branches)
(let ((natures (if natures-supplied?
natures
(guess-project-natures source))))
~2:*~{~A~^, ~}~]~@:>"
source natures (length natures))
(cond ((emptyp natures)
(mapcar (lambda (branch) (cons branch '())) branches))
((length= 1 natures)
(analyze source (first natures)))
(t
(let ((merged (make-hash-table)))
(dolist (result (analyze source natures))
(loop :for (key value) :on result :by #'cddr
:do (cond ((not (nth-value 1 (gethash key merged)))
(setf (gethash key merged) value))
((listp (gethash key merged))
(appendf (gethash key merged)
(ensure-list value))))))
(hash-table-plist merged))))))
(defmethod analyze :around ((source pathname) (kind (eql :auto)) &key)
(let+ ((cache (make-hash-table :test #'eq))
((&flet+ maybe-augment (result (key function))
(cond
((getf result key)
result)
((when-let ((value (getf (ensure-gethash
function cache
(funcall function source))
key)))
(list* key value result)))
(t
result)))))
(reduce #'maybe-augment
`((:license ,(rcurry #'analyze :license)))
:initial-value (call-next-method))))
(defmethod analyze ((source pathname) (kind cons) &rest args &key)
(mapcan (lambda (kind)
(with-simple-restart (continue "~@<Do not analyze ~A with ~
nature ~A~@:>"
source kind)
(list (apply #'analyze source kind args))))
kind))
(defmethod analyze ((source pathname) (kind (eql :freestyle)) &key)
'())
|
bab1e084501f7c76e4e55db485f22aabef929c682b57798f386aa87e4d25c0dc | AccelerateHS/accelerate-llvm | Async.hs | # LANGUAGE RecordWildCards #
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS -fno-warn-orphans #-}
-- |
Module : Data . Array . Accelerate . . Execute . Async
Copyright : [ 2014 .. 2015 ] The Accelerate Team
-- License : BSD3
--
Maintainer : < >
-- Stability : experimental
Portability : non - portable ( GHC extensions )
--
module Data.Array.Accelerate.LLVM.Multi.Execute.Async (
Async, Stream,
A.wait, A.after, A.streaming, A.async,
) where
-- accelerate-llvm
import Data.Array.Accelerate.LLVM.PTX.Internal ( PTX(..) )
import qualified Data.Array.Accelerate.LLVM.PTX.Internal as PTX
import qualified Data.Array.Accelerate.LLVM.Execute.Async as A
import Data.Array.Accelerate.LLVM.State
import Data.Array.Accelerate.LLVM.Multi.Target
-- standard library
import Control.Monad.State
type Async a = PTX.Async a
type Stream = PTX.Stream
-- The Multi-device backend does everything synchronously.
--
instance A.Async Multi where
type AsyncR Multi a = Async a
type StreamR Multi = Stream
# INLINE wait #
wait a =
A.wait a `with` ptxTarget
# INLINE after #
after stream a =
A.after stream a `with` ptxTarget
{-# INLINE streaming #-}
streaming first second = do
PTX{..} <- gets (ptxTarget . llvmTarget)
PTX.streaming ptxContext ptxStreamReservoir first (\event arr -> second (PTX.Async event arr))
# INLINE async #
async stream action = do
r <- action
A.async stream (return r) `with` ptxTarget
| null | https://raw.githubusercontent.com/AccelerateHS/accelerate-llvm/cf081587fecec23a19f68bfbd31334166868405e/icebox/accelerate-llvm-multidev/Data/Array/Accelerate/LLVM/Multi/Execute/Async.hs | haskell | # LANGUAGE TypeFamilies #
# OPTIONS -fno-warn-orphans #
|
License : BSD3
Stability : experimental
accelerate-llvm
standard library
The Multi-device backend does everything synchronously.
# INLINE streaming # | # LANGUAGE RecordWildCards #
Module : Data . Array . Accelerate . . Execute . Async
Copyright : [ 2014 .. 2015 ] The Accelerate Team
Maintainer : < >
Portability : non - portable ( GHC extensions )
module Data.Array.Accelerate.LLVM.Multi.Execute.Async (
Async, Stream,
A.wait, A.after, A.streaming, A.async,
) where
import Data.Array.Accelerate.LLVM.PTX.Internal ( PTX(..) )
import qualified Data.Array.Accelerate.LLVM.PTX.Internal as PTX
import qualified Data.Array.Accelerate.LLVM.Execute.Async as A
import Data.Array.Accelerate.LLVM.State
import Data.Array.Accelerate.LLVM.Multi.Target
import Control.Monad.State
type Async a = PTX.Async a
type Stream = PTX.Stream
instance A.Async Multi where
type AsyncR Multi a = Async a
type StreamR Multi = Stream
# INLINE wait #
wait a =
A.wait a `with` ptxTarget
# INLINE after #
after stream a =
A.after stream a `with` ptxTarget
streaming first second = do
PTX{..} <- gets (ptxTarget . llvmTarget)
PTX.streaming ptxContext ptxStreamReservoir first (\event arr -> second (PTX.Async event arr))
# INLINE async #
async stream action = do
r <- action
A.async stream (return r) `with` ptxTarget
|
87c1ff1691812adf67195495b361c920ab92f2a09e07c70fc1667e88594ea236 | heraldry/heraldicon | layout.cljs | (ns heraldicon.frontend.layout
(:require
[heraldicon.frontend.element.submenu :as submenu]
[re-frame.core :as rf]))
(defn three-columns [left middle right & {:keys [banner]}]
[:<>
banner
[:div {:style {:display "grid"
:grid-gap "10px"
:grid-template-columns "[start] auto [first] minmax(26em, 33%) [second] minmax(10em, 25%) [end]"
:grid-template-rows "[top] 100% [bottom]"
:grid-template-areas "'left middle right'"
:padding-right "10px"
:height "100%"}
:on-click #(rf/dispatch [::submenu/close-all])}
[:div.no-scrollbar {:style {:grid-area "left"
:position "relative"}}
left]
[:div.no-scrollbar {:style {:grid-area "middle"
:padding-top "10px"
:position "relative"}}
middle]
[:div.no-scrollbar {:style {:grid-area "right"
:padding-top "5px"
:position "relative"}}
right]]])
(defn two-columns [left right & {:keys [banner]}]
[:<>
banner
[:div {:style {:display "grid"
:grid-gap "10px"
:grid-template-columns "[start] auto [first] minmax(26em, 33%) [end]"
:grid-template-rows "[top] 100% [bottom]"
:grid-template-areas "'left right'"
:padding-right "10px"
:height "100%"}
:on-click #(rf/dispatch [::submenu/close-all])}
[:div.no-scrollbar {:style {:grid-area "left"
:position "relative"}}
left]
[:div.no-scrollbar {:style {:grid-area "right"
:padding-top "5px"
:position "relative"}}
right]]])
| null | https://raw.githubusercontent.com/heraldry/heraldicon/18b50856176c3d072e9ffc11505b47e32b6f0ee9/src/heraldicon/frontend/layout.cljs | clojure | (ns heraldicon.frontend.layout
(:require
[heraldicon.frontend.element.submenu :as submenu]
[re-frame.core :as rf]))
(defn three-columns [left middle right & {:keys [banner]}]
[:<>
banner
[:div {:style {:display "grid"
:grid-gap "10px"
:grid-template-columns "[start] auto [first] minmax(26em, 33%) [second] minmax(10em, 25%) [end]"
:grid-template-rows "[top] 100% [bottom]"
:grid-template-areas "'left middle right'"
:padding-right "10px"
:height "100%"}
:on-click #(rf/dispatch [::submenu/close-all])}
[:div.no-scrollbar {:style {:grid-area "left"
:position "relative"}}
left]
[:div.no-scrollbar {:style {:grid-area "middle"
:padding-top "10px"
:position "relative"}}
middle]
[:div.no-scrollbar {:style {:grid-area "right"
:padding-top "5px"
:position "relative"}}
right]]])
(defn two-columns [left right & {:keys [banner]}]
[:<>
banner
[:div {:style {:display "grid"
:grid-gap "10px"
:grid-template-columns "[start] auto [first] minmax(26em, 33%) [end]"
:grid-template-rows "[top] 100% [bottom]"
:grid-template-areas "'left right'"
:padding-right "10px"
:height "100%"}
:on-click #(rf/dispatch [::submenu/close-all])}
[:div.no-scrollbar {:style {:grid-area "left"
:position "relative"}}
left]
[:div.no-scrollbar {:style {:grid-area "right"
:padding-top "5px"
:position "relative"}}
right]]])
| |
638afe44478870919ba4cf0682df9960c2c789081f3c98f373b552985b3a6d27 | schell/steeloverseer | TemplateSpec.hs | module Sos.TemplateSpec where
import Sos.Exception
import Sos.Template
import Test.Hspec
spec :: Spec
spec = do
describe "parseTemplate" $ do
it "fails on the empty string" $
parseTemplate "" `shouldThrow` anySosException
it "parses templates" $ do
parseTemplate "hi" `shouldReturn` [Right "hi"]
parseTemplate "foo bar" `shouldReturn` [Right "foo bar"]
parseTemplate "\\25" `shouldReturn` [Left 25]
parseTemplate "gcc \\0" `shouldReturn` [Right "gcc ", Left 0]
describe "instantiateTemplate" $ do
it "ignores capture groups in templates with no captures" $ do
instantiateTemplate [] [Right "z"] `shouldReturn` "z"
instantiateTemplate ["a"] [Right "z"] `shouldReturn` "z"
instantiateTemplate ["a","b","c"] [Right "z"] `shouldReturn` "z"
it "substitutes capture groups" $ do
instantiateTemplate ["a","b","c"] [Left 2, Left 1, Left 0]
`shouldReturn` "cba"
it "errors when there are not enough capture groups" $ do
instantiateTemplate [] [Left 0] `shouldThrow` anySosException
instantiateTemplate ["a"] [Left 1] `shouldThrow` anySosException
anySosException :: Selector SosException
anySosException = const True
| null | https://raw.githubusercontent.com/schell/steeloverseer/dcc694460ac9713b4a9a2462a3eecc8b38ca9fa3/test/Sos/TemplateSpec.hs | haskell | module Sos.TemplateSpec where
import Sos.Exception
import Sos.Template
import Test.Hspec
spec :: Spec
spec = do
describe "parseTemplate" $ do
it "fails on the empty string" $
parseTemplate "" `shouldThrow` anySosException
it "parses templates" $ do
parseTemplate "hi" `shouldReturn` [Right "hi"]
parseTemplate "foo bar" `shouldReturn` [Right "foo bar"]
parseTemplate "\\25" `shouldReturn` [Left 25]
parseTemplate "gcc \\0" `shouldReturn` [Right "gcc ", Left 0]
describe "instantiateTemplate" $ do
it "ignores capture groups in templates with no captures" $ do
instantiateTemplate [] [Right "z"] `shouldReturn` "z"
instantiateTemplate ["a"] [Right "z"] `shouldReturn` "z"
instantiateTemplate ["a","b","c"] [Right "z"] `shouldReturn` "z"
it "substitutes capture groups" $ do
instantiateTemplate ["a","b","c"] [Left 2, Left 1, Left 0]
`shouldReturn` "cba"
it "errors when there are not enough capture groups" $ do
instantiateTemplate [] [Left 0] `shouldThrow` anySosException
instantiateTemplate ["a"] [Left 1] `shouldThrow` anySosException
anySosException :: Selector SosException
anySosException = const True
| |
2eb14b155bfa1ef6767744b9ec39d56f0109f309d1e55377428ebd725a7f7ba0 | andrewberls/predis | zsets_test.clj | (ns predis.zsets-test
(:require [clojure.test :refer :all]
[clojure.test.check :as tc]
(clojure.test.check
[clojure-test :refer [defspec]]
[generators :as gen]
[properties :as prop])
[taoensso.carmine :as carmine]
(predis
[core :as r]
[mock :as mock])
[predis.test-utils :as test-utils]))
(def carmine-client (test-utils/carmine-client))
(use-fixtures :each test-utils/flush-redis)
(defspec test-zadd-one
test-utils/nruns
(let [mock-client (mock/->redis)]
(prop/for-all [k gen/string-alphanumeric
score gen/int
m (gen/not-empty gen/string-alphanumeric)]
(is (= (r/zadd mock-client k score m) (r/zadd carmine-client k score m)))
(test-utils/dbs-equal mock-client carmine-client))))
(defspec test-zadd-many
test-utils/nruns
(let [mock-client (mock/->redis)]
(prop/for-all [k gen/string-alphanumeric
kvs test-utils/gen-kvs-vec]
(is (= (r/zadd mock-client k kvs) (r/zadd carmine-client k kvs)))
(test-utils/dbs-equal mock-client carmine-client))))
(defspec test-zcard
test-utils/nruns
(let [mock-client (mock/->redis)]
(prop/for-all [k gen/string-alphanumeric
kvs test-utils/gen-kvs-vec]
(test-utils/assert-zadd mock-client carmine-client k kvs)
(is (= (r/zcard mock-client k) (r/zcard carmine-client k)))
(test-utils/dbs-equal mock-client carmine-client))))
(defspec test-zcount
test-utils/nruns
(let [mock-client (mock/->redis)]
(prop/for-all [k gen/string-alphanumeric
kvs test-utils/gen-kvs-vec
min-score gen/int
max-score-incr gen/s-pos-int]
(let [max-score (+ min-score max-score-incr)]
(test-utils/assert-zadd mock-client carmine-client k kvs)
(is (= (r/zcount mock-client k min-score max-score)
(r/zcount carmine-client k min-score max-score)))
(test-utils/dbs-equal mock-client carmine-client)))))
(defspec test-zincrby
test-utils/nruns
(let [mock-client (mock/->redis)]
(prop/for-all [k gen/string-alphanumeric
kvs test-utils/gen-kvs-vec
increment gen/int]
(test-utils/assert-zadd mock-client carmine-client k kvs)
(let [m (second (first (shuffle kvs)))]
(is (= (r/zincrby mock-client k increment m)
(r/zincrby carmine-client k increment m)))
(test-utils/dbs-equal mock-client carmine-client)))))
;;(zinterstore [this dest numkeys ks weights])
( zlexcount [ this k min - val max - val ] )
(defspec test-zrange
test-utils/nruns
(let [mock-client (mock/->redis)]
(prop/for-all [k gen/string-alphanumeric
kvs test-utils/gen-kvs-vec
min-score gen/int
max-score-incr gen/s-pos-int]
(test-utils/assert-zadd mock-client carmine-client k kvs)
(let [max-score (+ min-score max-score-incr)]
(is (= (r/zrange mock-client k min-score max-score)
(r/zrange carmine-client k min-score max-score)))
(is (= (r/zrange mock-client k min-score max-score {:withscores true})
(r/zrange carmine-client k min-score max-score {:withscores true})))
(test-utils/dbs-equal mock-client carmine-client)))))
;;(zrangebylex [this k min-val max-val opts?])
(defspec test-zrangebyscore
test-utils/nruns
(let [mock-client (mock/->redis)]
(prop/for-all [k gen/string-alphanumeric
kvs test-utils/gen-kvs-vec
min-score gen/int
max-score-incr gen/s-pos-int]
(let [max-score (+ min-score max-score-incr)]
(test-utils/assert-zadd mock-client carmine-client k kvs)
(is (= (r/zrangebyscore mock-client k min-score max-score)
(r/zrangebyscore carmine-client k min-score max-score)))
(is (= (r/zrangebyscore mock-client k min-score max-score {:withscores true})
(r/zrangebyscore carmine-client k min-score max-score {:withscores true})))
; TODO: limit, offset
(test-utils/dbs-equal mock-client carmine-client)))))
(defspec test-zrank
test-utils/nruns
(let [mock-client (mock/->redis)]
(prop/for-all [k gen/string-alphanumeric
kvs test-utils/gen-kvs-vec]
(test-utils/assert-zadd mock-client carmine-client k kvs)
(let [m (second (first (shuffle kvs)))]
(is (= (r/zrank mock-client k m) (r/zrank carmine-client k m)))
(is (= (r/zrank mock-client k ["fake-member"]) (r/zrank carmine-client k ["fake-member"])))
(is (= (r/zrank mock-client "fake-key" m) (r/zrank carmine-client "fake-key" m)))
(test-utils/dbs-equal mock-client carmine-client)))))
(defspec test-zrem
test-utils/nruns
(let [mock-client (mock/->redis)]
(prop/for-all [k gen/string-alphanumeric
kvs test-utils/gen-kvs-vec]
(test-utils/assert-zadd mock-client carmine-client k kvs)
(let [num-members (inc (rand-int (dec (count kvs))))
ms (map second (take num-members (shuffle kvs)))]
(is (= (r/zrem mock-client k ms) (r/zrem carmine-client k ms)))
(is (= (r/zrem mock-client k ["fake-member"]) (r/zrem carmine-client k ["fake-member"])))
(is (= (r/zrem mock-client "fake-key" ms) (r/zrem carmine-client "fake-key" ms)))
(test-utils/dbs-equal mock-client carmine-client)))))
;;(zremrangebylex [this k min-val max-val])
( [ this k min - score max - score ] )
(defspec test-zrevrange
test-utils/nruns
(let [mock-client (mock/->redis)]
(prop/for-all [k gen/string-alphanumeric
kvs test-utils/gen-kvs-vec
min-score gen/int
max-score-incr gen/s-pos-int]
(test-utils/assert-zadd mock-client carmine-client k kvs)
(let [max-score (+ min-score max-score-incr)]
(is (= (r/zrevrange mock-client k min-score max-score)
(r/zrevrange carmine-client k min-score max-score)))
(is (= (r/zrevrange mock-client k min-score max-score {:withscores true})
(r/zrevrange carmine-client k min-score max-score {:withscores true})))
(test-utils/dbs-equal mock-client carmine-client)))))
( zrevrangebyscore [ this k max - score min - score opts ] )
(defspec test-zrevrank
test-utils/nruns
(let [mock-client (mock/->redis)]
(prop/for-all [k gen/string-alphanumeric
kvs test-utils/gen-kvs-vec]
(test-utils/assert-zadd mock-client carmine-client k kvs)
(let [m (second (first (shuffle kvs)))]
(is (= (r/zrevrank mock-client k m) (r/zrevrank carmine-client k m)))
(is (= (r/zrevrank mock-client k ["fake-member"]) (r/zrevrank carmine-client k ["fake-member"])))
(is (= (r/zrevrank mock-client "fake-key" m) (r/zrevrank carmine-client "fake-key" m)))
(test-utils/dbs-equal mock-client carmine-client)))))
(defspec test-zscore
test-utils/nruns
(let [mock-client (mock/->redis)]
(prop/for-all [k gen/string-alphanumeric
kvs test-utils/gen-kvs-vec]
(test-utils/assert-zadd mock-client carmine-client k kvs)
(let [m (second (first (shuffle kvs)))]
(is (= (r/zscore mock-client k m) (r/zscore carmine-client k m)))
(is (= (r/zscore mock-client k "fake-m") (r/zscore carmine-client k "fake-m")))
(is (= (r/zscore mock-client "fake-k" m) (r/zscore carmine-client "fake-k" m)))
(test-utils/dbs-equal mock-client carmine-client)))))
( [ dest numkeys ks weights ] )
( zscan [ this k cursor ] [ this k cursor opts ] )
| null | https://raw.githubusercontent.com/andrewberls/predis/9479323a757dc73ee5101c4904b6bd7ef742aed6/test/predis/zsets_test.clj | clojure | (zinterstore [this dest numkeys ks weights])
(zrangebylex [this k min-val max-val opts?])
TODO: limit, offset
(zremrangebylex [this k min-val max-val]) | (ns predis.zsets-test
(:require [clojure.test :refer :all]
[clojure.test.check :as tc]
(clojure.test.check
[clojure-test :refer [defspec]]
[generators :as gen]
[properties :as prop])
[taoensso.carmine :as carmine]
(predis
[core :as r]
[mock :as mock])
[predis.test-utils :as test-utils]))
(def carmine-client (test-utils/carmine-client))
(use-fixtures :each test-utils/flush-redis)
(defspec test-zadd-one
test-utils/nruns
(let [mock-client (mock/->redis)]
(prop/for-all [k gen/string-alphanumeric
score gen/int
m (gen/not-empty gen/string-alphanumeric)]
(is (= (r/zadd mock-client k score m) (r/zadd carmine-client k score m)))
(test-utils/dbs-equal mock-client carmine-client))))
(defspec test-zadd-many
test-utils/nruns
(let [mock-client (mock/->redis)]
(prop/for-all [k gen/string-alphanumeric
kvs test-utils/gen-kvs-vec]
(is (= (r/zadd mock-client k kvs) (r/zadd carmine-client k kvs)))
(test-utils/dbs-equal mock-client carmine-client))))
(defspec test-zcard
test-utils/nruns
(let [mock-client (mock/->redis)]
(prop/for-all [k gen/string-alphanumeric
kvs test-utils/gen-kvs-vec]
(test-utils/assert-zadd mock-client carmine-client k kvs)
(is (= (r/zcard mock-client k) (r/zcard carmine-client k)))
(test-utils/dbs-equal mock-client carmine-client))))
(defspec test-zcount
test-utils/nruns
(let [mock-client (mock/->redis)]
(prop/for-all [k gen/string-alphanumeric
kvs test-utils/gen-kvs-vec
min-score gen/int
max-score-incr gen/s-pos-int]
(let [max-score (+ min-score max-score-incr)]
(test-utils/assert-zadd mock-client carmine-client k kvs)
(is (= (r/zcount mock-client k min-score max-score)
(r/zcount carmine-client k min-score max-score)))
(test-utils/dbs-equal mock-client carmine-client)))))
(defspec test-zincrby
test-utils/nruns
(let [mock-client (mock/->redis)]
(prop/for-all [k gen/string-alphanumeric
kvs test-utils/gen-kvs-vec
increment gen/int]
(test-utils/assert-zadd mock-client carmine-client k kvs)
(let [m (second (first (shuffle kvs)))]
(is (= (r/zincrby mock-client k increment m)
(r/zincrby carmine-client k increment m)))
(test-utils/dbs-equal mock-client carmine-client)))))
( zlexcount [ this k min - val max - val ] )
(defspec test-zrange
test-utils/nruns
(let [mock-client (mock/->redis)]
(prop/for-all [k gen/string-alphanumeric
kvs test-utils/gen-kvs-vec
min-score gen/int
max-score-incr gen/s-pos-int]
(test-utils/assert-zadd mock-client carmine-client k kvs)
(let [max-score (+ min-score max-score-incr)]
(is (= (r/zrange mock-client k min-score max-score)
(r/zrange carmine-client k min-score max-score)))
(is (= (r/zrange mock-client k min-score max-score {:withscores true})
(r/zrange carmine-client k min-score max-score {:withscores true})))
(test-utils/dbs-equal mock-client carmine-client)))))
(defspec test-zrangebyscore
test-utils/nruns
(let [mock-client (mock/->redis)]
(prop/for-all [k gen/string-alphanumeric
kvs test-utils/gen-kvs-vec
min-score gen/int
max-score-incr gen/s-pos-int]
(let [max-score (+ min-score max-score-incr)]
(test-utils/assert-zadd mock-client carmine-client k kvs)
(is (= (r/zrangebyscore mock-client k min-score max-score)
(r/zrangebyscore carmine-client k min-score max-score)))
(is (= (r/zrangebyscore mock-client k min-score max-score {:withscores true})
(r/zrangebyscore carmine-client k min-score max-score {:withscores true})))
(test-utils/dbs-equal mock-client carmine-client)))))
(defspec test-zrank
test-utils/nruns
(let [mock-client (mock/->redis)]
(prop/for-all [k gen/string-alphanumeric
kvs test-utils/gen-kvs-vec]
(test-utils/assert-zadd mock-client carmine-client k kvs)
(let [m (second (first (shuffle kvs)))]
(is (= (r/zrank mock-client k m) (r/zrank carmine-client k m)))
(is (= (r/zrank mock-client k ["fake-member"]) (r/zrank carmine-client k ["fake-member"])))
(is (= (r/zrank mock-client "fake-key" m) (r/zrank carmine-client "fake-key" m)))
(test-utils/dbs-equal mock-client carmine-client)))))
(defspec test-zrem
test-utils/nruns
(let [mock-client (mock/->redis)]
(prop/for-all [k gen/string-alphanumeric
kvs test-utils/gen-kvs-vec]
(test-utils/assert-zadd mock-client carmine-client k kvs)
(let [num-members (inc (rand-int (dec (count kvs))))
ms (map second (take num-members (shuffle kvs)))]
(is (= (r/zrem mock-client k ms) (r/zrem carmine-client k ms)))
(is (= (r/zrem mock-client k ["fake-member"]) (r/zrem carmine-client k ["fake-member"])))
(is (= (r/zrem mock-client "fake-key" ms) (r/zrem carmine-client "fake-key" ms)))
(test-utils/dbs-equal mock-client carmine-client)))))
( [ this k min - score max - score ] )
(defspec test-zrevrange
test-utils/nruns
(let [mock-client (mock/->redis)]
(prop/for-all [k gen/string-alphanumeric
kvs test-utils/gen-kvs-vec
min-score gen/int
max-score-incr gen/s-pos-int]
(test-utils/assert-zadd mock-client carmine-client k kvs)
(let [max-score (+ min-score max-score-incr)]
(is (= (r/zrevrange mock-client k min-score max-score)
(r/zrevrange carmine-client k min-score max-score)))
(is (= (r/zrevrange mock-client k min-score max-score {:withscores true})
(r/zrevrange carmine-client k min-score max-score {:withscores true})))
(test-utils/dbs-equal mock-client carmine-client)))))
( zrevrangebyscore [ this k max - score min - score opts ] )
(defspec test-zrevrank
test-utils/nruns
(let [mock-client (mock/->redis)]
(prop/for-all [k gen/string-alphanumeric
kvs test-utils/gen-kvs-vec]
(test-utils/assert-zadd mock-client carmine-client k kvs)
(let [m (second (first (shuffle kvs)))]
(is (= (r/zrevrank mock-client k m) (r/zrevrank carmine-client k m)))
(is (= (r/zrevrank mock-client k ["fake-member"]) (r/zrevrank carmine-client k ["fake-member"])))
(is (= (r/zrevrank mock-client "fake-key" m) (r/zrevrank carmine-client "fake-key" m)))
(test-utils/dbs-equal mock-client carmine-client)))))
(defspec test-zscore
test-utils/nruns
(let [mock-client (mock/->redis)]
(prop/for-all [k gen/string-alphanumeric
kvs test-utils/gen-kvs-vec]
(test-utils/assert-zadd mock-client carmine-client k kvs)
(let [m (second (first (shuffle kvs)))]
(is (= (r/zscore mock-client k m) (r/zscore carmine-client k m)))
(is (= (r/zscore mock-client k "fake-m") (r/zscore carmine-client k "fake-m")))
(is (= (r/zscore mock-client "fake-k" m) (r/zscore carmine-client "fake-k" m)))
(test-utils/dbs-equal mock-client carmine-client)))))
( [ dest numkeys ks weights ] )
( zscan [ this k cursor ] [ this k cursor opts ] )
|
70c0fdc59967f99405dd55ee12e4c392843eb2b6360bccc3886a20927582e59a | tomsmalley/semantic-reflex | Icon.hs | # LANGUAGE TemplateHaskell #
-- | Semantic-UI Icon elements
--
-- <-ui.com/elements/icon.html>
module Reflex.Dom.SemanticUI.Icon where
import Control.Lens.TH (makeLensesWith, lensRules, simpleLenses)
import Control.Monad (void)
import Data.Default
import Data.Semigroup ((<>))
import Data.Text (Text)
import Reflex.Dom.Core
import Reflex.Active
import Reflex.Dom.SemanticUI.Common
import Reflex.Dom.SemanticUI.Transition
-- | Icons can be mirrored around an axis
data Flipped = HorizontallyFlipped | VerticallyFlipped
deriving (Eq, Ord, Read, Show, Enum, Bounded)
instance ToClassText Flipped where
toClassText HorizontallyFlipped = "horizontally flipped"
toClassText VerticallyFlipped = "vertically flipped"
| Icons can be rotated by 90 degrees in either direction
data Rotated = Clockwise | Anticlockwise
deriving (Eq, Ord, Read, Show, Enum, Bounded)
instance ToClassText Rotated where
toClassText Clockwise = "clockwise rotated"
toClassText Anticlockwise = "counterclockwise rotated"
-- | Icons can be put into a corner of an 'icons' group
data Corner = TopLeft | TopRight | BottomLeft | BottomRight
deriving (Eq, Ord, Read, Show, Enum, Bounded)
instance ToClassText Corner where
toClassText TopLeft = "top left corner"
toClassText TopRight = "top right corner"
toClassText BottomLeft = "bottom left corner"
toClassText BottomRight = "bottom right corner"
-- | Config for 'icon's.
data IconConfig t = IconConfig
{ _iconConfig_disabled :: Active t Bool
-- ^ (default: 'False') Icons can be disabled
, _iconConfig_loading :: Active t Bool
-- ^ (default: 'False') Icons can be "loading" (spinning)
, _iconConfig_fitted :: Active t Bool
-- ^ (default: 'False') Icons can be fitted (no spacing to the sides)
, _iconConfig_link :: Active t Bool
-- ^ (default: 'False') Icons can be formatted as a link (causes pointer
-- cursor on hover)
, _iconConfig_circular :: Active t Bool
-- ^ (default: 'False') Icons can have a circular border
, _iconConfig_bordered :: Active t Bool
-- ^ (default: 'False') Icons can have a square border
, _iconConfig_inverted :: Active t Bool
-- ^ (default: 'False') Icons can be inverted
, _iconConfig_size :: Active t (Maybe Size)
-- ^ (default: 'Nothing') Icons can have a different size
, _iconConfig_flipped :: Active t (Maybe Flipped)
-- ^ (default: 'Nothing') Icons can be flipped about an axis
, _iconConfig_rotated :: Active t (Maybe Rotated)
^ ( default : ' Nothing ' ) Icons can be rotated by 90 degrees
, _iconConfig_color :: Active t (Maybe Color)
-- ^ (default: 'Nothing') Icons can have a different color
, _iconConfig_corner :: Active t (Maybe Corner)
-- ^ (default: 'Nothing') Icons can be placed into a corner (for use inside an
-- 'icons' element)
, _iconConfig_title :: Active t (Maybe Text)
-- ^ (default: 'Nothing') Convenient way to add a "title" attribute
, _iconConfig_elConfig :: ActiveElConfig t
}
makeLensesWith (lensRules & simpleLenses .~ True) ''IconConfig
instance HasElConfig t (IconConfig t) where
elConfig = iconConfig_elConfig
instance Reflex t => Default (IconConfig t) where
def = IconConfig
{ _iconConfig_disabled = pure False
, _iconConfig_loading = pure False
, _iconConfig_fitted = pure False
, _iconConfig_link = pure False
, _iconConfig_circular = pure False
, _iconConfig_bordered = pure False
, _iconConfig_inverted = pure False
, _iconConfig_size = pure Nothing
, _iconConfig_flipped = pure Nothing
, _iconConfig_rotated = pure Nothing
, _iconConfig_color = pure Nothing
, _iconConfig_corner = pure Nothing
, _iconConfig_title = pure Nothing
, _iconConfig_elConfig = def
}
-- | Make the 'icon' classes.
iconConfigClasses :: Reflex t => IconConfig t -> Active t Classes
iconConfigClasses IconConfig {..} = dynClasses
[ pure $ Just "icon"
, boolClass "disabled" _iconConfig_disabled
, boolClass "loading" _iconConfig_loading
, boolClass "fitted" _iconConfig_fitted
, boolClass "link" _iconConfig_link
, boolClass "circular" _iconConfig_circular
, boolClass "bordered" _iconConfig_bordered
, boolClass "inverted" _iconConfig_inverted
, fmap toClassText . nothingIf Medium <$> _iconConfig_size
, fmap toClassText <$> _iconConfig_flipped
, fmap toClassText <$> _iconConfig_rotated
, fmap toClassText <$> _iconConfig_color
, fmap toClassText <$> _iconConfig_corner
]
-- | This is for inclusion in other element configs, fundamentally the same as
-- 'icon'.
data Icon t = Icon (Active t Text) (IconConfig t)
-- | Create an icon. Available icon types are listed here:
-- <-ui.com/elements/icon.html>
icon
:: UI t m
=> Active t Text -- ^ Icon type
-> IconConfig t -- ^ Icon config
-> m ()
icon i = void . icon' i
-- | Create an icon, returning the 'Element'. Available icon types are listed
-- here: <-ui.com/elements/icon.html>
icon'
:: UI t m => Active t Text -> IconConfig t
-> m (Element EventResult (DomBuilderSpace m) t)
icon' dynIcon config@IconConfig {..}
= fst <$> ui' "i" elConf blank
where
elConf = _iconConfig_elConfig <> def
{ _classes = addClass <$> dynIcon <*> iconConfigClasses config
, _attrs = maybe mempty ("title" =:) <$> _iconConfig_title
}
-- | Config for 'icons' groups
data IconsConfig t = IconsConfig
{ _iconsConfig_size :: Active t (Maybe Size)
-- ^ (default: 'Nothing') Icons can be resized as a group
, _iconsConfig_elConfig :: ActiveElConfig t
}
makeLensesWith (lensRules & simpleLenses .~ True) ''IconsConfig
instance HasElConfig t (IconsConfig t) where
elConfig = iconsConfig_elConfig
instance Reflex t => Default (IconsConfig t) where
def = IconsConfig
{ _iconsConfig_size = pure Nothing
, _iconsConfig_elConfig = def
}
-- | Make the 'icons' classes
iconsConfigClasses :: Reflex t => IconsConfig t -> Active t Classes
iconsConfigClasses IconsConfig {..} = dynClasses
[ pure $ Just "icons"
, fmap toClassText <$> _iconsConfig_size
]
-- | Create an icon group, returning the 'Element'.
icons'
:: UI t m => IconsConfig t -> m a
-> m (Element EventResult (DomBuilderSpace m) t, a)
icons' config@IconsConfig {..} = ui' "i" elConf
where
elConf = _iconsConfig_elConfig <> def
{ _classes = iconsConfigClasses config }
-- | Create an icon group.
icons :: UI t m => IconsConfig t -> m a -> m a
icons config = fmap snd . icons' config
| null | https://raw.githubusercontent.com/tomsmalley/semantic-reflex/5a973390fae1facbc4351b75ea59210d6756b8e5/semantic-reflex/src/Reflex/Dom/SemanticUI/Icon.hs | haskell | | Semantic-UI Icon elements
<-ui.com/elements/icon.html>
| Icons can be mirrored around an axis
| Icons can be put into a corner of an 'icons' group
| Config for 'icon's.
^ (default: 'False') Icons can be disabled
^ (default: 'False') Icons can be "loading" (spinning)
^ (default: 'False') Icons can be fitted (no spacing to the sides)
^ (default: 'False') Icons can be formatted as a link (causes pointer
cursor on hover)
^ (default: 'False') Icons can have a circular border
^ (default: 'False') Icons can have a square border
^ (default: 'False') Icons can be inverted
^ (default: 'Nothing') Icons can have a different size
^ (default: 'Nothing') Icons can be flipped about an axis
^ (default: 'Nothing') Icons can have a different color
^ (default: 'Nothing') Icons can be placed into a corner (for use inside an
'icons' element)
^ (default: 'Nothing') Convenient way to add a "title" attribute
| Make the 'icon' classes.
| This is for inclusion in other element configs, fundamentally the same as
'icon'.
| Create an icon. Available icon types are listed here:
<-ui.com/elements/icon.html>
^ Icon type
^ Icon config
| Create an icon, returning the 'Element'. Available icon types are listed
here: <-ui.com/elements/icon.html>
| Config for 'icons' groups
^ (default: 'Nothing') Icons can be resized as a group
| Make the 'icons' classes
| Create an icon group, returning the 'Element'.
| Create an icon group. | # LANGUAGE TemplateHaskell #
module Reflex.Dom.SemanticUI.Icon where
import Control.Lens.TH (makeLensesWith, lensRules, simpleLenses)
import Control.Monad (void)
import Data.Default
import Data.Semigroup ((<>))
import Data.Text (Text)
import Reflex.Dom.Core
import Reflex.Active
import Reflex.Dom.SemanticUI.Common
import Reflex.Dom.SemanticUI.Transition
data Flipped = HorizontallyFlipped | VerticallyFlipped
deriving (Eq, Ord, Read, Show, Enum, Bounded)
instance ToClassText Flipped where
toClassText HorizontallyFlipped = "horizontally flipped"
toClassText VerticallyFlipped = "vertically flipped"
| Icons can be rotated by 90 degrees in either direction
data Rotated = Clockwise | Anticlockwise
deriving (Eq, Ord, Read, Show, Enum, Bounded)
instance ToClassText Rotated where
toClassText Clockwise = "clockwise rotated"
toClassText Anticlockwise = "counterclockwise rotated"
data Corner = TopLeft | TopRight | BottomLeft | BottomRight
deriving (Eq, Ord, Read, Show, Enum, Bounded)
instance ToClassText Corner where
toClassText TopLeft = "top left corner"
toClassText TopRight = "top right corner"
toClassText BottomLeft = "bottom left corner"
toClassText BottomRight = "bottom right corner"
data IconConfig t = IconConfig
{ _iconConfig_disabled :: Active t Bool
, _iconConfig_loading :: Active t Bool
, _iconConfig_fitted :: Active t Bool
, _iconConfig_link :: Active t Bool
, _iconConfig_circular :: Active t Bool
, _iconConfig_bordered :: Active t Bool
, _iconConfig_inverted :: Active t Bool
, _iconConfig_size :: Active t (Maybe Size)
, _iconConfig_flipped :: Active t (Maybe Flipped)
, _iconConfig_rotated :: Active t (Maybe Rotated)
^ ( default : ' Nothing ' ) Icons can be rotated by 90 degrees
, _iconConfig_color :: Active t (Maybe Color)
, _iconConfig_corner :: Active t (Maybe Corner)
, _iconConfig_title :: Active t (Maybe Text)
, _iconConfig_elConfig :: ActiveElConfig t
}
makeLensesWith (lensRules & simpleLenses .~ True) ''IconConfig
instance HasElConfig t (IconConfig t) where
elConfig = iconConfig_elConfig
instance Reflex t => Default (IconConfig t) where
def = IconConfig
{ _iconConfig_disabled = pure False
, _iconConfig_loading = pure False
, _iconConfig_fitted = pure False
, _iconConfig_link = pure False
, _iconConfig_circular = pure False
, _iconConfig_bordered = pure False
, _iconConfig_inverted = pure False
, _iconConfig_size = pure Nothing
, _iconConfig_flipped = pure Nothing
, _iconConfig_rotated = pure Nothing
, _iconConfig_color = pure Nothing
, _iconConfig_corner = pure Nothing
, _iconConfig_title = pure Nothing
, _iconConfig_elConfig = def
}
iconConfigClasses :: Reflex t => IconConfig t -> Active t Classes
iconConfigClasses IconConfig {..} = dynClasses
[ pure $ Just "icon"
, boolClass "disabled" _iconConfig_disabled
, boolClass "loading" _iconConfig_loading
, boolClass "fitted" _iconConfig_fitted
, boolClass "link" _iconConfig_link
, boolClass "circular" _iconConfig_circular
, boolClass "bordered" _iconConfig_bordered
, boolClass "inverted" _iconConfig_inverted
, fmap toClassText . nothingIf Medium <$> _iconConfig_size
, fmap toClassText <$> _iconConfig_flipped
, fmap toClassText <$> _iconConfig_rotated
, fmap toClassText <$> _iconConfig_color
, fmap toClassText <$> _iconConfig_corner
]
data Icon t = Icon (Active t Text) (IconConfig t)
icon
:: UI t m
-> m ()
icon i = void . icon' i
icon'
:: UI t m => Active t Text -> IconConfig t
-> m (Element EventResult (DomBuilderSpace m) t)
icon' dynIcon config@IconConfig {..}
= fst <$> ui' "i" elConf blank
where
elConf = _iconConfig_elConfig <> def
{ _classes = addClass <$> dynIcon <*> iconConfigClasses config
, _attrs = maybe mempty ("title" =:) <$> _iconConfig_title
}
data IconsConfig t = IconsConfig
{ _iconsConfig_size :: Active t (Maybe Size)
, _iconsConfig_elConfig :: ActiveElConfig t
}
makeLensesWith (lensRules & simpleLenses .~ True) ''IconsConfig
instance HasElConfig t (IconsConfig t) where
elConfig = iconsConfig_elConfig
instance Reflex t => Default (IconsConfig t) where
def = IconsConfig
{ _iconsConfig_size = pure Nothing
, _iconsConfig_elConfig = def
}
iconsConfigClasses :: Reflex t => IconsConfig t -> Active t Classes
iconsConfigClasses IconsConfig {..} = dynClasses
[ pure $ Just "icons"
, fmap toClassText <$> _iconsConfig_size
]
icons'
:: UI t m => IconsConfig t -> m a
-> m (Element EventResult (DomBuilderSpace m) t, a)
icons' config@IconsConfig {..} = ui' "i" elConf
where
elConf = _iconsConfig_elConfig <> def
{ _classes = iconsConfigClasses config }
icons :: UI t m => IconsConfig t -> m a -> m a
icons config = fmap snd . icons' config
|
df79f9dfa63b562be67448c8a29b1e06a125b43e3c48f0c3a09d53cc8805668e | tnelson/Forge | client.rkt | #lang racket/base
(require "url.rkt")
(require "conn-api.rkt")
(require "hybi00/client.rkt")
(require "rfc6455/client.rkt")
(provide (all-from-out "url.rkt")
ws-connect)
(define (ws-connect u
#:headers [headers '()]
#:protocol [protocol 'rfc6455])
(case protocol
[(rfc6455) (rfc6455-connect u headers)]
[(hybi00) (hybi00-connect u headers)]
[else (error 'ws-connect "Unsupported WebSockets protocol variant ~v" protocol)]))
| null | https://raw.githubusercontent.com/tnelson/Forge/1687cba0ebdb598c29c51845d43c98a459d0588f/forge/racket-rfc6455/net/rfc6455/client.rkt | racket | #lang racket/base
(require "url.rkt")
(require "conn-api.rkt")
(require "hybi00/client.rkt")
(require "rfc6455/client.rkt")
(provide (all-from-out "url.rkt")
ws-connect)
(define (ws-connect u
#:headers [headers '()]
#:protocol [protocol 'rfc6455])
(case protocol
[(rfc6455) (rfc6455-connect u headers)]
[(hybi00) (hybi00-connect u headers)]
[else (error 'ws-connect "Unsupported WebSockets protocol variant ~v" protocol)]))
| |
a10964bfb095f23fb3138ce4c966081cc951b099ceb3685de6f156569010ac73 | documented/Clex | project.clj | (defproject cljex "1.0.0"
:description "cljex provides examples for clojure's existing core api documentation"
:repositories [["scala-tools" "-tools.org/repo-releases"]]
:dependencies [[org.clojure/clojure "1.1.0-master-SNAPSHOT"]
[org.clojure/clojure-contrib "1.0-SNAPSHOT"]
[org.clojars.liebke/compojure "0.3.1"]
[autodoc "0.3.0-SNAPSHOT"]
[org.markdownj/markdownj "0.3.0-1.0.2b4"]]
:dev-dependencies [[swank-clojure "1.1.0-SNAPSHOT"]]
:main "cljex.core")
| null | https://raw.githubusercontent.com/documented/Clex/3eeec8669cb7ae3898600a8ba472f150bba98d8d/project.clj | clojure | (defproject cljex "1.0.0"
:description "cljex provides examples for clojure's existing core api documentation"
:repositories [["scala-tools" "-tools.org/repo-releases"]]
:dependencies [[org.clojure/clojure "1.1.0-master-SNAPSHOT"]
[org.clojure/clojure-contrib "1.0-SNAPSHOT"]
[org.clojars.liebke/compojure "0.3.1"]
[autodoc "0.3.0-SNAPSHOT"]
[org.markdownj/markdownj "0.3.0-1.0.2b4"]]
:dev-dependencies [[swank-clojure "1.1.0-SNAPSHOT"]]
:main "cljex.core")
| |
5399fdc9eee49a9dca692542a0e430271d15af481ed5f876284f74dc42938edc | clj-kondo/clj-kondo | project.clj | ;; GENERATED by script/update-project.clj, DO NOT EDIT
To change dependencies , update deps.edn and run script / update - project.clj .
;; To change other things, edit project.template.clj and run script/update-project.clj.
(defproject clj-kondo "2023.02.18-SNAPSHOT"
:description "A linter for Clojure that sparks joy."
:url "-kondo/clj-kondo"
:scm {:name "git"
:url "-kondo/clj-kondo"}
:license {:name "Eclipse Public License 1.0"
:url "-1.0.php"}
:source-paths ["src" "parser" "inlined"]
:dependencies [[org.clojure/clojure "1.9.0"]
[com.cognitect/transit-clj "1.0.324"]
[io.replikativ/datalog-parser "0.2.25"]
[cheshire/cheshire "5.11.0"]
[nrepl/bencode "1.1.0"]
[org.babashka/sci "0.7.38"]
[babashka/fs "0.1.11"]
[org.ow2.asm/asm "9.2"]]
;; :global-vars {*print-namespace-maps* false}
:profiles {:clojure-1.9.0 {:dependencies [[org.clojure/clojure "1.9.0"]]}
:clojure-1.10.2 {:dependencies [[org.clojure/clojure "1.10.2"]]}
:test {:dependencies [[nubank/matcher-combinators "3.5.1"]
[org.clojure/clojurescript "1.11.54"]
[clj-commons/conch "0.9.2"]
[org.clojure/tools.deps.alpha "0.12.1048"]
[jonase/eastwood "1.3.0"]
[babashka/process "0.1.0"]
[borkdude/missing.test.assertions "0.0.2"]]
:source-paths ["src" "parser" "inlined" "extract"]}
:uberjar {:dependencies [[com.github.clj-easy/graal-build-time "0.1.0"]]
:jvm-opts ["-Dclojure.compiler.direct-linking=true"
"-Dclojure.spec.skip-macros=true"]
:main clj-kondo.main
:aot [clj-kondo.main]}}
:aliases {"clj-kondo" ["run" "-m" "clj-kondo.main"]}
:deploy-repositories [["clojars" {:url ""
:username :env/clojars_user
:password :env/clojars_pass
:sign-releases false}]])
| null | https://raw.githubusercontent.com/clj-kondo/clj-kondo/494909f149159d79ae3e97bb9a3d6edad060ffdd/project.clj | clojure | GENERATED by script/update-project.clj, DO NOT EDIT
To change other things, edit project.template.clj and run script/update-project.clj.
:global-vars {*print-namespace-maps* false} | To change dependencies , update deps.edn and run script / update - project.clj .
(defproject clj-kondo "2023.02.18-SNAPSHOT"
:description "A linter for Clojure that sparks joy."
:url "-kondo/clj-kondo"
:scm {:name "git"
:url "-kondo/clj-kondo"}
:license {:name "Eclipse Public License 1.0"
:url "-1.0.php"}
:source-paths ["src" "parser" "inlined"]
:dependencies [[org.clojure/clojure "1.9.0"]
[com.cognitect/transit-clj "1.0.324"]
[io.replikativ/datalog-parser "0.2.25"]
[cheshire/cheshire "5.11.0"]
[nrepl/bencode "1.1.0"]
[org.babashka/sci "0.7.38"]
[babashka/fs "0.1.11"]
[org.ow2.asm/asm "9.2"]]
:profiles {:clojure-1.9.0 {:dependencies [[org.clojure/clojure "1.9.0"]]}
:clojure-1.10.2 {:dependencies [[org.clojure/clojure "1.10.2"]]}
:test {:dependencies [[nubank/matcher-combinators "3.5.1"]
[org.clojure/clojurescript "1.11.54"]
[clj-commons/conch "0.9.2"]
[org.clojure/tools.deps.alpha "0.12.1048"]
[jonase/eastwood "1.3.0"]
[babashka/process "0.1.0"]
[borkdude/missing.test.assertions "0.0.2"]]
:source-paths ["src" "parser" "inlined" "extract"]}
:uberjar {:dependencies [[com.github.clj-easy/graal-build-time "0.1.0"]]
:jvm-opts ["-Dclojure.compiler.direct-linking=true"
"-Dclojure.spec.skip-macros=true"]
:main clj-kondo.main
:aot [clj-kondo.main]}}
:aliases {"clj-kondo" ["run" "-m" "clj-kondo.main"]}
:deploy-repositories [["clojars" {:url ""
:username :env/clojars_user
:password :env/clojars_pass
:sign-releases false}]])
|
d6608f1cadea7ac45eed1c0bc37da360261944d397a5adcfb0990289f5f2f271 | nuprl/gradual-typing-performance | view-controller.rkt | #lang racket/unit
;; this module implements the UI side of the stepper; it
;; opens a window, starts the stepper thread running,
;; and handles the resulting calls to 'break'.
;; this module lies outside of the "testing boundary"
;; of through-tests; it is not tested automatically at all.
;; this version of the view-controller just collects the steps up front rather
;; than blocking until the user presses the "next" button.
(require racket/class
racket/match
racket/list
drracket/tool
mred
string-constants
racket/async-channel
(prefix-in model: "model.rkt")
(prefix-in x: "mred-extensions.rkt")
"shared.rkt"
"model-settings.rkt"
"xml-sig.rkt"
images/compile-time
images/gui
(for-syntax racket/base images/icons/control images/icons/style images/logos))
(import drracket:tool^ xml^ stepper-frame^)
(export view-controller^)
(define drracket-eventspace (current-eventspace))
(define (definitions-text->settings definitions-text)
(send definitions-text get-next-settings))
;; the stored representation of a step
(define-struct step (text kind posns) #:transparent)
(define (show-about-dialog parent)
(define dlg
(new logo-about-dialog%
[label "About the Stepper"]
[parent parent]
[bitmap (compiled-bitmap (stepper-logo))]
[messages '("The Algebraic Stepper is formalized and proved correct in\n"
"\n"
" John Clements, Matthew Flatt, Matthias Felleisen\n"
" Modeling an Algebraic Stepper\n"
" European Symposium on Programming, 2001\n")]))
(send dlg show #t))
(define (go drracket-tab program-expander selection-start selection-end)
;; get the language-level:
(define language-settings
(definitions-text->settings
(send drracket-tab get-defs)))
(define language-level
(drracket:language-configuration:language-settings-language
language-settings))
(define simple-settings
(drracket:language-configuration:language-settings-settings
language-settings))
;; VALUE CONVERSION CODE:
render - to - string : TST - > string
(define (render-to-string val)
(let ([string-port (open-output-string)])
(send language-level render-value
val simple-settings string-port)
(get-output-string string-port)))
render - to - sexp : TST - > sexp
(define (render-to-sexp val)
(send language-level stepper:render-to-sexp
val simple-settings language-level))
;; channel for incoming views
(define view-channel (make-async-channel))
the first - step semaphore
(define first-step-sema (make-semaphore 0))
;; the list of available views
(define view-history null)
;; the number of available steps
(define num-steps-available 0)
;; the view in the stepper window
(define view #f)
;; wait for steps to show up on the channel.
;; When they do, add them to the list.
(define (start-listener-thread stepper-frame-eventspace)
as of 2012 - 06 - 20 , I no longer believe there 's any
;; need for this thread, as the queue-callback handles
;; the needed separation.
(thread
(lambda ()
(let loop ()
(define new-result (async-channel-get view-channel))
(receive-result-from-target new-result)
(loop)))))
;; handles an incoming result. Either adds it to the list of
;; steps, or prompts user to see whether to continue running.
(define (receive-result-from-target result)
(cond [(runaway-process? result)
(parameterize ([current-eventspace stepper-frame-eventspace])
(queue-callback
(lambda ()
(when (confirm-running)
(semaphore-post (runaway-process-sema result)))
(void))))]
[else
(define new-step (format-result result))
(parameterize ([current-eventspace stepper-frame-eventspace])
(queue-callback
(lambda ()
(set! view-history (append view-history (list new-step)))
(set! num-steps-available (length view-history))
this is only necessary the first time , but it 's cheap :
(semaphore-post first-step-sema)
(update-status-bar))))]))
;; find-later-step : given a predicate on history-entries, search through
the history for the first step that satisfies the predicate and whose
;; number is greater than n (or -1 if n is #f), return # of step on success,
;; on failure return (list 'nomatch last-step) or (list 'nomatch/seen-final
;; last-step) if we went past the final step
(define (find-later-step p n)
(let* ([n-as-num (or n -1)])
(let loop ([step 0]
[remaining view-history]
[seen-final? #f])
(cond [(null? remaining)
(cond [seen-final? (list `nomatch/seen-final (- step 1))]
[else (list `nomatch (- step 1))])]
[(and (> step n-as-num) (p (car remaining))) step]
[else (loop (+ step 1)
(cdr remaining)
(or seen-final? (finished-stepping-step? (car remaining))))]))))
;; find-earlier-step : like find-later-step, but searches backward from
;; the given step.
(define (find-earlier-step p n)
(unless (number? n)
(error 'find-earlier-step
"can't find earlier step when no step is displayed."))
(let* ([to-search (reverse (take view-history n))])
(let loop ([step (- n 1)]
[remaining to-search])
(cond [(null? remaining) `nomatch]
[(p (car remaining)) step]
[else (loop (- step 1) (cdr remaining))]))))
STEP PREDICATES :
;; is this an application step?
(define (application-step? history-entry)
(match history-entry
[(struct step (text (or 'user-application 'finished-or-error) posns)) #t]
[else #f]))
;; is this the finished-stepping step?
(define (finished-stepping-step? history-entry)
(match (step-kind history-entry)
['finished-or-error #t]
[else #f]))
;; is this step on the selected expression?
(define (selected-exp-step? history-entry)
(ormap (span-overlap selection-start selection-end) (step-posns history-entry)))
build object :
;; next-of-specified-kind : starting at the current view, search forward for the
;; desired step or wait for it if not found
(define (next-of-specified-kind right-kind? msg)
(next-of-specified-kind/helper right-kind? view msg))
first - of - specified - kind : similar to next - of - specified - kind , but
always start at zero
(define (first-of-specified-kind right-kind? msg)
(next-of-specified-kind/helper right-kind? #f msg))
;; next-of-specified-kind/helper : if the desired step
;; is already in the list, display it; otherwise, give up.
(define (next-of-specified-kind/helper right-kind? starting-step msg)
(match (find-later-step right-kind? starting-step)
[(? number? n)
(update-view/existing n)]
[(list `nomatch step)
(message-box (string-constant stepper-no-such-step/title) msg)
(when (>= num-steps-available 0)
(update-view/existing step))]
[(list `nomatch/seen-final step)
(message-box (string-constant stepper-no-such-step/title) msg)
(when (>= num-steps-available 0)
(update-view/existing step))]))
;; prior-of-specified-kind: if the desired step is already in the list, display
it ; otherwise , put up a dialog and jump to the first step .
(define (prior-of-specified-kind right-kind? msg)
(match (find-earlier-step right-kind? view)
[(? number? found-step)
(update-view/existing found-step)]
[`nomatch
(message-box (string-constant stepper-no-such-step/title) msg)
(when (>= num-steps-available 0)
(update-view/existing 0))]))
;; BUTTON/CHOICE BOX PROCEDURES
;; respond to a click on the "next" button
(define (next)
(next-of-specified-kind (lambda (x) #t)
(string-constant stepper-no-later-step)))
;; previous : the action of the 'previous' button
(define (previous)
(prior-of-specified-kind (lambda (x) #t)
(string-constant stepper-no-earlier-step)))
respond to a click on the " Jump To ... " choice
(define (jump-to control event)
((second (list-ref pulldown-choices (send control get-selection)))))
;; jump-to-beginning : the action of the choice menu entry
(define (jump-to-beginning)
(first-of-specified-kind (lambda (x) #t)
;; I don't believe this can fail...
"internal error 2010-01-10 21:48"))
;; jump-to-end : the action of the jump-to-end choice box option
(define (jump-to-end)
(first-of-specified-kind finished-stepping-step?
(string-constant stepper-no-last-step)))
;; jump-to-selected : the action of the jump to selected choice box option
(define (jump-to-selected)
(first-of-specified-kind selected-exp-step?
(string-constant stepper-no-selected-step)))
;; jump-to-next-application : the action of the jump to next application
;; choice box option
(define (jump-to-next-application)
(next-of-specified-kind application-step?
(string-constant stepper-no-later-application-step)))
;; jump-to-prior-application : the action of the "jump to prior application"
;; choice box option
(define (jump-to-prior-application)
(prior-of-specified-kind application-step?
(string-constant
stepper-no-earlier-application-step)))
;; GUI ELEMENTS:
(define s-frame
(make-object stepper-frame% drracket-tab))
(define top-panel
(new horizontal-panel% [parent (send s-frame get-area-container)] [horiz-margin 5]
;[style '(border)] ; for layout testing only
[stretchable-width #t]
[stretchable-height #f]))
(define button-panel
(new horizontal-panel% [parent top-panel] [alignment '(center top)]
;[style '(border)] ; for layout testing only
[stretchable-width #t]
[stretchable-height #f]))
(define logo-canvas
(new (class bitmap-canvas%
(super-new [parent top-panel] [bitmap (compiled-bitmap (stepper-logo #:height 32))])
(define/override (on-event evt)
(when (eq? (send evt get-event-type) 'left-up)
(show-about-dialog s-frame))))))
(define prev-img (compiled-bitmap (step-back-icon #:color run-icon-color
#:height (toolbar-icon-height))))
(define previous-button (new button%
[label (list prev-img (string-constant stepper-previous) 'left)]
[parent button-panel]
[callback (λ (_1 _2) (previous))]
[enabled #f]))
(define next-img (compiled-bitmap (step-icon #:color run-icon-color
#:height (toolbar-icon-height))))
(define next-button (new button%
[label (list next-img (string-constant stepper-next) 'right)]
[parent button-panel]
[callback (λ (_1 _2) (next))]
[enabled #f]))
(define pulldown-choices
`((,(string-constant stepper-jump-to-beginning) ,jump-to-beginning)
(,(string-constant stepper-jump-to-end) ,jump-to-end)
(,(string-constant stepper-jump-to-selected) ,jump-to-selected)
(,(string-constant stepper-jump-to-next-application) ,jump-to-next-application)
(,(string-constant stepper-jump-to-previous-application) ,jump-to-prior-application)))
(define jump-button (new choice%
[label (string-constant stepper-jump)]
[choices (map first pulldown-choices)]
[parent button-panel]
[callback jump-to]
[enabled #f]))
(define canvas
(make-object x:stepper-canvas% (send s-frame get-area-container)))
;; counting steps...
(define status-text
(new text%))
(define status-canvas
(new editor-canvas%
[parent button-panel]
[editor status-text]
[stretchable-width #f]
[style '(transparent no-border no-hscroll no-vscroll)]
;; some way to get the height of a line of text?
[min-width 100]))
;; update-view/existing : set an existing step as the one shown in the
;; frame
(define (update-view/existing new-view)
(set! view new-view)
(let ([e (step-text (list-ref view-history view))])
(send e begin-edit-sequence)
(send canvas set-editor e)
(send e reset-width canvas)
why set the position within the step ? I 'm confused by
(send e set-position (send e last-position))
(send e end-edit-sequence))
(update-status-bar))
;; set the status bar to the correct m/n text.
(define (update-status-bar)
(send status-text begin-edit-sequence)
(send status-text lock #f)
(send status-text delete 0 (send status-text last-position))
updated to yield 1 - based step numbering rather than 0 - based numbering .
(send status-text insert
(format "~a/~a" (if view (+ 1 view) "none") (length view-history)))
(send status-text lock #t)
(send status-text end-edit-sequence))
(define update-status-bar-semaphore (make-semaphore 1))
(define (enable-all-buttons)
(send previous-button enable #t)
(send next-button enable #t)
(send jump-button enable #t))
(define (print-current-view item evt)
(send (send canvas get-editor) print))
;; code for dealing with runaway processes:
(define runaway-counter-limit 500)
(define disable-runaway-counter #f)
(define runaway-counter 0)
;; runs on the stepped-process side.
;; checks to see if the process has taken too
;; many steps. If so, send a message and block
;; for a response, then send the result. Otherwise,
;; just send the result.
(define (deliver-result-to-gui result)
(when (not disable-runaway-counter)
(set! runaway-counter (+ runaway-counter 1)))
(when (= runaway-counter runaway-counter-limit)
(define runaway-semaphore (make-semaphore 0))
(async-channel-put view-channel
(runaway-process runaway-semaphore))
;; wait for a signal to continue running:
(semaphore-wait runaway-semaphore))
(async-channel-put view-channel result))
(define keep-running-message
(string-append
"The program running in the stepper has taken a whole bunch of steps. "
"Do you want to continue running it for now, halt, or let it run "
"without asking again?"))
(define (confirm-running)
(define message-box-result
(message-box/custom
"Keep Running Program?"
keep-running-message
"Continue for now"
"Halt"
"Continue uninterrupted"
#f ;; use the stepper window instead?
'(stop disallow-close default=1)
))
(match message-box-result
;; continue-for-now:
[1 (set! runaway-counter 0)
#t]
;; halt:
[2 #f]
;; continue-forever:
[3 (set! runaway-counter 0)
(set! disable-runaway-counter #t)
#t]))
;; translates a result into a step
;; format-result : step-result -> step?
(define (format-result result)
(match result
[(struct before-after-result (pre-exps post-exps kind pre-src post-src))
(make-step (new x:stepper-text%
[left-side pre-exps]
[right-side post-exps]
[show-inexactness?
(send language-level stepper:show-inexactness?)])
kind
(list pre-src post-src))]
[(struct before-error-result (pre-exps err-msg pre-src))
(make-step (new x:stepper-text%
[left-side pre-exps]
[right-side err-msg]
[show-inexactness?
(send language-level stepper:show-inexactness?)])
'finished-or-error
(list pre-src))]
[(struct error-result (err-msg))
(make-step (new x:stepper-text%
[left-side null]
[right-side err-msg]
[show-inexactness?
(send language-level stepper:show-inexactness?)])
'finished-or-error
(list))]
[(struct finished-stepping ())
(make-step x:finished-text 'finished-or-error (list))]))
;; program-expander-prime : wrap the program-expander for a couple of reasons:
;; 1) we need to capture the custodian as the thread starts up:
;; ok, it was just one.
;;
(define (program-expander-prime init iter)
(program-expander
(lambda args
(send s-frame set-custodian! (current-custodian))
(apply init args))
iter))
CONFIGURE GUI ELEMENTS
(send s-frame set-printing-proc print-current-view)
(send canvas stretchable-height #t)
(send (send s-frame edit-menu:get-undo-item) enable #f)
(send (send s-frame edit-menu:get-redo-item) enable #f)
(define stepper-frame-eventspace (send s-frame get-eventspace))
;; START THE MODEL
(start-listener-thread stepper-frame-eventspace)
(model:go
program-expander-prime
;; what do do with the results:
deliver-result-to-gui
(get-render-settings render-to-string
render-to-sexp
(send language-level stepper:enable-let-lifting?)
(send language-level stepper:show-consumed-and/or-clauses?)
(send language-level stepper:show-lambdas-as-lambdas?)))
(send s-frame show #t)
turn on the buttons and display the first step when it shows up :
(thread
(lambda ()
(semaphore-wait first-step-sema)
(parameterize
([current-eventspace stepper-frame-eventspace])
(queue-callback
(lambda ()
(jump-to-beginning)
(enable-all-buttons))))))
s-frame)
;; UTILITY FUNCTIONS:
;; span-overlap : number number -> posn-info -> boolean
return true if the selection is of zero length and precedes a char of the
;; stepping expression, *or* if the selection has positive overlap with the
;; stepping expression.
(define ((span-overlap selection-start selection-end) source-posn-info)
(match source-posn-info
[#f #f]
[(struct model:posn-info (posn span))
(let ([end (+ posn span)])
(and posn
you can * almost * combine these two , but not quite .
(cond [(= selection-start selection-end)
(and (<= posn selection-start) (< selection-start end))]
[else
(let ([overlap-begin (max selection-start posn)]
nb : we do n't want zero - length overlaps at the end .
compensate by subtracting one from the end of the
;; current expression.
[overlap-end (min selection-end end)])
;; #t if there's positive overlap:
(< overlap-begin overlap-end))])))]))
;; a few unit tests. Use them if changing span-overlap.
;; ...oops, can't use module+ inside of a unit.
#;(module+ test
(require rackunit)
zero - length selection cases :
(check-equal? ((span-overlap 13 13) (model:make-posn-info 14 4)) #f)
(check-equal? ((span-overlap 14 14) (model:make-posn-info 14 4)) #t)
(check-equal? ((span-overlap 18 18) (model:make-posn-info 14 4)) #f)
;; nonzero-length selection cases:
(check-equal? ((span-overlap 13 14) (model:make-posn-info 14 4)) #f)
(check-equal? ((span-overlap 13 15) (model:make-posn-info 14 4)) #t)
(check-equal? ((span-overlap 13 23) (model:make-posn-info 14 4)) #t)
(check-equal? ((span-overlap 16 17) (model:make-posn-info 14 4)) #t)
(check-equal? ((span-overlap 16 24) (model:make-posn-info 14 4)) #t)
(check-equal? ((span-overlap 18 21) (model:make-posn-info 14 4)) #f))
| null | https://raw.githubusercontent.com/nuprl/gradual-typing-performance/35442b3221299a9cadba6810573007736b0d65d4/pre-benchmark/ecoop/htdp-lib/stepper/private/view-controller.rkt | racket | this module implements the UI side of the stepper; it
opens a window, starts the stepper thread running,
and handles the resulting calls to 'break'.
this module lies outside of the "testing boundary"
of through-tests; it is not tested automatically at all.
this version of the view-controller just collects the steps up front rather
than blocking until the user presses the "next" button.
the stored representation of a step
get the language-level:
VALUE CONVERSION CODE:
channel for incoming views
the list of available views
the number of available steps
the view in the stepper window
wait for steps to show up on the channel.
When they do, add them to the list.
need for this thread, as the queue-callback handles
the needed separation.
handles an incoming result. Either adds it to the list of
steps, or prompts user to see whether to continue running.
find-later-step : given a predicate on history-entries, search through
number is greater than n (or -1 if n is #f), return # of step on success,
on failure return (list 'nomatch last-step) or (list 'nomatch/seen-final
last-step) if we went past the final step
find-earlier-step : like find-later-step, but searches backward from
the given step.
is this an application step?
is this the finished-stepping step?
is this step on the selected expression?
next-of-specified-kind : starting at the current view, search forward for the
desired step or wait for it if not found
next-of-specified-kind/helper : if the desired step
is already in the list, display it; otherwise, give up.
prior-of-specified-kind: if the desired step is already in the list, display
otherwise , put up a dialog and jump to the first step .
BUTTON/CHOICE BOX PROCEDURES
respond to a click on the "next" button
previous : the action of the 'previous' button
jump-to-beginning : the action of the choice menu entry
I don't believe this can fail...
jump-to-end : the action of the jump-to-end choice box option
jump-to-selected : the action of the jump to selected choice box option
jump-to-next-application : the action of the jump to next application
choice box option
jump-to-prior-application : the action of the "jump to prior application"
choice box option
GUI ELEMENTS:
[style '(border)] ; for layout testing only
[style '(border)] ; for layout testing only
counting steps...
some way to get the height of a line of text?
update-view/existing : set an existing step as the one shown in the
frame
set the status bar to the correct m/n text.
code for dealing with runaway processes:
runs on the stepped-process side.
checks to see if the process has taken too
many steps. If so, send a message and block
for a response, then send the result. Otherwise,
just send the result.
wait for a signal to continue running:
use the stepper window instead?
continue-for-now:
halt:
continue-forever:
translates a result into a step
format-result : step-result -> step?
program-expander-prime : wrap the program-expander for a couple of reasons:
1) we need to capture the custodian as the thread starts up:
ok, it was just one.
START THE MODEL
what do do with the results:
UTILITY FUNCTIONS:
span-overlap : number number -> posn-info -> boolean
stepping expression, *or* if the selection has positive overlap with the
stepping expression.
current expression.
#t if there's positive overlap:
a few unit tests. Use them if changing span-overlap.
...oops, can't use module+ inside of a unit.
(module+ test
nonzero-length selection cases: | #lang racket/unit
(require racket/class
racket/match
racket/list
drracket/tool
mred
string-constants
racket/async-channel
(prefix-in model: "model.rkt")
(prefix-in x: "mred-extensions.rkt")
"shared.rkt"
"model-settings.rkt"
"xml-sig.rkt"
images/compile-time
images/gui
(for-syntax racket/base images/icons/control images/icons/style images/logos))
(import drracket:tool^ xml^ stepper-frame^)
(export view-controller^)
(define drracket-eventspace (current-eventspace))
(define (definitions-text->settings definitions-text)
(send definitions-text get-next-settings))
(define-struct step (text kind posns) #:transparent)
(define (show-about-dialog parent)
(define dlg
(new logo-about-dialog%
[label "About the Stepper"]
[parent parent]
[bitmap (compiled-bitmap (stepper-logo))]
[messages '("The Algebraic Stepper is formalized and proved correct in\n"
"\n"
" John Clements, Matthew Flatt, Matthias Felleisen\n"
" Modeling an Algebraic Stepper\n"
" European Symposium on Programming, 2001\n")]))
(send dlg show #t))
(define (go drracket-tab program-expander selection-start selection-end)
(define language-settings
(definitions-text->settings
(send drracket-tab get-defs)))
(define language-level
(drracket:language-configuration:language-settings-language
language-settings))
(define simple-settings
(drracket:language-configuration:language-settings-settings
language-settings))
render - to - string : TST - > string
(define (render-to-string val)
(let ([string-port (open-output-string)])
(send language-level render-value
val simple-settings string-port)
(get-output-string string-port)))
render - to - sexp : TST - > sexp
(define (render-to-sexp val)
(send language-level stepper:render-to-sexp
val simple-settings language-level))
(define view-channel (make-async-channel))
the first - step semaphore
(define first-step-sema (make-semaphore 0))
(define view-history null)
(define num-steps-available 0)
(define view #f)
(define (start-listener-thread stepper-frame-eventspace)
as of 2012 - 06 - 20 , I no longer believe there 's any
(thread
(lambda ()
(let loop ()
(define new-result (async-channel-get view-channel))
(receive-result-from-target new-result)
(loop)))))
(define (receive-result-from-target result)
(cond [(runaway-process? result)
(parameterize ([current-eventspace stepper-frame-eventspace])
(queue-callback
(lambda ()
(when (confirm-running)
(semaphore-post (runaway-process-sema result)))
(void))))]
[else
(define new-step (format-result result))
(parameterize ([current-eventspace stepper-frame-eventspace])
(queue-callback
(lambda ()
(set! view-history (append view-history (list new-step)))
(set! num-steps-available (length view-history))
this is only necessary the first time , but it 's cheap :
(semaphore-post first-step-sema)
(update-status-bar))))]))
the history for the first step that satisfies the predicate and whose
(define (find-later-step p n)
(let* ([n-as-num (or n -1)])
(let loop ([step 0]
[remaining view-history]
[seen-final? #f])
(cond [(null? remaining)
(cond [seen-final? (list `nomatch/seen-final (- step 1))]
[else (list `nomatch (- step 1))])]
[(and (> step n-as-num) (p (car remaining))) step]
[else (loop (+ step 1)
(cdr remaining)
(or seen-final? (finished-stepping-step? (car remaining))))]))))
(define (find-earlier-step p n)
(unless (number? n)
(error 'find-earlier-step
"can't find earlier step when no step is displayed."))
(let* ([to-search (reverse (take view-history n))])
(let loop ([step (- n 1)]
[remaining to-search])
(cond [(null? remaining) `nomatch]
[(p (car remaining)) step]
[else (loop (- step 1) (cdr remaining))]))))
STEP PREDICATES :
(define (application-step? history-entry)
(match history-entry
[(struct step (text (or 'user-application 'finished-or-error) posns)) #t]
[else #f]))
(define (finished-stepping-step? history-entry)
(match (step-kind history-entry)
['finished-or-error #t]
[else #f]))
(define (selected-exp-step? history-entry)
(ormap (span-overlap selection-start selection-end) (step-posns history-entry)))
build object :
(define (next-of-specified-kind right-kind? msg)
(next-of-specified-kind/helper right-kind? view msg))
first - of - specified - kind : similar to next - of - specified - kind , but
always start at zero
(define (first-of-specified-kind right-kind? msg)
(next-of-specified-kind/helper right-kind? #f msg))
(define (next-of-specified-kind/helper right-kind? starting-step msg)
(match (find-later-step right-kind? starting-step)
[(? number? n)
(update-view/existing n)]
[(list `nomatch step)
(message-box (string-constant stepper-no-such-step/title) msg)
(when (>= num-steps-available 0)
(update-view/existing step))]
[(list `nomatch/seen-final step)
(message-box (string-constant stepper-no-such-step/title) msg)
(when (>= num-steps-available 0)
(update-view/existing step))]))
(define (prior-of-specified-kind right-kind? msg)
(match (find-earlier-step right-kind? view)
[(? number? found-step)
(update-view/existing found-step)]
[`nomatch
(message-box (string-constant stepper-no-such-step/title) msg)
(when (>= num-steps-available 0)
(update-view/existing 0))]))
(define (next)
(next-of-specified-kind (lambda (x) #t)
(string-constant stepper-no-later-step)))
(define (previous)
(prior-of-specified-kind (lambda (x) #t)
(string-constant stepper-no-earlier-step)))
respond to a click on the " Jump To ... " choice
(define (jump-to control event)
((second (list-ref pulldown-choices (send control get-selection)))))
(define (jump-to-beginning)
(first-of-specified-kind (lambda (x) #t)
"internal error 2010-01-10 21:48"))
(define (jump-to-end)
(first-of-specified-kind finished-stepping-step?
(string-constant stepper-no-last-step)))
(define (jump-to-selected)
(first-of-specified-kind selected-exp-step?
(string-constant stepper-no-selected-step)))
(define (jump-to-next-application)
(next-of-specified-kind application-step?
(string-constant stepper-no-later-application-step)))
(define (jump-to-prior-application)
(prior-of-specified-kind application-step?
(string-constant
stepper-no-earlier-application-step)))
(define s-frame
(make-object stepper-frame% drracket-tab))
(define top-panel
(new horizontal-panel% [parent (send s-frame get-area-container)] [horiz-margin 5]
[stretchable-width #t]
[stretchable-height #f]))
(define button-panel
(new horizontal-panel% [parent top-panel] [alignment '(center top)]
[stretchable-width #t]
[stretchable-height #f]))
(define logo-canvas
(new (class bitmap-canvas%
(super-new [parent top-panel] [bitmap (compiled-bitmap (stepper-logo #:height 32))])
(define/override (on-event evt)
(when (eq? (send evt get-event-type) 'left-up)
(show-about-dialog s-frame))))))
(define prev-img (compiled-bitmap (step-back-icon #:color run-icon-color
#:height (toolbar-icon-height))))
(define previous-button (new button%
[label (list prev-img (string-constant stepper-previous) 'left)]
[parent button-panel]
[callback (λ (_1 _2) (previous))]
[enabled #f]))
(define next-img (compiled-bitmap (step-icon #:color run-icon-color
#:height (toolbar-icon-height))))
(define next-button (new button%
[label (list next-img (string-constant stepper-next) 'right)]
[parent button-panel]
[callback (λ (_1 _2) (next))]
[enabled #f]))
(define pulldown-choices
`((,(string-constant stepper-jump-to-beginning) ,jump-to-beginning)
(,(string-constant stepper-jump-to-end) ,jump-to-end)
(,(string-constant stepper-jump-to-selected) ,jump-to-selected)
(,(string-constant stepper-jump-to-next-application) ,jump-to-next-application)
(,(string-constant stepper-jump-to-previous-application) ,jump-to-prior-application)))
(define jump-button (new choice%
[label (string-constant stepper-jump)]
[choices (map first pulldown-choices)]
[parent button-panel]
[callback jump-to]
[enabled #f]))
(define canvas
(make-object x:stepper-canvas% (send s-frame get-area-container)))
(define status-text
(new text%))
(define status-canvas
(new editor-canvas%
[parent button-panel]
[editor status-text]
[stretchable-width #f]
[style '(transparent no-border no-hscroll no-vscroll)]
[min-width 100]))
(define (update-view/existing new-view)
(set! view new-view)
(let ([e (step-text (list-ref view-history view))])
(send e begin-edit-sequence)
(send canvas set-editor e)
(send e reset-width canvas)
why set the position within the step ? I 'm confused by
(send e set-position (send e last-position))
(send e end-edit-sequence))
(update-status-bar))
(define (update-status-bar)
(send status-text begin-edit-sequence)
(send status-text lock #f)
(send status-text delete 0 (send status-text last-position))
updated to yield 1 - based step numbering rather than 0 - based numbering .
(send status-text insert
(format "~a/~a" (if view (+ 1 view) "none") (length view-history)))
(send status-text lock #t)
(send status-text end-edit-sequence))
(define update-status-bar-semaphore (make-semaphore 1))
(define (enable-all-buttons)
(send previous-button enable #t)
(send next-button enable #t)
(send jump-button enable #t))
(define (print-current-view item evt)
(send (send canvas get-editor) print))
(define runaway-counter-limit 500)
(define disable-runaway-counter #f)
(define runaway-counter 0)
(define (deliver-result-to-gui result)
(when (not disable-runaway-counter)
(set! runaway-counter (+ runaway-counter 1)))
(when (= runaway-counter runaway-counter-limit)
(define runaway-semaphore (make-semaphore 0))
(async-channel-put view-channel
(runaway-process runaway-semaphore))
(semaphore-wait runaway-semaphore))
(async-channel-put view-channel result))
(define keep-running-message
(string-append
"The program running in the stepper has taken a whole bunch of steps. "
"Do you want to continue running it for now, halt, or let it run "
"without asking again?"))
(define (confirm-running)
(define message-box-result
(message-box/custom
"Keep Running Program?"
keep-running-message
"Continue for now"
"Halt"
"Continue uninterrupted"
'(stop disallow-close default=1)
))
(match message-box-result
[1 (set! runaway-counter 0)
#t]
[2 #f]
[3 (set! runaway-counter 0)
(set! disable-runaway-counter #t)
#t]))
(define (format-result result)
(match result
[(struct before-after-result (pre-exps post-exps kind pre-src post-src))
(make-step (new x:stepper-text%
[left-side pre-exps]
[right-side post-exps]
[show-inexactness?
(send language-level stepper:show-inexactness?)])
kind
(list pre-src post-src))]
[(struct before-error-result (pre-exps err-msg pre-src))
(make-step (new x:stepper-text%
[left-side pre-exps]
[right-side err-msg]
[show-inexactness?
(send language-level stepper:show-inexactness?)])
'finished-or-error
(list pre-src))]
[(struct error-result (err-msg))
(make-step (new x:stepper-text%
[left-side null]
[right-side err-msg]
[show-inexactness?
(send language-level stepper:show-inexactness?)])
'finished-or-error
(list))]
[(struct finished-stepping ())
(make-step x:finished-text 'finished-or-error (list))]))
(define (program-expander-prime init iter)
(program-expander
(lambda args
(send s-frame set-custodian! (current-custodian))
(apply init args))
iter))
CONFIGURE GUI ELEMENTS
(send s-frame set-printing-proc print-current-view)
(send canvas stretchable-height #t)
(send (send s-frame edit-menu:get-undo-item) enable #f)
(send (send s-frame edit-menu:get-redo-item) enable #f)
(define stepper-frame-eventspace (send s-frame get-eventspace))
(start-listener-thread stepper-frame-eventspace)
(model:go
program-expander-prime
deliver-result-to-gui
(get-render-settings render-to-string
render-to-sexp
(send language-level stepper:enable-let-lifting?)
(send language-level stepper:show-consumed-and/or-clauses?)
(send language-level stepper:show-lambdas-as-lambdas?)))
(send s-frame show #t)
turn on the buttons and display the first step when it shows up :
(thread
(lambda ()
(semaphore-wait first-step-sema)
(parameterize
([current-eventspace stepper-frame-eventspace])
(queue-callback
(lambda ()
(jump-to-beginning)
(enable-all-buttons))))))
s-frame)
return true if the selection is of zero length and precedes a char of the
(define ((span-overlap selection-start selection-end) source-posn-info)
(match source-posn-info
[#f #f]
[(struct model:posn-info (posn span))
(let ([end (+ posn span)])
(and posn
you can * almost * combine these two , but not quite .
(cond [(= selection-start selection-end)
(and (<= posn selection-start) (< selection-start end))]
[else
(let ([overlap-begin (max selection-start posn)]
nb : we do n't want zero - length overlaps at the end .
compensate by subtracting one from the end of the
[overlap-end (min selection-end end)])
(< overlap-begin overlap-end))])))]))
(require rackunit)
zero - length selection cases :
(check-equal? ((span-overlap 13 13) (model:make-posn-info 14 4)) #f)
(check-equal? ((span-overlap 14 14) (model:make-posn-info 14 4)) #t)
(check-equal? ((span-overlap 18 18) (model:make-posn-info 14 4)) #f)
(check-equal? ((span-overlap 13 14) (model:make-posn-info 14 4)) #f)
(check-equal? ((span-overlap 13 15) (model:make-posn-info 14 4)) #t)
(check-equal? ((span-overlap 13 23) (model:make-posn-info 14 4)) #t)
(check-equal? ((span-overlap 16 17) (model:make-posn-info 14 4)) #t)
(check-equal? ((span-overlap 16 24) (model:make-posn-info 14 4)) #t)
(check-equal? ((span-overlap 18 21) (model:make-posn-info 14 4)) #f))
|
b8e0c7ce3978d45fd69fe1fcd1222a34abb8bd25db527afa921773a9bdbf8662 | cram-code/cram_core | unify.lisp | ;;;
Copyright ( c ) 2009 , < >
;;; All rights reserved.
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions are met:
;;;
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above copyright
;;; notice, this list of conditions and the following disclaimer in the
;;; documentation and/or other materials provided with the distribution.
* Neither the name of Willow Garage , Inc. nor the names of its
;;; contributors may be used to endorse or promote products derived from
;;; this software without specific prior written permission.
;;;
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS "
;;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER OR
LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR
;;; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
;;; SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN
;;; CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
;;; ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
;;; POSSIBILITY OF SUCH DAMAGE.
(in-package :crs-tests)
(define-test constant
(multiple-value-bind (result matched?)
(unify 'x 'x)
(assert-eq result nil)
(assert-true matched?)))
(define-test constant-fail
(assert-false (nth-value 1 (unify 'x 'y)))
(assert-false (nth-value 1 (unify '(a b) '(a b c))))
(assert-false (nth-value 1 (unify '(a b) '(a))))
(assert-false (nth-value 1 (unify '(a b c) '(a b foo)))))
(define-test like-patmatch
(multiple-value-bind (result matched?)
(unify '(?x b) '(a b))
(assert-equality #'bindings-equal result '((?x . a)))
(assert-true matched?)))
(define-test like-patmatch-fail
(assert-false (nth-value 1 (unify '(?x) 'a)))
(assert-false (nth-value 1 (unify '(?x ?x) '(a b))))
(assert-false (nth-value 1 (unify '(?x ?x) '(nil foo)))))
(define-test seg-form-errors
(assert-error 'simple-error (unify '!?foo 'bar))
(assert-error 'simple-error (unify 'bar '!?foo))
(assert-error 'simple-error (unify '(a . !?x) '(a . b)))
(assert-error 'simple-error (unify '(a . b) '(a . !?x))))
(define-test seg-form-like-patmatch
(handler-bind ((warning #'muffle-warning))
(assert-equality
#'bindings-equal '((?x b c)) (unify '(a !?x d) '(a b c d)))
(assert-equality
#'bindings-equal
'((?x . nil) (?y . nil) (?z . (bar bar foo)))
(unify '(foo !?x foo !?y !?z bar) '(foo foo bar bar foo bar)))
(assert-equality
#'bindings-equal
'((?x . (a b)) (?y . c))
(unify '(!?x ?y) '(a b c)))
(assert-equality
#'bindings-equal '((?x . (a b))) (unify '(!?x ?x) '(a b (a b))))))
(define-test seg-form-like-patmatch-fail
(handler-bind ((warning #'muffle-warning))
(assert-false (nth-value 1 (unify '(!?x d) '(a b c))))
(assert-false (nth-value 1 (unify '(a (b !?x ?y) c) '(a (b) c))))
(assert-false (nth-value 1 (unify '(!?x) 'a)))
(assert-false (nth-value 1 (unify '(a !?x) '(a b . c))))))
(define-test seg-var-proper-list
(handler-bind ((warning #'muffle-warning))
(assert-false (nth-value 1 (unify '(a !?x) '(a b . c))))))
(define-test simple-unification
(assert-equality #'bindings-equal
'((?x . a) (?y . b))
(unify '(?x b) '(a ?y)))
(assert-equality #'bindings-equal
'((?x . ?y))
(unify '?x '?y))
(assert-equality #'bindings-equal
'((?x . a) (?y . a))
(unify '(?x ?y c) '(a ?x c))))
(define-test unusual-unification
(assert-equality
#'bindings-equal
'((?x . (?y)) (?y . a)) (unify '(?x ?y ?x) '((?y) a (a))))
(assert-equality #'bindings-equal
'((?x . c) (?y . b))
(unify '(a (b ?x) ?_) '(a (?y c) ?x)))
(assert-equality #'bindings-equal
'((?x . c) (?y . b))
(unify '(a (b ?x) . ?_) '(a (?y c) ?x ?y ?z)))
(handler-bind ((warning #'muffle-warning))
(assert-equality #'bindings-equal
'((?x . c) (?y . b))
(unify '(a (b ?x) . (!?_)) '(a (?y c) . (?x ?y ?z))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Unify and segvar issues
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; (unify '(?x !?x !y) '((b c d) b c d e f)) -> nil (should unify)
;;
CRS - TESTS > ( unify ' ( a ! ? x d ) ' ( ? y d ) )
;; ((?X) (?Y . A))
;; T
CRS - TESTS > ( unify ' ( a ! ? x d ) ' ( ? y foo d ) )
;; ((?X FOO) (?Y . A))
;; T
CRS - TESTS > ( unify ' ( a ! ? x d ) ' ( ? y ? z d ) )
;; ((?X ?Z) (?Y . A))
;; T
CRS - TESTS > ( unify ' ( a ! ? x d ? z ( e ) ) ' ( ? y ? z d e ? x ) )
NIL
NIL | null | https://raw.githubusercontent.com/cram-code/cram_core/984046abe2ec9e25b63e52007ed3b857c3d9a13c/cram_reasoning/tests/unify.lisp | lisp |
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
(unify '(?x !?x !y) '((b c d) b c d e f)) -> nil (should unify)
((?X) (?Y . A))
T
((?X FOO) (?Y . A))
T
((?X ?Z) (?Y . A))
T | Copyright ( c ) 2009 , < >
* Neither the name of Willow Garage , Inc. nor the names of its
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS "
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER OR
LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN
(in-package :crs-tests)
(define-test constant
(multiple-value-bind (result matched?)
(unify 'x 'x)
(assert-eq result nil)
(assert-true matched?)))
(define-test constant-fail
(assert-false (nth-value 1 (unify 'x 'y)))
(assert-false (nth-value 1 (unify '(a b) '(a b c))))
(assert-false (nth-value 1 (unify '(a b) '(a))))
(assert-false (nth-value 1 (unify '(a b c) '(a b foo)))))
(define-test like-patmatch
(multiple-value-bind (result matched?)
(unify '(?x b) '(a b))
(assert-equality #'bindings-equal result '((?x . a)))
(assert-true matched?)))
(define-test like-patmatch-fail
(assert-false (nth-value 1 (unify '(?x) 'a)))
(assert-false (nth-value 1 (unify '(?x ?x) '(a b))))
(assert-false (nth-value 1 (unify '(?x ?x) '(nil foo)))))
(define-test seg-form-errors
(assert-error 'simple-error (unify '!?foo 'bar))
(assert-error 'simple-error (unify 'bar '!?foo))
(assert-error 'simple-error (unify '(a . !?x) '(a . b)))
(assert-error 'simple-error (unify '(a . b) '(a . !?x))))
(define-test seg-form-like-patmatch
(handler-bind ((warning #'muffle-warning))
(assert-equality
#'bindings-equal '((?x b c)) (unify '(a !?x d) '(a b c d)))
(assert-equality
#'bindings-equal
'((?x . nil) (?y . nil) (?z . (bar bar foo)))
(unify '(foo !?x foo !?y !?z bar) '(foo foo bar bar foo bar)))
(assert-equality
#'bindings-equal
'((?x . (a b)) (?y . c))
(unify '(!?x ?y) '(a b c)))
(assert-equality
#'bindings-equal '((?x . (a b))) (unify '(!?x ?x) '(a b (a b))))))
(define-test seg-form-like-patmatch-fail
(handler-bind ((warning #'muffle-warning))
(assert-false (nth-value 1 (unify '(!?x d) '(a b c))))
(assert-false (nth-value 1 (unify '(a (b !?x ?y) c) '(a (b) c))))
(assert-false (nth-value 1 (unify '(!?x) 'a)))
(assert-false (nth-value 1 (unify '(a !?x) '(a b . c))))))
(define-test seg-var-proper-list
(handler-bind ((warning #'muffle-warning))
(assert-false (nth-value 1 (unify '(a !?x) '(a b . c))))))
(define-test simple-unification
(assert-equality #'bindings-equal
'((?x . a) (?y . b))
(unify '(?x b) '(a ?y)))
(assert-equality #'bindings-equal
'((?x . ?y))
(unify '?x '?y))
(assert-equality #'bindings-equal
'((?x . a) (?y . a))
(unify '(?x ?y c) '(a ?x c))))
(define-test unusual-unification
(assert-equality
#'bindings-equal
'((?x . (?y)) (?y . a)) (unify '(?x ?y ?x) '((?y) a (a))))
(assert-equality #'bindings-equal
'((?x . c) (?y . b))
(unify '(a (b ?x) ?_) '(a (?y c) ?x)))
(assert-equality #'bindings-equal
'((?x . c) (?y . b))
(unify '(a (b ?x) . ?_) '(a (?y c) ?x ?y ?z)))
(handler-bind ((warning #'muffle-warning))
(assert-equality #'bindings-equal
'((?x . c) (?y . b))
(unify '(a (b ?x) . (!?_)) '(a (?y c) . (?x ?y ?z))))))
Unify and segvar issues
CRS - TESTS > ( unify ' ( a ! ? x d ) ' ( ? y d ) )
CRS - TESTS > ( unify ' ( a ! ? x d ) ' ( ? y foo d ) )
CRS - TESTS > ( unify ' ( a ! ? x d ) ' ( ? y ? z d ) )
CRS - TESTS > ( unify ' ( a ! ? x d ? z ( e ) ) ' ( ? y ? z d e ? x ) )
NIL
NIL |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.