code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
-- | -- * Unit tests for guardedness module CoALP.Tests.Unit.Guards ( tests ) where import CoALP import CoALP.UI import qualified Data.Array as Array import Data.List import Control.Applicative --import Control.Concurrent import Test.Tasty import Test.Tasty.HUnit import System.Directory import System.IO.Unsafe logicExt :: String logicExt = ".logic" -- FIXME: The relative path works only from the root of the source tree where -- the .cabal file is located. Consider adding a command-line option to the test -- executable to pass the directory with programs. programsDir :: FilePath programsDir = "programs" programsGuarded :: FilePath programsGuarded = programsDir ++ "/guarded" programsUnguarded1 :: FilePath programsUnguarded1 = programsDir ++ "/unguarded/Check1" programsUnguarded2 :: FilePath programsUnguarded2 = programsDir ++ "/unguarded/Check2" programsUnguarded3 :: FilePath programsUnguarded3 = programsDir ++ "/unguarded/Check3" onFile :: (Program1 -> Bool) -> FilePath -> TestTree onFile prop file = testCase file $ do (cls, _) <- parseItemsFile file prop (Program $ Array.listArray (0, length cls - 1) cls) @?= True {-# NOINLINE testOnFiles #-} testOnFiles :: String -> (Program1 -> Bool) -> IO [FilePath] -> TestTree testOnFiles name prop filesIO = testGroup name $ onFile prop <$> unsafePerformIO filesIO {-# NOINLINE logicInDir #-} logicInDir :: FilePath -> IO [FilePath] logicInDir dir = getDirectoryContents dir >>= return . map ((++) (dir ++ "/")) . filter (isSuffixOf logicExt) tests :: TestTree tests = testGroup "Guardedness" [ testOnFiles "Programs unguarded in tier 2 check fail it" (not . guardedMatch) $ logicInDir programsUnguarded2 , testOnFiles "Programs unguarded in tier 2 check fail tier 3 check" (not . guardedResolution) $ logicInDir programsUnguarded2 , testOnFiles "Programs unguarded in tier 3 check pass tier 2 check" guardedMatch $ logicInDir programsUnguarded3 , testOnFiles "Programs unguarded in tier 3 check fail it" (not . guardedResolution) $ logicInDir programsUnguarded3 , testOnFiles "Guarded programs pass tier 2 check" guardedMatch $ logicInDir programsGuarded , testOnFiles "Guarded programs pass tier 3 check" guardedResolution $ logicInDir programsGuarded ]
vkomenda/CoALP
tests/CoALP/Tests/Unit/Guards.hs
lgpl-3.0
2,422
0
15
514
485
261
224
53
1
-- This program displays information about the platform import ViperVM.Platform.Configuration import ViperVM.Platform.Platform import ViperVM.Runtime.Logger main :: IO () main = do let logger = stdOutLogger . filterLevel LogDebug config = Configuration { libraryOpenCL = "/usr/lib/libOpenCL.so", eventHandler = \e -> logger (CustomLog (show e)) } putStrLn "Initializing platform..." platform <- initPlatform config putStrLn "Querying platform infos..." putStrLn (platformInfo platform)
hsyl20/HViperVM
apps/PlatformInfo.hs
lgpl-3.0
542
0
17
114
124
63
61
14
1
{-| This package provides functions for building and signing both simple transactions and multisignature transactions. -} module Network.Haskoin.Transaction ( module X ) where import Network.Haskoin.Transaction.Builder as X import Network.Haskoin.Transaction.Genesis as X import Network.Haskoin.Transaction.Types as X
xenog/haskoin
src/Network/Haskoin/Transaction.hs
unlicense
356
0
4
73
41
31
10
5
0
{-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-| Module : Haskoin.Script.Standard Copyright : No rights reserved License : MIT Maintainer : [email protected] Stability : experimental Portability : POSIX Standard scripts like pay-to-public-key, pay-to-public-key-hash, pay-to-script-hash, pay-to-multisig and corresponding SegWit variants. -} module Haskoin.Script.Standard ( -- * Standard Script Outputs ScriptOutput(..) , RedeemScript , isPayPK , isPayPKHash , isPayMulSig , isPayScriptHash , isPayWitnessPKHash , isPayWitnessScriptHash , isDataCarrier , encodeOutput , encodeOutputBS , decodeOutput , decodeOutputBS , toP2SH , toP2WSH , sortMulSig -- * Standard Script Inputs , ScriptInput(..) , SimpleInput(..) , encodeInput , encodeInputBS , decodeInput , decodeInputBS , isSpendPK , isSpendPKHash , isSpendMulSig , isScriptHashInput ) where import Control.Applicative ((<|>)) import Control.DeepSeq import Control.Monad (guard, liftM2, (<=<)) import qualified Data.Aeson as A import qualified Data.Aeson.Encoding as A import Data.ByteString (ByteString) import qualified Data.ByteString as BS import Data.Bytes.Get import Data.Bytes.Put import Data.Bytes.Serial import Data.Function (on) import Data.Hashable import Data.List (sortBy) import Data.Maybe (fromJust, isJust, isNothing) import Data.Word (Word8) import GHC.Generics (Generic) import Haskoin.Constants import Haskoin.Crypto import Haskoin.Keys.Common import Haskoin.Script.Common import Haskoin.Script.SigHash import Haskoin.Util -- | Data type describing standard transaction output scripts. Output scripts -- provide the conditions that must be fulfilled for someone to spend the funds -- in a transaction output. data ScriptOutput -- | pay to public key = PayPK { getOutputPubKey :: !PubKeyI } -- | pay to public key hash | PayPKHash { getOutputHash :: !Hash160 } -- | multisig | PayMulSig { getOutputMulSigKeys :: ![PubKeyI] , getOutputMulSigRequired :: !Int } -- | pay to a script hash | PayScriptHash { getOutputHash :: !Hash160 } -- | pay to witness public key hash | PayWitnessPKHash { getOutputHash :: !Hash160 } -- | pay to witness script hash | PayWitnessScriptHash { getScriptHash :: !Hash256 } -- | another pay to witness address | PayWitness { getWitnessVersion :: !Word8 , getWitnessData :: !ByteString } -- | provably unspendable data carrier | DataCarrier { getOutputData :: !ByteString } deriving (Eq, Show, Read, Generic, Hashable, NFData) instance A.FromJSON ScriptOutput where parseJSON = A.withText "scriptoutput" $ \t -> either fail return $ maybeToEither "scriptoutput not hex" (decodeHex t) >>= decodeOutputBS instance A.ToJSON ScriptOutput where toJSON = A.String . encodeHex . encodeOutputBS toEncoding = A.text . encodeHex . encodeOutputBS -- | Is script a pay-to-public-key output? isPayPK :: ScriptOutput -> Bool isPayPK (PayPK _) = True isPayPK _ = False -- | Is script a pay-to-pub-key-hash output? isPayPKHash :: ScriptOutput -> Bool isPayPKHash (PayPKHash _) = True isPayPKHash _ = False -- | Is script a pay-to-multi-sig output? isPayMulSig :: ScriptOutput -> Bool isPayMulSig (PayMulSig _ _) = True isPayMulSig _ = False -- | Is script a pay-to-script-hash output? isPayScriptHash :: ScriptOutput -> Bool isPayScriptHash (PayScriptHash _) = True isPayScriptHash _ = False -- | Is script a pay-to-witness-pub-key-hash output? isPayWitnessPKHash :: ScriptOutput -> Bool isPayWitnessPKHash (PayWitnessPKHash _) = True isPayWitnessPKHash _ = False -- | Is script a pay-to-witness-script-hash output? isPayWitnessScriptHash :: ScriptOutput -> Bool isPayWitnessScriptHash (PayWitnessScriptHash _) = True isPayWitnessScriptHash _ = False -- | Is script paying to a different type of witness address? isPayWitness :: ScriptOutput -> Bool isPayWitness (PayWitness _ _) = True isPayWitness _ = False -- | Is script a data carrier output? isDataCarrier :: ScriptOutput -> Bool isDataCarrier (DataCarrier _) = True isDataCarrier _ = False -- | Tries to decode a 'ScriptOutput' from a 'Script'. This can fail if the -- script is not recognized as any of the standard output types. decodeOutput :: Script -> Either String ScriptOutput decodeOutput s = case scriptOps s of -- Pay to PubKey [OP_PUSHDATA bs _, OP_CHECKSIG] -> PayPK <$> runGetS deserialize bs -- Pay to PubKey Hash [OP_DUP, OP_HASH160, OP_PUSHDATA bs _, OP_EQUALVERIFY, OP_CHECKSIG] -> PayPKHash <$> runGetS deserialize bs -- Pay to Script Hash [OP_HASH160, OP_PUSHDATA bs _, OP_EQUAL] -> PayScriptHash <$> runGetS deserialize bs -- Pay to Witness [OP_0, OP_PUSHDATA bs OPCODE] | BS.length bs == 20 -> PayWitnessPKHash <$> runGetS deserialize bs | BS.length bs == 32 -> PayWitnessScriptHash <$> runGetS deserialize bs | BS.length bs /= 20 && BS.length bs /= 32 -> Left "Version 0 segwit program must be 20 or 32 bytes long" -- Other Witness [ver, OP_PUSHDATA bs _] | isJust (opWitnessVersion ver) && BS.length bs >= 2 && BS.length bs <= 40 -> Right $ PayWitness (fromJust (opWitnessVersion ver)) bs -- Provably unspendable data carrier output [OP_RETURN, OP_PUSHDATA bs _] -> Right $ DataCarrier bs -- Pay to MultiSig Keys _ -> matchPayMulSig s witnessVersionOp :: Word8 -> Maybe ScriptOp witnessVersionOp 0 = Just OP_0 witnessVersionOp 1 = Just OP_1 witnessVersionOp 2 = Just OP_2 witnessVersionOp 3 = Just OP_3 witnessVersionOp 4 = Just OP_4 witnessVersionOp 5 = Just OP_5 witnessVersionOp 6 = Just OP_6 witnessVersionOp 7 = Just OP_7 witnessVersionOp 8 = Just OP_8 witnessVersionOp 9 = Just OP_9 witnessVersionOp 10 = Just OP_10 witnessVersionOp 11 = Just OP_11 witnessVersionOp 12 = Just OP_12 witnessVersionOp 13 = Just OP_13 witnessVersionOp 14 = Just OP_14 witnessVersionOp 15 = Just OP_15 witnessVersionOp 16 = Just OP_16 opWitnessVersion :: ScriptOp -> Maybe Word8 opWitnessVersion OP_0 = Just 0 opWitnessVersion OP_1 = Just 1 opWitnessVersion OP_2 = Just 2 opWitnessVersion OP_3 = Just 3 opWitnessVersion OP_4 = Just 4 opWitnessVersion OP_5 = Just 5 opWitnessVersion OP_6 = Just 6 opWitnessVersion OP_7 = Just 7 opWitnessVersion OP_8 = Just 8 opWitnessVersion OP_9 = Just 9 opWitnessVersion OP_10 = Just 10 opWitnessVersion OP_11 = Just 11 opWitnessVersion OP_12 = Just 12 opWitnessVersion OP_13 = Just 13 opWitnessVersion OP_14 = Just 14 opWitnessVersion OP_15 = Just 15 opWitnessVersion OP_16 = Just 16 opWitnessVersion _ = Nothing -- | Similar to 'decodeOutput' but decodes from a 'ByteString'. decodeOutputBS :: ByteString -> Either String ScriptOutput decodeOutputBS = decodeOutput <=< runGetS deserialize -- | Computes a 'Script' from a standard 'ScriptOutput'. encodeOutput :: ScriptOutput -> Script encodeOutput s = Script $ case s of -- Pay to PubKey (PayPK k) -> [opPushData $ runPutS $ serialize k, OP_CHECKSIG] -- Pay to PubKey Hash Address (PayPKHash h) -> [ OP_DUP , OP_HASH160 , opPushData $ runPutS $ serialize h , OP_EQUALVERIFY, OP_CHECKSIG ] -- Pay to MultiSig Keys (PayMulSig ps r) | r <= length ps -> let opM = intToScriptOp r opN = intToScriptOp $ length ps keys = map (opPushData . runPutS . serialize) ps in opM : keys ++ [opN, OP_CHECKMULTISIG] | otherwise -> error "encodeOutput: PayMulSig r must be <= than pkeys" -- Pay to Script Hash Address (PayScriptHash h) -> [ OP_HASH160, opPushData $ runPutS $ serialize h, OP_EQUAL] -- Pay to Witness PubKey Hash Address (PayWitnessPKHash h) -> [ OP_0, opPushData $ runPutS $ serialize h ] (PayWitnessScriptHash h) -> [ OP_0, opPushData $ runPutS $ serialize h ] (PayWitness v h) -> [ case witnessVersionOp v of Nothing -> error "encodeOutput: invalid witness version" Just c -> c , opPushData h ] -- Provably unspendable output (DataCarrier d) -> [OP_RETURN, opPushData d] -- | Similar to 'encodeOutput' but encodes to a ByteString encodeOutputBS :: ScriptOutput -> ByteString encodeOutputBS = runPutS . serialize . encodeOutput -- | Encode script as pay-to-script-hash script toP2SH :: Script -> ScriptOutput toP2SH = PayScriptHash . addressHash . runPutS . serialize -- | Encode script as a pay-to-witness-script-hash script toP2WSH :: Script -> ScriptOutput toP2WSH = PayWitnessScriptHash . sha256 . runPutS . serialize -- | Match @[OP_N, PubKey1, ..., PubKeyM, OP_M, OP_CHECKMULTISIG]@ matchPayMulSig :: Script -> Either String ScriptOutput matchPayMulSig (Script ops) = case splitAt (length ops - 2) ops of (m:xs,[n,OP_CHECKMULTISIG]) -> do (intM,intN) <- liftM2 (,) (scriptOpToInt m) (scriptOpToInt n) if intM <= intN && length xs == intN then liftM2 PayMulSig (go xs) (return intM) else Left "matchPayMulSig: Invalid M or N parameters" _ -> Left "matchPayMulSig: script did not match output template" where go (OP_PUSHDATA bs _:xs) = liftM2 (:) (runGetS deserialize bs) (go xs) go [] = return [] go _ = Left "matchPayMulSig: invalid multisig opcode" -- | Sort the public keys of a multisig output in ascending order by comparing -- their compressed serialized representations. Refer to BIP-67. sortMulSig :: ScriptOutput -> ScriptOutput sortMulSig out = case out of PayMulSig keys r -> PayMulSig (sortBy (compare `on` (runPutS . serialize)) keys) r _ -> error "Can only call orderMulSig on PayMulSig scripts" -- | Data type describing standard transaction input scripts. Input scripts -- provide the signing data required to unlock the coins of the output they are -- trying to spend, except in pay-to-witness-public-key-hash and -- pay-to-script-hash transactions. data SimpleInput = SpendPK { getInputSig :: !TxSignature -- ^ transaction signature } | SpendPKHash { getInputSig :: !TxSignature -- ^ embedded signature , getInputKey :: !PubKeyI -- ^ public key } | SpendMulSig { getInputMulSigKeys :: ![TxSignature] -- ^ list of signatures } deriving (Eq, Show, Generic, NFData) -- | Returns true if the input script is spending from a pay-to-public-key -- output. isSpendPK :: ScriptInput -> Bool isSpendPK (RegularInput (SpendPK _)) = True isSpendPK _ = False -- | Returns true if the input script is spending from a pay-to-public-key-hash -- output. isSpendPKHash :: ScriptInput -> Bool isSpendPKHash (RegularInput (SpendPKHash _ _)) = True isSpendPKHash _ = False -- | Returns true if the input script is spending a multisig output. isSpendMulSig :: ScriptInput -> Bool isSpendMulSig (RegularInput (SpendMulSig _)) = True isSpendMulSig _ = False -- | Returns true if the input script is spending a pay-to-script-hash output. isScriptHashInput :: ScriptInput -> Bool isScriptHashInput (ScriptHashInput _ _) = True isScriptHashInput _ = False -- | A redeem script is the output script serialized into the spending input -- script. It must be included in inputs that spend pay-to-script-hash outputs. type RedeemScript = ScriptOutput -- | Standard input script high-level representation. data ScriptInput = RegularInput { getRegularInput :: !SimpleInput -- ^ get wrapped simple input } | ScriptHashInput { getScriptHashInput :: !SimpleInput -- ^ get simple input associated with redeem script , getScriptHashRedeem :: !RedeemScript -- ^ redeem script } deriving (Eq, Show, Generic, NFData) -- | Heuristic to decode an input script into one of the standard types. decodeSimpleInput :: Network -> Script -> Either String SimpleInput decodeSimpleInput net (Script ops) = maybeToEither errMsg $ matchPK ops <|> matchPKHash ops <|> matchMulSig ops where matchPK [op] = SpendPK <$> f op matchPK _ = Nothing matchPKHash [op, OP_PUSHDATA pub _] = SpendPKHash <$> f op <*> eitherToMaybe (runGetS deserialize pub) matchPKHash _ = Nothing matchMulSig (x:xs) = do guard $ x == OP_0 SpendMulSig <$> mapM f xs matchMulSig _ = Nothing f OP_0 = return TxSignatureEmpty f (OP_PUSHDATA "" OPCODE) = f OP_0 f (OP_PUSHDATA bs _) = eitherToMaybe $ decodeTxSig net bs f _ = Nothing errMsg = "decodeInput: Could not decode script input" -- | Heuristic to decode a 'ScriptInput' from a 'Script'. This function fails if -- the script can not be parsed as a standard script input. decodeInput :: Network -> Script -> Either String ScriptInput decodeInput net s@(Script ops) = maybeToEither errMsg $ matchSimpleInput <|> matchPayScriptHash where matchSimpleInput = RegularInput <$> eitherToMaybe (decodeSimpleInput net s) matchPayScriptHash = case splitAt (length (scriptOps s) - 1) ops of (is, [OP_PUSHDATA bs _]) -> do rdm <- eitherToMaybe $ decodeOutputBS bs inp <- eitherToMaybe $ decodeSimpleInput net $ Script is return $ ScriptHashInput inp rdm _ -> Nothing errMsg = "decodeInput: Could not decode script input" -- | Like 'decodeInput' but decodes directly from a serialized script -- 'ByteString'. decodeInputBS :: Network -> ByteString -> Either String ScriptInput decodeInputBS net = decodeInput net <=< runGetS deserialize -- | Encode a standard input into a script. encodeInput :: ScriptInput -> Script encodeInput s = case s of RegularInput ri -> encodeSimpleInput ri ScriptHashInput i o -> Script $ scriptOps (encodeSimpleInput i) ++ [opPushData $ encodeOutputBS o] -- | Similar to 'encodeInput' but encodes directly to a serialized script -- 'ByteString'. encodeInputBS :: ScriptInput -> ByteString encodeInputBS = runPutS . serialize . encodeInput -- | Encode a standard 'SimpleInput' into opcodes as an input 'Script'. encodeSimpleInput :: SimpleInput -> Script encodeSimpleInput s = Script $ case s of SpendPK ts -> [f ts] SpendPKHash ts p -> [f ts, opPushData $ runPutS $ serialize p] SpendMulSig xs -> OP_0 : map f xs where f TxSignatureEmpty = OP_0 f ts = opPushData $ encodeTxSig ts
haskoin/haskoin
src/Haskoin/Script/Standard.hs
unlicense
15,179
0
17
3,838
3,284
1,723
1,561
313
9
module Network.NSFW.Firewall.Config ( Config(..) , loadConfig , showConfigParseError ) where import Control.Monad.Except (join, liftIO, runExceptT) import Data.ConfigFile (CPError, emptyCP, get, readfile) import Data.Default (Default, def) -- | Configuration data. data Config = Config { getLogLevel :: Int } deriving (Eq, Read, Show) instance Default Config where def = Config 0 loadConfig :: IO (Either CPError Config) loadConfig = runExceptT $ do cp <- join $ liftIO $ readfile emptyCP "/etc/nsfw/nsfw.cfg" logLevel <- get cp "DEFAULT" "log_level" return $ Config logLevel showConfigParseError :: CPError -> IO () showConfigParseError err = do putStrLn "Error when parsing NSFW configuration file:" putStrLn $ "\t" ++ show err
m-renaud/NSFW
src/Network/NSFW/Firewall/Config.hs
bsd-2-clause
779
0
10
152
230
124
106
21
1
{-# LANGUAGE FlexibleInstances #-} module Jira2Sheet.Types.Input where import Control.Monad.Except (ExceptT (..)) import Control.Monad.Log (LoggingT) import Control.Monad.Trans.Class (lift) import Control.Monad.Trans.Maybe (MaybeT (..)) import System.Console.Haskeline (InputT, defaultSettings, runInputT) import qualified System.Console.Haskeline as Haskeline import UnexceptionalIO (UIO, unsafeFromIO) class (Monad m) => MonadInput m where getInputLine :: String -> m String getPassword :: Maybe Char -> String -> m String getPassword' :: (MonadInput m) => String -> m String getPassword' = getPassword (Just '*') runInput :: InputT IO (Maybe a) -> MaybeT UIO a -- TODO add back MonadException, convert to MonadError? runInput = MaybeT . unsafeFromIO . runInputT defaultSettings instance MonadInput (MaybeT UIO) where getInputLine = runInput . Haskeline.getInputLine getPassword c = runInput . Haskeline.getPassword c instance (MonadInput m) => MonadInput (LoggingT message m) where getInputLine = lift . getInputLine getPassword c = lift . getPassword c instance (MonadInput m) => MonadInput (ExceptT e m) where getInputLine = lift . getInputLine getPassword c = lift . getPassword c
berdario/jira2sheet
src/Jira2Sheet/Types/Input.hs
bsd-3-clause
1,315
0
9
284
365
201
164
25
1
{-# LANGUAGE OverloadedStrings #-} module XML where import Types ( Book(..) ) import Text.XML.Lens import Text.XML import Data.Maybe ( catMaybes ) import Data.Text ( Text ) import Data.Monoid ( (<>) ) import Control.Applicative import Control.Lens.Combinators ( lengthOf ) import Control.Lens.Lens ( (??) ) import Control.Lens.Fold ( (^..) , (^?) ) {- Functions for translating XML elements into objects. E.g. "book". -} numReviews :: Document -> Int numReviews doc = lengthOf ?? doc $ root . el "GoodreadsResponse" ... el "reviews" ... el "review" tities :: Document -> [Text] tities doc = doc ^.. root . el "GoodreadsResponse" ... el "reviews" ... el "review" ... el "book" ... el "title" . text parseBookInfo :: Document -> Maybe Text --Either String String parseBookInfo doc = doc ^? root . el "GoodreadsResponse" ... el "book" ... el "description" . text parseBookSearch :: Document -> Either String [Book] parseBookSearch doc = let bookElems = doc ^.. root . el "GoodreadsResponse" ... el "search" ... el "results" ... el "work" books = catMaybes $ fmap parseFindBook bookElems in if null bookElems then Left $ "Unable to parse any items from " <> show doc else if (length bookElems) /= (length books) then Left $ "Unable to parse all items from " <> show bookElems else Right books parseFindBook :: Element -> Maybe Book parseFindBook e = Book <$> t "title" <*> Just (t "id") where t n = e ^? el "work" ... el "best_book" ... el n . text parseGoodreadsFeed :: Document -> Either String [Book] parseGoodreadsFeed doc = let bookElems = doc ^.. root . el "GoodreadsResponse" ... el "reviews" ... el "review" books = catMaybes $ fmap parseBook bookElems in if null bookElems then Left $ "Unable to parse any items from " <> show doc else if (length bookElems) /= (length books) then Left $ "Unable to parse all items from " <> show bookElems else Right books parseBook :: Element -> Maybe Book parseBook e = Book <$> t "title" <*> Just (t "id") where t n = e ^? el "review" ... el "book" ... el n . text
jmn/goodreads
src/XML.hs
bsd-3-clause
2,551
0
13
894
694
353
341
-1
-1
-- | -- Module : Data.Boolean.DPLL -- Copyright : Holger Siegel -- License : BSD3 -- module Data.Boolean.DPLL ( Solvable, fromProposition, fromDimacs, conjunction, nextLiteral, freeze, isSatisfied, ) where import Data.Boolean.Proposition(Proposition) import Data.Boolean.Dimacs(Dimacs) class Solvable a where fromProposition :: Proposition -> a fromDimacs :: Dimacs -> a conjunction :: a -> a -> a -- | -- Finds the next literal to be specialized. -- If the result is positve, then the non-negated literal -- will be tried with higher priority by the solver. -- Otherwise the negated literal will be preferred. -- -- The first component of the result is the number of times -- the literal occurs in the current clause. The second component -- is the varibale index of the literal. -- -- Returns @(0, 0)@ if there is no clause to be satisfied. nextLiteral :: a -> (Int, Int) -- | -- @freeze n b@ returns a copy of @b@ in which every literal with index -- @n@ is set to @True@ and every literal with index @(-n)@ is set to @False@. freeze :: Int -> a -> a -- | -- This monadic action checks whether the @SatSolver@ has found a solution. -- If all constraints are solved, then it returns @True@. -- If there are unsolved constraints, then it returns @False@. -- It @fail@s when the given constraints are known to be unsatisfiable. isSatisfied :: Monad m => a -> m Bool
hsiegel/incremental-sat-solver
Data/Boolean/DPLL.hs
bsd-3-clause
1,514
0
9
385
164
105
59
12
0
module CallByReference.ParserSuite ( tests ) where import CallByReference.Data import CallByReference.Parser import Test.HUnit.Base import Text.Megaparsec import Text.Megaparsec.String tests :: Test tests = TestList [ TestLabel "Test const expression" testConstExpr , TestLabel "Test binary-operator expression" testBinOpExpr , TestLabel "Test unary-operator expression" testUnaryOpExpr , TestLabel "Test condition expression" testCondExpr , TestLabel "Test var expression" testVarExpr , TestLabel "Test let expression" testLetExpr , TestLabel "Test expression" testExpression , TestLabel "Test parse program" testParseProgram , TestLabel "Test parse proc expression" testParseProc ] constNum = ConstExpr . ExprNum constBool = ConstExpr . ExprBool parserEqCase :: (Eq a, Show a) => Parser a -> String -> a -> String -> Test parserEqCase parser msg expect input = TestCase $ assertEqual msg (Right expect) runP where runP = runParser parser "Test equal case" input parserFailCase :: (Eq a, Show a) => Parser a -> String -> String -> Test parserFailCase parser msg input = TestCase $ assertBool msg (isLeft runP) where isLeft (Left _) = True isLeft (Right _) = False runP = runParser parser "Test fail case" input testEq :: String -> Expression -> String -> Test testEq = parserEqCase expression testFail :: String -> String -> Test testFail = parserFailCase expression testConstExpr :: Test testConstExpr = TestList [ testEq "Parse single number" (constNum 5) "5" , testEq "Parse multi-numbers" (constNum 123) "123" , testEq "Parse negative number" (constNum (-233)) "-233" ] testBinOpExpr :: Test testBinOpExpr = TestList [ testEq "Parse '-' expression (no space)" (BinOpExpr Sub (constNum 3) (constNum 4)) "-(3,4)" , testEq "Parse '*' expression (with spaces)" (BinOpExpr Mul (constNum 10) (constNum 24)) "* ( 10 , 24 )" , testEq "Parse binary num-to-bool expression" (BinOpExpr Gt (constNum 1) (constNum 2)) "greater?(1, 2)" ] testUnaryOpExpr :: Test testUnaryOpExpr = TestList [ testEq "Parse isZero expression (no space)" (UnaryOpExpr IsZero (constNum 1)) "zero?(1)" , testEq "Parse isZero expression (with space)" (UnaryOpExpr IsZero (constNum 3)) "zero? ( 3 )" , testEq "Parse minus expression" (UnaryOpExpr Minus (constNum 1)) "minus(1)" ] testCondExpr :: Test testCondExpr = TestList [ testEq "Parse if expression" (CondExpr [ (UnaryOpExpr IsZero (constNum 3), constNum 4) , (constBool True, constNum 5) ]) "if zero?(3) then 4 else 5" , testEq "Parse cond expression" (CondExpr [ (UnaryOpExpr IsZero (constNum 3), constNum 4) , (BinOpExpr Gt (constNum 3) (constNum 5), constNum 4) , (UnaryOpExpr IsZero (constNum 0), constNum 4) ]) $ unlines [ "cond zero?(3) ==> 4\n" , " greater?(3, 5) ==> 4\n" , " zero?(0) ==> 4\n" , "end" ] ] testVarExpr :: Test testVarExpr = TestList [ testEq "Parse var expression" (VarExpr "foo") "foo" , testFail "Parse reserved word should fail" "then" ] testLetExpr :: Test testLetExpr = TestList [ testEq "Parse let expression with 0 binding" (LetExpr [] (VarExpr "bar")) "let in bar" , testEq "Parse let expression with 1 binding" (LetExpr [("bar", constNum 1)] (VarExpr "bar")) "let bar = 1 in bar" , testEq "Parse let expression with multi bindings" (LetExpr [("x", constNum 1), ("y", constNum 2), ("z", constNum 3)] (VarExpr "bar")) "let x = 1 y = 2 z = 3 in bar" , testEq "Parse let recursive expression" (LetRecExpr [("double", ["xxx"], BinOpExpr Mul (constNum 2) (VarExpr "xxx"))] (CallExpr (VarExpr "double") [constNum 5])) "letrec double(xxx) = *(2, xxx) in (double 5)" ] testExpression :: Test testExpression = TestList [ testEq "Parse complex expression" (LetExpr [("bar", constNum 1)] (CondExpr [ (UnaryOpExpr IsZero (VarExpr "bar"), constNum 3) , (constBool True, VarExpr "zero") ])) "let bar = 1 in if zero? (bar) then 3 else zero" ] testParseProgram :: Test testParseProgram = TestList [ testEq "Parse program (with spaces)" (Prog (LetExpr [("x", constNum 3)] (VarExpr "x"))) "let x = 3 in x" ] where testEq msg expect prog = TestCase $ assertEqual msg (Right expect) (parseProgram prog) testParseProc :: Test testParseProc = TestList [ testEq "Parse proc expression" (ProcExpr ["x"] (VarExpr "x")) "proc (x) x" , testEq "Parse call expression" (CallExpr (ProcExpr ["f"] (CallExpr (VarExpr "f") [CallExpr (VarExpr "f") [constNum 77]])) [ProcExpr ["x"] (BinOpExpr Sub (VarExpr "x") (constNum 11))]) "(proc (f) (f (f 77)) proc (x) -(x,11))" ]
li-zhirui/EoplLangs
test/CallByReference/ParserSuite.hs
bsd-3-clause
5,237
0
17
1,509
1,371
712
659
124
2
import System.CPUTime import Data.Time.Calendar import Data.List data DataTypes = Boolean Bool | Double Double | Date Int | String String | Int Int deriving (Eq, Show) type Record = [DataTypes] type Table = [Record] gs :: DataTypes -> String gs (String s) = s -- sort by 2nd column: stupidSort = sortBy (\x y -> compare (gs $ x!!1) (gs $ y!!1) ) -- then we add groupBy over the sorted list and then can do different folds - that should cover pivot functionality testTable = [ [Double 2435, String "NA", Date 1, Boolean True, Int 1241], [Double 52435, String "EM", Date 3, Boolean True], [Double 142435, String "EMEA", Date 1, Boolean True, Int 131], [Double 22535, String "NA", Date 2, Boolean True, Int 141], [Double 9435, String "EMEA", Date 2] ] -- Naive Graph based on JValue. Eventually, we may want to add support for Haskell datatypes via type classes ('synchronizable or something') data KValue = KString String | KNumber Double | KBool Bool | KNull | KArray [KValue] deriving (Eq, Ord, Show) type KVP = [(String, KValue)] getString :: KValue -> Maybe String getString (KString s) = Just s getString _ = Nothing getInt (KNumber n) = Just (truncate n) getInt _ = Nothing getDouble (KNumber n) = Just n getDouble _ = Nothing getBool (KBool b) = Just b getBool _ = Nothing getArray (KArray a) = Just a getArray _ = Nothing isNull v = v == KNull -- stub for typical Graph functions: to be expanded and used for testing with different backends -- stupid placeholder for now type Graph = Int type Node = Int type Edge = Int type GValue = KVP -- checks if 2 nodes are adjacent adjacent :: Graph -> Node -> Node -> Bool adjacent g x y = True -- gets all neighboring nodes neighbors :: Graph -> Node -> [Node] neighbors g x = [] -- add and delete an edge between 2 nodes add :: Graph -> Node -> Node -> Bool add g x y = True delete :: Graph -> Node -> Node -> Bool delete g x y = True -- manipulating Node and Edge values: getNodeValue :: Graph -> Node -> GValue getNodeValue g x = [] getEdgeValue :: Graph -> Node -> Node -> GValue getEdgeValue g x y = [] setNodeValue :: Graph -> Node -> GValue -> Bool setNodeValue g x v = True setEdgeValue :: Graph -> Node -> Node -> GValue -> Bool setEdgeValue g x y v = True
superstringsoftware/HasGraph
experiments/Data.hs
bsd-3-clause
2,379
12
11
588
798
426
372
54
1
module Identifiers ( Imsi (..), genImsi, genRandId ) where import System.Random import Control.Monad.IO.Class () import Data.Binary -- IMSI data Imsi = Imsi { mcc :: !String, mnc :: !String, msin :: !String } deriving (Eq) instance Show Imsi where show m = show ((mcc m)++"-"++(mnc m)++"-"++(msin m)) instance Binary Imsi where put m = do put (mcc m) put (mnc m) put (msin m) get = do mccTemp <- get mncTemp <- get msinTemp <- get return (Imsi mccTemp mncTemp msinTemp) genImsi :: Int -> Int -> Imsi genImsi seed1 seed2= --all the imsi are swedish ones Imsi {mcc = "260", mnc = genRandId 2 seed1 , msin = genRandId 10 seed2} -- Random id string genRandId :: Int -> Int -> String genRandId size seed = take size (randomRs ('0','9') (mkStdGen seed))
Ilydocus/frp-prototype
src/Identifiers.hs
bsd-3-clause
1,005
0
13
390
330
174
156
36
1
module Lang.TypeChecker.Waldmeister where import Lang.TypeChecker.TypeChecker waldmeister :: Text -> Term -> StateT TCMState m Bool waldmeister = undefined
Alasdair/Mella
Lang/TypeChecker/Waldmeister.hs
bsd-3-clause
157
0
7
19
38
22
16
4
1
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DuplicateRecordFields #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE OverloadedStrings #-} module Serv.Server.Core.HealthTypes ( HealthResponse(..) , healthUp , healthDown ) where import Control.Lens import Data.Aeson import Data.Text (Text) import GHC.Generics import Servant.API -- | HealthStatus data HealthStatus = UP | DOWN deriving (Generic, Show) instance FromJSON HealthStatus instance ToJSON HealthStatus -- | HealthResponse data HealthResponse = HealthResponse { status::HealthStatus } deriving (Generic, Show) instance FromJSON HealthResponse instance ToJSON HealthResponse healthUp::HealthResponse healthUp = HealthResponse UP healthDown::HealthResponse healthDown = HealthResponse DOWN
orangefiredragon/bear
src/Serv/Server/Core/HealthTypes.hs
bsd-3-clause
860
0
8
208
160
93
67
27
1
{-# LANGUAGE ScopedTypeVariables, Rank2Types #-} module Lseed.Geometry where import Lseed.Data import Lseed.Data.Functions import Lseed.Constants import Lseed.Geometry.Generator import Data.List import Data.Maybe import Data.Ord import qualified Data.Map as M import qualified Data.Foldable as F import Control.Monad hiding (mapM,forM) import Data.Traversable (mapM,forM) import Prelude hiding (mapM) import Control.Monad.ST import Data.STRef import Control.Applicative type Point = (Double, Double) type Line = (Point, Point) lineLength ((x1,y1),(x2,y2)) = sqrt ((x1-x2)^2 + (y1-y2)^2) -- | from http://www.pdas.com/lineint.htm crossPoint :: Line -> Line -> Maybe Point crossPoint ((x1,y1),(x2,y2)) ((x3,y3),(x4,y4)) = let a1 = y2-y1 b1 = x1-x2 c1 = x2*y1 - x1*y2 -- { a1*x + b1*y + c1 = 0 is line 1 } a2 = y4-y3 b2 = x3-x4 c2 = x4*y3 - x3*y4 -- { a2*x + b2*y + c2 = 0 is line 2 } denom = a1*b2 - a2*b1 in if abs denom > eps then let x = (b1*c2 - b2*c1)/denom y = (a2*c1 - a1*c2)/denom in if x1 <= x && x <= x2 && y1 <= y && y <= y2 && x3 <= x && x <= x4 && y3 <= y && y <= y4 then Just (x,y) else Nothing else Nothing plantedToLines :: Planted a -> [(Line, a)] plantedToLines planted = runGeometryGenerator (plantPosition planted, 0) 0 $ plantToGeometry (phenotype planted) plantToGeometry :: Plant a -> GeometryGenerator a () plantToGeometry (Plant x len ang _ ps) = rotated ang $ do addLine x ((0,0),(0,len * stipeLength)) translated (0,len * stipeLength) $ mapM_ plantToGeometry ps -- | Lines are annotated with its plant, identified by the extra data gardenToLines :: Garden a -> [(Line, a)] gardenToLines = concatMap (\planted -> plantedToLines planted) -- | Add lightning from a given angle lightenLines :: Double -> [(Line, a)] -> [(Line, a, Double)] lightenLines angle lines = let (lighted,_) = allKindsOfStuffWithAngle angle lines in lighted lightPolygons :: Double -> [(Line, a)] -> [(Point,Point,Point,Point,Double)] lightPolygons angle lines = let (_,polygons) = allKindsOfStuffWithAngle angle lines in polygons allKindsOfStuffWithAngle :: forall a. Double -> [(Line, a)] -> ( [(Line, a, Double)] , [(Point,Point,Point,Point,Double)] ) allKindsOfStuffWithAngle angle lines = (lighted, polygons) where projectLine :: Line -> (Double, Double) projectLine (p1, p2) = (projectPoint p1, projectPoint p2) projectTan :: Double projectTan = 1 / tan (pi-angle) projectPoint :: Point -> Double projectPoint (x,y) = x + y * projectTan -- False means Beginning of Line sweepPoints :: [(Double, Bool, (Line, a))] sweepPoints = sortBy (comparing (\(a,b,_)->(a,b))) $ concatMap (\l@((p1,p2),i) -> if abs (projectPoint p1 - projectPoint p2) < eps then [] else if projectPoint p1 < projectPoint p2 then [(projectPoint p1,False,l), (projectPoint p2,True,l)] else [(projectPoint p2,False,l), (projectPoint p1,True,l)] ) lines -- Find all crossing points crossings :: [Double] crossings = case mapAccumL step [] sweepPoints of ([],crosses) -> nub (sort (concat crosses)) _ -> error "Lines left open after sweep" where -- accumulator is open lines, return is list of cross points step :: [Line] -> (Double, Bool, (Line, a)) -> ([Line], [Double]) step [] (_, True, _) = error $ "Line ends with no lines open" -- Beginning of a new line, mark it as open, and mark it as a cross-point step ol (x, False, (l,_)) = (l:ol, [x]) -- End of a line. Calculate crosses with all open line, and remove it from the -- list of open lines step ol (x, True, (l,_)) = let ol' = delete l ol crosses = map projectPoint $ mapMaybe (crossPoint l) ol' in (ol', x:crosses) -- Cross points inverval intervals = zip crossings (tail crossings) unlighted = map (\(l,i) -> (l,i,0)) lines unprojectPoint x (p1@(x1,y1),p2@(x2,y2)) = let t = (x - projectPoint p1) / (projectPoint p2 - projectPoint p1) in (x1 + t * (x2-x1), y1 + t * (y2-y1)) lineAtRay x l = let (x1',x2') = projectLine l in abs (x1' - x2') > eps && -- avoid lines that parallel to the rays (x1' <= x && x <= x2' || x2' <= x && x <= x1') aboveFirst x l1 l2 = let (_,y1) = unprojectPoint x l1 (_,y2) = unprojectPoint x l2 in y2 `compare` y1 lighted :: [(Line, a, Double)] lighted = foldl go unlighted intervals where go llines (x1,x2) = curlines' ++ otherlines where -- Calculation based on the ray at the mid point mid = (x1 + x2) / 2 -- Light intensity width = abs ((x2 - x1) * sin angle) * lightIntensity (curlines, otherlines) = partition (\(l,_,_) -> lineAtRay mid l) llines sorted = sortBy (\(l1,_,_) (l2,_,_) -> aboveFirst mid l1 l2) curlines curlines' = snd $ mapAccumL shine width sorted shine intensity (l,i,amount) = (intensity * lightFalloff, (l,i,amount + (1-lightFalloff) * intensity)) lightIntensity = sin angle polygons = concatMap go intervals where go (x1,x2) = if null sorted then [nothingPoly] else lightedPolys where mid = (x1 + x2) / 2 curlines = filter (lineAtRay mid) (map fst lines) sorted = sortBy (aboveFirst mid) curlines ceiling = ((0,10),(1,10)) floor = ((0,0),(1,0)) nothingPoly = let p1 = unprojectPoint x1 ceiling p2 = unprojectPoint x1 floor p3 = unprojectPoint x2 floor p4 = unprojectPoint x2 ceiling in (p1,p2,p3,p4, lightIntensity) firstPoly = let p1 = unprojectPoint x1 ceiling p2 = unprojectPoint x1 (head sorted) p3 = unprojectPoint x2 (head sorted) p4 = unprojectPoint x2 ceiling in (p1,p2,p3,p4) lastPoly = let p1 = unprojectPoint x1 (last sorted) p2 = unprojectPoint x1 floor p3 = unprojectPoint x2 floor p4 = unprojectPoint x2 (last sorted) in (p1,p2,p3,p4) polys = zipWith (\l1 l2 -> let p1 = unprojectPoint x1 l1 p2 = unprojectPoint x1 l2 p3 = unprojectPoint x2 l2 p4 = unprojectPoint x2 l1 in (p1,p2,p3,p4)) sorted (tail sorted) polys' = [firstPoly] ++ polys ++ [lastPoly] lightedPolys = snd $ mapAccumL shine lightIntensity polys' shine intensity (p1,p2,p3,p4) = ( intensity * lightFalloff , (p1,p2,p3,p4,intensity)) -- | Annotates each piece of the garden with the amount of line it attacts lightenGarden :: Angle -> Garden a -> Garden (a, Double) lightenGarden angle = mapLine (lightenLines angle) 0 (+) -- | Helper to apply a function that works on lines to a garden mapLine :: (forall b. [(Line, b)] -> [(Line, b, c)]) -> c -> (c -> c -> c) -> Garden a -> Garden (a,c) mapLine process init combine garden = runST $ do gardenWithPointers <- mapM (mapM (\d -> (,) d <$> newSTRef init)) garden let linesWithPointers = gardenToLines gardenWithPointers let processedLines = process linesWithPointers -- Update values via the STRef forM_ processedLines $ \(_,(_,stRef),result) -> modifySTRef stRef (combine result) -- Undo the STRefs mapM (mapM (\(d,stRef) -> (,) d <$> readSTRef stRef)) gardenWithPointers -- | Slightly shifts angles windy s = mapGarden (mapPlanted (go 0)) where go d p = let a' = pAngle p + windFactor * offset * pLength p * cos (d + pAngle p) d' = (d+a') in p { pAngle = a' , pData = (pData p) { siDirection = d' } , pBranches = map (go d') (pBranches p) } offset = sin (windChangeFrequency * s) windFactor = 0.015 windChangeFrequency = 1 -- | For a Garden, calculates the maximum size to the left, to the right, and -- maximum height gardenOffset :: AnnotatedGarden -> (Double, Double, Double) gardenOffset = pad . F.foldr max3 (0.5,0.5,0) . map (F.foldr max3 (0.5,0.5,0) . go ) where go planted = fmap (\si -> ( siOffset si + plantPosition planted , siOffset si + plantPosition planted , siHeight si ) ) planted max3 (a,b,c) (a',b',c') = (min a a', max b b', max c c') pad (a,b,c) = (a-0.02,b+0.02,c+0.02)
nomeata/L-seed
src/Lseed/Geometry.hs
bsd-3-clause
8,745
154
26
2,585
3,145
1,774
1,371
169
7
{-# LANGUAGE OverloadedStrings #-} module Radio.Util( getElementPosition , styleBlock , getMousePosition , getDocumentSize , cbutton , cbuttonM , timeout , clearTimers , wloop , panel , labelRow ) where import Prelude hiding (div, id) import Haste import Haste.Foreign import Haste.App (MonadIO) import Haste.Prim import Control.Applicative import Control.Monad.IO.Class (liftIO) import Control.Monad import Data.Monoid import Haste.Perch (ToElem, Perch, nelem, child, span) import Haste.HPlay.View hiding (head) import System.IO.Unsafe (unsafePerformIO) import Data.IORef import Unsafe.Coerce newtype JQuery = JQuery JSAny newtype JPosition = JPosition JSAny newtype JMouse = JMouse JSAny newtype JDocument = JDocument JSAny jsJquery :: JSString -> IO JQuery jsJquery v = JQuery <$> ffi "(function(e) {return $(e);})" v jsOffset :: JQuery -> IO JPosition jsOffset (JQuery jsany) = JPosition <$> ffi "(function(jq) {return jq.offset();})" jsany jsLeft :: JPosition -> IO Int jsLeft (JPosition jsany) = ffi "(function(jp) {return jp.left;})" jsany jsTop :: JPosition -> IO Int jsTop (JPosition jsany) = ffi "(function(jp) {return jp.top;})" jsany jsMouse :: IO JMouse jsMouse = JMouse <$> ffi "(function() {return mouse;})" jsMouseX :: JMouse -> IO Int jsMouseX (JMouse jsany) = ffi "(function(m) {return m.x;})" jsany jsMouseY :: JMouse -> IO Int jsMouseY (JMouse jsany) = ffi "(function(m) {return m.y;})" jsany jsDocument :: IO JDocument jsDocument = JDocument <$> ffi "(function() {return document.documentElement;})" jsPageScrollX :: JDocument -> IO Int jsPageScrollX (JDocument jsany) = ffi "(function(doc) {return (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0);})" jsany jsPageScrollY :: JDocument -> IO Int jsPageScrollY (JDocument jsany) = ffi "(function(doc) {return (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0);})" jsany jsDocumentWidth :: IO Int jsDocumentWidth = ffi "(function() {return $(document).width();})" jsDocumentHeight :: IO Int jsDocumentHeight = ffi "(function() {return $(document).height();})" jsSetOnPageLoad :: JSFun a -> IO () jsSetOnPageLoad (JSFun f) = ffi "(function (c) { document.onload = c; })" $ (unsafeCoerce f :: JSAny) -- | Since we can't name it '$', let's just call it 'j'. j :: JSString -> (JQuery -> IO a) -> IO a j s action = jsJquery s >>= action -- | Returns element position getElementPosition :: String -> IO (Int, Int) getElementPosition sel = j (toJSStr sel) $ \jq -> do pos <- jsOffset jq xpos <- jsLeft pos ypos <- jsTop pos return (xpos, ypos) getMousePosition :: IO (Int, Int) getMousePosition = do m <- jsMouse x <- jsMouseX m y <- jsMouseY m doc <- jsDocument sx <- jsPageScrollX doc sy <- jsPageScrollY doc return (x+sx, y+sy) getDocumentSize :: IO (Int, Int) getDocumentSize = do x <- jsDocumentWidth y <- jsDocumentHeight return (x, y) styleBlock :: ToElem a => a -> Perch styleBlock cont = nelem "style" `child` cont -- | active button. When clicked, return the first parameter cbutton :: a -> String -> Widget a cbutton x slabel= static $ do button slabel ! id slabel ! atr "class" "btn btn-primary" ! atr "type" "button" ! atr "style" "margin-right: 10px; margin-left: 10px; margin-top: 3px" `pass` OnClick return x `continuePerch` slabel cbuttonM :: IO a -> String -> Widget a cbuttonM x slabel= static $ do button slabel ! id slabel ! atr "class" "btn btn-primary" ! atr "type" "button" ! atr "style" "margin-right: 10px; margin-left: 10px; margin-top: 3px" `pass` OnClick liftIO x `continuePerch` slabel timeoutStore :: IORef [String] timeoutStore = unsafePerformIO $ newIORef [] storeTimeout :: String -> IO () storeTimeout ids = do idss <- readIORef timeoutStore writeIORef timeoutStore $ ids : idss removeTimeout :: String -> IO () removeTimeout ids = do idss <- readIORef timeoutStore writeIORef timeoutStore $ filter (/= ids) idss hasTimeout :: String -> IO Bool hasTimeout ids = elem ids <$> readIORef timeoutStore peekTimeout :: String -> Widget () peekTimeout ids = do idss <- liftIO $ readIORef timeoutStore case ids `elem` idss of True -> noWidget False -> return () clearTimers :: IO () clearTimers = writeIORef timeoutStore [] timeout :: Int -> Widget a -> Widget a timeout mss wa = do id <- genNewId liftIO $ storeTimeout id cont <- getCont ht <- liftIO $ hasTimeout id when ht $ setTimeout mss $ do ht' <- liftIO $ hasTimeout id when ht' $ do removeTimeout id runCont cont peekTimeout id wa wloop :: a -> (a -> Widget a) -> Widget () wloop initialState wa = View $ do nid <- genNewId FormElm form mx <- runView $ go nid initialState return $ FormElm ((Haste.Perch.span ! atr "id" nid $ noHtml) <> form) mx where go nid state = do nextState <- at nid Insert (wa state) go nid nextState panel :: String -> Perch -> Perch panel ts bd = div ! atr "class" "panel panel-default" $ mconcat [ div ! atr "class" "panel-heading" $ h3 ! atr "class" "panel-title" $ toJSString ts , div ! atr "class" "panel-body" $ bd ] labelRow :: Int -> String -> String -> Perch labelRow ri ts vs = div ! atr "class" "row" $ mconcat [ div ! atr "class" (colClass ri) $ label $ toJSString ts , div ! atr "class" (colClass (12-ri)) $ toJSString vs ] where colClass i = "col-md-" ++ show i
Teaspot-Studio/bmstu-radio-problem-haste
Radio/Util.hs
bsd-3-clause
5,437
0
15
1,099
1,769
876
893
144
2
module Reflex.Dom (module X) where import Reflex as X import Reflex.Dom.Builder.Class as X import Reflex.Dom.Builder.Immediate as X import Reflex.Dom.Builder.InputDisabled as X import Reflex.Dom.Builder.Static as X import Reflex.Dom.Class as X import Reflex.Dom.Internal as X import Reflex.Dom.Location as X import Reflex.Dom.Old as X import Reflex.Dom.Time as X import Reflex.Dom.WebSocket as X import Reflex.Dom.Widget as X import Reflex.Dom.Xhr as X
manyoo/reflex-dom
src/Reflex/Dom.hs
bsd-3-clause
454
0
4
58
117
88
29
14
0
-- |Models representing the apidoc specification. -- -- http://apidoc.me/bryzek/apidoc-spec/latest -- module Apidoc.DSL (module Exports) where import Apidoc.DSL.Lenses as Exports import Apidoc.DSL.Types as Exports
chrisbarrett/apidoc-checker
src/Apidoc/DSL.hs
bsd-3-clause
239
0
4
48
32
24
8
3
0
----------------------------------------------------------------------------- -- | -- Module : Data.Matrix.Banded.Class -- Copyright : Copyright (c) , Patrick Perry <[email protected]> -- License : BSD3 -- Maintainer : Patrick Perry <[email protected]> -- Stability : experimental -- -- An overloaded interface to mutable banded matrices. For matrix types -- than can be used with this interface, see "Data.Matrix.Banded.IO" and -- "Data.Matrix.Banded.ST". Many of these functions can also be used with -- the immutable type defined in "Data.Matrix.Banded". -- module Data.Matrix.Banded.Class ( -- * Banded matrix type classes BaseBanded( numLower, numUpper, bandwidths, ldaBanded, isHermBanded , transEnumBanded, maybeMatrixStorageFromBanded , maybeBandedFromMatrixStorage ), ReadBanded, WriteBanded, -- * Overloaded interface for matrices module Data.Matrix.Class, module Data.Matrix.Class.MMatrix, -- * Creating banded matrices newBanded_, newBanded, newListsBanded, -- * Special banded matrices newZeroBanded, setZeroBanded, newConstantBanded, setConstantBanded, -- * Copying banded matrices newCopyBanded, copyBanded, -- * Conversions between banded matrices and vectors viewVectorAsBanded, viewVectorAsDiagBanded, maybeViewBandedAsVector, -- * Row and column views rowViewBanded, colViewBanded, diagViewBanded, -- * Getting diagonals getDiagBanded, -- * Overloaded interface for reading and writing banded matrix elements module Data.Tensor.Class, module Data.Tensor.Class.MTensor, -- * Conversions between mutable and immutable banded matrices freezeBanded, thawBanded, unsafeFreezeBanded, unsafeThawBanded, -- * Conversions from @IOBanded@s unsafeBandedToIOBanded, unsafeConvertIOBanded, unsafePerformIOWithBanded, ) where import Data.Matrix.Banded.Base import Data.Matrix.Class import Data.Matrix.Class.MMatrix import Data.Tensor.Class import Data.Tensor.Class.MTensor
patperry/hs-linear-algebra
lib/Data/Matrix/Banded/Class.hs
bsd-3-clause
2,116
0
5
432
194
146
48
40
0
module Network.Wai.Util ( withLBS ) where import Control.Concurrent import Control.Concurrent.MVar import Control.Exception (SomeException, catch, finally) import Control.Monad (when) import Control.Monad.IO.Class import qualified Data.ByteString as B import qualified Data.ByteString.Char8 as B8 import qualified Data.ByteString.Lazy as L import Data.Enumerator (($$)) import qualified Data.Enumerator as E import Network.Wai import System.IO.Unsafe import Prelude hiding (catch) withLBS :: (L.ByteString -> IO a) -> E.Iteratee B.ByteString IO (Either SomeException a) withLBS f = do (mcont, mbs, mres) <- liftIO $ do mbs <- newEmptyMVar mres <- newEmptyMVar mcont <- newMVar True forkIO $ finally (catch (do a <- f =<< evalLBS mcont mbs a `seq` putMVar mres (Right a)) (putMVar mres . Left)) (putMVar mcont False) return (mcont, mbs, mres) iterateLBS mcont mbs liftIO $ takeMVar mres evalLBS :: MVar Bool -> MVar [B.ByteString] -> IO L.ByteString evalLBS mcont mbs = fmap L.fromChunks go where go = unsafeInterleaveIO $ do next <- takeMVar mbs case next of [] -> return [] bs -> do putMVar mcont True fmap (bs ++) go iterateLBS :: MVar Bool -> MVar [B.ByteString] -> E.Iteratee B.ByteString IO () iterateLBS mcont mbs = E.continue go where go (E.Chunks []) = E.continue go go (E.Chunks cs) = do succ <- liftIO $ waitPut cs if succ then E.continue go else E.yield () $ E.Chunks cs go E.EOF = do liftIO $ waitPut [] E.yield () E.EOF waitPut cs = do cont <- takeMVar mcont when cont $ putMVar mbs cs return cont
softmechanics/wai-utils
Network/Wai/Util.hs
bsd-3-clause
1,824
0
21
552
651
331
320
53
4
import File.Binary.PNG import System.Environment main :: IO () main = do fin : _ <- getArgs cnt <- readBinaryFile fin let p = readPNG' cnt putStrLn $ take 1000 $ show p
YoshikuniJujo/png-file
test/readPNG2.hs
bsd-3-clause
174
1
10
37
80
36
44
8
1
module Chapter14 where import Data.List (sort) import Test.QuickCheck half :: Fractional a => a -> a half x = x / 2 prop_halfIdentity :: (Fractional a, Eq a) => a -> Bool prop_halfIdentity x = x == ((*2) . half $ x) listOrdered :: (Ord a) => [a] -> Bool listOrdered xs = snd $ foldr go (Nothing, True) xs where go _ status@(_, False) = status go y (Nothing, t) = (Just y, t) go y (Just x, t) = (Just y, x >= y) prop_listOrdered :: (Ord a) => [a] -> Bool prop_listOrdered = listOrdered . sort prop_plusAssociative x y z = x + (y + z) == (x + y) + z prop_plusCommutative x y = x + y == y + x prop_quotRem :: (Eq a, Integral a) => a -> NonZero a -> Bool prop_quotRem x (NonZero y) = (quot x y) * y + (rem x y) == x prop_divMod :: (Eq a, Integral a) => a -> NonZero a -> Bool prop_divMod x (NonZero y) = (div x y) * y + (mod x y) == x prop_divMod' :: (Eq a, Integral a) => a -> a -> Bool prop_divMod' x y = (div x y) * y + (mod x y) == x intId :: Integer -> Integer intId x |x > 1 = -1 |otherwise = x prop_intId x = x == intId x prop_reverse xs = (reverse . reverse) xs == id xs prop_foldrConsConcat xs ys = foldr (:) xs ys == (xs ++ ys) prop_foldrConcat :: Eq a => [[a]] -> Bool prop_foldrConcat xs = foldr (++) [] xs == concat xs prop_showRoundTrip x = (read.show $ x) == x square x = x * x squareIdentity x = (square . sqrt $ x) == x data Fool = Fulse | Frue deriving (Eq, Show) fairFoolGen :: Gen Fool fairFoolGen = oneof [pure Fulse, pure Frue] foolGen :: Gen Fool foolGen = frequency [(2, pure Fulse), (1, pure Frue)]
taojang/haskell-programming-book-exercise
src/ch14/Chapter14.hs
bsd-3-clause
1,560
0
9
370
829
435
394
40
3
{-# LANGUAGE UndecidableInstances, FlexibleInstances, MultiParamTypeClasses, TemplateHaskell, PolymorphicComponents, DeriveDataTypeable,ExistentialQuantification, KindSignatures, StandaloneDeriving, GADTs #-} {- | This module defines 'Typeable' indexes and convenience functions. Should probably be considered private to @Data.IxSet.Typed@. -} module Data.IxSet.Typed.Ix ( Ix(..) , insert , delete , fromList , insertList , deleteList , union , intersection ) where import Control.DeepSeq -- import Data.Generics hiding (GT) -- import qualified Data.Generics.SYB.WithClass.Basics as SYBWC import qualified Data.List as List import Data.Map (Map) import qualified Data.Map as Map import qualified Data.Map.Strict as Map.Strict import Data.Set (Set) import qualified Data.Set as Set -- the core datatypes -- | 'Ix' is a 'Map' from some key (of type 'ix') to a 'Set' of -- values (of type 'a') for that key. data Ix (ix :: *) (a :: *) where Ix :: !(Map ix (Set a)) -> (a -> [ix]) -> Ix ix a instance (NFData ix, NFData a) => NFData (Ix ix a) where rnf (Ix m f) = rnf m `seq` f `seq` () -- deriving instance Typeable (Ix ix a) {- -- minimal hacky instance instance Data a => Data (Ix a) where toConstr (Ix _ _) = con_Ix_Data gunfold _ _ = error "gunfold" dataTypeOf _ = ixType_Data -} {- con_Ix_Data :: Constr con_Ix_Data = mkConstr ixType_Data "Ix" [] Prefix ixType_Data :: DataType ixType_Data = mkDataType "Happstack.Data.IxSet.Ix" [con_Ix_Data] -} {- ixConstr :: SYBWC.Constr ixConstr = SYBWC.mkConstr ixDataType "Ix" [] SYBWC.Prefix ixDataType :: SYBWC.DataType ixDataType = SYBWC.mkDataType "Ix" [ixConstr] -} {- instance (SYBWC.Data ctx a, SYBWC.Sat (ctx (Ix a))) => SYBWC.Data ctx (Ix a) where gfoldl = error "gfoldl Ix" toConstr _ (Ix _ _) = ixConstr gunfold = error "gunfold Ix" dataTypeOf _ _ = ixDataType -} -- modification operations -- | Convenience function for inserting into 'Map's of 'Set's as in -- the case of an 'Ix'. If they key did not already exist in the -- 'Map', then a new 'Set' is added transparently. insert :: (Ord a, Ord k) => k -> a -> Map k (Set a) -> Map k (Set a) insert k v index = Map.Strict.insertWith Set.union k (Set.singleton v) index -- | Helper function to 'insert' a list of elements into a set. insertList :: (Ord a, Ord k) => [(k,a)] -> Map k (Set a) -> Map k (Set a) insertList xs index = List.foldl' (\m (k,v)-> insert k v m) index xs -- | Helper function to create a new index from a list. fromList :: (Ord a, Ord k) => [(k, a)] -> Map k (Set a) fromList xs = Map.fromListWith Set.union (List.map (\ (k, v) -> (k, Set.singleton v)) xs) -- | Convenience function for deleting from 'Map's of 'Set's. If the -- resulting 'Set' is empty, then the entry is removed from the 'Map'. delete :: (Ord a, Ord k) => k -> a -> Map k (Set a) -> Map k (Set a) delete k v index = Map.update remove k index where remove set = let set' = Set.delete v set in if Set.null set' then Nothing else Just set' -- | Helper function to 'delete' a list of elements from a set. deleteList :: (Ord a, Ord k) => [(k,a)] -> Map k (Set a) -> Map k (Set a) deleteList xs index = List.foldl' (\m (k,v) -> delete k v m) index xs -- | Takes the union of two sets. union :: (Ord a, Ord k) => Map k (Set a) -> Map k (Set a) -> Map k (Set a) union index1 index2 = Map.unionWith Set.union index1 index2 -- | Takes the intersection of two sets. intersection :: (Ord a, Ord k) => Map k (Set a) -> Map k (Set a) -> Map k (Set a) intersection index1 index2 = Map.filter (not . Set.null) $ Map.intersectionWith Set.intersection index1 index2
well-typed/ixset-typed
src/Data/IxSet/Typed/Ix.hs
bsd-3-clause
3,854
0
12
940
933
508
425
50
2
{-# LANGUAGE TypeSynonymInstances ,NoMonomorphismRestriction,FlexibleInstances#-} module Display.Cube ( draw ) where import qualified Graphics.Rendering.OpenGL as GL import Graphics.Rendering.OpenGL import qualified Graphics.UI.GLUT as GLUT import Data.StateVar import Linear.Matrix import Linear.V3 import Linear.V4 import Control.Lens import Data.Functor.Compose --import Vectorization import Data.Foldable(toList) import Foreign hiding(rotate) import Rotation.SO3 instance GL.Matrix (Compose V4 V4) where withMatrix m f =withArray (toList m) (f GL.RowMajor) drawBall c (x,l) = do GL.preservingMatrix $ do GL.translate l GL.color $ c (x::GL.GLfloat) GLUT.renderObject GLUT.Solid (GLUT.Sphere' (0.1*(realToFrac x)) 10 10) vec3ToVertex3 (GL.Vector3 x y z) = GL.Vertex3 x y z vertex3ToVector3 (GL.Vertex3 x y z) = GL.Vector3 x y z data Box a = Box { position :: V3 a , size :: V3 a , orientation :: SO3 a }deriving(Show) v3ToVector3 (V3 x y z ) = fmap realToFrac (Vector3 x y z) transformation (SO3 orient)= m43_to_m44 $ vector orient drawBox (Box pos len orient) = do multMatrix (fmap realToFrac $ Compose $ transformation orient :: Compose V4 V4 GLdouble) translate (v3ToVector3 pos :: Vector3 GLdouble) let (V3 l w h) = fmap realToFrac len :: V3 GLdouble GL.scale l w h GLUT.renderObject GLUT.Wireframe (GLUT.Cube 1) drawFloor s = do scale s s s rotate (-90) (Vector3 0 1 0 :: Vector3 GLdouble) rotate (-90) (Vector3 1 0 0 :: Vector3 GLdouble) rotate 0 (Vector3 0 0 1 :: Vector3 GLdouble) rotate 0 (Vector3 0 1 0 :: Vector3 GLdouble) scale 1 1 (0.1 :: GLdouble) GLUT.renderObject GLUT.Solid (GLUT.Cube 1) scale 1 1 (10 :: GLdouble ) scale s s s drawAxisElem l a c = GL.preservingMatrix $ do color c GL.renderPrimitive Lines $ do vertex (Vertex3 0 0 0 :: Vertex3 GLdouble) vertex a translate $ vertex3ToVector3 a GLUT.renderObject GLUT.Solid (GLUT.Sphere' 0.02 10 10) let s = 0.0010 :: GLfloat fscale = scale s s s fscale color white GLUT.renderString GLUT.Roman l drawAxis lz ly lx= do let origin ,ax,ay,az:: Vertex3 GLfloat origin = Vertex3 0 0 0 ax = Vertex3 0.25 0 0 ay = Vertex3 0 0.25 0 az = Vertex3 0 0 0.25 drawAxisElem lx ax blue drawAxisElem ly ay green drawAxisElem lz az red showVec3 (Vector3 x y z) = "(" ++ (show x ) ++ " , " ++ (show y ) ++ " , " ++ (show z ) ++")" draw s (l,i) = do GL.color white GL.preservingMatrix $ do translate $ Vector3 (-0.9::GLfloat) (-0.9) 0 scale 0.0002 0.0002 (0.0002 ::GLfloat) color white GLUT.renderString GLUT.Roman (show $ angles (SO3 i)) GL.color gray drawFloor s translate (Vector3 0 0 1 ::Vector3 GLdouble) drawAxis "North" "East" "Up" GL.preservingMatrix $ do GL.color green renderPrimitive LineStrip $ mapM_ (vertex . vec3ToVertex3)l let ld = fromIntegral (length l) GL.preservingMatrix $ do GL.color blue mapM_ (drawBall blueg ) $ zip (map (^2) $ map (/ld) [ld,(ld-1)..1]) l GL.preservingMatrix $ do GL.color red drawBox (Box 0 (V3 1 1 1) (SO3 i)) drawAxis "Ax" "Ay" "Az" GL.preservingMatrix $ do renderPrimitive Lines $ do vertex (vec3ToVertex3 $ head l) vertex (Vertex3 0 0 (0::GLfloat) ) GL.translate (head l) GL.color red GLUT.renderObject GLUT.Solid (GLUT.Sphere' 0.1 10 10) white,red, green,gray, blue :: GL.Color4 GL.GLfloat red = GL.Color4 1 0 0 1 green = GL.Color4 0 1 0 1 blue = GL.Color4 0 0 1 1 blueg x = GL.Color4 0 0 1 x white = GL.Color4 (1/3) (1/3) (1/3) 1 gray = GL.Color4 (1) (1) (1) 1 z, n1, p1 :: GL.GLfloat z = 0 n1 = -1 p1 = 1
massudaw/mtk
filters/attitude/Display/Cube.hs
bsd-3-clause
3,905
2
20
1,067
1,629
806
823
111
1
{-# LANGUAGE OverloadedStrings, NoMonomorphismRestriction #-} ------------------------------------------------------------------------------ -- | This module is where all the routes and handlers are defined for your -- site. The 'app' function is the initializer that combines everything -- together and is exported by this module. module Site ( app ) where ------------------------------------------------------------------------------ import Control.Applicative import Data.ByteString (ByteString) import Data.Maybe import qualified Data.Text as T import Snap.Core import Snap.Snaplet import Snap.Snaplet.Auth import Snap.Snaplet.Auth.Backends.JsonFile import Snap.Snaplet.Heist import Snap.Snaplet.Session.Backends.CookieSession import Snap.Util.FileServe import Text.Templating.Heist ------------------------------------------------------------------------------ import Application import StaticDoc myHandler = do writeText "Hello" ------------------------------------------------------------------------------ -- | The application's routes. routes :: [(ByteString, Handler App App ())] routes = [ ("/images", with staticDoc retrieve) , ("", with staticDoc retrieve) ] ------------------------------------------------------------------------------ -- | The application initializer. app :: SnapletInit App App app = makeSnaplet "app" "An snaplet example application." Nothing $ do h <- nestSnaplet "" heist $ heistInit "" s <- nestSnaplet "" staticDoc $ staticInit "/Users/drakej/Code/SOCRweb/wiki" "/Users/drakej/Code/SOCRweb/images" "/Users/drakej/Code/SOCRweb/templates" "clockworks" addRoutes routes return $ App h s
madebyjeffrey/snaplet-fetch
example/Site.hs
bsd-3-clause
1,963
0
10
498
259
149
110
31
1
import GHC.Generics import Control.Monad import Control.Monad.Reader import System.IO import Database.Seakale.PostgreSQL hiding (withConn) import Database.Seakale.PostgreSQL.FromRow import Database.Seakale.Store import Shared newtype TableStats = TableStats { numRows :: Integer } deriving Generic instance Storable PSQL Two One TableStats where data EntityID TableStats = TableStatsID String String deriving Generic relation _ = Relation { relationName = "pg_stat_user_tables" , relationIDColumns = ["schemaname", "relname"] , relationColumns = ["n_live_tup"] } instance FromRow PSQL One TableStats instance FromRow PSQL Two (EntityID TableStats) dbProg :: Select [Entity TableStats] dbProg = select mempty $ asc EntityID main :: IO () main = withConn $ \conn -> do eRes <- runReaderT (runRequest defaultPSQL (runSelectT dbProg)) conn case eRes of Left err -> hPutStrLn stderr $ "Error: " ++ show err Right res -> forM_ res $ \(Entity (TableStatsID schemaName relName) TableStats{..}) -> putStrLn $ "Table " ++ schemaName ++ "." ++ relName ++ " has around " ++ show numRows ++ " rows."
thoferon/seakale
demo/src/Storable.hs
bsd-3-clause
1,169
0
20
234
346
183
163
-1
-1
module Physics.Falling.Constraint.Solver.FirstOrderWorldAccumulatedImpulse ( addFirstOrderEquations , firstOrderIntegrate ) where import qualified Data.Vector as V import qualified Data.Vector.Unboxed as UV import Physics.Falling.Math.Transform import Physics.Falling.Math.Error import Physics.Falling.Collision.Collision import Physics.Falling.RigidBody.Positionable import Physics.Falling.RigidBody.Dynamic import Physics.Falling.Constraint.Solver.ContactDynamicConfiguration hiding(linearVelocity, angularVelocity) import Physics.Falling.Constraint.Solver.AccumulatedImpulseSystem -- FIXME: instead of all that, define a type «FirstOrderWorld» and «SecondOrderWorld» and add -- contact to them, and let them solve themselves addFirstOrderEquations :: (Dynamic rb t lv av ii, UnitVector lv n) => Double -> V.Vector rb -> Int -> ContactManifold lv n -> AccumulatedImpulseSystem lv av -> AccumulatedImpulseSystem lv av addFirstOrderEquations dt bodies shift cm sys = foldr (addFirstOrderEquation dt bodies shift) sys cm addFirstOrderEquation :: (Dynamic rb t lv av ii, UnitVector lv n) => Double -> V.Vector rb -> Int -> Collision lv n -> AccumulatedImpulseSystem lv av -> AccumulatedImpulseSystem lv av addFirstOrderEquation dt bodies shift (UnibodyCollision idx coll _) sys = foldr (\conf s -> addSingleBodyEquation conf sid 0.0 infinity (err / dt) s) sys confs -- FIXME: uggly to set limits and depth here where sid = idx + shift rb = bodies V.! sid confs = firstOrderWorldContact dt rb coll False depth = penetrationDepth coll err = firstOrderErrorEstimator depth addFirstOrderEquation dt bodies shift (BibodyCollision id1 id2 coll _) sys = foldr (\(conf1, conf2) s -> addTwoBodiesEquation conf1 conf2 sid1 sid2 0.0 infinity (err / dt) s) sys $ zip confs1 confs2 -- FIXME: uggly to set limits and depth here where sid1 = id1 + shift sid2 = id2 + shift rb1 = bodies V.! sid1 rb2 = bodies V.! sid2 confs1 = firstOrderWorldContact dt rb1 coll True confs2 = firstOrderWorldContact dt rb2 coll False depth = penetrationDepth coll err = firstOrderErrorEstimator depth firstOrderErrorEstimator :: Double -> Double firstOrderErrorEstimator penDepth = max 0.0 $ penDepth - gap firstOrderWorldContact :: (Dynamic rb t lv av ii, UnitVector lv n) => Double -> rb -> CollisionDescr lv n -> Bool -> [ ContactDynamicConfiguration lv av ] firstOrderWorldContact _ rb (CollisionDescr c _ _ n _) invN = [ contactConfiguration (translation $ localToWorld rb) zero zero (inverseMass rb) (worldSpaceInverseInertiaTensor rb) (if invN then neg (fromNormal n) else (fromNormal n)) c ] -- Note: this step will fail with an index out of range if a body without collision is in the -- system firstOrderIntegrate :: (Dynamic rb t lv av ii, UV.Unbox lv, UV.Unbox av) => Double -> [ (Int, rb) ] -> UV.Vector lv -> UV.Vector av -> Int -> [ (Int, rb) ] firstOrderIntegrate dt bodies linImpVect angImpVect shift = map applyBodyImpulses bodies where applyBodyImpulses (i, rb) = let idx = i + shift in let linImp = linImpVect UV.! idx in let angImp = angImpVect UV.! idx in (i, applyPositionImpulses (dt *& linImp) (dt *& angImp) rb)
sebcrozet/falling
Physics/Falling/Constraint/Solver/FirstOrderWorldAccumulatedImpulse.hs
bsd-3-clause
4,279
0
16
1,621
936
499
437
67
2
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE RecordWildCards #-} module Acquire.Game.Core where import Data.Aeson (FromJSON, ToJSON) import Data.Array import qualified Data.Map as M import GHC.Generics import System.Random import System.Random.Shuffle import Acquire.Game.Cells import Acquire.Game.Hotels import Acquire.Game.Player import Acquire.Game.Tiles data MergerPhase = TakeOver Tile [ChainName] | DisposeStock { initialPlayer :: PlayerName , buyerChain :: ChainName , buyeeChain :: ChainName , buyeePrice :: Int , playersToDecide :: [PlayerName] } deriving (Eq,Show,Read,Generic) instance ToJSON MergerPhase instance FromJSON MergerPhase data Phase = PlaceTile | FundChain Tile | BuySomeStock Int | ResolveMerger MergerPhase Turn | GameEnds deriving (Eq, Show, Read, Generic) instance ToJSON Phase instance FromJSON Phase type Turn = (PlayerName, Phase) data Order = Place PlayerName Tile | Merge PlayerName Tile ChainName ChainName | Fund PlayerName ChainName Tile | BuyStock PlayerName ChainName | SellStock PlayerName ChainName Int Int | ExchangeStock PlayerName ChainName ChainName Int | Pass | EndGame | Cancel deriving (Eq, Show, Read, Generic) instance ToJSON Order instance FromJSON Order type GameId = String data Game = Game { gameId :: GameId , gameBoard :: GameBoard , players :: Players , drawingTiles :: [ Tile ] , hotelChains :: HotelChains , turn :: Turn } deriving (Eq, Show, Read, Generic) instance ToJSON Game instance FromJSON Game numberOfTilesPerPlayer :: Int numberOfTilesPerPlayer = 6 newGame :: GameId -> StdGen -> [(PlayerName,PlayerType)] -> Game newGame gid g playersDescription = Game gid initialBoard (M.fromList players) draw chains (firstPlayerName, PlaceTile) where initialBoard = array (Tile ('A',1),Tile ('I',12)) (map (\ cell@(Cell c _) -> (c, cell)) cells) coords = shuffle' (indices initialBoard) (9 * 12) g (players, draw) = makePlayers playersDescription ([],coords) firstPlayerName = fst $ head playersDescription cells = concatMap (\ (cs,n) -> map (\ (r,e) -> Cell (Tile (n,r)) e) cs) rows rows = zip (replicate 9 (take 12 cols)) [ 'A' .. ] cols = zip [ 1 .. ] (repeat Empty) chains = M.fromList $ map (\ n -> (n, HotelChain n [] maximumStock)) (enumFrom American) makePlayers :: [(PlayerName,PlayerType)] -> ([(PlayerName, Player)],[Tile]) -> ([(PlayerName, Player)],[Tile]) makePlayers ((pname,ptype):rest) (ps,coords) = makePlayers rest ((pname, Player pname ptype (take numberOfTilesPerPlayer coords) emptyStock 6000):ps, drop numberOfTilesPerPlayer coords) makePlayers [] res = res currentPlayer :: Game -> Player currentPlayer game = let p = fst $ turn game in players game M.! p hasNeutralChainAt :: GameBoard -> Tile -> Bool hasNeutralChainAt board coord = isNeutral (cellContent $ board ! coord) && hasAdjacentNeutralTile board coord hasActiveChain :: Game -> ChainName -> Bool hasActiveChain Game{..} chain = length (chainTiles (hotelChains M.! chain)) > 0 hasAdjacentNeutralTile :: GameBoard -> Tile -> Bool hasAdjacentNeutralTile board coord = not (null (adjacentCells (isNeutral . cellContent) board coord)) nextPlayer :: Game -> PlayerName nextPlayer game = let (p,_) = turn game in case M.lookupGT p (players game) of Nothing -> fst $ M.findMin (players game) Just (p',_) -> p'
abailly/hsgames
acquire/src/Acquire/Game/Core.hs
apache-2.0
3,913
0
16
1,131
1,207
666
541
83
2
{-# LANGUAGE BangPatterns, ScopedTypeVariables, TupleSections #-} module Language.Haskell.GhcMod.GhcPkg ( ghcPkgDbOpt , ghcPkgDbStackOpts , ghcDbStackOpts , ghcDbOpt , fromInstalledPackageId , fromInstalledPackageId' , getPackageDbStack , getPackageCachePaths ) where import Config (cProjectVersion, cTargetPlatformString, cProjectVersionInt) import Control.Applicative ((<$>)) import Data.List (intercalate) import Data.List.Split (splitOn) import Data.Maybe import Distribution.Package (InstalledPackageId(..)) import Exception (handleIO) import Language.Haskell.GhcMod.PathsAndFiles import Language.Haskell.GhcMod.Types import System.Directory (doesDirectoryExist, getAppUserDataDirectory) import System.FilePath ((</>)) ghcVersion :: Int ghcVersion = read cProjectVersionInt getPackageDbStack :: FilePath -- ^ Project Directory (where the -- cabal.sandbox.config file would be if it -- exists) -> IO [GhcPkgDb] getPackageDbStack cdir = do mSDir <- getSandboxDb cdir return $ [GlobalDb] ++ case mSDir of Nothing -> [UserDb] Just db -> [PackageDb db] ---------------------------------------------------------------- fromInstalledPackageId' :: InstalledPackageId -> Maybe Package fromInstalledPackageId' pid = let InstalledPackageId pkg = pid in case reverse $ splitOn "-" pkg of i:v:rest -> Just (intercalate "-" (reverse rest), v, i) _ -> Nothing fromInstalledPackageId :: InstalledPackageId -> Package fromInstalledPackageId pid = case fromInstalledPackageId' pid of Just p -> p Nothing -> error $ "fromInstalledPackageId: `"++show pid++"' is not a valid package-id" ---------------------------------------------------------------- -- | Get options needed to add a list of package dbs to ghc-pkg's db stack ghcPkgDbStackOpts :: [GhcPkgDb] -- ^ Package db stack -> [String] ghcPkgDbStackOpts dbs = ghcPkgDbOpt `concatMap` dbs -- | Get options needed to add a list of package dbs to ghc's db stack ghcDbStackOpts :: [GhcPkgDb] -- ^ Package db stack -> [String] ghcDbStackOpts dbs = ghcDbOpt `concatMap` dbs ---------------------------------------------------------------- ghcPkgDbOpt :: GhcPkgDb -> [String] ghcPkgDbOpt GlobalDb = ["--global"] ghcPkgDbOpt UserDb = ["--user"] ghcPkgDbOpt (PackageDb pkgDb) | ghcVersion < 706 = ["--no-user-package-conf", "--package-conf=" ++ pkgDb] | otherwise = ["--no-user-package-db", "--package-db=" ++ pkgDb] ghcDbOpt :: GhcPkgDb -> [String] ghcDbOpt GlobalDb | ghcVersion < 706 = ["-global-package-conf"] | otherwise = ["-global-package-db"] ghcDbOpt UserDb | ghcVersion < 706 = ["-user-package-conf"] | otherwise = ["-user-package-db"] ghcDbOpt (PackageDb pkgDb) | ghcVersion < 706 = ["-no-user-package-conf", "-package-conf", pkgDb] | otherwise = ["-no-user-package-db", "-package-db", pkgDb] ---------------------------------------------------------------- getPackageCachePaths :: FilePath -> Cradle -> IO [FilePath] getPackageCachePaths sysPkgCfg crdl = catMaybes <$> resolvePackageConfig sysPkgCfg `mapM` cradlePkgDbStack crdl -- TODO: use PkgConfRef --- Copied from ghc module `Packages' unfortunately it's not exported :/ resolvePackageConfig :: FilePath -> GhcPkgDb -> IO (Maybe FilePath) resolvePackageConfig sysPkgCfg GlobalDb = return $ Just sysPkgCfg resolvePackageConfig _ UserDb = handleIO (\_ -> return Nothing) $ do appdir <- getAppUserDataDirectory "ghc" let dir = appdir </> (target_arch ++ '-':target_os ++ '-':cProjectVersion) pkgconf = dir </> "package.conf.d" exist <- doesDirectoryExist pkgconf return $ if exist then Just pkgconf else Nothing where [target_arch,_,target_os] = splitOn "-" cTargetPlatformString resolvePackageConfig _ (PackageDb name) = return $ Just name
cabrera/ghc-mod
Language/Haskell/GhcMod/GhcPkg.hs
bsd-3-clause
3,978
0
16
768
904
487
417
77
2
{-# LANGUAGE TemplateHaskell #-} import Data.Digest.Pure.MD5 import Test.QuickCheck.All (quickCheckAll) import qualified Data.ByteString.Lazy.Char8 as L import qualified Data.ByteString.Char8 as B twoPartMD5 :: String -> String -> MD5Digest twoPartMD5 x y = let initial = md5Update md5InitialContext (B.pack x) update = md5Update initial (B.pack y) in md5Finalize update (B.pack " ") prop_md5 :: String -> String -> Bool prop_md5 x y = show (md5 (L.pack (x ++ y))) == show (twoPartMD5 x y) main :: IO () main = $quickCheckAll >> return ()
beni55/PureMD5Improvements
Test/main.hs
bsd-3-clause
618
0
12
160
204
109
95
13
1
{- | Module : $Header$ Copyright : (c) Felix Gabriel Mance License : GPLv2 or higher, see LICENSE.txt Maintainer : [email protected] Stability : provisional Portability : portable script for running the parsing of XML -} import System.Environment import OWL2.XML import Text.XML.Light import OWL2.Print () import OWL2.ManchesterPrint () import Common.DocUtils processFile :: String -> IO () processFile file = do s <- readFile file case parseXML s of elems -> print (map xmlBasicSpec $ concatMap (filterElementsName $ isSmth "Ontology") $ onlyElems elems) main :: IO () main = do args <- getArgs mapM_ processFile args
keithodulaigh/Hets
OWL2/scripts/runXML.hs
gpl-2.0
715
0
17
179
150
75
75
17
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.CloudSearch.DescribeSuggesters -- Copyright : (c) 2013-2014 Brendan Hay <[email protected]> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | Gets the suggesters configured for a domain. A suggester enables you to -- display possible matches before users finish typing their queries. Can be -- limited to specific suggesters by name. By default, shows all suggesters and -- includes any pending changes to the configuration. Set the 'Deployed' option to 'true' to show the active configuration and exclude pending changes. For more -- information, see Getting Search Suggestions in the /Amazon CloudSearchDeveloper Guide/. -- -- <http://docs.aws.amazon.com/cloudsearch/latest/developerguide/API_DescribeSuggesters.html> module Network.AWS.CloudSearch.DescribeSuggesters ( -- * Request DescribeSuggesters -- ** Request constructor , describeSuggesters -- ** Request lenses , ds1Deployed , ds1DomainName , ds1SuggesterNames -- * Response , DescribeSuggestersResponse -- ** Response constructor , describeSuggestersResponse -- ** Response lenses , dsrSuggesters ) where import Network.AWS.Prelude import Network.AWS.Request.Query import Network.AWS.CloudSearch.Types import qualified GHC.Exts data DescribeSuggesters = DescribeSuggesters { _ds1Deployed :: Maybe Bool , _ds1DomainName :: Text , _ds1SuggesterNames :: List "member" Text } deriving (Eq, Ord, Read, Show) -- | 'DescribeSuggesters' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'ds1Deployed' @::@ 'Maybe' 'Bool' -- -- * 'ds1DomainName' @::@ 'Text' -- -- * 'ds1SuggesterNames' @::@ ['Text'] -- describeSuggesters :: Text -- ^ 'ds1DomainName' -> DescribeSuggesters describeSuggesters p1 = DescribeSuggesters { _ds1DomainName = p1 , _ds1SuggesterNames = mempty , _ds1Deployed = Nothing } -- | Whether to display the deployed configuration ('true') or include any pending -- changes ('false'). Defaults to 'false'. ds1Deployed :: Lens' DescribeSuggesters (Maybe Bool) ds1Deployed = lens _ds1Deployed (\s a -> s { _ds1Deployed = a }) -- | The name of the domain you want to describe. ds1DomainName :: Lens' DescribeSuggesters Text ds1DomainName = lens _ds1DomainName (\s a -> s { _ds1DomainName = a }) -- | The suggesters you want to describe. ds1SuggesterNames :: Lens' DescribeSuggesters [Text] ds1SuggesterNames = lens _ds1SuggesterNames (\s a -> s { _ds1SuggesterNames = a }) . _List newtype DescribeSuggestersResponse = DescribeSuggestersResponse { _dsrSuggesters :: List "member" SuggesterStatus } deriving (Eq, Read, Show, Monoid, Semigroup) instance GHC.Exts.IsList DescribeSuggestersResponse where type Item DescribeSuggestersResponse = SuggesterStatus fromList = DescribeSuggestersResponse . GHC.Exts.fromList toList = GHC.Exts.toList . _dsrSuggesters -- | 'DescribeSuggestersResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'dsrSuggesters' @::@ ['SuggesterStatus'] -- describeSuggestersResponse :: DescribeSuggestersResponse describeSuggestersResponse = DescribeSuggestersResponse { _dsrSuggesters = mempty } -- | The suggesters configured for the domain specified in the request. dsrSuggesters :: Lens' DescribeSuggestersResponse [SuggesterStatus] dsrSuggesters = lens _dsrSuggesters (\s a -> s { _dsrSuggesters = a }) . _List instance ToPath DescribeSuggesters where toPath = const "/" instance ToQuery DescribeSuggesters where toQuery DescribeSuggesters{..} = mconcat [ "Deployed" =? _ds1Deployed , "DomainName" =? _ds1DomainName , "SuggesterNames" =? _ds1SuggesterNames ] instance ToHeaders DescribeSuggesters instance AWSRequest DescribeSuggesters where type Sv DescribeSuggesters = CloudSearch type Rs DescribeSuggesters = DescribeSuggestersResponse request = post "DescribeSuggesters" response = xmlResponse instance FromXML DescribeSuggestersResponse where parseXML = withElement "DescribeSuggestersResult" $ \x -> DescribeSuggestersResponse <$> x .@? "Suggesters" .!@ mempty
kim/amazonka
amazonka-cloudsearch/gen/Network/AWS/CloudSearch/DescribeSuggesters.hs
mpl-2.0
5,112
0
10
1,039
627
378
249
71
1
---- This is comment -- This too (-->) x y = x + y -- but this is an operator main = 3
roberth/uu-helium
test/simple/parser/MaximalMunch2.hs
gpl-3.0
91
0
5
27
25
15
10
2
1
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="si-LK"> <title>WebSockets | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
thc202/zap-extensions
addOns/websocket/src/main/javahelp/org/zaproxy/zap/extension/websocket/resources/help_si_LK/helpset_si_LK.hs
apache-2.0
971
78
66
158
411
208
203
-1
-1
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 Pattern-matching bindings (HsBinds and MonoBinds) Handles @HsBinds@; those at the top level require different handling, in that the @Rec@/@NonRec@/etc structure is thrown away (whereas at lower levels it is preserved with @let@/@letrec@s). -} {-# LANGUAGE CPP #-} module DsBinds ( dsTopLHsBinds, dsLHsBinds, decomposeRuleLhs, dsSpec, dsHsWrapper, dsTcEvBinds, dsTcEvBinds_s, dsEvBinds ) where #include "HsVersions.h" import {-# SOURCE #-} DsExpr( dsLExpr ) import {-# SOURCE #-} Match( matchWrapper ) import DsMonad import DsGRHSs import DsUtils import HsSyn -- lots of things import CoreSyn -- lots of things import Literal ( Literal(MachStr) ) import CoreSubst import OccurAnal ( occurAnalyseExpr ) import MkCore import CoreUtils import CoreArity ( etaExpand ) import CoreUnfold import CoreFVs import UniqSupply import Digraph import PrelNames import TysPrim ( mkProxyPrimTy ) import TyCon import TcEvidence import TcType import Type import Kind (returnsConstraintKind) import Coercion hiding (substCo) import TysWiredIn ( eqBoxDataCon, coercibleDataCon, mkListTy , mkBoxedTupleTy, stringTy, typeNatKind, typeSymbolKind ) import Id import MkId(proxyHashId) import Class import DataCon ( dataConTyCon ) import Name import IdInfo ( IdDetails(..) ) import Var import VarSet import Rules import VarEnv import Outputable import Module import SrcLoc import Maybes import OrdList import Bag import BasicTypes hiding ( TopLevel ) import DynFlags import FastString import Util import MonadUtils import Control.Monad(liftM) import Fingerprint(Fingerprint(..), fingerprintString) {- ************************************************************************ * * \subsection[dsMonoBinds]{Desugaring a @MonoBinds@} * * ************************************************************************ -} dsTopLHsBinds :: LHsBinds Id -> DsM (OrdList (Id,CoreExpr)) dsTopLHsBinds binds = ds_lhs_binds binds dsLHsBinds :: LHsBinds Id -> DsM [(Id,CoreExpr)] dsLHsBinds binds = do { binds' <- ds_lhs_binds binds ; return (fromOL binds') } ------------------------ ds_lhs_binds :: LHsBinds Id -> DsM (OrdList (Id,CoreExpr)) ds_lhs_binds binds = do { ds_bs <- mapBagM dsLHsBind binds ; return (foldBag appOL id nilOL ds_bs) } dsLHsBind :: LHsBind Id -> DsM (OrdList (Id,CoreExpr)) dsLHsBind (L loc bind) = putSrcSpanDs loc $ dsHsBind bind dsHsBind :: HsBind Id -> DsM (OrdList (Id,CoreExpr)) dsHsBind (VarBind { var_id = var, var_rhs = expr, var_inline = inline_regardless }) = do { dflags <- getDynFlags ; core_expr <- dsLExpr expr -- Dictionary bindings are always VarBinds, -- so we only need do this here ; let var' | inline_regardless = var `setIdUnfolding` mkCompulsoryUnfolding core_expr | otherwise = var ; return (unitOL (makeCorePair dflags var' False 0 core_expr)) } dsHsBind (FunBind { fun_id = L _ fun, fun_matches = matches , fun_co_fn = co_fn, fun_tick = tick , fun_infix = inf }) = do { dflags <- getDynFlags ; (args, body) <- matchWrapper (FunRhs (idName fun) inf) matches ; let body' = mkOptTickBox tick body ; rhs <- dsHsWrapper co_fn (mkLams args body') ; {- pprTrace "dsHsBind" (ppr fun <+> ppr (idInlinePragma fun)) $ -} return (unitOL (makeCorePair dflags fun False 0 rhs)) } dsHsBind (PatBind { pat_lhs = pat, pat_rhs = grhss, pat_rhs_ty = ty , pat_ticks = (rhs_tick, var_ticks) }) = do { body_expr <- dsGuarded grhss ty ; let body' = mkOptTickBox rhs_tick body_expr ; sel_binds <- mkSelectorBinds var_ticks pat body' -- We silently ignore inline pragmas; no makeCorePair -- Not so cool, but really doesn't matter ; return (toOL sel_binds) } -- A common case: one exported variable -- Non-recursive bindings come through this way -- So do self-recursive bindings, and recursive bindings -- that have been chopped up with type signatures dsHsBind (AbsBinds { abs_tvs = tyvars, abs_ev_vars = dicts , abs_exports = [export] , abs_ev_binds = ev_binds, abs_binds = binds }) | ABE { abe_wrap = wrap, abe_poly = global , abe_mono = local, abe_prags = prags } <- export = do { dflags <- getDynFlags ; bind_prs <- ds_lhs_binds binds ; let core_bind = Rec (fromOL bind_prs) ; ds_binds <- dsTcEvBinds_s ev_binds ; rhs <- dsHsWrapper wrap $ -- Usually the identity mkLams tyvars $ mkLams dicts $ mkCoreLets ds_binds $ Let core_bind $ Var local ; (spec_binds, rules) <- dsSpecs rhs prags ; let global' = addIdSpecialisations global rules main_bind = makeCorePair dflags global' (isDefaultMethod prags) (dictArity dicts) rhs ; return (main_bind `consOL` spec_binds) } dsHsBind (AbsBinds { abs_tvs = tyvars, abs_ev_vars = dicts , abs_exports = exports, abs_ev_binds = ev_binds , abs_binds = binds }) -- See Note [Desugaring AbsBinds] = do { dflags <- getDynFlags ; bind_prs <- ds_lhs_binds binds ; let core_bind = Rec [ makeCorePair dflags (add_inline lcl_id) False 0 rhs | (lcl_id, rhs) <- fromOL bind_prs ] -- Monomorphic recursion possible, hence Rec locals = map abe_mono exports tup_expr = mkBigCoreVarTup locals tup_ty = exprType tup_expr ; ds_binds <- dsTcEvBinds_s ev_binds ; let poly_tup_rhs = mkLams tyvars $ mkLams dicts $ mkCoreLets ds_binds $ Let core_bind $ tup_expr ; poly_tup_id <- newSysLocalDs (exprType poly_tup_rhs) ; let mk_bind (ABE { abe_wrap = wrap, abe_poly = global , abe_mono = local, abe_prags = spec_prags }) = do { tup_id <- newSysLocalDs tup_ty ; rhs <- dsHsWrapper wrap $ mkLams tyvars $ mkLams dicts $ mkTupleSelector locals local tup_id $ mkVarApps (Var poly_tup_id) (tyvars ++ dicts) ; let rhs_for_spec = Let (NonRec poly_tup_id poly_tup_rhs) rhs ; (spec_binds, rules) <- dsSpecs rhs_for_spec spec_prags ; let global' = (global `setInlinePragma` defaultInlinePragma) `addIdSpecialisations` rules -- Kill the INLINE pragma because it applies to -- the user written (local) function. The global -- Id is just the selector. Hmm. ; return ((global', rhs) `consOL` spec_binds) } ; export_binds_s <- mapM mk_bind exports ; return ((poly_tup_id, poly_tup_rhs) `consOL` concatOL export_binds_s) } where inline_env :: IdEnv Id -- Maps a monomorphic local Id to one with -- the inline pragma from the source -- The type checker put the inline pragma -- on the *global* Id, so we need to transfer it inline_env = mkVarEnv [ (lcl_id, setInlinePragma lcl_id prag) | ABE { abe_mono = lcl_id, abe_poly = gbl_id } <- exports , let prag = idInlinePragma gbl_id ] add_inline :: Id -> Id -- tran add_inline lcl_id = lookupVarEnv inline_env lcl_id `orElse` lcl_id dsHsBind (PatSynBind{}) = panic "dsHsBind: PatSynBind" ------------------------ makeCorePair :: DynFlags -> Id -> Bool -> Arity -> CoreExpr -> (Id, CoreExpr) makeCorePair dflags gbl_id is_default_method dict_arity rhs | is_default_method -- Default methods are *always* inlined = (gbl_id `setIdUnfolding` mkCompulsoryUnfolding rhs, rhs) | DFunId is_newtype <- idDetails gbl_id = (mk_dfun_w_stuff is_newtype, rhs) | otherwise = case inlinePragmaSpec inline_prag of EmptyInlineSpec -> (gbl_id, rhs) NoInline -> (gbl_id, rhs) Inlinable -> (gbl_id `setIdUnfolding` inlinable_unf, rhs) Inline -> inline_pair where inline_prag = idInlinePragma gbl_id inlinable_unf = mkInlinableUnfolding dflags rhs inline_pair | Just arity <- inlinePragmaSat inline_prag -- Add an Unfolding for an INLINE (but not for NOINLINE) -- And eta-expand the RHS; see Note [Eta-expanding INLINE things] , let real_arity = dict_arity + arity -- NB: The arity in the InlineRule takes account of the dictionaries = ( gbl_id `setIdUnfolding` mkInlineUnfolding (Just real_arity) rhs , etaExpand real_arity rhs) | otherwise = pprTrace "makeCorePair: arity missing" (ppr gbl_id) $ (gbl_id `setIdUnfolding` mkInlineUnfolding Nothing rhs, rhs) -- See Note [ClassOp/DFun selection] in TcInstDcls -- See Note [Single-method classes] in TcInstDcls mk_dfun_w_stuff is_newtype | is_newtype = gbl_id `setIdUnfolding` mkInlineUnfolding (Just 0) rhs `setInlinePragma` alwaysInlinePragma { inl_sat = Just 0 } | otherwise = gbl_id `setIdUnfolding` mkDFunUnfolding dfun_bndrs dfun_constr dfun_args `setInlinePragma` dfunInlinePragma (dfun_bndrs, dfun_body) = collectBinders (simpleOptExpr rhs) (dfun_con, dfun_args) = collectArgs dfun_body dfun_constr | Var id <- dfun_con , DataConWorkId con <- idDetails id = con | otherwise = pprPanic "makeCorePair: dfun" (ppr rhs) dictArity :: [Var] -> Arity -- Don't count coercion variables in arity dictArity dicts = count isId dicts {- [Desugaring AbsBinds] ~~~~~~~~~~~~~~~~~~~~~ In the general AbsBinds case we desugar the binding to this: tup a (d:Num a) = let fm = ...gm... gm = ...fm... in (fm,gm) f a d = case tup a d of { (fm,gm) -> fm } g a d = case tup a d of { (fm,gm) -> fm } Note [Rules and inlining] ~~~~~~~~~~~~~~~~~~~~~~~~~ Common special case: no type or dictionary abstraction This is a bit less trivial than you might suppose The naive way woudl be to desguar to something like f_lcl = ...f_lcl... -- The "binds" from AbsBinds M.f = f_lcl -- Generated from "exports" But we don't want that, because if M.f isn't exported, it'll be inlined unconditionally at every call site (its rhs is trivial). That would be ok unless it has RULES, which would thereby be completely lost. Bad, bad, bad. Instead we want to generate M.f = ...f_lcl... f_lcl = M.f Now all is cool. The RULES are attached to M.f (by SimplCore), and f_lcl is rapidly inlined away. This does not happen in the same way to polymorphic binds, because they desugar to M.f = /\a. let f_lcl = ...f_lcl... in f_lcl Although I'm a bit worried about whether full laziness might float the f_lcl binding out and then inline M.f at its call site Note [Specialising in no-dict case] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Even if there are no tyvars or dicts, we may have specialisation pragmas. Class methods can generate AbsBinds [] [] [( ... spec-prag] { AbsBinds [tvs] [dicts] ...blah } So the overloading is in the nested AbsBinds. A good example is in GHC.Float: class (Real a, Fractional a) => RealFrac a where round :: (Integral b) => a -> b instance RealFrac Float where {-# SPECIALIZE round :: Float -> Int #-} The top-level AbsBinds for $cround has no tyvars or dicts (because the instance does not). But the method is locally overloaded! Note [Abstracting over tyvars only] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When abstracting over type variable only (not dictionaries), we don't really need to built a tuple and select from it, as we do in the general case. Instead we can take AbsBinds [a,b] [ ([a,b], fg, fl, _), ([b], gg, gl, _) ] { fl = e1 gl = e2 h = e3 } and desugar it to fg = /\ab. let B in e1 gg = /\b. let a = () in let B in S(e2) h = /\ab. let B in e3 where B is the *non-recursive* binding fl = fg a b gl = gg b h = h a b -- See (b); note shadowing! Notice (a) g has a different number of type variables to f, so we must use the mkArbitraryType thing to fill in the gaps. We use a type-let to do that. (b) The local variable h isn't in the exports, and rather than clone a fresh copy we simply replace h by (h a b), where the two h's have different types! Shadowing happens here, which looks confusing but works fine. (c) The result is *still* quadratic-sized if there are a lot of small bindings. So if there are more than some small number (10), we filter the binding set B by the free variables of the particular RHS. Tiresome. Why got to this trouble? It's a common case, and it removes the quadratic-sized tuple desugaring. Less clutter, hopefully faster compilation, especially in a case where there are a *lot* of bindings. Note [Eta-expanding INLINE things] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider foo :: Eq a => a -> a {-# INLINE foo #-} foo x = ... If (foo d) ever gets floated out as a common sub-expression (which can happen as a result of method sharing), there's a danger that we never get to do the inlining, which is a Terribly Bad thing given that the user said "inline"! To avoid this we pre-emptively eta-expand the definition, so that foo has the arity with which it is declared in the source code. In this example it has arity 2 (one for the Eq and one for x). Doing this should mean that (foo d) is a PAP and we don't share it. Note [Nested arities] ~~~~~~~~~~~~~~~~~~~~~ For reasons that are not entirely clear, method bindings come out looking like this: AbsBinds [] [] [$cfromT <= [] fromT] $cfromT [InlPrag=INLINE] :: T Bool -> Bool { AbsBinds [] [] [fromT <= [] fromT_1] fromT :: T Bool -> Bool { fromT_1 ((TBool b)) = not b } } } Note the nested AbsBind. The arity for the InlineRule on $cfromT should be gotten from the binding for fromT_1. It might be better to have just one level of AbsBinds, but that requires more thought! -} ------------------------ dsSpecs :: CoreExpr -- Its rhs -> TcSpecPrags -> DsM ( OrdList (Id,CoreExpr) -- Binding for specialised Ids , [CoreRule] ) -- Rules for the Global Ids -- See Note [Handling SPECIALISE pragmas] in TcBinds dsSpecs _ IsDefaultMethod = return (nilOL, []) dsSpecs poly_rhs (SpecPrags sps) = do { pairs <- mapMaybeM (dsSpec (Just poly_rhs)) sps ; let (spec_binds_s, rules) = unzip pairs ; return (concatOL spec_binds_s, rules) } dsSpec :: Maybe CoreExpr -- Just rhs => RULE is for a local binding -- Nothing => RULE is for an imported Id -- rhs is in the Id's unfolding -> Located TcSpecPrag -> DsM (Maybe (OrdList (Id,CoreExpr), CoreRule)) dsSpec mb_poly_rhs (L loc (SpecPrag poly_id spec_co spec_inl)) | isJust (isClassOpId_maybe poly_id) = putSrcSpanDs loc $ do { warnDs (ptext (sLit "Ignoring useless SPECIALISE pragma for class method selector") <+> quotes (ppr poly_id)) ; return Nothing } -- There is no point in trying to specialise a class op -- Moreover, classops don't (currently) have an inl_sat arity set -- (it would be Just 0) and that in turn makes makeCorePair bleat | no_act_spec && isNeverActive rule_act = putSrcSpanDs loc $ do { warnDs (ptext (sLit "Ignoring useless SPECIALISE pragma for NOINLINE function:") <+> quotes (ppr poly_id)) ; return Nothing } -- Function is NOINLINE, and the specialiation inherits that -- See Note [Activation pragmas for SPECIALISE] | otherwise = putSrcSpanDs loc $ do { uniq <- newUnique ; let poly_name = idName poly_id spec_occ = mkSpecOcc (getOccName poly_name) spec_name = mkInternalName uniq spec_occ (getSrcSpan poly_name) ; (bndrs, ds_lhs) <- liftM collectBinders (dsHsWrapper spec_co (Var poly_id)) ; let spec_ty = mkPiTypes bndrs (exprType ds_lhs) ; -- pprTrace "dsRule" (vcat [ ptext (sLit "Id:") <+> ppr poly_id -- , ptext (sLit "spec_co:") <+> ppr spec_co -- , ptext (sLit "ds_rhs:") <+> ppr ds_lhs ]) $ case decomposeRuleLhs bndrs ds_lhs of { Left msg -> do { warnDs msg; return Nothing } ; Right (rule_bndrs, _fn, args) -> do { dflags <- getDynFlags ; this_mod <- getModule ; let fn_unf = realIdUnfolding poly_id unf_fvs = stableUnfoldingVars fn_unf `orElse` emptyVarSet in_scope = mkInScopeSet (unf_fvs `unionVarSet` exprsFreeVars args) spec_unf = specUnfolding dflags (mkEmptySubst in_scope) bndrs args fn_unf spec_id = mkLocalId spec_name spec_ty `setInlinePragma` inl_prag `setIdUnfolding` spec_unf rule = mkRule this_mod False {- Not auto -} is_local_id (mkFastString ("SPEC " ++ showPpr dflags poly_name)) rule_act poly_name rule_bndrs args (mkVarApps (Var spec_id) bndrs) ; spec_rhs <- dsHsWrapper spec_co poly_rhs -- Commented out: see Note [SPECIALISE on INLINE functions] -- ; when (isInlinePragma id_inl) -- (warnDs $ ptext (sLit "SPECIALISE pragma on INLINE function probably won't fire:") -- <+> quotes (ppr poly_name)) ; return (Just (unitOL (spec_id, spec_rhs), rule)) -- NB: do *not* use makeCorePair on (spec_id,spec_rhs), because -- makeCorePair overwrites the unfolding, which we have -- just created using specUnfolding } } } where is_local_id = isJust mb_poly_rhs poly_rhs | Just rhs <- mb_poly_rhs = rhs -- Local Id; this is its rhs | Just unfolding <- maybeUnfoldingTemplate (realIdUnfolding poly_id) = unfolding -- Imported Id; this is its unfolding -- Use realIdUnfolding so we get the unfolding -- even when it is a loop breaker. -- We want to specialise recursive functions! | otherwise = pprPanic "dsImpSpecs" (ppr poly_id) -- The type checker has checked that it *has* an unfolding id_inl = idInlinePragma poly_id -- See Note [Activation pragmas for SPECIALISE] inl_prag | not (isDefaultInlinePragma spec_inl) = spec_inl | not is_local_id -- See Note [Specialising imported functions] -- in OccurAnal , isStrongLoopBreaker (idOccInfo poly_id) = neverInlinePragma | otherwise = id_inl -- Get the INLINE pragma from SPECIALISE declaration, or, -- failing that, from the original Id spec_prag_act = inlinePragmaActivation spec_inl -- See Note [Activation pragmas for SPECIALISE] -- no_act_spec is True if the user didn't write an explicit -- phase specification in the SPECIALISE pragma no_act_spec = case inlinePragmaSpec spec_inl of NoInline -> isNeverActive spec_prag_act _ -> isAlwaysActive spec_prag_act rule_act | no_act_spec = inlinePragmaActivation id_inl -- Inherit | otherwise = spec_prag_act -- Specified by user {- Note [SPECIALISE on INLINE functions] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We used to warn that using SPECIALISE for a function marked INLINE would be a no-op; but it isn't! Especially with worker/wrapper split we might have {-# INLINE f #-} f :: Ord a => Int -> a -> ... f d x y = case x of I# x' -> $wf d x' y We might want to specialise 'f' so that we in turn specialise '$wf'. We can't even /name/ '$wf' in the source code, so we can't specialise it even if we wanted to. Trac #10721 is a case in point. Note [Activation pragmas for SPECIALISE] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ From a user SPECIALISE pragma for f, we generate a) A top-level binding spec_fn = rhs b) A RULE f dOrd = spec_fn We need two pragma-like things: * spec_fn's inline pragma: inherited from f's inline pragma (ignoring activation on SPEC), unless overriden by SPEC INLINE * Activation of RULE: from SPECIALISE pragma (if activation given) otherwise from f's inline pragma This is not obvious (see Trac #5237)! Examples Rule activation Inline prag on spec'd fn --------------------------------------------------------------------- SPEC [n] f :: ty [n] Always, or NOINLINE [n] copy f's prag NOINLINE f SPEC [n] f :: ty [n] NOINLINE copy f's prag NOINLINE [k] f SPEC [n] f :: ty [n] NOINLINE [k] copy f's prag INLINE [k] f SPEC [n] f :: ty [n] INLINE [k] copy f's prag SPEC INLINE [n] f :: ty [n] INLINE [n] (ignore INLINE prag on f, same activation for rule and spec'd fn) NOINLINE [k] f SPEC f :: ty [n] INLINE [k] ************************************************************************ * * \subsection{Adding inline pragmas} * * ************************************************************************ -} decomposeRuleLhs :: [Var] -> CoreExpr -> Either SDoc ([Var], Id, [CoreExpr]) -- (decomposeRuleLhs bndrs lhs) takes apart the LHS of a RULE, -- The 'bndrs' are the quantified binders of the rules, but decomposeRuleLhs -- may add some extra dictionary binders (see Note [Free dictionaries]) -- -- Returns Nothing if the LHS isn't of the expected shape -- Note [Decomposing the left-hand side of a RULE] decomposeRuleLhs orig_bndrs orig_lhs | not (null unbound) -- Check for things unbound on LHS -- See Note [Unused spec binders] = Left (vcat (map dead_msg unbound)) | Just (fn_id, args) <- decompose fun2 args2 , let extra_dict_bndrs = mk_extra_dict_bndrs fn_id args = -- pprTrace "decmposeRuleLhs" (vcat [ ptext (sLit "orig_bndrs:") <+> ppr orig_bndrs -- , ptext (sLit "orig_lhs:") <+> ppr orig_lhs -- , ptext (sLit "lhs1:") <+> ppr lhs1 -- , ptext (sLit "extra_dict_bndrs:") <+> ppr extra_dict_bndrs -- , ptext (sLit "fn_id:") <+> ppr fn_id -- , ptext (sLit "args:") <+> ppr args]) $ Right (orig_bndrs ++ extra_dict_bndrs, fn_id, args) | otherwise = Left bad_shape_msg where lhs1 = drop_dicts orig_lhs lhs2 = simpleOptExpr lhs1 -- See Note [Simplify rule LHS] (fun2,args2) = collectArgs lhs2 lhs_fvs = exprFreeVars lhs2 unbound = filterOut (`elemVarSet` lhs_fvs) orig_bndrs orig_bndr_set = mkVarSet orig_bndrs -- Add extra dict binders: Note [Free dictionaries] mk_extra_dict_bndrs fn_id args = [ mkLocalId (localiseName (idName d)) (idType d) | d <- varSetElems (exprsFreeVars args `delVarSetList` (fn_id : orig_bndrs)) -- fn_id: do not quantify over the function itself, which may -- itself be a dictionary (in pathological cases, Trac #10251) , isDictId d ] decompose (Var fn_id) args | not (fn_id `elemVarSet` orig_bndr_set) = Just (fn_id, args) decompose _ _ = Nothing bad_shape_msg = hang (ptext (sLit "RULE left-hand side too complicated to desugar")) 2 (vcat [ text "Optimised lhs:" <+> ppr lhs2 , text "Orig lhs:" <+> ppr orig_lhs]) dead_msg bndr = hang (sep [ ptext (sLit "Forall'd") <+> pp_bndr bndr , ptext (sLit "is not bound in RULE lhs")]) 2 (vcat [ text "Orig bndrs:" <+> ppr orig_bndrs , text "Orig lhs:" <+> ppr orig_lhs , text "optimised lhs:" <+> ppr lhs2 ]) pp_bndr bndr | isTyVar bndr = ptext (sLit "type variable") <+> quotes (ppr bndr) | Just pred <- evVarPred_maybe bndr = ptext (sLit "constraint") <+> quotes (ppr pred) | otherwise = ptext (sLit "variable") <+> quotes (ppr bndr) drop_dicts :: CoreExpr -> CoreExpr drop_dicts e = wrap_lets needed bnds body where needed = orig_bndr_set `minusVarSet` exprFreeVars body (bnds, body) = split_lets (occurAnalyseExpr e) -- The occurAnalyseExpr drops dead bindings which is -- crucial to ensure that every binding is used later; -- which in turn makes wrap_lets work right split_lets :: CoreExpr -> ([(DictId,CoreExpr)], CoreExpr) split_lets e | Let (NonRec d r) body <- e , isDictId d , (bs, body') <- split_lets body = ((d,r):bs, body') | otherwise = ([], e) wrap_lets :: VarSet -> [(DictId,CoreExpr)] -> CoreExpr -> CoreExpr wrap_lets _ [] body = body wrap_lets needed ((d, r) : bs) body | rhs_fvs `intersectsVarSet` needed = Let (NonRec d r) (wrap_lets needed' bs body) | otherwise = wrap_lets needed bs body where rhs_fvs = exprFreeVars r needed' = (needed `minusVarSet` rhs_fvs) `extendVarSet` d {- Note [Decomposing the left-hand side of a RULE] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ There are several things going on here. * drop_dicts: see Note [Drop dictionary bindings on rule LHS] * simpleOptExpr: see Note [Simplify rule LHS] * extra_dict_bndrs: see Note [Free dictionaries] Note [Drop dictionary bindings on rule LHS] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ drop_dicts drops dictionary bindings on the LHS where possible. E.g. let d:Eq [Int] = $fEqList $fEqInt in f d --> f d Reasoning here is that there is only one d:Eq [Int], and so we can quantify over it. That makes 'd' free in the LHS, but that is later picked up by extra_dict_bndrs (Note [Dead spec binders]). NB 1: We can only drop the binding if the RHS doesn't bind one of the orig_bndrs, which we assume occur on RHS. Example f :: (Eq a) => b -> a -> a {-# SPECIALISE f :: Eq a => b -> [a] -> [a] #-} Here we want to end up with RULE forall d:Eq a. f ($dfEqList d) = f_spec d Of course, the ($dfEqlist d) in the pattern makes it less likely to match, but there is no other way to get d:Eq a NB 2: We do drop_dicts *before* simplOptEpxr, so that we expect all the evidence bindings to be wrapped around the outside of the LHS. (After simplOptExpr they'll usually have been inlined.) dsHsWrapper does dependency analysis, so that civilised ones will be simple NonRec bindings. We don't handle recursive dictionaries! NB3: In the common case of a non-overloaded, but perhaps-polymorphic specialisation, we don't need to bind *any* dictionaries for use in the RHS. For example (Trac #8331) {-# SPECIALIZE INLINE useAbstractMonad :: ReaderST s Int #-} useAbstractMonad :: MonadAbstractIOST m => m Int Here, deriving (MonadAbstractIOST (ReaderST s)) is a lot of code but the RHS uses no dictionaries, so we want to end up with RULE forall s (d :: MonadAbstractIOST (ReaderT s)). useAbstractMonad (ReaderT s) d = $suseAbstractMonad s Trac #8848 is a good example of where there are some intersting dictionary bindings to discard. The drop_dicts algorithm is based on these observations: * Given (let d = rhs in e) where d is a DictId, matching 'e' will bind e's free variables. * So we want to keep the binding if one of the needed variables (for which we need a binding) is in fv(rhs) but not already in fv(e). * The "needed variables" are simply the orig_bndrs. Consider f :: (Eq a, Show b) => a -> b -> String ... SPECIALISE f :: (Show b) => Int -> b -> String ... Then orig_bndrs includes the *quantified* dictionaries of the type namely (dsb::Show b), but not the one for Eq Int So we work inside out, applying the above criterion at each step. Note [Simplify rule LHS] ~~~~~~~~~~~~~~~~~~~~~~~~ simplOptExpr occurrence-analyses and simplifies the LHS: (a) Inline any remaining dictionary bindings (which hopefully occur just once) (b) Substitute trivial lets so that they don't get in the way Note that we substitute the function too; we might have this as a LHS: let f71 = M.f Int in f71 (c) Do eta reduction. To see why, consider the fold/build rule, which without simplification looked like: fold k z (build (/\a. g a)) ==> ... This doesn't match unless you do eta reduction on the build argument. Similarly for a LHS like augment g (build h) we do not want to get augment (\a. g a) (build h) otherwise we don't match when given an argument like augment (\a. h a a) (build h) Note [Matching seqId] ~~~~~~~~~~~~~~~~~~~ The desugarer turns (seq e r) into (case e of _ -> r), via a special-case hack and this code turns it back into an application of seq! See Note [Rules for seq] in MkId for the details. Note [Unused spec binders] ~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider f :: a -> a ... SPECIALISE f :: Eq a => a -> a ... It's true that this *is* a more specialised type, but the rule we get is something like this: f_spec d = f RULE: f = f_spec d Note that the rule is bogus, because it mentions a 'd' that is not bound on the LHS! But it's a silly specialisation anyway, because the constraint is unused. We could bind 'd' to (error "unused") but it seems better to reject the program because it's almost certainly a mistake. That's what the isDeadBinder call detects. Note [Free dictionaries] ~~~~~~~~~~~~~~~~~~~~~~~~ When the LHS of a specialisation rule, (/\as\ds. f es) has a free dict, which is presumably in scope at the function definition site, we can quantify over it too. *Any* dict with that type will do. So for example when you have f :: Eq a => a -> a f = <rhs> ... SPECIALISE f :: Int -> Int ... Then we get the SpecPrag SpecPrag (f Int dInt) And from that we want the rule RULE forall dInt. f Int dInt = f_spec f_spec = let f = <rhs> in f Int dInt But be careful! That dInt might be GHC.Base.$fOrdInt, which is an External Name, and you can't bind them in a lambda or forall without getting things confused. Likewise it might have an InlineRule or something, which would be utterly bogus. So we really make a fresh Id, with the same unique and type as the old one, but with an Internal name and no IdInfo. ************************************************************************ * * Desugaring evidence * * ************************************************************************ -} dsHsWrapper :: HsWrapper -> CoreExpr -> DsM CoreExpr dsHsWrapper WpHole e = return e dsHsWrapper (WpTyApp ty) e = return $ App e (Type ty) dsHsWrapper (WpLet ev_binds) e = do bs <- dsTcEvBinds ev_binds return (mkCoreLets bs e) dsHsWrapper (WpCompose c1 c2) e = do { e1 <- dsHsWrapper c2 e ; dsHsWrapper c1 e1 } dsHsWrapper (WpFun c1 c2 t1 _) e = do { x <- newSysLocalDs t1 ; e1 <- dsHsWrapper c1 (Var x) ; e2 <- dsHsWrapper c2 (e `mkCoreAppDs` e1) ; return (Lam x e2) } dsHsWrapper (WpCast co) e = ASSERT(tcCoercionRole co == Representational) dsTcCoercion co (mkCastDs e) dsHsWrapper (WpEvLam ev) e = return $ Lam ev e dsHsWrapper (WpTyLam tv) e = return $ Lam tv e dsHsWrapper (WpEvApp tm) e = liftM (App e) (dsEvTerm tm) -------------------------------------- dsTcEvBinds_s :: [TcEvBinds] -> DsM [CoreBind] dsTcEvBinds_s [] = return [] dsTcEvBinds_s (b:rest) = ASSERT( null rest ) -- Zonker ensures null dsTcEvBinds b dsTcEvBinds :: TcEvBinds -> DsM [CoreBind] dsTcEvBinds (TcEvBinds {}) = panic "dsEvBinds" -- Zonker has got rid of this dsTcEvBinds (EvBinds bs) = dsEvBinds bs dsEvBinds :: Bag EvBind -> DsM [CoreBind] dsEvBinds bs = mapM ds_scc (sccEvBinds bs) where ds_scc (AcyclicSCC (EvBind { eb_lhs = v, eb_rhs = r })) = liftM (NonRec v) (dsEvTerm r) ds_scc (CyclicSCC bs) = liftM Rec (mapM ds_pair bs) ds_pair (EvBind { eb_lhs = v, eb_rhs = r }) = liftM ((,) v) (dsEvTerm r) sccEvBinds :: Bag EvBind -> [SCC EvBind] sccEvBinds bs = stronglyConnCompFromEdgedVertices edges where edges :: [(EvBind, EvVar, [EvVar])] edges = foldrBag ((:) . mk_node) [] bs mk_node :: EvBind -> (EvBind, EvVar, [EvVar]) mk_node b@(EvBind { eb_lhs = var, eb_rhs = term }) = (b, var, varSetElems (evVarsOfTerm term)) --------------------------------------- dsEvTerm :: EvTerm -> DsM CoreExpr dsEvTerm (EvId v) = return (Var v) dsEvTerm (EvCast tm co) = do { tm' <- dsEvTerm tm ; dsTcCoercion co $ mkCastDs tm' } -- 'v' is always a lifted evidence variable so it is -- unnecessary to call varToCoreExpr v here. dsEvTerm (EvDFunApp df tys tms) = return (Var df `mkTyApps` tys `mkApps` (map Var tms)) dsEvTerm (EvCoercion (TcCoVarCo v)) = return (Var v) -- See Note [Simple coercions] dsEvTerm (EvCoercion co) = dsTcCoercion co mkEqBox dsEvTerm (EvSuperClass d n) = do { d' <- dsEvTerm d ; let (cls, tys) = getClassPredTys (exprType d') sc_sel_id = classSCSelId cls n -- Zero-indexed ; return $ Var sc_sel_id `mkTyApps` tys `App` d' } dsEvTerm (EvDelayedError ty msg) = return $ Var errorId `mkTyApps` [ty] `mkApps` [litMsg] where errorId = tYPE_ERROR_ID litMsg = Lit (MachStr (fastStringToByteString msg)) dsEvTerm (EvLit l) = case l of EvNum n -> mkIntegerExpr n EvStr s -> mkStringExprFS s dsEvTerm (EvCallStack cs) = dsEvCallStack cs dsEvTerm (EvTypeable ev) = dsEvTypeable ev dsEvTypeable :: EvTypeable -> DsM CoreExpr dsEvTypeable ev = do tyCl <- dsLookupTyCon typeableClassName typeRepTc <- dsLookupTyCon typeRepTyConName let tyRepType = mkTyConApp typeRepTc [] (ty, rep) <- case ev of EvTypeableTyCon tc ks -> do ctr <- dsLookupGlobalId mkPolyTyConAppName mkTyCon <- dsLookupGlobalId mkTyConName dflags <- getDynFlags let mkRep cRep kReps tReps = mkApps (Var ctr) [ cRep, mkListExpr tyRepType kReps , mkListExpr tyRepType tReps ] let kindRep k = case splitTyConApp_maybe k of Nothing -> panic "dsEvTypeable: not a kind constructor" Just (kc,ks) -> do kcRep <- tyConRep dflags mkTyCon kc reps <- mapM kindRep ks return (mkRep kcRep [] reps) tcRep <- tyConRep dflags mkTyCon tc kReps <- mapM kindRep ks return ( mkTyConApp tc ks , mkRep tcRep kReps [] ) EvTypeableTyApp t1 t2 -> do e1 <- getRep tyCl t1 e2 <- getRep tyCl t2 ctr <- dsLookupGlobalId mkAppTyName return ( mkAppTy (snd t1) (snd t2) , mkApps (Var ctr) [ e1, e2 ] ) EvTypeableTyLit t -> do e <- tyLitRep t return (snd t, e) -- TyRep -> Typeable t -- see also: Note [Memoising typeOf] repName <- newSysLocalDs tyRepType let proxyT = mkProxyPrimTy (typeKind ty) ty method = bindNonRec repName rep $ mkLams [mkWildValBinder proxyT] (Var repName) -- package up the method as `Typeable` dictionary return $ mkCastDs method $ mkSymCo $ getTypeableCo tyCl ty where -- co: method -> Typeable k t getTypeableCo tc t = case instNewTyCon_maybe tc [typeKind t, t] of Just (_,co) -> co _ -> panic "Class `Typeable` is not a `newtype`." -- Typeable t -> TyRep getRep tc (ev,t) = do typeableExpr <- dsEvTerm ev let co = getTypeableCo tc t method = mkCastDs typeableExpr co proxy = mkTyApps (Var proxyHashId) [typeKind t, t] return (mkApps method [proxy]) -- KnownNat t -> TyRep (also used for KnownSymbol) tyLitRep (ev,t) = do dict <- dsEvTerm ev fun <- dsLookupGlobalId $ case typeKind t of k | eqType k typeNatKind -> typeNatTypeRepName | eqType k typeSymbolKind -> typeSymbolTypeRepName | otherwise -> panic "dsEvTypeable: unknown type lit kind" let finst = mkTyApps (Var fun) [t] proxy = mkTyApps (Var proxyHashId) [typeKind t, t] return (mkApps finst [ dict, proxy ]) -- This part could be cached tyConRep dflags mkTyCon tc = do pkgStr <- mkStringExprFS pkg_fs modStr <- mkStringExprFS modl_fs nameStr <- mkStringExprFS name_fs return (mkApps (Var mkTyCon) [ int64 high, int64 low , pkgStr, modStr, nameStr ]) where tycon_name = tyConName tc modl = nameModule tycon_name pkg = modulePackageKey modl modl_fs = moduleNameFS (moduleName modl) pkg_fs = packageKeyFS pkg name_fs = occNameFS (nameOccName tycon_name) hash_name_fs | isPromotedTyCon tc = appendFS (mkFastString "$k") name_fs | isPromotedDataCon tc = appendFS (mkFastString "$c") name_fs | isTupleTyCon tc && returnsConstraintKind (tyConKind tc) = appendFS (mkFastString "$p") name_fs | otherwise = name_fs hashThis = unwords $ map unpackFS [pkg_fs, modl_fs, hash_name_fs] Fingerprint high low = fingerprintString hashThis int64 | wORD_SIZE dflags == 4 = mkWord64LitWord64 | otherwise = mkWordLit dflags . fromIntegral {- Note [Memoising typeOf] ~~~~~~~~~~~~~~~~~~~~~~~~~~ See #3245, #9203 IMPORTANT: we don't want to recalculate the TypeRep once per call with the proxy argument. This is what went wrong in #3245 and #9203. So we help GHC by manually keeping the 'rep' *outside* the lambda. -} dsEvCallStack :: EvCallStack -> DsM CoreExpr -- See Note [Overview of implicit CallStacks] in TcEvidence.hs dsEvCallStack cs = do df <- getDynFlags m <- getModule srcLocDataCon <- dsLookupDataCon srcLocDataConName let srcLocTyCon = dataConTyCon srcLocDataCon let srcLocTy = mkTyConTy srcLocTyCon let mkSrcLoc l = liftM (mkCoreConApps srcLocDataCon) (sequence [ mkStringExprFS (packageKeyFS $ modulePackageKey m) , mkStringExprFS (moduleNameFS $ moduleName m) , mkStringExprFS (srcSpanFile l) , return $ mkIntExprInt df (srcSpanStartLine l) , return $ mkIntExprInt df (srcSpanStartCol l) , return $ mkIntExprInt df (srcSpanEndLine l) , return $ mkIntExprInt df (srcSpanEndCol l) ]) let callSiteTy = mkBoxedTupleTy [stringTy, srcLocTy] matchId <- newSysLocalDs $ mkListTy callSiteTy callStackDataCon <- dsLookupDataCon callStackDataConName let callStackTyCon = dataConTyCon callStackDataCon let callStackTy = mkTyConTy callStackTyCon let emptyCS = mkCoreConApps callStackDataCon [mkNilExpr callSiteTy] let pushCS name loc rest = mkWildCase rest callStackTy callStackTy [( DataAlt callStackDataCon , [matchId] , mkCoreConApps callStackDataCon [mkConsExpr callSiteTy (mkCoreTup [name, loc]) (Var matchId)] )] let mkPush name loc tm = do nameExpr <- mkStringExprFS name locExpr <- mkSrcLoc loc case tm of EvCallStack EvCsEmpty -> return (pushCS nameExpr locExpr emptyCS) _ -> do tmExpr <- dsEvTerm tm -- at this point tmExpr :: IP sym CallStack -- but we need the actual CallStack to pass to pushCS, -- so we use unwrapIP to strip the dictionary wrapper -- See Note [Overview of implicit CallStacks] let ip_co = unwrapIP (exprType tmExpr) return (pushCS nameExpr locExpr (mkCastDs tmExpr ip_co)) case cs of EvCsTop name loc tm -> mkPush name loc tm EvCsPushCall name loc tm -> mkPush (occNameFS $ getOccName name) loc tm EvCsEmpty -> panic "Cannot have an empty CallStack" --------------------------------------- dsTcCoercion :: TcCoercion -> (Coercion -> CoreExpr) -> DsM CoreExpr -- This is the crucial function that moves -- from TcCoercions to Coercions; see Note [TcCoercions] in Coercion -- e.g. dsTcCoercion (trans g1 g2) k -- = case g1 of EqBox g1# -> -- case g2 of EqBox g2# -> -- k (trans g1# g2#) -- thing_inside will get a coercion at the role requested dsTcCoercion co thing_inside = do { us <- newUniqueSupply ; let eqvs_covs :: [(EqVar,CoVar)] eqvs_covs = zipWith mk_co_var (varSetElems (coVarsOfTcCo co)) (uniqsFromSupply us) subst = mkCvSubst emptyInScopeSet [(eqv, mkCoVarCo cov) | (eqv, cov) <- eqvs_covs] result_expr = thing_inside (ds_tc_coercion subst co) result_ty = exprType result_expr ; return (foldr (wrap_in_case result_ty) result_expr eqvs_covs) } where mk_co_var :: Id -> Unique -> (Id, Id) mk_co_var eqv uniq = (eqv, mkUserLocal occ uniq ty loc) where eq_nm = idName eqv occ = nameOccName eq_nm loc = nameSrcSpan eq_nm ty = mkCoercionType (getEqPredRole (evVarPred eqv)) ty1 ty2 (ty1, ty2) = getEqPredTys (evVarPred eqv) wrap_in_case result_ty (eqv, cov) body = case getEqPredRole (evVarPred eqv) of Nominal -> Case (Var eqv) eqv result_ty [(DataAlt eqBoxDataCon, [cov], body)] Representational -> Case (Var eqv) eqv result_ty [(DataAlt coercibleDataCon, [cov], body)] Phantom -> panic "wrap_in_case/phantom" ds_tc_coercion :: CvSubst -> TcCoercion -> Coercion -- If the incoming TcCoercion if of type (a ~ b) (resp. Coercible a b) -- the result is of type (a ~# b) (reps. a ~# b) -- The VarEnv maps EqVars of type (a ~ b) to Coercions of type (a ~# b) (resp. and so on) -- No need for InScope set etc because the ds_tc_coercion subst tc_co = go tc_co where go (TcRefl r ty) = Refl r (Coercion.substTy subst ty) go (TcTyConAppCo r tc cos) = mkTyConAppCo r tc (map go cos) go (TcAppCo co1 co2) = mkAppCo (go co1) (go co2) go (TcForAllCo tv co) = mkForAllCo tv' (ds_tc_coercion subst' co) where (subst', tv') = Coercion.substTyVarBndr subst tv go (TcAxiomInstCo ax ind cos) = AxiomInstCo ax ind (map go cos) go (TcPhantomCo ty1 ty2) = UnivCo (fsLit "ds_tc_coercion") Phantom ty1 ty2 go (TcSymCo co) = mkSymCo (go co) go (TcTransCo co1 co2) = mkTransCo (go co1) (go co2) go (TcNthCo n co) = mkNthCo n (go co) go (TcLRCo lr co) = mkLRCo lr (go co) go (TcSubCo co) = mkSubCo (go co) go (TcLetCo bs co) = ds_tc_coercion (ds_co_binds bs) co go (TcCastCo co1 co2) = mkCoCast (go co1) (go co2) go (TcCoVarCo v) = ds_ev_id subst v go (TcAxiomRuleCo co ts cs) = AxiomRuleCo co (map (Coercion.substTy subst) ts) (map go cs) go (TcCoercion co) = co ds_co_binds :: TcEvBinds -> CvSubst ds_co_binds (EvBinds bs) = foldl ds_scc subst (sccEvBinds bs) ds_co_binds eb@(TcEvBinds {}) = pprPanic "ds_co_binds" (ppr eb) ds_scc :: CvSubst -> SCC EvBind -> CvSubst ds_scc subst (AcyclicSCC (EvBind { eb_lhs = v, eb_rhs = ev_term })) = extendCvSubstAndInScope subst v (ds_co_term subst ev_term) ds_scc _ (CyclicSCC other) = pprPanic "ds_scc:cyclic" (ppr other $$ ppr tc_co) ds_co_term :: CvSubst -> EvTerm -> Coercion ds_co_term subst (EvCoercion tc_co) = ds_tc_coercion subst tc_co ds_co_term subst (EvId v) = ds_ev_id subst v ds_co_term subst (EvCast tm co) = mkCoCast (ds_co_term subst tm) (ds_tc_coercion subst co) ds_co_term _ other = pprPanic "ds_co_term" (ppr other $$ ppr tc_co) ds_ev_id :: CvSubst -> EqVar -> Coercion ds_ev_id subst v | Just co <- Coercion.lookupCoVar subst v = co | otherwise = pprPanic "ds_tc_coercion" (ppr v $$ ppr tc_co) {- Note [Simple coercions] ~~~~~~~~~~~~~~~~~~~~~~~ We have a special case for coercions that are simple variables. Suppose cv :: a ~ b is in scope Lacking the special case, if we see f a b cv we'd desguar to f a b (case cv of EqBox (cv# :: a ~# b) -> EqBox cv#) which is a bit stupid. The special case does the obvious thing. This turns out to be important when desugaring the LHS of a RULE (see Trac #7837). Suppose we have normalise :: (a ~ Scalar a) => a -> a normalise_Double :: Double -> Double {-# RULES "normalise" normalise = normalise_Double #-} Then the RULE we want looks like forall a, (cv:a~Scalar a). normalise a cv = normalise_Double But without the special case we generate the redundant box/unbox, which simpleOpt (currently) doesn't remove. So the rule never matches. Maybe simpleOpt should be smarter. But it seems like a good plan to simply never generate the redundant box/unbox in the first place. -}
acowley/ghc
compiler/deSugar/DsBinds.hs
bsd-3-clause
48,323
0
24
15,238
8,288
4,232
4,056
543
21
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE NoImplicitPrelude, MagicHash, UnboxedTuples #-} {-# OPTIONS_HADDOCK hide #-} ----------------------------------------------------------------------------- -- | -- Module : GHC.Num -- Copyright : (c) The University of Glasgow 1994-2002 -- License : see libraries/base/LICENSE -- -- Maintainer : [email protected] -- Stability : internal -- Portability : non-portable (GHC Extensions) -- -- The 'Num' class and the 'Integer' type. -- ----------------------------------------------------------------------------- module GHC.Num (module GHC.Num, module GHC.Integer) where import GHC.Base import GHC.Integer infixl 7 * infixl 6 +, - default () -- Double isn't available yet, -- and we shouldn't be using defaults anyway -- | Basic numeric class. class Num a where {-# MINIMAL (+), (*), abs, signum, fromInteger, (negate | (-)) #-} (+), (-), (*) :: a -> a -> a -- | Unary negation. negate :: a -> a -- | Absolute value. abs :: a -> a -- | Sign of a number. -- The functions 'abs' and 'signum' should satisfy the law: -- -- > abs x * signum x == x -- -- For real numbers, the 'signum' is either @-1@ (negative), @0@ (zero) -- or @1@ (positive). signum :: a -> a -- | Conversion from an 'Integer'. -- An integer literal represents the application of the function -- 'fromInteger' to the appropriate value of type 'Integer', -- so such literals have type @('Num' a) => a@. fromInteger :: Integer -> a {-# INLINE (-) #-} {-# INLINE negate #-} x - y = x + negate y negate x = 0 - x -- | the same as @'flip' ('-')@. -- -- Because @-@ is treated specially in the Haskell grammar, -- @(-@ /e/@)@ is not a section, but an application of prefix negation. -- However, @('subtract'@ /exp/@)@ is equivalent to the disallowed section. {-# INLINE subtract #-} subtract :: (Num a) => a -> a -> a subtract x y = y - x -- | @since 2.01 instance Num Int where I# x + I# y = I# (x +# y) I# x - I# y = I# (x -# y) negate (I# x) = I# (negateInt# x) I# x * I# y = I# (x *# y) abs n = if n `geInt` 0 then n else negate n signum n | n `ltInt` 0 = negate 1 | n `eqInt` 0 = 0 | otherwise = 1 {-# INLINE fromInteger #-} -- Just to be sure! fromInteger i = I# (integerToInt i) -- | @since 2.01 instance Num Word where (W# x#) + (W# y#) = W# (x# `plusWord#` y#) (W# x#) - (W# y#) = W# (x# `minusWord#` y#) (W# x#) * (W# y#) = W# (x# `timesWord#` y#) negate (W# x#) = W# (int2Word# (negateInt# (word2Int# x#))) abs x = x signum 0 = 0 signum _ = 1 fromInteger i = W# (integerToWord i) -- | @since 2.01 instance Num Integer where (+) = plusInteger (-) = minusInteger (*) = timesInteger negate = negateInteger fromInteger x = x abs = absInteger signum = signumInteger
ezyang/ghc
libraries/base/GHC/Num.hs
bsd-3-clause
3,135
0
12
962
669
373
296
51
1
module RnHsDoc ( rnHsDoc, rnLHsDoc, rnMbLHsDoc ) where import TcRnTypes import HsSyn import SrcLoc rnMbLHsDoc :: Maybe LHsDocString -> RnM (Maybe LHsDocString) rnMbLHsDoc mb_doc = case mb_doc of Just doc -> do doc' <- rnLHsDoc doc return (Just doc') Nothing -> return Nothing rnLHsDoc :: LHsDocString -> RnM LHsDocString rnLHsDoc (L pos doc) = do doc' <- rnHsDoc doc return (L pos doc') rnHsDoc :: HsDocString -> RnM HsDocString rnHsDoc (HsDocString s) = return (HsDocString s)
ghc-android/ghc
compiler/rename/RnHsDoc.hs
bsd-3-clause
501
0
12
99
184
90
94
16
2
{-# LANGUAGE OverloadedStrings #-} -- | Module : Text.Pandoc.PlantUML.Filter.Formats -- Determines the image type to be used for one particular -- pandoc output format. -- -- Currently uses EPS for latex-based outputs (including PDF), -- and PNG for anything else. -- module Text.Pandoc.PlantUML.Filter.Formats(imageFormatTypeFor) where import Text.Pandoc.Definition import Text.Pandoc.PlantUML.Filter.Types import qualified Data.Text as T -- | The image file type to be used for the given output format. -- EPS is used for latex outputs, as it provides lossless scalability -- All other output formats use PNG for now. imageFormatTypeFor :: Format -> ImageFormat imageFormatTypeFor (Format "latex") = "eps" imageFormatTypeFor _ = "png"
thriqon/pandoc-plantuml-diagrams
src/Text/Pandoc/PlantUML/Filter/Formats.hs
isc
757
0
7
122
78
53
25
8
1
module Main where import Control.Monad import System.Environment import Text.ParserCombinators.Parsec hiding (spaces) main :: IO() main = do args <- getArgs putStrLn (readExpr (args !! 0)) data LispVal = Atom String | List [LispVal] | DottedList [LispVal] LispVal | Number Integer | String String | Bool Bool spaces :: Parser () spaces = skipMany1 space symbol :: Parser Char symbol = oneOf "!$%&|*+-/:<=?>@^~#" parseString :: Parser LispVal parseString = do char '"' x <- many (noneOf "\"") char '"' return $ String x parseAtom :: Parser LispVal parseAtom = do first <- letter <|> symbol rest <- many (letter <|> digit <|> symbol) let atom = [first] ++ rest return $ case atom of "#t" -> Bool True "#f" -> Bool False otherwise -> Atom atom parseNumber :: Parser LispVal parseNumber = liftM (Number . read) $ many1 digit parseExpr :: Parser LispVal parseExpr = parseAtom <|> parseString <|> parseNumber readExpr :: String -> String readExpr input = case parse parseExpr "lisp" input of Left err -> "No match: " ++ show err Right val -> "Found value"
liyanchang/scheme-in-haskell
src/chp2.hs
mit
1,206
0
11
333
397
199
198
43
3
module Ori.Random ( module Ori.Random ) where import Ori.Types import System.Random doubles :: Int -> [Double] doubles seed = randomRs (0, 1) (mkStdGen seed) rats :: Int -> [Rat] rats seed = map (\x -> approxRational x 1e-30) (doubles seed)
pbl64k/icfpc2016
Ori/Random.hs
mit
253
0
8
52
105
58
47
8
1
{-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleInstances #-} module Types where import qualified Data.IntMap as I defsToGame :: [Definition] -> Either String Game defsToGame = validateGame . foldl addDef emptyGame addDef :: Game -> Definition -> Game addDef g (DefRule r) = g{ gameRules = (gameRules g) ++ [r] } addDef g (DefBoard b) = g{ gameBoard = b } addDef g (DefGerm gm) = let gms = gameGerms g i = I.size gms in g{ gameGerms = I.insert i gm gms} validateGame :: Game -> Either String Game validateGame g = validateBoard (gameBoard g) >> validateGerms (gameGerms g) >> return g validateBoard :: Board -> Either String Board validateBoard b = validateCellsExist b >> validateCells b where w = boardWidth b cs = boardCells b validateCellsExist b' = if length cs > 0 then Right b' else Left "Board contains no cells" validateCells b' = if length cs `mod` w == 0 then Right b' else Left "Board has funky cell row counts" validateGerms :: I.IntMap Germ -> Either String (I.IntMap Germ) validateGerms gs = if 1 <= I.size gs then Right gs else Left "Game must contain at least one Germ" emptyGame :: Game emptyGame = Game{ gameBoard = Board{ boardCells = [] , boardWidth = 0 } , gameGerms = I.empty , gameRules = [] , gameSteps = 0 } instance Show Game where show (Game b gs rs s) = unwords [ "Game\n" , show b , "\n" , show gs , "\n" , show rs , "\n" , show s ] data Game = Game { gameBoard :: Board -- ^ All the cells in the world. , gameGerms :: I.IntMap Germ -- ^ A map of all our species of germs. , gameRules :: [Rule] -- ^ The world's environmental rules. , gameSteps :: Int -- ^ The current number of steps so far. } data Definition = DefRule Rule | DefGerm Germ | DefBoard Board deriving (Show) instance Show Rule where show _ = "Rule" type Rule = Moore -> Maybe Moore data Moore = Moore Cell Cell Cell Cell Cell Cell Cell Cell Cell instance Show Board where show (Board _ []) = "" show (Board w cells) = concat ["Board " , show w ,"\n" , unlines $ groupBy w $ concatMap show cells ] groupBy :: Int -> [a] -> [[a]] groupBy _ [] = [] groupBy i xs = take i xs:groupBy i (drop i xs) data Board = Board { boardWidth :: Int , boardCells :: [Cell] } deriving (Eq) instance Show Cell where show Rock = "#" show (Cell i) = show i show Empty = " " transitionCell :: Int -> TCell -> Cell -> Cell transitionCell i TSelf Empty = Cell i transitionCell _ TEmpty (Cell _) = Empty transitionCell _ _ cell = cell matchesCell :: Int -> TCell -> Cell -> Bool matchesCell _ TRock Rock = True matchesCell i TFood (Cell n) = i /= n matchesCell _ TEmpty Empty = True matchesCell i TSelf (Cell n) = i == n matchesCell _ TWild _ = True matchesCell _ _ _ = False data Cell = Cell Int | Rock | Empty deriving (Eq) type Germ = [Transition] instance Show Transition where show (NW b c d f g h i) = inject 4 'X' $ inject 0 '^' $ concatMap show [b,c,d,f,g,h,i] show (N a c d f g h i) = inject 4 'X' $ inject 1 '^' $ concatMap show [a,c,d,f,g,h,i] show (NE a b d f g h i) = inject 4 'X' $ inject 2 '^' $ concatMap show [a,b,d,f,g,h,i] show (W a b c f g h i) = inject 4 'X' $ inject 3 '^' $ concatMap show [a,b,c,f,g,h,i] show (E a b c d g h i) = inject 4 'X' $ inject 4 '^' $ concatMap show [a,b,c,d,g,h,i] show (SW a b c d f h i) = inject 4 'X' $ inject 5 '^' $ concatMap show [a,b,c,d,f,h,i] show (S a b c d f g i) = inject 4 'X' $ inject 6 '^' $ concatMap show [a,b,c,d,f,g,i] show (SE a b c d f g h) = inject 4 'X' $ inject 7 '^' $ concatMap show [a,b,c,d,f,g,h] show (Die a b c d f g h i) = inject 4 ' ' $ concatMap show [a,b,c,d,f,g,h,i] show (Stay a b c d f g h i)= inject 4 'X' $ concatMap show [a,b,c,d,f,g,h,i] inject :: Int -> a -> [a] -> [a] inject i a as | i > (length as - 1) = as | otherwise = take i as ++ [a] ++ drop i as preTransitionToMooreList :: Transition -> [TCell] preTransitionToMooreList (NW b c d f g h i) = [TEmpty, b, c, d, TSelf, f, g, h, i] preTransitionToMooreList (N a c d f g h i) = [ a, TEmpty, c, d, TSelf, f, g, h, i] preTransitionToMooreList (NE a b d f g h i) = [ a, b, TEmpty, d, TSelf, f, g, h, i] preTransitionToMooreList (W a b c f g h i) = [ a, b, c, TEmpty, TSelf, f, g, h, i] preTransitionToMooreList (E a b c d g h i) = [ a, b, c, d, TSelf, TEmpty, g, h, i] preTransitionToMooreList (SW a b c d f h i) = [ a, b, c, d, TSelf, f, TEmpty, h, i] preTransitionToMooreList (S a b c d f g i) = [ a, b, c, d, TSelf, f, g, TEmpty, i] preTransitionToMooreList (SE a b c d f g h) = [ a, b, c, d, TSelf, f, g, h, TEmpty] preTransitionToMooreList (Die a b c d f g h i) = [ a, b, c, d, TSelf, f, g, h, i] preTransitionToMooreList (Stay a b c d f g h i) = [ a, b, c, d, TSelf, f, g, h, i] postTransitionToMooreList :: Transition -> [TCell] postTransitionToMooreList (NW b c d f g h i) = [TSelf, b, c, d, TEmpty, f, g, h, i] postTransitionToMooreList (N a c d f g h i) = [ a, TSelf, c, d, TEmpty, f, g, h, i] postTransitionToMooreList (NE a b d f g h i) = [ a, b, TSelf, d, TEmpty, f, g, h, i] postTransitionToMooreList (W a b c f g h i) = [ a, b, c, TSelf, TEmpty, f, g, h, i] postTransitionToMooreList (E a b c d g h i) = [ a, b, c, d, TEmpty, TSelf, g, h, i] postTransitionToMooreList (SW a b c d f h i) = [ a, b, c, d, TEmpty, f, TSelf, h, i] postTransitionToMooreList (S a b c d f g i) = [ a, b, c, d, TEmpty, f, g, TSelf, i] postTransitionToMooreList (SE a b c d f g h) = [ a, b, c, d, TEmpty, f, g, h, TSelf] postTransitionToMooreList (Die a b c d f g h i) = [ a, b, c, d, TEmpty, f, g, h, i] postTransitionToMooreList (Stay a b c d f g h i) = [ a, b, c, d, TSelf, f, g, h, i] -- | The player can write rules for moving the cell -- in a cardinal or ordinal direction. data Transition = N TCell {-n-} TCell TCell {-X-} TCell TCell TCell TCell | NE TCell TCell {-ne-} TCell {-X-} TCell TCell TCell TCell | E TCell TCell TCell TCell {-X-} {-e-} TCell TCell TCell | SE TCell TCell TCell TCell {-X-} TCell TCell TCell {-se-} | S TCell TCell TCell TCell {-X-} TCell TCell {-s-} TCell | SW TCell TCell TCell TCell {-X-} TCell {-sw-} TCell TCell | W TCell TCell TCell {-w-} {-X-} TCell TCell TCell TCell | NW {-nw-} TCell TCell TCell {-X-} TCell TCell TCell TCell | Stay TCell TCell TCell TCell {-X-} TCell TCell TCell TCell | Die TCell TCell TCell TCell {-X-} TCell TCell TCell TCell instance Show TCell where show TRock = "0" show TFood = "$" show TEmpty = " " show TSelf = "X" show TWild = "*" data TCell = TRock | TFood | TEmpty | TSelf | TWild
schell/germs
src/Types.hs
mit
8,967
0
11
3,957
3,207
1,764
1,443
169
3
{-# LANGUAGE NoImplicitPrelude #-} module Test.Data.Raft.Term where import Control.Applicative import Control.Monad import Test.Tasty.QuickCheck import Data.Raft.Term import Data.RaftPrelude instance Arbitrary Term where arbitrary = Term <$> arbitrary orderedTermPair :: Gen (Term, Term) orderedTermPair = do anchor <- arbitrary larger <- largerTerm anchor return (anchor, larger) smallerTerm :: Term -> Gen Term smallerTerm (Term x) = Term <$> choose (minBound, x - 1) largerTerm :: Term -> Gen Term largerTerm (Term x) = Term <$> choose (x + 1, maxBound)
AndrewRademacher/zotac
test/Test/Data/Raft/Term.hs
mit
623
0
8
144
187
101
86
18
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE CPP #-} module Keter ( keter ) where import Data.Yaml #if MIN_VERSION_aeson(2, 0, 0) import qualified Data.Aeson.KeyMap as Map #else import qualified Data.HashMap.Strict as Map #endif import qualified Data.Text as T import System.Environment (getEnvironment) import System.Exit import System.Process import Control.Monad import System.Directory hiding (findFiles) import Data.Maybe (mapMaybe,isJust,maybeToList) import Data.Monoid import System.FilePath ((</>)) import qualified Codec.Archive.Tar as Tar import Control.Exception import qualified Data.ByteString.Lazy as L import Codec.Compression.GZip (compress) import qualified Data.Foldable as Fold import Control.Monad.Trans.Writer (tell, execWriter) run :: String -> [String] -> IO () run a b = do ec <- rawSystem a b unless (ec == ExitSuccess) $ exitWith ec keter :: String -- ^ cabal command -> Bool -- ^ no build? -> Bool -- ^ no copy to? -> [String] -- ^ build args -> IO () keter cabal noBuild noCopyTo buildArgs = do ketercfg <- keterConfig mvalue <- decodeFile ketercfg value <- case mvalue of Nothing -> error "No config/keter.yaml found" Just (Object value) -> case Map.lookup "host" value of Just (String s) | "<<" `T.isPrefixOf` s -> error $ "Please set your hostname in " ++ ketercfg _ -> case Map.lookup "user-edited" value of Just (Bool False) -> error $ "Please edit your Keter config file at " ++ ketercfg _ -> return value Just _ -> error $ ketercfg ++ " is not an object" env' <- getEnvironment cwd' <- getCurrentDirectory files <- getDirectoryContents "." project <- case mapMaybe (T.stripSuffix ".cabal" . T.pack) files of [x] -> return x [] -> error "No cabal file found" _ -> error "Too many cabal files found" let findFiles (Object v) = mapM_ go $ Map.toList v where go ("exec", String s) = tellFile s go ("extraFiles", Array a) = Fold.mapM_ tellExtra a go (_, v') = findFiles v' tellFile s = tell [collapse $ "config" </> T.unpack s] tellExtra (String s) = tellFile s tellExtra _ = error "extraFiles should be a flat array" findFiles (Array v) = Fold.mapM_ findFiles v findFiles _ = return () bundleFiles = execWriter $ findFiles $ Object value collapse = T.unpack . T.intercalate "/" . collapse' . T.splitOn "/" . T.pack collapse' (_:"..":rest) = collapse' rest collapse' (".":xs) = collapse' xs collapse' (x:xs) = x : collapse' xs collapse' [] = [] unless noBuild $ do stackQueryRunSuccess <- do eres <- try $ readProcessWithExitCode "stack" ["query"] "" :: IO (Either IOException (ExitCode, String, String)) return $ either (\_ -> False) (\(ec, _, _) -> (ec == ExitSuccess)) eres let inStackExec = isJust $ lookup "STACK_EXE" env' mStackYaml = lookup "STACK_YAML" env' useStack = inStackExec || isJust mStackYaml || stackQueryRunSuccess if useStack then do let stackYaml = maybeToList $ fmap ("--stack-yaml="<>) mStackYaml localBinPath = cwd' </> "dist/bin" run "stack" $ stackYaml <> ["clean"] createDirectoryIfMissing True localBinPath run "stack" (stackYaml <> ["--local-bin-path",localBinPath,"build","--copy-bins"] <> buildArgs) else do run cabal ["clean"] run cabal ["configure"] run cabal ("build" : buildArgs) _ <- try' $ removeDirectoryRecursive "static/tmp" archive <- Tar.pack "" $ "config" : "static" : bundleFiles let fp = T.unpack project ++ ".keter" L.writeFile fp $ compress $ Tar.write archive unless noCopyTo $ case Map.lookup "copy-to" value of Just (String s) -> let baseArgs = [fp, T.unpack s] :: [String] scpArgs = case parseMaybe (.: "copy-to-args") value of Just as -> as ++ baseArgs Nothing -> baseArgs args = case parseMaybe (.: "copy-to-port") value of Just i -> "-P" : show (i :: Int) : scpArgs Nothing -> scpArgs in run "scp" args _ -> return () where -- Test for alternative config file extension (yaml or yml). keterConfig = do let yml = "config/keter.yml" ymlExists <- doesFileExist yml return $ if ymlExists then yml else "config/keter.yaml" try' :: IO a -> IO (Either SomeException a) try' = try
yesodweb/yesod
yesod-bin/Keter.hs
mit
5,102
0
21
1,762
1,431
727
704
114
20
module NoUnionStrictTuple.FV where import Types import qualified Data.IntSet as IntSet import Data.IntSet (IntSet) type InterestingVarFun = Var -> Bool data StrictTuple = StrictTuple ![Var] !IntSet stFst :: StrictTuple -> [Var] stFst (StrictTuple vs _) = vs type FV = InterestingVarFun -> IntSet -> StrictTuple -> StrictTuple unionFV :: FV -> FV -> FV unionFV fv fv2 p1 p2 acc = fv p1 p2 $! fv2 p1 p2 $! acc oneFV :: Var -> FV oneFV v fv_cand in_scope acc@(StrictTuple have haveSet) | IntSet.member v in_scope = acc | IntSet.member v haveSet = acc | fv_cand v = StrictTuple (v:have) (IntSet.insert v haveSet) | otherwise = acc noFV :: FV noFV _ _ acc = acc runFV :: FV -> [Var] runFV fv = stFst $ fv (const True) IntSet.empty (StrictTuple [] IntSet.empty) delFV :: Var -> FV -> FV delFV v fv fv_cand in_scope acc = fv fv_cand (IntSet.insert v in_scope) $! acc f :: Term -> FV f (Var v) fv_cand in_scope acc = oneFV v fv_cand in_scope $! acc f (App t tys) fv_cand in_scope acc = f t fv_cand in_scope $! fs tys fv_cand in_scope $! acc f (Lam v t) fv_cand in_scope acc = delFV v (f t) fv_cand in_scope $! acc fs :: [Term] -> FV fs (t:tys) fv_cand in_scope acc = f t fv_cand in_scope $! fs tys fv_cand in_scope $! acc fs [] fv_cand in_scope acc = acc fvs :: Term -> [Var] fvs t = runFV $ f t funs :: [(String, Term -> [Var])] funs = [("NoUnionStrictTuple", fvs)]
niteria/deterministic-fvs
NoUnionStrictTuple/FV.hs
mit
1,391
0
9
289
626
322
304
43
1
module Examples.Tests.Branching where import Improb.AST -- TODO: Read in from the actual file and roll in the IO monad branchingString = unlines [ "tempo: 120" , ":piano:" , "=> (C4,4)" , "(C4,4) => (F4,2)" , "(C4,4) => (Eb4,2)" , "(F4,2) => (G4,4)" ] c44 = (Single (NoteLiteral (Note (Tone {octave = 4, key = C}) 4))) f42 = (Single (NoteLiteral (Note (Tone {octave = 4, key = F}) 2))) eb42 = (Single (NoteLiteral (Note (Tone {octave = 4, key = Compound E Flat}) 2))) g44 = (Single (NoteLiteral (Note (Tone {octave = 4, key = G}) 4))) branchExpects = Right ( Program 120 [] [ Voice "piano" [ Intro c44 , Transition c44 f42 , Transition c44 eb42 , Transition f42 g44 ] ] )
michaelbjames/improb
Examples/Tests/Branching.hs
mit
790
0
14
243
270
152
118
20
1
module Battleship.Coconut (coconut,coconutfunc,CoconutDataStruct(..)) where data CoconutDataStruct = CoconutConstr [Integer] deriving (Show) coconut :: Integer coconut = 10 coconutfunc :: CoconutDataStruct -> Int coconutfunc (CoconutConstr l) = length l
sgrove/battlehaskell
src/Battleship/Coconut.hs
mit
256
0
7
30
76
44
32
6
1
import PrimeList primeList = fmap toPrime [P2 ..] primeFactorizeCount :: Integer -> Integer -> Integer primeFactorizeCount n p | n `mod` p == 0 = 1 + primeFactorizeCount (n `div` p) p | otherwise = 0 primeFactorizeWoker :: Integer -> [Integer] -> [Integer] primeFactorizeWoker n [] = [] primeFactorizeWoker n (p:px) = [primeFactorizeCount n p] ++ primeFactorizeWoker n px primeFactorizeList :: Integer -> [(Integer, Integer)] primeFactorizeList n | pmax * pmax <= n = [] | otherwise = zip primeList (primeFactorizeWoker n primeList) where pmax = 99991 primeFactorize :: Integer -> [(Integer, Integer)] primeFactorize n = [ tuple | tuple <- primeFactorizeList n, snd tuple /= 0 ] list = fmap primeFactorize [1..10] radWorker :: [(Integer, Integer)] -> Integer radWorker (x:xs) | null xs = (fst x) * 1 | otherwise = (fst x) * radWorker xs radWorker2 :: [(Integer, Integer)] -> Integer radWorker2 (x:xs) | null xs = (snd x) + 0 | otherwise = (snd x) + radWorker2 xs radWorker3 :: [(Integer, Integer)] -> Integer radWorker3 (x:xs) | null xs = (snd x) * 1 | otherwise = (snd x) * radWorker3 xs radWorker4 :: [(Integer, Integer)] -> Integer radWorker4 (x:xs) | null xs = (fst x) + 0 | otherwise = (fst x) + radWorker4 xs rad :: Integer -> [Integer] rad n = [n, (radWorker ( primeFactorize n))] rad' :: Integer -> [Integer] rad' n = [radWorker2 (primeFactorize (radWorker4 (primeFactorize n))), (radWorker2 (primeFactorize n))] cut :: Show a => [a] -> String cut (x:xs) = show x ++ " " ++ (show ( last xs)) main = do mapM_ putStrLn $ fmap cut (fmap rad [2..10000])
mino2357/Hello_Haskell
primeList/Main.hs
mit
1,622
0
12
334
771
395
376
41
1
module ProjectEuler.Problem013Spec (main, spec) where import Test.Hspec import ProjectEuler.Problem013 main :: IO () main = hspec spec spec :: Spec spec = parallel $ describe "solve" $ it "finds the first 10-digits of the sum of 100 50-digit numbers" $ solve `shouldBe` 5537376230
hachibu/project-euler
test/ProjectEuler/Problem013Spec.hs
mit
296
0
9
58
76
42
34
10
1
{-| Module : Test.Problem.ProblemExpr.Class Description : The ProblemExpr Class tests Copyright : (c) Andrew Burnett, 2014-2015 Maintainer : [email protected] Stability : experimental Portability : - Exports the testing functionality of the ProblemExpr Class -} module Test.Problem.ProblemExpr.Class ( tests ) where import HSat.Problem.Instances.CNF.Internal import HSat.Problem.ProblemExpr.Class import Test.Problem.Instances.CNF.Internal (genCNF) import TestUtils name :: String name = "Class" tests :: TestTree tests = testGroup name [ testGroup "fromProblemExpr" [ testFromProblemExpr1 ] ] testFromProblemExpr1 :: TestTree testFromProblemExpr1 = testProperty ("fromProblemExpr (ProblemExpr cnf) " `equiv` " cnf") $ property (\cnf -> case fromProblemExpr $ ProblemExpr cnf of Just cnf'@CNF{} -> cnf === cnf' Nothing -> counterexample "Incorrect value from fromProblemExpr" False ) instance Arbitrary ProblemExpr where arbitrary = oneof [ ProblemExpr <$> sized genCNF ] shrink problemExpr = case fromProblemExpr problemExpr of Just cnf@CNF{} -> map ProblemExpr . shrink $ cnf Nothing -> []
aburnett88/HSat
tests-src/Test/Problem/ProblemExpr/Class.hs
mit
1,206
0
14
247
236
130
106
27
2
{-# LANGUAGE GeneralizedNewtypeDeriving, FlexibleContexts, MultiWayIf #-} module Main where import BattleStatus import Haskmon import System.Random.Shuffle (shuffleM) import Control.Lens (ASetter, view, over) import Control.Monad.State import Control.Monad.Random import Data.Monoid ((<>)) import qualified Data.Text as T -- | App type. A composition of Random and StateT newtype PB m a = PB { runPB :: RandT StdGen (StateT BattleStatus m) a } deriving (Functor, Applicative, Monad, MonadIO, MonadRandom, MonadState BattleStatus) -- Get a random pokemon from the original 151 getRandomPkmn :: MonadIO m => PB m Pokemon getRandomPkmn = do randomInt <- getRandomR (1, 151) liftIO $ getPokemonById randomInt -- Given a pokemon, get 4 random moves from it downloadMoves :: MonadIO m => Pokemon -> PB m [Move] downloadMoves pkm = do let metaMoves = pokemonMoves pkm randMoves <- shuffleM metaMoves -- Randomize the getters liftIO (mapM getMove $ take 4 randMoves) -- Pick 4 from the random getters and download them data DamageResult = Damage Int | Missed instance Show DamageResult where show (Damage amt) = "dealing " ++ show amt ++ " damage!" show Missed = "but it missed!" -- | Given a pokemon and a move, calculate, randomly, how much damage that -- move will do. -- -- Sadly, pokeapi.co doesn't seem to have move categories for any of the -- moves, so we can't properly calculate the damage. We will just add the -- pokemon Attack and Special Attack stats to any move. -- -- Additionally, accuracy is a plain check with a growing probability for -- each miss. This is different than the actual pokemon damage equation since -- you don't have any stats and pure randomness is boring. -- -- Another difference is the damage scale. Here were are picking the damage -- to be between 0 and some top value. In reality, damage in pokemon games -- are based on the defense of the defendes (your stats that you don't have), -- the type of attack vs the type of the defender, the base and the level. -- We don't have that yet, so for now it is that simple, kind of arbitrary -- equation. calculateDamage :: Monad m => Pokemon -> Move -> PB m DamageResult calculateDamage pkmn move = do let pkAtk = (+) <$> pokemonAttack <*> pokemonSpAtk $ pkmn top = floor (fromIntegral (pkAtk * movePower move) / 300 :: Double) pkmAtkDmg <- getRandomR (0, top) prevHitC <- view bsPrevHitCount <$> get let modAcc = prevHitC * 5 didItHit <- (moveAccuracy move + modAcc >=) <$> getRandomR (0, 100) if didItHit then resetHitCount >> return (Damage pkmAtkDmg) else incHitCount >> return Missed where resetHitCount = modBS bsPrevHitCount (const 0) incHitCount = modBS bsPrevHitCount (+ 1) main :: IO () main = do gen <- newStdGen battleReport <- view bsMessages <$> execStateT (evalRandT play gen) (initialBattleStatus 100) mapM_ (putStrLn . T.unpack) battleReport where play = runPB $ do pk <- getRandomPkmn moves <- downloadMoves pk battle pk moves type HP = Int type MoveCount = Int type MoveSet = [Move] -- | A battle consists of an initial HP (your HP), a count, a pokemon and -- a moveset from said pokemon. The pokemon will continusly attack you with -- one of the moves from the moveset until you die, counting how many moves -- it took. battle :: Monad m => Pokemon -> MoveSet -> PB m () battle pkm moves = do addMsgS $ "A wild " <> showT (pokemonName pkm) <> " has appeared!" battle' where addMsgS msg = modBS bsMessages (++ [msg]) battle' = do (BS hp turn _ _) <- get if | hp <= 0 -> addMsgS $ "You were defeated in " <> showT turn <> " moves!" | turn > 50 -> addMsgS "You survived over 50 turns. You win!" | otherwise -> do move <- choose moves dmg <- calculateDamage pkm move addMsgS $ printResult (pokemonName pkm) (moveName move) dmg updateHP dmg incTurnS battle' where printResult pkName mvName dmg = T.pack pkName <> " attacked you with " <> T.pack mvName <> " " <> showT dmg updateHP Missed = return () -- do nothing updateHP (Damage dmg) = damageHPS dmg damageHPS dmg = modBS bsHP (\h -> h - dmg) incTurnS = modBS bsTurn (+ 1) -- Utility for choosing a move from a MoveSet choose :: MonadRandom m => [a] -> m a choose xs = head <$> shuffleM xs showT :: Show a => a -> T.Text showT = T.pack . show -- | Helper function for modifying the battle status inside a PB using -- lenses modBS :: Monad m => ASetter BattleStatus BattleStatus a b -> (a -> b) -> PB m () modBS l f = modify' (over l f)
pjrt/PokemonBattle
src/Main.hs
mit
4,732
0
16
1,136
1,158
594
564
78
4
{-# LANGUAGE TemplateHaskell, OverloadedStrings, FlexibleInstances #-} module ServerState ( ServerState , makeServerStateInit , ServerStateHandler ) where import Snap ( addRoutes, writeBS ) import Snap.Snaplet ( Snaplet, subSnaplet, SnapletInit, makeSnaplet, nestSnaplet, Handler, with ) import Snap.Snaplet.Heist ( Heist, HasHeist(heistLens), heistInit ) import Control.Lens ( makeLenses ) import Data.ByteString.Char8 ( ByteString ) import Control.Monad.State ( get ) import Snap.Snaplet.Groundhog.Postgresql ( HasGroundhogPostgres, GroundhogPostgres, getGroundhogPostgresState , initGroundhogPostgres ) import Data.Text type ServerStateHandler = Handler ServerState ServerState () data ServerState = ServerState { _heist :: Snaplet ( Heist ServerState ) , _db :: Snaplet GroundhogPostgres } makeLenses ''ServerState instance HasHeist ServerState where heistLens = subSnaplet heist instance HasGroundhogPostgres (Handler b ServerState) where getGroundhogPostgresState = with db Control.Monad.State.get makeServerStateInit :: [(ByteString, ServerStateHandler)] -> SnapletInit ServerState ServerState makeServerStateInit routes = let name = "Substance" desc = "Substance System V1" maybeFilepath = Nothing in makeSnaplet name desc maybeFilepath $ do heistData <- nestSnaplet "heist" heist $ heistInit "templates" dbData <- nestSnaplet "db" db initGroundhogPostgres addRoutes routes return $ ServerState { _heist = heistData , _db = dbData }
GetContented/substance
src/ServerState.hs
mit
1,571
0
12
300
359
201
158
40
1
{-# LANGUAGE OverloadedStrings #-} module Test.Hspec.Wai.MatcherSpec (main, spec) where import Test.Hspec.Meta import Network.HTTP.Types import Network.Wai.Test import Test.Hspec.Wai.Matcher main :: IO () main = hspec spec spec :: Spec spec = do describe "match" $ do context "when both status and body do match" $ do it "returns Nothing" $ do SResponse status200 [] "" `match` 200 `shouldBe` Nothing context "when status does not match" $ do it "returns an error message" $ do SResponse status404 [] "" `match` 200 `shouldBe` (Just . unlines) [ "status mismatch:" , " expected: 200" , " but got: 404" ] context "when body does not match" $ do it "returns an error message" $ do SResponse status200 [] "foo" `match` "bar" `shouldBe` (Just . unlines) [ "body mismatch:" , " expected: bar" , " but got: foo" ] context "when one body contains unsafe characters" $ do it "uses show for both bodies in the error message" $ do SResponse status200 [] "foo\nbar" `match` "bar" `shouldBe` (Just . unlines) [ "body mismatch:" , " expected: \"bar\"" , " but got: \"foo\\nbar\"" ] context "when both status and body do not match" $ do it "combines error messages" $ do SResponse status404 [] "foo" `match` "bar" `shouldBe` (Just . unlines) [ "status mismatch:" , " expected: 200" , " but got: 404" , "body mismatch:" , " expected: bar" , " but got: foo" ] context "when matching headers" $ do context "when header is missing" $ do it "returns an error message" $ do SResponse status200 [] "" `match` 200 {matchHeaders = [("Content-Type", "application/json")]} `shouldBe` (Just . unlines) [ "missing header:" , " Content-Type: application/json" , "the actual headers were:" ] context "when multiple headers are missing" $ do context "combines error messages" $ do it "returns an error message" $ do let expectedHeaders = [("Content-Type", "application/json"), ("Content-Encoding", "chunked")] SResponse status200 [(hContentLength, "23")] "" `match` 200 {matchHeaders = expectedHeaders} `shouldBe` (Just . unlines) [ "missing headers:" , " Content-Type: application/json" , " Content-Encoding: chunked" , "the actual headers were:" , " Content-Length: 23" ]
begriffs/hspec-wai
test/Test/Hspec/Wai/MatcherSpec.hs
mit
2,808
0
32
1,004
597
316
281
65
1
module Main ( main ) where import Control.Monad ( when, unless ) import System.Console.GetOpt import System.Environment ( getArgs, getProgName ) import System.Exit ( exitFailure, exitSuccess ) import System.IO import Text.Printf ( printf ) import Main.Command as Cmd import Main.Command.Init as Init import Main.Command.Help as Help -- |List of all commands commands = [ Help.command commands , Init.command ] -- ----- COMMAND LINE OPTIONS ----- data Flag = Help deriving (Show) -- |Available command line options options :: [OptDescr Flag] options = [ Option "h" ["help"] (NoArg Help) "Show a brief usage summary." ] -- |Handle any state change implied by a command-line flag handleFlag :: Flag -> IO () handleFlag Help = printUsage >> exitSuccess -- |Given the program name, generate a string giving top-level usage -- information. usage :: String -> String usage pn = unlines [ printf "Usage: %s <command> [<arguments>]" pn , "" , usageInfo "Allowed options:" options , "Available commands:" , Cmd.descTable commands , printf "See `%s help <command>' for more information on a specific command." pn ] -- |Print a brief top-level usage summary to the console. printUsage :: IO () printUsage = hPutUsage stdout -- |Print a brief top-level usage summary to a filehandle hPutUsage :: Handle -> IO () hPutUsage h = getProgName >>= (hPutStr h . usage) -- ----- MAIN PROGRAM ----- -- |Run the named command with the provided argument list. Return a flag -- indicating successful completion. runCmd :: String -> [String] -> IO Bool runCmd cmd args = do rv <- Cmd.run commands cmd args case rv of Nothing -> do pn <- getProgName hPutStr stderr (printf "%s: unrecognized command: `%s'\n" pn cmd) hPutUsage stderr exitFailure Just f -> return f main :: IO () main = do -- get arguments args <- getArgs -- process top-level options let (opts, nonopts, errs) = getOpt RequireOrder options args -- handle flags mapM_ handleFlag opts -- if there were any errors, show them unless (null errs) $ do -- print each error on one line pn <- getProgName mapM_ (hPutStr stderr . printf "%s: %s" pn) errs hPutUsage stderr exitFailure -- if no arguments given, print a usage summary and fail when (null nonopts) $ hPutUsage stderr >> exitFailure -- run the specified command success <- runCmd (head nonopts) (tail nonopts) unless success exitFailure
rjw57/cloudsync
cs/cs.hs
mit
2,706
0
14
761
587
307
280
53
2
{-# LINE 1 "HOpenCV/CV/HighGui.hsc" #-} {-# LANGUAGE ForeignFunctionInterface, EmptyDataDecls #-} {-# LINE 2 "HOpenCV/CV/HighGui.hsc" #-} {- | While OpenCV was designed for use in full-scale applications and can be used within functionally rich UI frameworks (such as Qt*, WinForms*, or Cocoa*) or without any UI at all, sometimes there it is required to try functionality quickly and visualize the results. This is what the "OpenCV.HighGui" module has been designed for. It provides easy interface to: * Create and manipulate windows that can display images and “remember” their content (no need to handle repaint events from OS). * Add trackbars to the windows, handle simple mouse events as well as keyboard commands. -} module HOpenCV.CV.HighGui where import Control.Monad import Foreign.ForeignPtrWrap import Foreign.C.Types import Foreign.Ptr import Foreign.ForeignPtr import Foreign.C.String import Foreign.Marshal import Foreign.Storable import HOpenCV.CV.CxCore import HOpenCV.CV.Util import HOpenCV.CV.Error -- * List of functions in the module: {-# LINE 19 "HOpenCV/CV/HighGui.hsc" #-} ------------------------------------------------ foreign import ccall unsafe "opencv/highgui.h cvConvertImage" c_cvConvertImage :: Ptr Priv_IplImage -> Ptr Priv_IplImage -> CInt -> IO () -- | Function convertImage convertImage :: IplImage -> IplImage -> Int -> IO () convertImage src dst flags = withForeignPtr2 src dst $ \s d -> c_cvConvertImage s d (fromIntegral flags) ------------------------------------------------ -- | Definition Type Capture data Priv_CvCapture type Capture = ForeignPtr Priv_CvCapture foreign import ccall unsafe "opencv/highgui.h cvCreateCameraCapture" c_cvCreateCameraCapture :: CInt -> IO (Ptr Priv_CvCapture) -- | self-documenting camera specification pickAnyCam :: Int pickAnyCam = -1 -- | self-documenting camera specification cam :: Int -> Int cam = id -- |Open a capture stream from a connected camera. The parameter is -- the index of the camera to be used, or 'Nothing' if it does not -- matter what camera is used. The returned action may be used to -- query for the next available frame. createCameraCapture :: Int -> IO (ErrCV Capture) createCameraCapture x = do p <- mycheckPtr_2 $ c_cvCreateCameraCapture . fromIntegral $ x case p of (Return p') -> do ptr <- newForeignPtr cp_release_capture p' return (Return ptr) (Raise s) -> return( throwErrorCV ("Failed to create camera (" ++ s ++ ")") ) foreign import ccall unsafe "opencv/highgui.h cvCreateFileCapture" c_cvCreateFileCapture :: CString -> IO (Ptr Priv_CvCapture) createFileCapture :: String -> IO (ErrCV Capture) createFileCapture filename = do c <- mycheckPtr_2 $ withCString filename f case c of (Return c') -> do ptr <- newForeignPtr cp_release_capture c' return (Return ptr) (Raise s) -> return( throwErrorCV ("Failed to capture from file: '" ++ filename ++ "' (" ++ s ++ ")") ) where f filenameC = c_cvCreateFileCapture filenameC foreign import ccall unsafe "HOpenCV_wrap.h &release_capture" cp_release_capture :: FunPtr (Ptr Priv_CvCapture -> IO ()) foreign import ccall unsafe "opencv/highgui.h cvReleaseCapture" cv_release_capture :: Ptr Priv_CvCapture -> IO () release_capture :: Capture -> IO () release_capture cap = withForeignPtr cap $ \c -> cv_release_capture c foreign import ccall unsafe "opencv/highgui.h cvQueryFrame" c_cvQueryFrame :: Ptr Priv_CvCapture -> IO (Ptr Priv_IplImage) -- |If 'cvQueryFrame' returns 'Nothing', try rewinding the video and -- querying again. If it still fails, raise an error. When a non-null -- frame is obtained, return it. queryFrame :: Capture -> IO (ErrCV IplImage) queryFrame cap = do i <- withForeignPtr cap $ \c -> mycheckPtr_2 $ c_cvQueryFrame c case i of (Return i') -> do fp <- newForeignPtr_ i' -- no free! OpenCV demands queryFrame results not be freed by user. return (Return fp) (Raise s) -> return( throwErrorCV ("Failed to query frame from camera (" ++ s ++ ")") ) ------------------------------------------------- -- * Windows foreign import ccall unsafe "opencv/highgui.h cvNamedWindow" cvNamedWindow :: CString -> CInt -> IO CInt type AutoSize = Bool -- | self-documenting window sizing specification autoSize :: AutoSize autoSize = True namedWindow :: String -> AutoSize -> IO () namedWindow s a = withCString s $ \cs -> do _ <- cvNamedWindow cs (fromIntegral $ fromEnum a) return () foreign import ccall unsafe "opencv/highgui.h cvDestroyWindow" cvDestroyWindow :: CString -> IO () destroyWindow :: String -> IO () destroyWindow wId = withCString wId cvDestroyWindow foreign import ccall unsafe "opencv/highgui.h cvShowImage" cvShowImage :: CString -> Ptr Priv_IplImage -> IO () showImage :: String -> IplImage -> IO () showImage wId p = withCString wId $ \w -> withForeignPtr p $ cvShowImage w foreign import ccall unsafe "opencv/highgui.h cvWaitKey" cvWaitKey :: CInt -> IO CInt waitKey :: Int -> IO (ErrCV Int) waitKey milliSecs = do i <- cvWaitKey $ fromIntegral milliSecs if i == (-1) then return (throwErrorCV ("No Key press...")) else return (Return (fromIntegral i)) -- |Determine the color model of an image loaded from a file. newtype LoadImageColor = LoadImageColor { unLoadImageColor :: CInt } loadImageColor :: LoadImageColor loadImageColor = LoadImageColor 1 loadImageGrayscale :: LoadImageColor loadImageGrayscale = LoadImageColor 0 loadImageUnchanged :: LoadImageColor loadImageUnchanged = LoadImageColor (-1) {-# LINE 135 "HOpenCV/CV/HighGui.hsc" #-} foreign import ccall unsafe "opencv/highgui.h cvLoadImage" c_cvLoadImage :: CString -> CInt -> IO (Ptr Priv_IplImage) loadImage :: String -> LoadImageColor -> IO (ErrCV IplImage) loadImage filename (LoadImageColor color) = do i <- mycheckPtr_2 $ withCString filename $ \fn -> c_cvLoadImage fn color case i of (Return x) -> do fp <- newForeignPtr cvFree x return (Return fp) (Raise s) -> return (throwErrorCV ("Failed to load from file: '" ++ filename ++ "' (" ++ s ++ ")") ) foreign import ccall unsafe "opencv/highgui.h cvSaveImage" c_cvSaveImage :: CString -> Ptr Priv_IplImage -> IO CInt saveImage :: String -> IplImage -> IO (ErrCV Int) saveImage filename image = withCString filename f where f filenameC = do ret <- withForeignPtr image $ \i -> c_cvSaveImage filenameC i if (ret == 0) then return (throwErrorCV ("Failed to save to file: '" ++ filename ++ "'") ) else return (Return (fromIntegral ret)) ------------------------------------------------ -- * Trackbar foreign import ccall unsafe "HOpenCV_Wrap.h wrap_createTrackbar" wrap_createTrackbar :: CString -> CString -> Ptr CInt -> CInt -> IO () createTrackbar :: String -> String -> Maybe Int -> Int -> IO () createTrackbar trackbarName winName startPosition maxValue = withCString trackbarName $ \tb -> withCString winName $ \wn -> alloca $ \sp -> do maybeToPtr sp startPosition wrap_createTrackbar tb wn sp (fromIntegral maxValue) where maybeToPtr mem (Just i) = poke mem (fromIntegral i) maybeToPtr mem Nothing = poke mem (fromIntegral 0) foreign import ccall unsafe "opencv/highgui.h cvGetTrackbarPos" cvGetTrackbarPos :: CString -> CString -> IO CInt getTrackbarPos :: String -> String -> IO (ErrCV Int) getTrackbarPos trackbarName winName = withCString trackbarName $ \tb -> withCString winName $ \wn -> do i <- cvGetTrackbarPos tb wn if (i == 0) then return (throwErrorCV ("Failed to getTrackbarPos to: '" ++ trackbarName ++ "' in winName: '"++ winName ++ "'") ) else return (Return (fromIntegral i)) foreign import ccall unsafe "opencv/highgui.h cvSetTrackbarPos" cvSetTrackbarPos :: CString -> CString -> CInt -> IO () setTrackbarPos :: String -> String -> Int -> IO () setTrackbarPos trackbarName winName pos = withCString trackbarName $ \tb -> withCString winName $ \wn -> cvSetTrackbarPos tb wn (fromIntegral pos)
juanmab37/HOpenCV-0.5.0.1
src/HOpenCV/CV/HighGui.hs
gpl-2.0
8,469
0
19
1,881
1,978
1,001
977
-1
-1
module Machine.Numerical.Inter where import qualified Machine.Numerical.Type as N import Machine.Fun import Machine.Class import qualified Challenger as C import Inter.Types import Autolib.Reporter hiding ( output ) import Autolib.ToDoc import Autolib.Reader import Autolib.Informed computer :: ( N.TypeC c m, Machine m dat conf, Numerical dat ) => String -- aufgabe (major) -> String -- version ( minor ) -> N.Type c m -> Var N.Computer ( N.Type c m ) m computer auf ver num = computer_mat auf ver ( const num ) computer_mat :: ( N.TypeC c m, Machine m dat conf, Numerical dat ) => String -- aufgabe (major) -> String -- version ( minor ) -> ( Key -> N.Type c m ) -> Var N.Computer ( N.Type c m ) m computer_mat auf ver fnum = Var { problem = N.Computer , tag = auf ++ "-" ++ ver , key = \ matrikel -> do return matrikel , gen = \ _vnr _manr key _cache -> return $ do return $ fnum key } instance ( N.TypeC c m, Machine m dat conf, Numerical dat, Reader m ) => C.Partial N.Computer (N.Type c m) m where describe p i = vcat [ text "Konstruieren Sie eine Maschine," , text "die die Funktion" <+> info i <+> text "berechnet!" , N.extra_info i ] initial p i = N.start i partial p i b = N.check i b total p i b = do numerical_test' i b return () -- größe der maschine (hier) ignorieren
florianpilz/autotool
src/Machine/Numerical/Inter.hs
gpl-2.0
1,430
8
12
392
506
265
241
-1
-1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE ViewPatterns #-} module Cow.ParseTree.Viz where import Control.Monad (foldM) import Control.Monad.State (evalState, get, put) import Data.Functor ((<$>)) import Data.Maybe (fromMaybe, listToMaybe) import qualified Data.Tree as Rose import Diagrams.Backend.SVG.CmdLine import Diagrams.Prelude import Diagrams.TwoD.Layout.Tree import Cow.Diff import Cow.ParseTree import Cow.ParseTree.Read -- | Render a tree with functions to control edge colors (based on the -- the nodes they're connecting) and node shapes. renderAnnotTree edgeColor renderNode parseTree = renderTree' renderNode renderEdge tree where tree = clusterLayoutTree parseTree renderEdge (annot1, p1) (annot2, p2) = curve p1 p2 # lc (edgeColor annot1 annot2) # lw 5 -- Connects nodes with a Bézier curve to help avoid -- overlapping edges and make connections easy to follow curve start@(unp2 -> (x1, y1)) end@(unp2 -> (x2, y2)) = fromLocSegments $ [ bezier3 (r2 (0, 0)) (r2 (dx, dy/4)) (r2 (dx, dy)) ] `at` p2 (x1, y1) where (dx, dy) = (x2 - x1, y2 - y1) -- | Renders trees annotated with add/remove/unchanged actions. If an -- internal is added or removed, all its children and edges are -- colored. renderDiffTree = renderAnnotTree edgeColor $ \case (action, Nothing) -> circle 0.5 # fc (colorOf action) # lw 5 (action, Just str) -> (strutY 0.5 === text str) <> rect (w str) 1 # fc (bgOf action) # lc (bgOf action) where colorOf Add' = green colorOf Remove' = red colorOf None' = black bgOf action = blend 0.6 (colorOf action) white w label = fromIntegral (length label) * charWidth + nodeSpacing - 1 edgeColor (action, _) _ = colorOf action -- | Renders a parse tree ignoring its annotations. renderParseTree = renderAnnotTree (\ a b -> black) renderNode where -- Render leaves as white circles and nodes as black dots renderNode (_, Nothing) = circle 0.2 # fc black renderNode (_, Just str) = text str <> rect (w str) 1 # fc white w label = fromIntegral (length label) * charWidth + nodeSpacing - 1 -- TODO: abstract over this! nodeSpacing, charWidth :: (Floating n, Ord n) => n nodeSpacing = 4 charWidth = 0.25 -- | Calculates the y coordinate of each node in a tree, counting up -- from the leaves which are all at y = 0. nodeY :: (Floating n, Ord n) => Parse annot leaf -> Parse (n, annot) leaf nodeY (Leaf annot leaf) = Leaf (0, annot) leaf nodeY (Node annot children) = Node (maximum depths + nodeSpacing, annot) children' where children' = nodeY <$> children depths = children' ^.. each . topAnnot . _1 -- | Calculates the x coordinate for each node in a tree. The leaves -- are all evenly arranged at the bottom of the tree, with each -- internal node centered *relative to its leaves* (not necessarily -- its direct sub-nodes). nodeX :: (Floating n, Ord n) => Parse annot String -> Parse (n, annot) String nodeX tree = offsetAndCenter $ nodeWidth tree where -- Calculate the x offset of every node in a tree to center -- the root node and move the subtrees relative to each other -- as needed. offsetAndCenter (Leaf (width, annot) leaf) = Leaf (width / 2, annot) leaf offsetAndCenter (Node (width, annot) children) = Node (width / 2, annot) $ reverse offsetChildren where offsetChildren = evalState (foldM go [] $ offsetAndCenter <$> children) 0 go children' node = do offset <- get let node' = node & annots . _1 +~ offset put $ offset + 2 * (node ^. topAnnot . _1) return $ node' : children' -- Calculate how many leaves are under each node (any number -- of levels down). Leaves have a width that depends on the -- length of their label, with 'nodeSpacing' padding. nodeWidth (Leaf annot leaf) = Leaf (nodeSpacing + textWidth leaf, annot) leaf where textWidth str = fromIntegral (length str) * charWidth nodeWidth (Node annot children) = Node (sum widths, annot) children' where children' = nodeWidth <$> children widths = children' ^.. each . topAnnot . _1 -- | Lays a whole tree out with everything aligned from the leaves up. clusterLayoutTree :: (Floating n, Ord n) => Parse annot String -> Rose.Tree ((annot, Maybe String), P2 n) clusterLayoutTree = fmap go . toRoseTreeAnnot . (annots %~ toP2) . nodeX . nodeY where go ((pos, annot), leaf) = ((annot, leaf), pos) toP2 (width, (depth, annot)) = (p2 (width, depth), annot) exampleTree :: Parse () String exampleTree = show <$> readTree' "[[1][2[3 4]][5[6][7[[8 9 10 11 12]][13 14 15]]]]" exampleTreeDiagram = renderParseTree exampleTree # translateY 10 # pad 1.1 # bg white
TikhonJelvis/Cow
src/Cow/ParseTree/Viz.hs
gpl-3.0
5,458
0
16
1,644
1,400
753
647
-1
-1
{-# LANGUAGE RankNTypes #-} module Lib ( countLinesPp , printLineCount , countFileLines , printLinesIn , countFilesIn , listFilesIn , concatFilesIn , catFile , concatFilesInStr ) where import Control.Applicative import Control.Monad import Control.Monad.IO.Class import Data.ByteString (ByteString) import Data.DirStream import Data.Text (Text) import qualified Data.Text as T import Data.Text.Encoding import qualified Filesystem.Path as FS import Filesystem.Path.CurrentOS (decodeString, encodeString) import Pipes import qualified Pipes.ByteString as PB import qualified Pipes.Prelude as PP import qualified Pipes.Prelude.Text as PPT import Pipes.Safe (MonadSafe, SafeT, bracket, liftBase, runSafeT) import Pipes.Safe.Prelude (withFile) import qualified Pipes.Text.Encoding as PT import System.Directory import qualified System.IO as IO -- | Count the lines that pass through this pipe. countLinesPp :: Monad m => Pipe Text Int m () countLinesPp = forever $ await >>= yield . length . filter T.null . T.lines -- | Count the lines of a file. countFileLines :: FilePath -> Producer Int (SafeT IO) () countFileLines fPath = readFileAsText fPath >-> countLinesPp -- | Pass only the existing files. existingFiles :: MonadIO m => Pipe FilePath FilePath m () existingFiles = forever $ do fp <- await exists <- lift $ liftIO $ doesFileExist fp when exists (yield fp) -- | Pass only the readable files. readableFiles :: MonadIO m => Pipe FilePath FilePath m () -- Note that this pattern could be abstracted. Maybe in the dirstream library. readableFiles = forever $ do fp <- await perms <- lift $ liftIO $ getPermissions fp when (readable perms) (yield fp) -- | Pass only regular files (no symbolic links) regularFiles :: MonadIO m => Pipe FilePath FilePath m () regularFiles = forever $ do fp <- await symLink <- lift $ liftIO $ pathIsSymbolicLink fp when (not symLink) (yield fp) -- | Print the number of lines in a file. printLineCount :: FilePath -> IO () printLineCount fPath = do sum <- runSafeT $ PP.sum $ for files countFileLines print $ "Number of lines in " ++ fPath ++ ": " ++ (show sum) where files = yield fPath >-> existingFiles >-> readableFiles -- | Cat a file catFile :: FilePath -> IO () catFile fPath = do sum <- runSafeT $ runEffect $ files >-> catFiles >-> PP.map T.unpack >-> PP.stdoutLn print $ "Number of lines in " ++ fPath ++ ": " ++ (show sum) where files = yield fPath >-> existingFiles >-> readableFiles readFileAsText :: FilePath -> Producer' Text (SafeT IO) () readFileAsText fPath = readFileBS fPath >-> decodeUtf8Pp decodeUtf8Pp :: Monad m => Pipe ByteString Text m () decodeUtf8Pp = do chunk <- await yield $ decodeUtf8With ignore chunk where ignore _ _ = Just '?' readFileBS :: FilePath -> Producer' ByteString (SafeT IO) () readFileBS file = bracket (IO.openFile file IO.ReadMode) (IO.hClose) PB.fromHandle catFiles :: Pipe FilePath Text (SafeT IO) () catFiles = forever $ do fPath <- await for (readFileAsText fPath) yield catFiles' :: Pipe FilePath Text (SafeT IO) () catFiles' = forever $ do fPath <- await bracket (IO.openFile fPath IO.ReadMode) (IO.hClose) PPT.fromHandleLn one :: Monad m => Pipe a Int m () one = await >> yield 1 >> one myDescentOf :: MonadSafe m => FS.FilePath -> ListT m FS.FilePath myDescentOf path = do child <- childOf path isDir <- liftIO $ isDirectory child isSymLink <- liftIO $ pathIsSymbolicLink (encodeString child) if isDir && not isSymLink then return child <|> myDescentOf child else return child -- | List the files in a directory. listFilesIn :: FilePath -> IO () listFilesIn fPath = do IO.withFile "mystdout" IO.WriteMode $ \h -> runSafeT $ runEffect $ every (myDescentOf (decodeString fPath)) >-> PP.map encodeString >-> readableFiles >-> existingFiles >-> regularFiles >-> PP.toHandle h -- | Count the number of files in a directory. -- PROBLEM: this will list the symbolic files as well! countFilesIn :: FilePath -> IO () countFilesIn fPath = do sum <- runSafeT $ PP.sum $ every (myDescentOf (decodeString fPath)) >-> PP.map encodeString >-> readableFiles >-> existingFiles >-> regularFiles >-> one print $ "Total number of lines of files under " ++ fPath ++ ": " ++ (show sum) -- | Print the total number of lines of all the files in a directory. -- -- This should implement: -- -- > find $fPath -type f -print | xargs cat | wc -l -- printLinesIn :: FilePath -> IO () printLinesIn fPath = do sum <- runSafeT $ PP.sum $ every (myDescentOf (decodeString fPath)) >-> PP.map encodeString >-> readableFiles >-> existingFiles >-> regularFiles >-> catFiles' >-> one -- >-> countLinesPp print $ "Total number of lines under directory " ++ fPath ++ ": " ++ (show sum) -- | Make a huge file by concatenating all the files in the directory. concatFilesIn :: FilePath -> IO () concatFilesIn fPath = do IO.withFile "mylargefile" IO.WriteMode $ \h -> runSafeT $ runEffect $ every (myDescentOf (decodeString fPath)) >-> PP.map encodeString >-> readableFiles >-> existingFiles >-> regularFiles >-> catFiles' >-> PP.map T.unpack >-> PP.toHandle h readFileAsStr :: Pipe FilePath String (SafeT IO) () readFileAsStr = forever $ do fPath <- await bracket (IO.openFile fPath IO.ReadMode) (IO.hClose) PP.fromHandle -- This will fail when trying to convert to the file contents to utf 8 it seems: -- -- > *** Exception: /usr/include/php/ext/standard/php_ext_syslog.h: hGetLine: invalid argument (invalid byte sequence) -- -- Maybe we just need to count the number of new-lines: -- -- - http://www.scs.stanford.edu/16wi-cs240h/slides/iteratee-slides.html#(15) -- -- > L8.break (== '\n') -- concatFilesInStr :: FilePath -> IO () concatFilesInStr fPath = do IO.withFile "mylargefileStr" IO.WriteMode $ \h -> runSafeT $ runEffect $ every (myDescentOf (decodeString fPath)) >-> PP.map encodeString >-> readableFiles >-> existingFiles >-> regularFiles >-> readFileAsStr >-> PP.toHandle h -- TODO: test with /usr/include/php/ext/standard/ -- TODO: test with `/usr/include/libkern`
capitanbatata/sandbox
pw-pipes/src/Lib.hs
gpl-3.0
6,622
0
21
1,630
1,744
890
854
151
2
-- | -- Copyright : © 2009 CNRS - École Polytechnique - INRIA -- License : GPL -- -- Check that all occurrences of variables are in scope of their definitions. -- Other well-formedness checks can also be found here, such as rejecting -- duplicate top-level definitions. module Dedukti.Analysis.Scope where import Dedukti.Core import Dedukti.Module import qualified Dedukti.Rule as Rule import Dedukti.Pretty () import Dedukti.DkM import Data.List (sort, group) import qualified Data.Traversable as T import qualified Data.Map as Map import qualified StringTable.AtomSet as AtomSet newtype DuplicateDefinition = DuplicateDefinition Qid deriving (Eq, Ord, Typeable) instance Show DuplicateDefinition where show (DuplicateDefinition id) = show (text "duplicate definition" <+> pretty id) instance Exception DuplicateDefinition newtype ScopeError = ScopeError Qid deriving (Eq, Ord, Typeable) instance Show ScopeError where show (ScopeError id) = show (pretty id <+> text "not in scope.") instance Exception ScopeError newtype IllegalEnvironment = IllegalEnvironment Qid deriving (Eq, Ord, Typeable) instance Show IllegalEnvironment where show (IllegalEnvironment id) = show (pretty id <+> text "appears in environment but not in head of rule.") instance Exception IllegalEnvironment -- | Check that all environments, including the global one, are linear. checkUniqueness :: Module Qid a -> DkM () checkUniqueness (decls, rules) = do say Verbose $ text "Checking linearity of environments ..." chk decls mapM_ (\(env :@ _) -> chk (env_bindings env)) rules where chk bs = mapM_ (\x -> when (length x > 1) (throw $ DuplicateDefinition (head x))) $ group $ sort $ map bind_name bs type Context = Map.Map MName AtomSet.AtomSet -- | Initial environment to pass to 'checkScopes'. initContext :: [Qid] -- ^ declarations from other modules. -> Context initContext qids = Map.fromListWith AtomSet.union $ map (\qid -> (qid_qualifier qid, AtomSet.singleton (qid_stem qid))) qids -- | Check that all variables and constants are well scoped. checkScopes :: Context -> Module Qid a -> DkM () checkScopes env (decls, rules) = do say Verbose $ text "Checking that all declarations are well scoped ..." topenv <- foldM chkBinding env decls mapM_ (chkRule topenv) rules where ins qid env = Map.insertWith' AtomSet.union (qid_qualifier qid) (AtomSet.singleton (qid_stem qid)) env notmem qid env = maybe False (AtomSet.notMember (qid_stem qid)) (Map.lookup (qid_qualifier qid) env) chkBinding env (L x ty) = do chkExpr env `T.mapM` ty return $ ins x env chkBinding env (x ::: ty) = do chkExpr env ty return $ ins x env chkBinding env (x := t) = do chkExpr env t return $ ins x env chkRule topenv r@(env :@ rule) = do let lhsvars = AtomSet.fromList [ qid_stem x | V x _ <- everyone (Rule.head r) ] mapM_ (\x -> when (qid_stem x `AtomSet.notMember` lhsvars) $ throw (IllegalEnvironment x)) (map bind_name $ env_bindings env) ruleenv <- foldM chkBinding topenv $ env_bindings env descendM (chkExpr (Map.unionWith AtomSet.union topenv ruleenv)) rule chkExpr env t@(V x _) = do when (x `notmem` env) (throw $ ScopeError x) return t chkExpr env (B (L x ty) t _) = do chkExpr env `T.mapM` ty chkExpr (ins x env) t chkExpr env (B (x ::: ty) t _) = do chkExpr env ty chkExpr (ins x env) t chkExpr env t = descendM (chkExpr env) t
mboes/dedukti
Dedukti/Analysis/Scope.hs
gpl-3.0
3,806
0
19
1,026
1,166
586
580
73
6
{-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE PatternGuards #-} -- Copyright : (c) 2019 Robert Künnemann -- License : GPL v3 (see LICENSE) -- -- Maintainer : Robert Künnemann <[email protected]> -- Portability : GHC only -- -- Translation rules common for different translation types in SAPIC module Sapic.Basetranslation ( baseTransNull , baseTransComb , baseTransAction , baseTrans , baseInit , toEx , baseRestr -- types , TransFact , TranslationResultNull , TranslationResultAct , TranslationResultComb , TransFNull , TransFAct , TransFComb ) where import Control.Exception import Control.Monad.Catch import Data.Set hiding (map, (\\)) import Data.List (nub, (\\)) import qualified Extension.Data.Label as L import Sapic.Annotation import Sapic.Exceptions import Sapic.Facts import Sapic.ProcessUtils import qualified Text.RawString.QQ as QQ import Theory import Theory.Sapic import Theory.Sapic.Print import Theory.Text.Parser -- import Debug.Trace type TranslationResultNull = ([([TransFact], [TransAction], [TransFact], [SyntacticLNFormula])]) type TranslationResultAct = ([([TransFact], [TransAction], [TransFact], [SyntacticLNFormula])], Set LVar) type TranslationResultComb = ([([TransFact], [TransAction], [TransFact], [SyntacticLNFormula])], Set LVar, Set LVar) type TransFNull t = ProcessAnnotation -> ProcessPosition -> Set LVar -> t type TransFAct t = SapicAction -> ProcessAnnotation -> ProcessPosition -> Set LVar -> t type TransFComb t = ProcessCombinator -> ProcessAnnotation -> ProcessPosition -> Set LVar -> t -- | The basetranslation has three functions, one for translating the Null -- Process, one for actions (i.e. constructs with only one child process) and -- one for combinators (i.e., constructs with two child processes). baseTrans :: MonadThrow m => Bool -> (TransFNull (m TranslationResultNull), TransFAct (m TranslationResultAct), TransFComb (m TranslationResultComb)) baseTrans needsInEvRes = (\ a p tx -> return $ baseTransNull a p tx, \ ac an p tx -> return $ baseTransAction needsInEvRes ac an p tx, \ comb an p tx -> return $ baseTransComb comb an p tx) -- I am sure there is nice notation for that. -- | Each part of the translation outputs a set of multiset rewrite rules, -- and ~x (tildex), the set of variables hitherto bound baseTransNull :: TransFNull TranslationResultNull baseTransNull _ p tildex = [([State LState p tildex ], [], [], [])] baseTransAction :: Bool -> TransFAct TranslationResultAct baseTransAction needsInEvRes ac an p tildex | Rep <- ac = ([ ([def_state], [], [State PSemiState (p++[1]) tildex ], []), ([State PSemiState (p++[1]) tildex], [], [def_state' tildex], []) ], tildex) | (New v) <- ac = let tx' = v `insert` tildex in ([ ([def_state, Fr v], [], [def_state' tx'], []) ], tx') | (ChIn (Just tc) t) <- ac, (Just (AnLVar _)) <- secretChannel an = let tx' = freeset tc `union` freeset t `union` tildex in ([ ([def_state, Message tc t], [], [Ack tc t, def_state' tx'], [])], tx') | (ChIn (Just tc) t) <- ac, Nothing <- secretChannel an = let tx' = freeset tc `union` freeset t `union` tildex in let ts = fAppPair (tc,t) in ([ ([def_state, In ts], [ChannelIn ts | needsInEvRes], [def_state' tx'], []), ([def_state, Message tc t], [], [Ack tc t, def_state' tx'], [])], tx') | (ChIn Nothing t) <- ac = let tx' = freeset t `union` tildex in ([ ([def_state, In t ], [ChannelIn t | needsInEvRes], [def_state' tx'], []) ], tx') | (ChOut (Just tc) t) <- ac, (Just (AnLVar _)) <- secretChannel an = let semistate = State LSemiState (p++[1]) tildex in ([ ([def_state], [], [Message tc t,semistate], []), ([semistate, Ack tc t], [], [def_state' tildex], [])], tildex) | (ChOut (Just tc) t) <- ac, Nothing <- secretChannel an = let semistate = State LSemiState (p++[1]) tildex in ([ ([def_state, In tc], [ChannelIn tc | needsInEvRes], [Out t, def_state' tildex], []), ([def_state], [], [Message tc t,semistate], []), ([semistate, Ack tc t], [], [def_state' tildex], [])], tildex) | (ChOut Nothing t) <- ac = ([ ([def_state], [], [def_state' tildex, Out t], [])], tildex) | (Insert t1 t2 ) <- ac = ([ ([def_state], [InsertA t1 t2], [def_state' tildex], [])], tildex) | (Delete t ) <- ac = ([ ([def_state], [DeleteA t ], [def_state' tildex], [])], tildex) | (Lock t ) <- ac, (Just (AnLVar v)) <- lock an = let tx' = v `insert` tildex in ([ ([def_state, Fr v], [LockNamed t v, LockUnnamed t v ], [def_state' tx'], [])], tx') | (Lock _ ) <- ac, Nothing <- lock an = throw (NotImplementedError "Unannotated lock" :: SapicException AnnotatedProcess) | (Unlock t ) <- ac, (Just (AnLVar v)) <- unlock an = ([([def_state], [UnlockNamed t v, UnlockUnnamed t v ], [def_state' tildex], [])], tildex) | (Unlock _ ) <- ac, Nothing <- lock an = throw ( NotImplementedError "Unannotated unlock" :: SapicException AnnotatedProcess) | (Event f ) <- ac = ([([def_state], TamarinAct f : [EventEmpty | needsInEvRes], [def_state' tildex], [])], tildex) | (MSR (l,a,r,res)) <- ac = let tx' = freeset' l `union` tildex in ([(def_state:map TamarinFact l, map TamarinAct a ++ [EventEmpty | needsInEvRes], def_state' tx':map TamarinFact r, res)], tx') | otherwise = throw ((NotImplementedError $ "baseTransAction:" ++ prettySapicAction ac) :: SapicException AnnotatedProcess) where def_state = State LState p tildex -- default state when entering def_state' tx = State LState (p++[1]) tx -- default follow upstate, possibly with new bound variables freeset = fromList . frees freeset' = fromList . concatMap getFactVariables -- | The translation for combinators expects: -- c - the combinator -- _ - annotations (for future use, currently ignored) -- p - the current position -- tildex - the logical variables bound up to here -- It outputs -- a set of mrs -- the set of bound variables for the lhs process -- the set of bound variables for the rhs process baseTransComb :: TransFComb TranslationResultComb baseTransComb c _ p tildex | Parallel <- c = ( [([def_state], [], [def_state1 tildex,def_state2 tildex], [])] , tildex, tildex ) | NDC <- c = ( [] , tildex, tildex ) | Cond f <- c = let freevars_f = fromList $ freesList f in if freevars_f `isSubsetOf` tildex then ([ ([def_state], [], [def_state1 tildex], [f]), ([def_state], [], [def_state2 tildex], [Not f])] , tildex, tildex ) else throw ( ProcessNotWellformed $ WFUnboundProto (freevars_f `difference` tildex) :: SapicException AnnotatedProcess) | CondEq t1 t2 <- c = let fa = (protoFact Linear "Eq" [t1,t2]) in let vars_f = fromList $ getFactVariables fa in if vars_f `isSubsetOf` tildex then ([ ([def_state], [PredicateA fa], [def_state1 tildex], []), ([def_state], [NegPredicateA fa], [def_state2 tildex], [])] , tildex, tildex ) else throw ( ProcessNotWellformed $ WFUnboundProto (vars_f `difference` tildex) :: SapicException AnnotatedProcess) | Lookup t v <- c = let tx' = v `insert` tildex in ( [ ([def_state], [IsIn t v], [def_state1 tx' ], []), ([def_state], [IsNotSet t], [def_state2 tildex], [])] , tx', tildex ) | otherwise = throw (NotImplementedError "baseTransComb":: SapicException AnnotatedProcess) where def_state = State LState p tildex def_state1 tx = State LState (p++[1]) tx def_state2 tx = State LState (p++[2]) tx -- | @baseInit@ provides the initial rule that is used to create the first -- linear statefact. An additional restriction on InitEmpty makes sure it can -- only be used once. baseInit :: AnProcess ann -> ([AnnotatedRule ann], Set a) baseInit anP = ([AnnotatedRule (Just "Init") anP (Right InitPosition) l a r [] 0],empty) where l = [] a = [InitEmpty ] r = [State LState [] empty] -- | Convert parsing erros into Exceptions. To make restrictions easier to -- modify and thus maintain, we use the parser to convert from -- a hand-written string. It is possible that there are syntax arrors, in -- which case the translation should crash with the following error -- message. toEx :: MonadThrow m => String -> m SyntacticRestriction toEx s | (Left err) <- parseRestriction s = throwM ( ImplementationError ( "Error parsing hard-coded restriction: " ++ s ++ show err )::SapicException AnnotatedProcess) | (Right res) <- parseRestriction s = return res | otherwise = throwM ( ImplementationError "toEx, otherwise case to satisfy compiler"::SapicException AnnotatedProcess) resSetIn :: String resSetIn = [QQ.r|restriction set_in: "All x y #t3 . IsIn(x,y)@t3 ==> (Ex #t2 . Insert(x,y)@t2 & #t2<#t3 & ( All #t1 . Delete(x)@t1 ==> (#t1<#t2 | #t3<#t1)) & ( All #t1 yp . Insert(x,yp)@t1 ==> (#t1<#t2 | #t1=#t2 | #t3<#t1)) )" |] resSetNotIn :: String resSetNotIn = [QQ.r|restriction set_notin: "All x #t3 . IsNotSet(x)@t3 ==> (All #t1 y . Insert(x,y)@t1 ==> #t3<#t1 ) | ( Ex #t1 . Delete(x)@t1 & #t1<#t3 & (All #t2 y . Insert(x,y)@t2 & #t2<#t3 ==> #t2<#t1))" |] resSetInNoDelete :: String resSetInNoDelete = [QQ.r|restriction set_in: "All x y #t3 . IsIn(x,y)@t3 ==> (Ex #t2 . Insert(x,y)@t2 & #t2<#t3 & ( All #t1 yp . Insert(x,yp)@t1 ==> (#t1<#t2 | #t1=#t2 | #t3<#t1)) )" |] resSetNotInNoDelete :: String resSetNotInNoDelete = [QQ.r|restriction set_notin: "All x #t3 . IsNotSet(x)@t3 ==> (All #t1 y . Insert(x,y)@t1 ==> #t3<#t1 )" |] resSingleSession :: String resSingleSession = [QQ.r|restrictionsingle_session: // for a single session "All #i #j. Init()@i & Init()@j ==> #i=#j" |] -- | Restriction for Locking. Note that LockPOS hardcodes positions that -- should be modified below. resLockingL :: String resLockingL = [QQ.r|restriction locking: "All p pp l x lp #t1 #t3 . LockPOS(p,l,x)@t1 & Lock(pp,lp,x)@t3 ==> ( #t1<#t3 & (Ex #t2. UnlockPOS(p,l,x)@t2 & #t1<#t2 & #t2<#t3 & (All #t0 pp . Unlock(pp,l,x)@t0 ==> #t0=#t2) & (All pp lpp #t0 . Lock(pp,lpp,x)@t0 ==> #t0<#t1 | #t0=#t1 | #t2<#t0) & (All pp lpp #t0 . Unlock(pp,lpp,x)@t0 ==> #t0<#t1 | #t2<#t0 | #t2=#t0 ) )) | #t3<#t1 | #t1=#t3" |] -- | Restriction for Locking where no Unlock is necessary. resLockingLNoUnlockPOS :: String resLockingLNoUnlockPOS = [QQ.r|restriction locking: "All p l x #t1 . LockPOS(p,l,x)@t1 ==> (All pp lp #t2. LockPOS(pp,lp,x)@t2 ==> #t1=#t2)" |] -- | Restriction for Locking where no Unlock is necessary. resLockingNoUnlock :: String resLockingNoUnlock = [QQ.r|restriction locking: "All p l x #t1 . Lock(p,l,x)@t1 ==> (All pp lp #t2. Lock(pp,lp,x)@t2 ==> #t1=#t2)" |] -- | Produce locking lemma for variable v by instantiating resLockingL -- with (Un)Lock_pos instead of (Un)LockPOS, where pos is the variable id -- of v. resLocking :: MonadThrow m => Bool -> LVar -> m SyntacticRestriction resLocking hasUnlock v = do rest <- if hasUnlock then toEx resLockingL else toEx resLockingLNoUnlockPOS return $ mapName hardcode $ mapFormula (mapAtoms subst) rest where subst _ a | (Action t f) <- a, Fact {factTag = ProtoFact Linear "LockPOS" 3} <- f = Action t (f {factTag = ProtoFact Linear (hardcode "Lock") 3}) | (Action t f) <- a, Fact {factTag = ProtoFact Linear "UnlockPOS" 3} <- f = Action t (f {factTag = ProtoFact Linear (hardcode "Unlock") 3}) | otherwise = a hardcode s = s ++ "_" ++ show (lvarIdx v) mapFormula = L.modify rstrFormula mapName = L.modify rstrName resEq :: String resEq = [QQ.r|restriction predicate_eq: "All #i a b. Pred_Eq(a,b)@i ==> a = b" |] resNotEq :: String resNotEq = [QQ.r|restriction predicate_not_eq: "All #i a b. Pred_Not_Eq(a,b)@i ==> not(a = b)" |] resInEv :: String resInEv = [QQ.r|restriction in_event: "All x #t3. ChannelIn(x)@t3 ==> (Ex #t2. K(x)@t2 & #t2 < #t3 & (All #t1. Event()@t1 ==> #t1 < #t2 | #t3 < #t1) & (All #t1 xp. K(xp)@t1 ==> #t1 < #t2 | #t1 = #t2 | #t3 < #t1))" |] -- | generate restrictions depending on options set (op) and the structure -- of the process (anP) baseRestr :: (MonadThrow m, MonadCatch m) => AnProcess ProcessAnnotation -> Bool -> Bool -> [SyntacticRestriction] -> m [SyntacticRestriction] baseRestr anP needsInEvRes hasAccountabilityLemmaWithControl prevRestr = let hardcoded_l = (if contains isLookup then if contains isDelete then [resSetIn, resSetNotIn] else [resSetInNoDelete, resSetNotInNoDelete] else []) ++ addIf (contains isEq) [resEq, resNotEq] ++ addIf hasAccountabilityLemmaWithControl [resSingleSession] ++ addIf needsInEvRes [resInEv] in do hardcoded <- mapM toEx hardcoded_l lockingWithUnlock <- mapM (resLocking True) (nub $ getUnlockPositions anP) lockingOnlyLock <- mapM (resLocking False) ((getLockPositions anP) \\ (getUnlockPositions anP)) singleLocking <- toEx resLockingNoUnlock return $ prevRestr ++ hardcoded ++ lockingWithUnlock ++ lockingOnlyLock ++ addIf ((not $ contains isUnlock) && (contains isLock)) [singleLocking] where addIf phi list = if phi then list else [] contains = processContains anP getLock p | (ProcessAction (Lock _) an _) <- p, (Just (AnLVar v)) <- lock an = [v] -- annotation is Maybe type | otherwise = [] getUnlock p | (ProcessAction (Unlock _) an _) <- p, (Just (AnLVar v)) <- unlock an = [v] -- annotation is Maybe type | otherwise = [] getLockPositions = pfoldMap getLock getUnlockPositions = pfoldMap getUnlock -- This is what SAPIC did -- @ (if op.accountability then [] else [res_single_session_l])
tamarin-prover/tamarin-prover
lib/sapic/src/Sapic/Basetranslation.hs
gpl-3.0
15,334
0
16
4,442
4,082
2,234
1,848
236
4
module HLinear.Hook.LeftTransformation ( module Basic , module Column , module Definition ) where import HLinear.Hook.LeftTransformation.Algebra () import HLinear.Hook.LeftTransformation.Basic as Basic import HLinear.Hook.LeftTransformation.Column as Column hiding ( one, isOne, zipWith ) import HLinear.Hook.LeftTransformation.Definition as Definition import HLinear.Hook.LeftTransformation.QuickCheck () import HLinear.Hook.LeftTransformation.SmallCheck ()
martinra/hlinear
src/HLinear/Hook/LeftTransformation.hs
gpl-3.0
468
0
5
49
90
65
25
10
0
{-# LANGUAGE Rank2Types, NoMonomorphismRestriction, ScopedTypeVariables #-} module Database.Design.Ampersand.Test.Parser.QuickChecks (parserQuickChecks) where import Database.Design.Ampersand.Test.Parser.ParserTest (parseReparse) import Database.Design.Ampersand.Test.Parser.ArbitraryTree() import Database.Design.Ampersand.ADL1.PrettyPrinters(prettyPrint) import Database.Design.Ampersand.Core.ParseTree (P_Context) import Database.Design.Ampersand.Input.ADL1.CtxError (Guarded(..)) import Test.QuickCheck(Args(..), quickCheckWithResult, Testable, Result(..)) import Debug.Trace -- Tries to parse a string, and if successful, tests the result with the given function testParse :: String -> (P_Context -> Bool) -> Bool testParse text check = case parseReparse "QuickChecks.hs" text of Checked a -> check a Errors e -> trace (show e ++ "\n" ++ text) False -- TODO: Errors e -> do { showErrors e; return False } -- Tests whether the parsed context is equal to the original one prop_pretty :: P_Context -> Bool prop_pretty ctx = testParse prettyCtx eq where eq p = ctx == p || trace ("Printed versions are different: " ++ prettyCtx ++ "\n\n---------\n\n" ++ prettyPrint p) False prettyCtx = prettyPrint ctx checkArgs :: Args checkArgs = Args { replay = Nothing , maxSuccess = 64 , maxDiscardRatio = 8 , maxSize = 8 -- otherwise there's nothing quick about it. , chatty = False } -- TODO: Improve the messages given here, remove all trace's test :: Testable prop => prop -> IO Bool test p = do res <- quickCheckWithResult checkArgs p case trace (show res) res of Success {} -> return True _ -> return False parserQuickChecks :: IO Bool parserQuickChecks = test prop_pretty
DanielSchiavini/ampersand
src/Database/Design/Ampersand/Test/Parser/QuickChecks.hs
gpl-3.0
1,837
0
12
394
410
232
178
31
2
--www.haskell.org/haskellwiki/99_questions --3 elementAt :: [a]-> Int -> a elementAt (x:xs) i | i == 1 = x | otherwise = elementAt xs (i-1) elementAt [] i = error "Can't get element from empty list/Index out of bounds" --4 myLength :: [a] -> Int myLength [] = 0 myLength [x] = 1 myLength (x:xs) = 1 + myLength(xs) --5 myReverse :: [a] -> [a] myReverse [x] = [x] myReverse (x:xs) = myReverse xs ++ (x:[]) --6 isPalindrome :: Eq a => [a] -> Bool isPalindrome (x:xs) = all (True==) [fst pairs == snd pairs | pairs <- zip (x:xs) (reverse (x:xs)) ] --isPalindrome (x:xs) = length (x:xs) == 10
dasfaha/miscelaneous
nn.hs
gpl-3.0
690
1
13
210
291
155
136
14
1
module TextParser.Header (parseHeader) where import TextData.Data import TextData.Keywords import Text.Parsec import Text.Parsec.String import Text.Parsec.Combinator {-PARSE a header-} parseHeader :: Parser Header parseHeader = do t <- parseHeaderTag title_tag l <- parseHeaderTag lastname_tag f <- parseHeaderTag firstname_tag d <- parseHeaderTag date_tag parseHeaderSeperator return $ Header t l f d parseHeaderTag :: String -> Parser String parseHeaderTag s = do string s char colon manyTill anyChar $ try $ string "\n" parseHeaderSeperator :: Parser () parseHeaderSeperator = do count header_seperator_count (char dash) manyTill (char dash) $ try $ string "\n" return ()
DarkTilRisen/FlashText
TextParser/Header.hs
gpl-3.0
862
0
11
277
220
104
116
21
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Books.MyLibrary.Annotations.Update -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Updates an existing annotation. -- -- /See:/ <https://developers.google.com/books/docs/v1/getting_started Books API Reference> for @books.mylibrary.annotations.update@. module Network.Google.Resource.Books.MyLibrary.Annotations.Update ( -- * REST Resource MyLibraryAnnotationsUpdateResource -- * Creating a Request , myLibraryAnnotationsUpdate , MyLibraryAnnotationsUpdate -- * Request Lenses , mlauPayload , mlauAnnotationId , mlauSource ) where import Network.Google.Books.Types import Network.Google.Prelude -- | A resource alias for @books.mylibrary.annotations.update@ method which the -- 'MyLibraryAnnotationsUpdate' request conforms to. type MyLibraryAnnotationsUpdateResource = "books" :> "v1" :> "mylibrary" :> "annotations" :> Capture "annotationId" Text :> QueryParam "source" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] Annotation :> Put '[JSON] Annotation -- | Updates an existing annotation. -- -- /See:/ 'myLibraryAnnotationsUpdate' smart constructor. data MyLibraryAnnotationsUpdate = MyLibraryAnnotationsUpdate' { _mlauPayload :: !Annotation , _mlauAnnotationId :: !Text , _mlauSource :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'MyLibraryAnnotationsUpdate' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'mlauPayload' -- -- * 'mlauAnnotationId' -- -- * 'mlauSource' myLibraryAnnotationsUpdate :: Annotation -- ^ 'mlauPayload' -> Text -- ^ 'mlauAnnotationId' -> MyLibraryAnnotationsUpdate myLibraryAnnotationsUpdate pMlauPayload_ pMlauAnnotationId_ = MyLibraryAnnotationsUpdate' { _mlauPayload = pMlauPayload_ , _mlauAnnotationId = pMlauAnnotationId_ , _mlauSource = Nothing } -- | Multipart request metadata. mlauPayload :: Lens' MyLibraryAnnotationsUpdate Annotation mlauPayload = lens _mlauPayload (\ s a -> s{_mlauPayload = a}) -- | The ID for the annotation to update. mlauAnnotationId :: Lens' MyLibraryAnnotationsUpdate Text mlauAnnotationId = lens _mlauAnnotationId (\ s a -> s{_mlauAnnotationId = a}) -- | String to identify the originator of this request. mlauSource :: Lens' MyLibraryAnnotationsUpdate (Maybe Text) mlauSource = lens _mlauSource (\ s a -> s{_mlauSource = a}) instance GoogleRequest MyLibraryAnnotationsUpdate where type Rs MyLibraryAnnotationsUpdate = Annotation type Scopes MyLibraryAnnotationsUpdate = '["https://www.googleapis.com/auth/books"] requestClient MyLibraryAnnotationsUpdate'{..} = go _mlauAnnotationId _mlauSource (Just AltJSON) _mlauPayload booksService where go = buildClient (Proxy :: Proxy MyLibraryAnnotationsUpdateResource) mempty
rueshyna/gogol
gogol-books/gen/Network/Google/Resource/Books/MyLibrary/Annotations/Update.hs
mpl-2.0
3,811
0
15
843
467
278
189
73
1
import Test.HUnit import qualified Data.Map as Map import qualified Data.Set as Set import Constraints import Types import Obj import Parsing import Infer import Eval main :: IO () main = do _ <- runTestTT (groupTests "Constraints" testConstraints) return () groupTests :: String -> [Test] -> Test groupTests label testCases = TestList (zipWith TestLabel (map ((\s -> label ++ " Test " ++ s) . show) [1..]) testCases) -- | Helper functions for testing unification of Constraints isUnificationFailure :: Either UnificationFailure TypeMappings -> Bool isUnificationFailure (Left _) = True isUnificationFailure (Right _) = False assertUnificationFailure :: [Constraint] -> Test assertUnificationFailure constraints = TestCase $ assertBool "Failure" (isUnificationFailure (solve constraints)) assertSolution :: [Constraint] -> [(String, Ty)] -> Test assertSolution constraints solution = TestCase $ assertEqual "Solution" (Right (Map.fromList solution)) (solve constraints) -- | A dummy XObj x = XObj (External Nothing) Nothing Nothing -- | Some type variables t0 = VarTy "t0" t1 = VarTy "t1" t2 = VarTy "t2" t3 = VarTy "t3" -- | Test constraints testConstraints = [testConstr1, testConstr2, testConstr3, testConstr4, testConstr5 ,testConstr6, testConstr7, testConstr8, testConstr9, testConstr10 ,testConstr11, testConstr12, testConstr13 ,testConstr20, testConstr21, testConstr22, testConstr23, testConstr24 ,testConstr30, testConstr31, testConstr32, testConstr33 ,testConstr34, testConstr35 ] testConstr1 = assertUnificationFailure [Constraint FloatTy IntTy x x OrdNo] testConstr2 = assertSolution [Constraint IntTy t0 x x OrdNo] [("t0", IntTy)] testConstr3 = assertSolution [Constraint t0 IntTy x x OrdNo] [("t0", IntTy)] testConstr4 = assertSolution [Constraint t0 t1 x x OrdNo, Constraint t0 IntTy x x OrdNo] [("t0", IntTy), ("t1", IntTy)] testConstr5 = assertSolution [Constraint t0 t1 x x OrdNo, Constraint t1 IntTy x x OrdNo] [("t0", IntTy), ("t1", IntTy)] testConstr6 = assertSolution [Constraint t0 t1 x x OrdNo, Constraint t1 t3 x x OrdNo, Constraint t2 IntTy x x OrdNo, Constraint t3 IntTy x x OrdNo] [("t0", IntTy), ("t1", IntTy), ("t2", IntTy), ("t3", IntTy)] testConstr7 = assertUnificationFailure [Constraint t0 IntTy x x OrdNo, Constraint t0 FloatTy x x OrdNo] testConstr8 = assertSolution [Constraint t0 IntTy x x OrdNo, Constraint t0 t0 x x OrdNo] [("t0", IntTy)] testConstr9 = assertSolution [Constraint t0 IntTy x x OrdNo, Constraint t0 t1 x x OrdNo] [("t0", IntTy), ("t1", IntTy)] testConstr10 = assertSolution [Constraint (PointerTy (VarTy "a")) (PointerTy (VarTy "b")) x x OrdNo] [("a", (VarTy "a")), ("b", (VarTy "a"))] testConstr11 = assertSolution [Constraint (PointerTy (VarTy "a")) (PointerTy (StructTy "Monkey" [])) x x OrdNo] [("a", (StructTy "Monkey" []))] testConstr12 = assertSolution [Constraint t1 (PointerTy (StructTy "Array" [IntTy])) x x OrdNo ,Constraint t1 (PointerTy t2) x x OrdNo] [("t1", (PointerTy (StructTy "Array" [IntTy]))) ,("t2", (StructTy "Array" [IntTy]))] testConstr13 = assertSolution [Constraint t1 CharTy x x OrdNo ,Constraint t1 CharTy x x OrdNo] [("t1", CharTy)] -- -- Should collapse type variables into minimal set: -- testConstr10 = assertSolution -- [Constraint t0 t1 x x, Constraint t1 t2 x x, Constraint t2 t3 x x OrdNo] -- [("t0", VarTy "t0"), ("t1", VarTy "t0"), ("t2", VarTy "t0")] -- m7 = solve ([Constraint t1 t2 x x, Constraint t0 t1 x x OrdNo]) -- Struct types testConstr20 = assertSolution [Constraint t0 (StructTy "Vector" [t1]) x x OrdNo ,Constraint t0 (StructTy "Vector" [IntTy]) x x OrdNo] [("t0", (StructTy "Vector" [IntTy])), ("t1", IntTy)] testConstr21 = assertSolution [Constraint t1 (StructTy "Array" [t2]) x x OrdNo ,Constraint t1 (StructTy "Array" [t3]) x x OrdNo ,Constraint t3 BoolTy x x OrdNo] [("t1", (StructTy "Array" [BoolTy])) ,("t2", BoolTy) ,("t3", BoolTy)] testConstr22 = assertSolution [Constraint t1 (StructTy "Array" [t2]) x x OrdNo ,Constraint t2 (StructTy "Array" [t3]) x x OrdNo ,Constraint t3 FloatTy x x OrdNo] [("t1", (StructTy "Array" [(StructTy "Array" [FloatTy])])) ,("t2", (StructTy "Array" [FloatTy])) ,("t3", FloatTy)] testConstr23 = assertUnificationFailure [Constraint (StructTy "Array" [t1]) (StructTy "Array" [t2]) x x OrdNo ,Constraint t1 IntTy x x OrdNo ,Constraint t2 FloatTy x x OrdNo] testConstr24 = assertUnificationFailure [Constraint t2 FloatTy x x OrdNo ,Constraint t1 IntTy x x OrdNo ,Constraint (StructTy "Array" [t1]) (StructTy "Array" [t2]) x x OrdNo] -- m9 = solve [Constraint (StructTy "Vector" [IntTy]) (StructTy "Vector" [t1]) x x OrdNo] -- m10 = solve [Constraint (StructTy "Vector" [t1]) (StructTy "Vector" [t2]) x x OrdNo] -- Func types testConstr30 = assertSolution [Constraint t2 (FuncTy [t0] t1) x x OrdNo ,Constraint t2 (FuncTy [IntTy] BoolTy) x x OrdNo] [("t0", IntTy), ("t1", BoolTy), ("t2", (FuncTy [IntTy] BoolTy))] testConstr31 = assertSolution [Constraint (FuncTy [t0] t1) (FuncTy [IntTy] BoolTy) x x OrdNo] [("t0", IntTy), ("t1", BoolTy)] testConstr32 = assertSolution [Constraint t0 (FuncTy [IntTy] BoolTy) x x OrdNo] [("t0", (FuncTy [IntTy] BoolTy))] testConstr33 = assertSolution [Constraint t1 (FuncTy [t2] IntTy) x x OrdNo ,Constraint t1 (FuncTy [t3] IntTy) x x OrdNo ,Constraint t3 BoolTy x x OrdNo] [("t1", (FuncTy [BoolTy] IntTy)) ,("t2", BoolTy) ,("t3", BoolTy)] testConstr34 = assertSolution [Constraint (VarTy "a") (StructTy "Pair" [(VarTy "x0"), (VarTy "y0")]) x x OrdNo ,Constraint (StructTy "Array" [(VarTy "a")]) (StructTy "Array" [(StructTy "Pair" [(VarTy "x1"), (VarTy "y1")])]) x x OrdNo] [("a", (StructTy "Pair" [(VarTy "x0"), (VarTy "y0")])) ,("x0", (VarTy "x0")) ,("y0", (VarTy "y0")) ,("x1", (VarTy "x0")) ,("y1", (VarTy "y0")) ] -- Same as testConstr34, except everything is wrapped in refs testConstr35 = assertSolution [Constraint (RefTy (VarTy "a")) (RefTy (StructTy "Pair" [(VarTy "x0"), (VarTy "y0")])) x x OrdNo ,Constraint (RefTy (StructTy "Array" [(VarTy "a")])) (RefTy (StructTy "Array" [(StructTy "Pair" [(VarTy "x1"), (VarTy "y1")])])) x x OrdNo] [("a", (StructTy "Pair" [(VarTy "x0"), (VarTy "y0")])) ,("x0", (VarTy "x0")) ,("y0", (VarTy "y0")) ,("x1", (VarTy "x0")) ,("y1", (VarTy "y0")) ]
eriksvedang/Carp
test/Spec.hs
mpl-2.0
6,485
4
16
1,193
2,490
1,350
1,140
134
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Blogger.Blogs.GetByURL -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Retrieve a Blog by URL. -- -- /See:/ <https://developers.google.com/blogger/docs/3.0/getting_started Blogger API Reference> for @blogger.blogs.getByUrl@. module Network.Google.Resource.Blogger.Blogs.GetByURL ( -- * REST Resource BlogsGetByURLResource -- * Creating a Request , blogsGetByURL , BlogsGetByURL -- * Request Lenses , bgbuURL , bgbuView ) where import Network.Google.Blogger.Types import Network.Google.Prelude -- | A resource alias for @blogger.blogs.getByUrl@ method which the -- 'BlogsGetByURL' request conforms to. type BlogsGetByURLResource = "blogger" :> "v3" :> "blogs" :> "byurl" :> QueryParam "url" Text :> QueryParam "view" BlogsGetByURLView :> QueryParam "alt" AltJSON :> Get '[JSON] Blog -- | Retrieve a Blog by URL. -- -- /See:/ 'blogsGetByURL' smart constructor. data BlogsGetByURL = BlogsGetByURL' { _bgbuURL :: !Text , _bgbuView :: !(Maybe BlogsGetByURLView) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'BlogsGetByURL' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'bgbuURL' -- -- * 'bgbuView' blogsGetByURL :: Text -- ^ 'bgbuURL' -> BlogsGetByURL blogsGetByURL pBgbuURL_ = BlogsGetByURL' { _bgbuURL = pBgbuURL_ , _bgbuView = Nothing } -- | The URL of the blog to retrieve. bgbuURL :: Lens' BlogsGetByURL Text bgbuURL = lens _bgbuURL (\ s a -> s{_bgbuURL = a}) -- | Access level with which to view the blog. Note that some fields require -- elevated access. bgbuView :: Lens' BlogsGetByURL (Maybe BlogsGetByURLView) bgbuView = lens _bgbuView (\ s a -> s{_bgbuView = a}) instance GoogleRequest BlogsGetByURL where type Rs BlogsGetByURL = Blog type Scopes BlogsGetByURL = '["https://www.googleapis.com/auth/blogger", "https://www.googleapis.com/auth/blogger.readonly"] requestClient BlogsGetByURL'{..} = go (Just _bgbuURL) _bgbuView (Just AltJSON) bloggerService where go = buildClient (Proxy :: Proxy BlogsGetByURLResource) mempty
rueshyna/gogol
gogol-blogger/gen/Network/Google/Resource/Blogger/Blogs/GetByURL.hs
mpl-2.0
3,049
0
14
721
396
237
159
59
1
{-# LANGUAGE ScopedTypeVariables #-} {- Copyright 2017 The CodeWorld Authors. All rights reserved. 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 http://www.apache.org/licenses/LICENSE-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. -} -- this separate module was required because of cyclic dependency between CommentUtil and CollaborationUtil module CommentFolder where import Control.Monad import Data.Aeson import Data.ByteString (ByteString) import qualified Data.ByteString as B import qualified Data.ByteString.Char8 as BC import qualified Data.ByteString.Lazy as LB import Data.List import Data.Maybe (fromJust) import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Encoding as T import System.Directory import System.FilePath import CollaborationUtil import DataUtil import Model cleanCommentPaths :: BuildMode -> Text -> FilePath -> IO () cleanCommentPaths mode userId' file = do fileBool <- doesFileExist file case fileBool of True -> removeProjectIfExists mode userId' file False -> return () deleteFolderWithComments :: BuildMode -> Text -> FilePath -> IO (Either String ()) deleteFolderWithComments mode userId' finalDir = do let dir' = userProjectDir mode userId' </> finalDir dirBool <- doesDirectoryExist dir' case dirBool of True -> do case finalDir == "commentables" of True -> return $ Left "`commentables` Directory Cannot Be Deleted" False -> do allFilePaths <- getFilesRecursive dir' case length (splitDirectories finalDir) of x | x == 0 -> return $ Left "Root Directory Cannot Be Deleted" | (x /= 0) && ((splitDirectories finalDir) !! 0 == "commentables") -> do mapM_ (removeUserFromComments userId') allFilePaths removeDirectoryIfExists dir' cleanBaseDirectory dir' return $ Right () | otherwise -> do mapM_ (cleanCommentPaths mode userId') allFilePaths removeDirectoryIfExists dir' cleanBaseDirectory dir' return $ Right () False -> return $ Left "Directory Does Not Exists" removeUserFromComments :: Text -> FilePath -> IO () removeUserFromComments userId' userPath = do fileBool <- doesFileExist userPath case fileBool of True -> do commentHashFile <- BC.unpack <$> B.readFile userPath commentFolder <- BC.unpack <$> B.readFile commentHashFile Just (currentUsers :: [UserDump]) <- decodeStrict <$> B.readFile (commentHashFile <.> "users") let currentUserIds = map uuserId currentUsers currentUser = currentUsers !! (fromJust $ userId' `elemIndex` currentUserIds) removeFileIfExists $ commentFolder <.> "users" </> T.unpack (uuserIdent currentUser) B.writeFile (commentHashFile <.> "users") $ LB.toStrict $ encode (delete currentUser currentUsers) removeFileIfExists userPath removeFileIfExists $ userPath <.> "info" cleanBaseDirectory userPath False -> return () copyFileFromCommentables :: BuildMode -> Text -> Text -> FilePath -> FilePath -> ByteString -> Value -> IO () copyFileFromCommentables mode userId' userIdent' fromFile toFile name emptyPH = do cleanCommentPaths mode userId' toFile createDirectoryIfMissing False $ takeDirectory toFile commentHashFile <- BC.unpack <$> B.readFile fromFile commentFolder <- BC.unpack <$> B.readFile commentHashFile Just (project :: Project) <- decodeStrict <$> B.readFile (take (length commentFolder - 9) commentFolder) _ <- newCollaboratedProject mode userId' userIdent' name toFile $ Project (projectSource project) emptyPH return () copyFolderFromCommentables :: BuildMode -> Text -> Text -> FilePath -> FilePath -> Text -> Value -> IO () copyFolderFromCommentables mode userId' userIdent' fromDir toDir name emptyPH = do createNewFolder mode userId' toDir $ T.unpack name dirList <- listDirectoryWithPrefix fromDir dirFiles <- dirFilter dirList 'S' forM_ dirFiles $ \ f -> do let file = takeFileName f case isSuffixOf ".info" file of True -> return () False -> do let toFile = toDir </> take 3 file </> file fileName <- B.readFile (f <.> "info") copyFileFromCommentables mode userId' userIdent' f toFile fileName emptyPH dirDirs <- dirFilter dirList 'D' forM_ dirDirs $ \d -> do dirName <- T.decodeUtf8 <$> B.readFile (d </> "dir.info") let newToDir = toDir </> (dirBase . nameToDirId $ dirName) copyFolderFromCommentables mode userId' userIdent' d newToDir dirName emptyPH copyFileFromSelf :: BuildMode -> Text -> Text -> FilePath -> FilePath -> ByteString -> IO () copyFileFromSelf mode userId' userIdent' fromFile toFile name = do cleanCommentPaths mode userId' toFile createDirectoryIfMissing False $ takeDirectory toFile collabPath <- BC.unpack <$> B.readFile fromFile Just (project :: Project) <- decodeStrict <$> B.readFile collabPath _ <- newCollaboratedProject mode userId' userIdent' name toFile project return () copyFolderFromSelf :: BuildMode -> Text -> Text -> FilePath -> FilePath -> Text -> IO () copyFolderFromSelf mode userId' userIdent' fromDir toDir name = do createNewFolder mode userId' toDir $ T.unpack name dirList <- listDirectoryWithPrefix fromDir dirFiles <- dirFilter dirList 'S' forM_ dirFiles $ \f -> do let file = takeFileName f fileBool <- doesFileExist f case (fileBool, isSuffixOf ".cw" file) of (True, True) -> do let toFile = toDir </> take 3 file </> file name' <- B.readFile $ f <.> "info" copyFileFromSelf mode userId' userIdent' f toFile name' (_, _) -> return () dirDirs <- dirFilter dirList 'D' forM_ dirDirs $ \d -> do dirName <- T.decodeUtf8 <$> B.readFile (d </> "dir.info") let newToDir = toDir </> (dirBase . nameToDirId $ dirName) copyFolderFromSelf mode userId' userIdent' d newToDir dirName moveFileFromCommentables :: Text -> FilePath -> FilePath -> Text -> IO () moveFileFromCommentables userId' fromFile toFile name = do removeUserFromComments userId' toFile createDirectoryIfMissing False $ takeDirectory toFile mapM_ (\x -> renameFile (fromFile <.> x) (toFile <.> x)) ["", "info"] cleanBaseDirectory fromFile correctUserPathInComments userId' toFile B.writeFile (toFile <.> "info") $ T.encodeUtf8 name moveFolderFromCommentables :: BuildMode -> Text -> FilePath -> FilePath -> Text -> IO () moveFolderFromCommentables mode userId' fromDir toDir name = do createNewFolder mode userId' toDir $ T.unpack name dirList <- listDirectoryWithPrefix fromDir dirFiles <- dirFilter dirList 'S' forM_ dirFiles $ \f -> do let file = takeFileName f case isSuffixOf ".info" file of True -> return () False -> do let toFile = toDir </> take 3 file </> file fileName <- T.decodeUtf8 <$> B.readFile (f <.> "info") moveFileFromCommentables userId' f toFile fileName dirDirs <- dirFilter dirList 'D' forM_ dirDirs $ \ d -> do dirName <- T.decodeUtf8 <$> B.readFile (d </> "dir.info") let newToDir = toDir </> (dirBase . nameToDirId $ dirName) moveFolderFromCommentables mode userId' d newToDir dirName removeDirectoryIfExists fromDir cleanBaseDirectory fromDir moveFileFromSelf :: BuildMode -> Text -> FilePath -> FilePath -> Text -> IO () moveFileFromSelf mode userId' fromFile toFile name = do cleanCommentPaths mode userId' toFile createDirectoryIfMissing False $ takeDirectory toFile mapM_ (\x -> renameFile (fromFile <.> x) (toFile <.> x)) ["", "info"] cleanBaseDirectory fromFile B.writeFile (toFile <.> "info") $ T.encodeUtf8 name modifyCollabPathIfReq mode userId' fromFile toFile moveFolderFromSelf :: BuildMode -> Text -> FilePath -> FilePath -> Text -> IO () moveFolderFromSelf mode userId' fromDir toDir name = do createNewFolder mode userId' toDir $ T.unpack name dirList <- listDirectoryWithPrefix fromDir dirFiles <- dirFilter dirList 'S' forM_ dirFiles $ \ f -> do let file = takeFileName f fileBool <- doesFileExist f case (fileBool, isSuffixOf ".cw" file) of (True, True) -> do let toFile = toDir </> take 3 file </> file name' <- T.decodeUtf8 <$> B.readFile (f <.> "info") moveFileFromSelf mode userId' f toFile name' (_, _) -> return () dirDirs <- dirFilter dirList 'D' forM_ dirDirs $ \d -> do dirName <- T.decodeUtf8 <$> B.readFile (d </> "dir.info") let newToDir = toDir </> (dirBase . nameToDirId $ dirName) moveFolderFromSelf mode userId' d newToDir dirName removeDirectoryIfExists fromDir cleanBaseDirectory fromDir correctUserPathInComments :: Text -> FilePath -> IO () correctUserPathInComments userId' userPath = do fileBool <- doesFileExist userPath case fileBool of True -> do commentHashFile <- BC.unpack <$> B.readFile userPath Just (currentUsers :: [UserDump]) <- decodeStrict <$> B.readFile (commentHashFile <.> "users") let newUsr usr = usr { upath = T.pack userPath } newUsers = map (\usr -> if uuserId usr /= userId' then usr else newUsr usr) currentUsers B.writeFile (commentHashFile <.> "users") $ LB.toStrict . encode $ newUsers False -> return ()
parvmor/codeworld
codeworld-server/src/CommentFolder.hs
apache-2.0
10,516
0
28
2,861
2,860
1,352
1,508
192
3
module Walk.A293689Spec (main, spec) where import Test.Hspec import Walk.A293689 (a293689) main :: IO () main = hspec spec spec :: Spec spec = describe "A293689" $ it "correctly computes the first 20 elements" $ take 20 (map a293689 [0..]) `shouldBe` expectedValue where expectedValue = [0,1,2,1,2,3,4,3,4,5,6,5,4,3,2,3,4,5,6,5]
peterokagey/haskellOEIS
test/Walk/A293689Spec.hs
apache-2.0
343
0
10
59
160
95
65
10
1
{-# LANGUAGE CPP #-} module FFT where import Foreign.CUDA.FFT import CUDAEx import ArgMapper data Mode = Forward | Reverse | Inverse fft2dComplexDSqInplace :: Maybe Stream -> Mode -> Int -> CxDoubleDevPtr -> IO () fft2dComplexDSqInplace mbstream mode size inoutp = do handle <- plan2D size size Z2Z case mbstream of Just str -> setStream handle str _ -> return () execZ2Z handle (castDevPtr inoutp) (castDevPtr inoutp) (signOfMode mode) destroy handle where signOfMode Forward = -1 signOfMode Reverse = 1 signOfMode Inverse = 1 #define __k(n) foreign import ccall unsafe "&" n :: Fun __k(ifftshift_kernel) __k(fftshift_kernel) fft2dComplexDSqInplaceCentered :: Maybe Stream -> Mode -> Int -> CxDoubleDevPtr -> IO () fft2dComplexDSqInplaceCentered mbstream mode size inoutp = do mkshift ifftshift_kernel fft2dComplexDSqInplace mbstream mode size inoutp mkshift fftshift_kernel where threads_per_dim = min size 16 blocks_per_dim0 = (size + threads_per_dim - 1) `div` threads_per_dim blocks_per_dim1 = (size - 1) `div` (threads_per_dim * 2) + 1 mkshift sfun = launchKernel sfun (blocks_per_dim0, blocks_per_dim1, 1) (threads_per_dim, threads_per_dim, 1) 0 mbstream $ mapArgs inoutp size fftGridPolarization :: CxDoubleDevPtr -> IO () fftGridPolarization polp = fft2dComplexDSqInplaceCentered Nothing Forward gridsize polp where gridsize = 4096
SKA-ScienceDataProcessor/RC
MS3/Sketches/FFT/FFT.hs
apache-2.0
1,450
0
11
294
416
210
206
-1
-1
{- Copyright 2015 Tristan Aubrey-Jones 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 http://www.apache.org/licenses/LICENSE-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. -} {-| Copyright : (c) Tristan Aubrey-Jones, 2015 License : Apache-2 Maintainer : [email protected] Stability : experimental For more information please see <http://www.flocc.net/> -} module Compiler.Back.GraphBuilder where import Compiler.Front.Common (lookupIntOrError, initIdxSet, updateListItem, vids, eids, imapUnionCheckDisjoint, debug, ShowP(..)) import Compiler.Front.Indices (Idx, IdxSet, newidST, IdxMonad) import Compiler.Front.ExprTree (Expr(..), IdxTree(..), Val(..), getExprId, getIdxTreeId, getIdxTreeVars) --import Compiler.Types.TermLanguage (Term(Term), Scheme(Scheme), FunctionToken(TupTok)) --import Compiler.Types.TypeAssignment (TyTerm, TyScheme, showTyScheme) import Compiler.Back.Graph hiding (Tree(Tup){-, TyScheme, Ty-}) import qualified Compiler.Back.Graph as B import Data.List (sort) import qualified Data.IntMap.Strict as IM import qualified Data.IntSet as IS import qualified Data.Map.Strict as DM import Data.Functor.Identity (runIdentity) import Control.Monad.State.Strict ( StateT, get, gets, modify, runStateT, evalStateT, execStateT, mapM, lift ) import Debug.Trace (trace) -- TODO translate types? -- Graph helpers emptyGraphVars = DM.empty emptyGraph :: Graph emptyGraph = Graph { graphNodes=IM.empty, graphIn=(-1), graphOut=(-1), graphVars=emptyGraphVars } modifyNodes :: (NodeEnv Node -> NodeEnv Node) -> Graph -> Graph modifyNodes f graph = graph { graphNodes=f $ graphNodes graph} nd :: NodeId -> [NodeId] -> [NodeId] -> NodeTy -> Node nd nid ins outs ty = Node {nodeId=nid, nodeIn=ins, nodeOut=outs, nodeTy=ty} addNodeOut :: Node -> NodeId -> Node addNodeOut node outid = node { nodeOut=(nodeOut node)++[outid] } -- ======== DFG Creation from ExprTrees ============== -- TODO change graph to graph stack! -- need var ids above current.... -- can we pass a var env to graphFromExpr data GBuildSt = GBuildSt { stVarToNodeMap :: NodeEnv Idx, stExpToNodeMap :: NodeEnv Idx, stCurGraph :: Graph, stVarNames :: DM.Map String Idx } deriving (Show) initGBuildSt = GBuildSt { stVarToNodeMap=IM.empty, stExpToNodeMap=IM.empty, stCurGraph=emptyGraph, stVarNames=DM.empty } type GraphBuilder m = StateT GBuildSt (StateT (NodeEnv Ty) (StateT IdxSet m)) modifyGraph :: Monad m => (Graph -> Graph) -> GraphBuilder m () modifyGraph f = modify (\st -> st { stCurGraph=f (stCurGraph st) }) -- |addExpToNodeMapping adds a mapping between the expression id and the node id -- |that supercedes it. addExpToNodeMapping :: Monad m => Idx -> Idx -> (GraphBuilder m) () addExpToNodeMapping exprId nodeId = modify (\st -> st { stExpToNodeMap=IM.insert exprId nodeId (stExpToNodeMap st) }) -- |addNode takes a node id and a list of input node ids, along with node and edge -- |information, within a state monad containing a map of var ids to node ids, and -- |the DFG, and adds this node to the DFG. addNode :: Monad m => Node -> (GraphBuilder m) () addNode node = do -- add nodeId to the output list of all of its inputs modifyGraph $ modifyNodes (\nodes -> foldl (\g -> \inId -> IM.adjust (\inputNode -> addNodeOut inputNode (nodeId $ node)) inId g) nodes $ nodeIn node) -- add node to the graph modifyGraph $ modifyNodes (\nodes -> IM.insert (nodeId node) node nodes) -- add mapping from expr id to node id let nodeid = nodeId node addExpToNodeMapping nodeid nodeid return () -- |addVarBinding takes a var id and an node id, and records a binding between -- |the two in the state. addVarBinding :: Monad m => Idx -> String -> Idx -> (GraphBuilder m) () addVarBinding varId varName nodeId = modify (\st -> st { stVarToNodeMap=IM.insert varId nodeId (stVarToNodeMap st), stVarNames=DM.insert varName nodeId (stVarNames st) }) -- |makeTupleAccessorNodes takes an idx tree and input node id -- |and creates tuple accessor nodes for all nodes in the tree. makeTupleAccessorNodes :: Monad m => Idx -> IdxTree -> (GraphBuilder m) () makeTupleAccessorNodes inId it = case it of (IdxNub _) -> return () (IdxLeaf _ vid _) -> modify (\st -> st { stVarToNodeMap=IM.insert vid inId (stVarToNodeMap st) }) (IdxTup _ l) -> do -- make accessor nodes nodeIds <- mapM (\_ -> lift $ lift $ newidST eids) l mapM (\(i, id) -> do addNode $ nd id [inId] [] (TupAccNd i)) $ zip [0..] nodeIds -- add type for each node tyEnv <- lift $ get let (B.Tup inTys) = lookupIntOrError "DFG:makeTupleAccessorNodes: get input expression type." inId tyEnv mapM (\(nid, ty) -> lift $ modify (\env -> IM.insert nid ty env)) $ zip nodeIds inTys -- call recursively for each accessor node mapM (\(id, subIt) -> makeTupleAccessorNodes id subIt) $ zip nodeIds l return () -- |addVarBindings takes an idx tree and an expression and adds the maps -- |between var ids and expression ids to the bindings. addVarBindings :: Monad m => IdxTree -> Expr -> (GraphBuilder m) () addVarBindings it expr = case (it, expr) of -- ignore nub (IdxNub _, _) -> return () -- leaf (IdxLeaf eid vid vname, e) -> do modify (\st -> let nid = (lookupIntOrError "DFG:addVarBindings:1:expr id not found in exprid->nodeid map." (getExprId e) (stExpToNodeMap st)) in st { stVarToNodeMap=IM.insert vid nid (stVarToNodeMap st), stVarNames=DM.insert vname nid (stVarNames st), stExpToNodeMap=IM.insert eid nid (stExpToNodeMap st) } ) -- conformable tuples (IdxTup _ l, Tup _ l') | length l == length l' -> do mapM (\(i,e) -> addVarBindings i e) $ zip l l' return () -- non-conformable tuples -- (add accessor nodes to graph, and return them...) (IdxTup _ l, e) -> do expIdsToNodeIds <- gets stExpToNodeMap makeTupleAccessorNodes (lookupIntOrError "DFG:addVarBindings:2:expr id not found in exprid->nodeid map." (getExprId e) expIdsToNodeIds) it -- |addIdxTreeBindings adds new VarNodes to the current graph -- |for all of the ids in the IdxTree {-addIdxTreeBindings :: Monad m => IdxTree -> (GraphBuilder m) () addIdxTreeBindings it = case it of (IdxLeaf eid vid name) -> do addNode $ nd eid [] [] (VarNd name) -- TODO add vid to VarNds addVarBinding vid eid -- I think we can omit the following, since the graphIn nodes don't seem to be used in building the DFG -- so instead we explicitly set the graphIn node id to the expr id of the root idx pattern in the -- Fun case of exprToGraph: -- -------------------- --modify (\(m,g,b) -> (m, g { graphIn=if (graphIn g) /= (-1) then error $ "GraphBuilder:addIdxTreeBindings: multiple idx leaves being set as graph input!" else eid }, b)) --modify (\(m,g,b) -> (m, g { graphIn=eid:(graphIn g) }, b)) (IdxTup _ l) -> do mapM addIdxTreeBindings l; return () other -> return ()-} -- |addIdxTreeBindingsR tupleOffset nodeId indexTree. Creates tuple accessor nodes -- |for the sub tree it, using nodeid as an input. addIdxTreeBindingsR :: Monad m => Int -> Idx -> IdxTree -> (GraphBuilder m) () addIdxTreeBindingsR tupIdx nodeid it = case it of -- add tuple accessor nodes (IdxTup eid l) -> do addNode $ nd eid [nodeid] [] (TupAccNd tupIdx) mapM (\(tupIdx', it') -> addIdxTreeBindingsR tupIdx' eid it') $ zip [0..] l return () -- add leaf node (IdxLeaf eid vid name) -> do addNode $ nd eid [nodeid] [] (TupAccNd tupIdx) addVarBinding vid name eid return () (IdxNub _) -> return () -- |addIdxTreeBindings idxTree. Creates nodes for the idx tree pattern. addIdxTreeBindings :: Monad m => IdxTree -> (GraphBuilder m) Idx addIdxTreeBindings it = do let eid = getIdxTreeId it addNode $ nd eid [] [] (VarNd "in") case it of (IdxTup _ l) -> do mapM (\(tupIdx', it') -> addIdxTreeBindingsR tupIdx' eid it') $ zip [0..] l return () (IdxLeaf _ vid name) -> do addVarBinding vid name eid ; return () _ -> return () return eid -- |addVarNode takes a var id and a node, and adds the node to the graph -- |and adds its id to the output list of the expression that its bound to. addVarNode :: Monad m => Idx -> Node -> (GraphBuilder m) Idx addVarNode varId node = do -- get input node id from state varMap <- gets stVarToNodeMap graphs <- gets stCurGraph expMap <- gets stExpToNodeMap varNames <- gets stVarNames case IM.lookup varId varMap of -- if we can resolve to an input expression, just return its expression id Just inNodeId -> do return inNodeId -- OLD: adds var node too --addNode $ addNodeInput node inNodeID -- if can't resolve to input expression, return this var node (as extern var) Nothing -> do --let name = getVarNodeName node --if name == "x0" --then error $ "GraphBuilder:addVarNode: couldn't resolve " ++ name ++ " " ++ (show varId) ++ " to a node in:\n" ++ (showP varMap) ++ "\n" ++ (show varNames) ++ "\n" --else do addNode node return $ nodeId node --nodeId [] (ExternVarNode varId) nullVal --error $ "addVarNode: no node bound to var " ++ (show varId) -- |getDFG inputs takes a DFG and returns all the node id's that occur as inputs -- |that are not defined in the graph. getGraphInputs :: Graph -> IS.IntSet getGraphInputs graph = inputIDs IS.\\ nodeIDs where nodes = graphNodes graph inputIDs = IS.unions $ map (\(k, node) -> IS.fromList $ nodeIn node) $ IM.toList nodes nodeIDs = IM.keysSet nodes getEdgeType :: NodeEnv Ty -> Idx -> Ty getEdgeType env exprId = case IM.lookup exprId env of Just ty -> ty Nothing -> error $ "getEdgeType: expression " ++ (show exprId) ++ " is not in the type environment." toScalVal :: Val -> ScalVal toScalVal v = case v of (S s) -> StrVal s (I i) -> IntVal i (B b) -> BolVal b (F f) -> FltVal f (NullVal) -> NulVal other -> error $ "GraphBuilder:toScalVal: error can't translate Val " ++ (show v) ++ " to ScalVal." -- |exprToDFG takes an expression and creates a DFG in the state transformer, -- |returning the node id of the expression. exprToGraph :: Monad m => NodeEnv Ty -> Expr -> (GraphBuilder m) Idx exprToGraph env expr = do st0 <- get case {-trace ((showP expr) ++ "\n\n" ++ (show st0)) $-} expr of (Lit i v) -> do addNode $ nd i [] [] (LitNd $ toScalVal v) return i (Var i vid name) -> do varNodeID <- addVarNode vid $ nd i [] [] (VarNd name) -- newDFGNode i [] (VarNode vid name) [] addExpToNodeMapping i varNodeID return varNodeID (Tup i l) -> do l' <- mapM recur l addNode $ nd i l' [] TupNd --newDFGNode i l' (TupNode) [] --(newEdge i) return i (Rel i l) -> do l' <- mapM recur l addNode $ error "GraphBuilder:exprToGraph:Rel case: not implemented." --newDFGNode i l' (RelNode) [] --(newEdge i) return i (App i fe ae) -> do fi <- recur fe ai <- recur ae addNode $ nd i [fi,ai] [] AppNd --newDFGNode i [fi, ai] (AppNode) [] --(newEdge i) return i (If i pe te ee) -> do -- TODO should be nested error $ "GraphBuilder:exprToGraph:If not implemented. Pre-process to convert to 'if' func apps." {--- visit predicate pi <- recur pe (m1, g1, b1) <- get -- visit 'then' subtree modify (\(m,g,b) -> (m, emptyGraph, b)) ti <- recur te (_, thenGraph, _) <- get let thenGraph' = Digraph { graphParent=graphParent thenGraph, graphName=graphName thenGraph, graphNodes=graphNodes thenGraph, graphInNodes=graphInNodes thenGraph, graphOutNode=ti } -- visit 'else' subtree modify (\(m,g,b) -> (m, emptyGraph, b)) ei <- recur ee (_, elseGraph, _) <- get let elseGraph' = Digraph { graphParent=graphParent elseGraph, graphName=graphName elseGraph, graphNodes=graphNodes elseGraph, graphInNodes=graphInNodes elseGraph, graphOutNode=ei } -- return to top level graph and add ifthenelse node modify (\(_,_,b) -> (m1, g1, b)) addNode $ newDFGNode i [pi] (IfNode) [thenGraph', elseGraph'] -- (newEdge i) return i-} (Let i it be ie) -> do recur be varEnv <- gets stVarToNodeMap varNames <- gets stVarNames addVarBindings it be inExpID <- recur ie --st <- get --if elem "y0" (map fst $ getIdxTreeVars it) then error $ "Let: " ++ (show st) ++ "\n\n" else return () modify (\st -> st { stVarToNodeMap=varEnv , stVarNames=varNames }) addExpToNodeMapping i inExpID return inExpID -- go straight from inExpression (can omit the let entirely) (Fun i it exp) -> do -- save current graph m1 <- gets stVarToNodeMap names0 <- gets stVarNames g1 <- gets stCurGraph b1 <- gets stExpToNodeMap -- create subgraph modify (\st -> st { stCurGraph=emptyGraph }) inNodeId <- addIdxTreeBindings it expI <- recur exp -- add output var node outEid <- lift $ lift $ newidST eids addNode $ nd outEid [expI] [] (VarNd "out") -- add in and out to current subgraph modify (\st -> st { stCurGraph=(stCurGraph st) { graphIn=inNodeId, graphOut=expI, graphVars=names0 } }) m2 <- gets stVarToNodeMap innerGraph <- gets stCurGraph b2 <- gets stExpToNodeMap let inputIDs = getGraphInputs innerGraph -- return to original graph modify (\st -> st { stVarToNodeMap=m1, stVarNames=names0, stCurGraph=g1 } ) addNode $ nd i (IS.toList inputIDs) [] (FunNd innerGraph) --newDFGNode i (Data.Set.toList inputIDs) (FunNode it) [innerGraph] --(newEdge i) let i' = {-trace ("exprToGraph:FunNd:created from:\nGraph:"++ (show innerGraph) ++ "\nExpr: " ++ (show expr) ++ "\n\n")-} i return i' where recur = exprToGraph env --newEdge = (\i -> ValEdge $ getEdgeType env i) -- |graphFromExpr takes an expression and returns the corresponding -- |data flow graph. graphFromExpr :: Monad m => NodeEnv Ty -> Expr -> IdxMonad m (Graph, NodeEnv Ty) graphFromExpr env expr = do -- build graph from expr --let tyEnv = IM.map (\(Scheme _ t) -> t) env ((outID, st1), tyEnv') <- runStateT (runStateT (exprToGraph env expr) initGBuildSt) env let (varMap, graph, eidsToNids, varNames) = (stVarToNodeMap st1, stCurGraph st1, stExpToNodeMap st1, stVarNames st1) let graph' = graph { graphOut=outID, graphVars=varNames {-imapUnionCheckDisjoint "GraphBuilder:graphFromExpr:adding varMap:" (graphVars graph) varMap-} } -- update node ids of all the graphs in tyEnv' let tyEnv'' = IM.map (mapGraphsInTy (replaceNodeIds eidsToNids)) tyEnv' return (graph', if debug then trace ("graphFromExpr: new types: \n" ++ (show tyEnv') ++ "\nupdated types: " ++ (show tyEnv'')) tyEnv'' else tyEnv'') -- ======================= mapNodeM :: Monad m => (Node -> m Node) -> Node -> m Node mapNodeM f n = do n' <- f n case nodeTy n' of (FunNd g) -> do g' <- mapGraphM f g return $ n' { nodeTy=(FunNd g') } _ -> return n' mapGraphM :: Monad m => (Node -> m Node) -> Graph -> m Graph mapGraphM f g = do let nodes = IM.elems $ graphNodes g nodes' <- mapM f nodes let nodes'' = IM.fromList $ map (\n -> (nodeId n, n)) nodes' return $ g { graphNodes=nodes'' } -- |encapFun node ty. Encapsulates n in a FunNd subgraph, and adds types of new -- |expressions to the state. encapFun :: Monad m => Node -> Ty -> StateT (NodeEnv Ty) (IdxMonad m) Node encapFun n ty = do let (VarNd vname) = nodeTy n -- create expression varVid <- lift $ newidST vids varEid <- lift $ newidST eids let varName = ("v" ++ (show varVid)) let varExpr = Var varEid varVid varName funVid <- lift $ newidST vids let funExpr = Var (nodeId n) funVid vname appEid <- lift $ newidST eids let appExpr = App appEid funExpr varExpr patEid <- lift $ newidST eids let patExpr = IdxLeaf patEid varVid varName lamEid <- lift $ newidST eids let lamExpr = Fun lamEid patExpr appExpr -- add new types for new exprs let (inTy :-> outTy) = ty types <- get let types' = IM.union types $ IM.fromList [ (varEid, inTy), (nodeId n, ty), (appEid, outTy), (patEid, inTy), (lamEid, ty) ] -- build graph for it (g, types'') <- lift $ graphFromExpr types' lamExpr -- create FunNd to contain graph nid <- lift $ newidST eids let n' = nd nid (nodeIn n) (nodeOut n) (FunNd g) modify (\_ -> IM.insert nid ty types'') return n' -- |encapFun n. If n is a var with a function type, then encapsulate it: replace it with a -- |a simple FunNd with a subgraph that calls it. encapFuns :: Monad m => Node -> StateT (NodeEnv Ty) (IdxMonad m) Node encapFuns n = case nodeTy n of -- a var node -- TODO NEED TO ADD CHECK TO SEE IF THIS IS BEING IMMEDIATELY APPLIED. -- IF IT IS A CHILD OF AN APPNODE, THEN ITS A COMBINATOR RATHER THAN A -- FUNCTION PARAMTER AND SHOULD NOT BE ENCAPSULATED. (VarNd vname) -> do -- get var type let nid = nodeId n ty <- gets (lookupIntOrError ("GraphBuilder:encapFun: missing type for node " ++ (show n)) nid) case isFunTree ty of -- var is a function True -> encapFun n ty -- is not a function False -> return n -- any other node other -> return n --postProcessGraph :: Monad m => Graph -> IdxMonad m Graph --postProcessGraph g = mapGraphM () g
flocc-net/flocc
v0.1/Compiler/Back/GraphBuilder.hs
apache-2.0
17,938
0
21
4,106
4,422
2,251
2,171
245
8
{-# LANGUAGE Trustworthy #-} {-| Copyright : (C) 2013-2015, University of Twente License : BSD2 (see the file LICENSE) Maintainer : Christiaan Baaij <[email protected]> -} module CLaSH.Sized.Signed ( Signed ) where import CLaSH.Sized.Internal.Signed
Ericson2314/clash-prelude
src/CLaSH/Sized/Signed.hs
bsd-2-clause
271
0
4
45
21
15
6
4
0
-- | -- Module : Text.Megaparsec.Expr -- Copyright : © 2015–2017 Megaparsec contributors -- © 2007 Paolo Martini -- © 1999–2001 Daan Leijen -- License : FreeBSD -- -- Maintainer : Mark Karpov <[email protected]> -- Stability : experimental -- Portability : non-portable -- -- A helper module to parse expressions. It can build a parser given a table -- of operators. module Text.Megaparsec.Expr ( Operator (..) , makeExprParser ) where import Text.Megaparsec -- | This data type specifies operators that work on values of type @a@. An -- operator is either binary infix or unary prefix or postfix. A binary -- operator has also an associated associativity. data Operator m a = InfixN (m (a -> a -> a)) -- ^ Non-associative infix | InfixL (m (a -> a -> a)) -- ^ Left-associative infix | InfixR (m (a -> a -> a)) -- ^ Right-associative infix | Prefix (m (a -> a)) -- ^ Prefix | Postfix (m (a -> a)) -- ^ Postfix -- | @'makeExprParser' term table@ builds an expression parser for terms -- @term@ with operators from @table@, taking the associativity and -- precedence specified in the @table@ into account. -- -- @table@ is a list of @[Operator m a]@ lists. The list is ordered in -- descending precedence. All operators in one list have the same precedence -- (but may have different associativity). -- -- Prefix and postfix operators of the same precedence associate to the left -- (i.e. if @++@ is postfix increment, than @-2++@ equals @-1@, not @-3@). -- -- Unary operators of the same precedence can only occur once (i.e. @--2@ is -- not allowed if @-@ is prefix negate). If you need to parse several prefix -- or postfix operators in a row, (like C pointers—@**i@) you can use this -- approach: -- -- > manyUnaryOp = foldr1 (.) <$> some singleUnaryOp -- -- This is not done by default because in some cases allowing repeating -- prefix or postfix operators is not desirable. -- -- If you want to have an operator that is a prefix of another operator in -- the table, use the following (or similar) wrapper instead of plain -- 'Text.Megaparsec.Char.Lexer.symbol': -- -- > op n = (lexeme . try) (string n <* notFollowedBy punctuationChar) -- -- 'makeExprParser' takes care of all the complexity involved in building an -- expression parser. Here is an example of an expression parser that -- handles prefix signs, postfix increment and basic arithmetic: -- -- > expr = makeExprParser term table <?> "expression" -- > -- > term = parens expr <|> integer <?> "term" -- > -- > table = [ [ prefix "-" negate -- > , prefix "+" id ] -- > , [ postfix "++" (+1) ] -- > , [ binary "*" (*) -- > , binary "/" div ] -- > , [ binary "+" (+) -- > , binary "-" (-) ] ] -- > -- > binary name f = InfixL (f <$ symbol name) -- > prefix name f = Prefix (f <$ symbol name) -- > postfix name f = Postfix (f <$ symbol name) makeExprParser :: MonadParsec e s m => m a -- ^ Term parser -> [[Operator m a]] -- ^ Operator table, see 'Operator' -> m a -- ^ Resulting expression parser makeExprParser = foldl addPrecLevel {-# INLINEABLE makeExprParser #-} -- | @addPrecLevel p ops@ adds the ability to parse operators in table @ops@ -- to parser @p@. addPrecLevel :: MonadParsec e s m => m a -> [Operator m a] -> m a addPrecLevel term ops = term' >>= \x -> choice [ras' x, las' x, nas' x, return x] <?> "operator" where (ras, las, nas, prefix, postfix) = foldr splitOp ([],[],[],[],[]) ops term' = pTerm (choice prefix) term (choice postfix) ras' = pInfixR (choice ras) term' las' = pInfixL (choice las) term' nas' = pInfixN (choice nas) term' -- | @pTerm prefix term postfix@ parses a @term@ surrounded by optional -- prefix and postfix unary operators. Parsers @prefix@ and @postfix@ are -- allowed to fail, in this case 'id' is used. pTerm :: MonadParsec e s m => m (a -> a) -> m a -> m (a -> a) -> m a pTerm prefix term postfix = do pre <- option id (hidden prefix) x <- term post <- option id (hidden postfix) return . post . pre $ x -- | @pInfixN op p x@ parses non-associative infix operator @op@, then term -- with parser @p@, then returns result of the operator application on @x@ -- and the term. pInfixN :: MonadParsec e s m => m (a -> a -> a) -> m a -> a -> m a pInfixN op p x = do f <- op y <- p return $ f x y -- | @pInfixL op p x@ parses left-associative infix operator @op@, then term -- with parser @p@, then returns result of the operator application on @x@ -- and the term. pInfixL :: MonadParsec e s m => m (a -> a -> a) -> m a -> a -> m a pInfixL op p x = do f <- op y <- p let r = f x y pInfixL op p r <|> return r -- | @pInfixR op p x@ parses right-associative infix operator @op@, then -- term with parser @p@, then returns result of the operator application on -- @x@ and the term. pInfixR :: MonadParsec e s m => m (a -> a -> a) -> m a -> a -> m a pInfixR op p x = do f <- op y <- p >>= \r -> pInfixR op p r <|> return r return $ f x y type Batch m a = ( [m (a -> a -> a)] , [m (a -> a -> a)] , [m (a -> a -> a)] , [m (a -> a)] , [m (a -> a)] ) -- | A helper to separate various operators (binary, unary, and according to -- associativity) and return them in a tuple. splitOp :: Operator m a -> Batch m a -> Batch m a splitOp (InfixR op) (r, l, n, pre, post) = (op:r, l, n, pre, post) splitOp (InfixL op) (r, l, n, pre, post) = (r, op:l, n, pre, post) splitOp (InfixN op) (r, l, n, pre, post) = (r, l, op:n, pre, post) splitOp (Prefix op) (r, l, n, pre, post) = (r, l, n, op:pre, post) splitOp (Postfix op) (r, l, n, pre, post) = (r, l, n, pre, op:post)
recursion-ninja/megaparsec
Text/Megaparsec/Expr.hs
bsd-2-clause
5,756
0
11
1,388
1,285
715
570
57
1
module Import ( module Import ) where import Prelude as Import hiding (head, init, last, readFile, tail, writeFile) import Yesod as Import hiding (Route (..)) import Control.Applicative as Import (pure, (<$>), (<*>)) import Data.Text as Import (Text) import Foundation as Import import Model as Import import Settings as Import import Settings.Development as Import import Settings.StaticFiles as Import import Data.Aeson as Import (toJSON) #if __GLASGOW_HASKELL__ >= 704 import Data.Monoid as Import (Monoid (mappend, mempty, mconcat), (<>)) #else import Data.Monoid as Import (Monoid (mappend, mempty, mconcat)) infixr 5 <> (<>) :: Monoid m => m -> m -> m (<>) = mappend #endif
JanAhrens/yesod-oauth-demo
Import.hs
bsd-2-clause
1,114
0
6
535
154
112
42
18
1
module Language.Drasil.Code.Imperative.GOOL.LanguageRenderer ( -- * Common Syntax doxConfigName, makefileName, sampleInputName ) where ---------------------------------------- -- Syntax common to several renderers -- ---------------------------------------- doxConfigName, makefileName, sampleInputName :: String doxConfigName = "doxConfig" makefileName = "Makefile" sampleInputName = "input.txt"
JacquesCarette/literate-scientific-software
code/drasil-code/Language/Drasil/Code/Imperative/GOOL/LanguageRenderer.hs
bsd-2-clause
403
0
4
41
49
35
14
6
1
{-# LANGUAGE QuasiQuotes #-} import LiquidHaskell -- some tests for the 'expandDefaultCase' trick to case-split -- on the "missing" constructors. mylen :: [a] -> Int mylen [] = 0 mylen (_:xs) = 1 + mylen xs [lq| foo :: [a] -> {v: Int | v = 0} |] foo :: [a] -> Int foo zs = case zs of (x:xs) -> 0 _ -> mylen zs [lq| bar :: [a] -> {v: Int | v > 0} |] bar :: [a] -> Int bar zs = case zs of [] -> 1 _ -> mylen zs
spinda/liquidhaskell
tests/gsoc15/unknown/pos/meas7.hs
bsd-3-clause
490
0
9
177
158
85
73
15
2
---------------------------------------------------------------------------- -- | -- Module : ModuleWithQualifiedImport -- Copyright : (c) Sergey Vinokurov 2015 -- License : BSD3-style (see LICENSE) -- Maintainer : [email protected] ---------------------------------------------------------------------------- module ModuleWithQualifiedImport where import qualified Imported1 as Imp baz :: a -> a baz x = x
sergv/tags-server
test-data/0001module_with_imports/ModuleWithQualifiedImport.hs
bsd-3-clause
427
0
5
61
34
24
10
4
1
-- | This variant of Tutorial #3 keeps geometry and colors in two -- separate lists. {-# LANGUAGE OverloadedStrings #-} module Main where -- General Haskell modules import Control.Applicative import System.FilePath ((</>)) -- Import all OpenGL libraries qualified, for pedagogical reasons import qualified Graphics.Rendering.OpenGL as GL import qualified Graphics.UI.GLFW as GLFW import Graphics.Rendering.OpenGL (($=)) import qualified Graphics.GLUtil as U -- Local modules import qualified Util.GLFW as W main :: IO () main = do -- GLFW code will be the same in all variants win <- W.initialize "My First Triangle" prog <- initResources W.mainLoop (draw prog win) win W.cleanup win initResources :: IO Resources initResources = do GL.blend $= GL.Enabled GL.blendFunc $= (GL.SrcAlpha, GL.OneMinusSrcAlpha) -- As our shaders take more inputs, collecting the attributes gets -- annoying. GLUtil helps out with the ShaderProgram type, which -- keeps track of the 'AttribLocations' and 'UniformLocation's by -- name. let v = shaderPath </> "triangle.v.glsl" f = shaderPath </> "triangle.f.glsl" Resources <$> U.simpleShaderProgram v f <*> U.makeBuffer GL.ArrayBuffer vertices <*> U.makeBuffer GL.ArrayBuffer colors draw :: Resources -> GLFW.Window -> IO () draw r win = do GL.clearColor $= GL.Color4 1 1 1 1 GL.clear [GL.ColorBuffer] -- In C++ example GLUT handles resizing the viewport? (width, height) <- GLFW.getFramebufferSize win GL.viewport $= (GL.Position 0 0, GL.Size (fromIntegral width) (fromIntegral height)) t <- maybe 0 id <$> GLFW.getTime -- time in seconds since program launch let fade :: GL.Index1 GL.GLfloat fade = GL.Index1 . realToFrac $ sin (t * 2 * pi / 5) / 2 + 0.5 GL.currentProgram $= (Just . U.program . triProgram $ r) -- More helpers from GLUtil, equivalent to: -- GL.vertexAttribArray coord2d $= GL.Enabled -- GL.vertexAttribArray v_color $= GL.Enabled U.enableAttrib (triProgram r) "coord2d" U.enableAttrib (triProgram r) "v_color" GL.bindBuffer GL.ArrayBuffer $= Just (vertBuffer r) U.setAttrib (triProgram r) "coord2d" GL.ToFloat $ GL.VertexArrayDescriptor 2 GL.Float 0 U.offset0 GL.bindBuffer GL.ArrayBuffer $= Just (colorBuffer r) U.setAttrib (triProgram r) "v_color" GL.ToFloat $ GL.VertexArrayDescriptor 3 GL.Float 0 U.offset0 U.setUniform (triProgram r) "fade" fade GL.drawArrays GL.Triangles 0 3 -- 3 is the number of vertices -- GLUtil does not yet provide a function to disable attributes GL.vertexAttribArray (U.getAttrib (triProgram r) "coord2d") $= GL.Disabled GL.vertexAttribArray (U.getAttrib (triProgram r) "v_color") $= GL.Disabled -- | Represents the shader program and its input buffers data Resources = Resources { triProgram :: U.ShaderProgram , vertBuffer :: GL.BufferObject , colorBuffer :: GL.BufferObject } shaderPath :: FilePath shaderPath = "wikibook" </> "tutorial-03-attributes" vertices :: [Float] vertices = [ 0.0, 0.8 , -0.8, -0.8 , 0.8, -0.8 ] colors :: [Float] colors = [ 1, 1, 0 , 0, 0, 1 , 1, 0, 0 ]
bergey/haskell-OpenGL-examples
wikibook/tutorial-03-attributes/Separate.hs
bsd-3-clause
3,351
0
17
818
847
443
404
59
1
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. An additional grant -- of patent rights can be found in the PATENTS file in the same directory. ----------------------------------------------------------------- -- Auto-generated by regenClassifiers -- -- DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING -- @generated ----------------------------------------------------------------- {-# LANGUAGE OverloadedStrings #-} module Duckling.Ranking.Classifiers.NE_XX (classifiers) where import Data.String import Prelude import qualified Data.HashMap.Strict as HashMap import Duckling.Ranking.Types classifiers :: Classifiers classifiers = HashMap.fromList []
facebookincubator/duckling
Duckling/Ranking/Classifiers/NE_XX.hs
bsd-3-clause
828
0
6
105
66
47
19
8
1
{-# LANGUAGE CPP, ExistentialQuantification, GADTs, ScopedTypeVariables, TypeFamilies, FlexibleInstances, MultiParamTypeClasses, GeneralizedNewtypeDeriving, RankNTypes, BangPatterns, UndecidableInstances, EmptyDataDecls, RecursiveDo, RoleAnnotations, LambdaCase #-} module Reflex.Spider.Internal where import Prelude hiding (mapM, mapM_, any, sequence, concat) import qualified Reflex.Class as R import qualified Reflex.Host.Class as R import Data.IORef import System.Mem.Weak import Data.Foldable import Data.Traversable import Control.Monad hiding (mapM, mapM_, forM_, forM, sequence) import Control.Monad.Reader hiding (mapM, mapM_, forM_, forM, sequence) import GHC.Exts import Control.Applicative import Data.Dependent.Map (DMap, DSum (..)) import qualified Data.Dependent.Map as DMap import Data.GADT.Compare import Data.Functor.Misc import Data.Maybe import Data.IntMap (IntMap) import qualified Data.IntMap as IntMap import Control.Lens hiding (coerce) import Control.Monad.TypedId import Control.Monad.Ref import Data.Monoid ((<>)) import System.IO.Unsafe import Unsafe.Coerce import Control.Monad.Primitive debugPropagate :: Bool debugInvalidateHeight :: Bool #ifdef DEBUG #define DEBUG_NODEIDS debugPropagate = True debugInvalidateHeight = True class HasNodeId a where getNodeId :: a -> Int instance HasNodeId (Hold a) where getNodeId = holdNodeId instance HasNodeId (PushSubscribed a b) where getNodeId = pushSubscribedNodeId instance HasNodeId (SwitchSubscribed a) where getNodeId = switchSubscribedNodeId instance HasNodeId (MergeSubscribed a) where getNodeId = mergeSubscribedNodeId instance HasNodeId (FanSubscribed a) where getNodeId = fanSubscribedNodeId instance HasNodeId (CoincidenceSubscribed a) where getNodeId = coincidenceSubscribedNodeId instance HasNodeId (RootSubscribed a) where getNodeId = rootSubscribedNodeId showNodeId :: HasNodeId a => a -> String showNodeId = ("#"<>) . show . getNodeId #else debugPropagate = False debugInvalidateHeight = False showNodeId :: a -> String showNodeId = const "" #endif #ifdef DEBUG_NODEIDS {-# NOINLINE nextNodeIdRef #-} nextNodeIdRef :: IORef Int nextNodeIdRef = unsafePerformIO $ newIORef 1 {-# NOINLINE unsafeNodeId #-} unsafeNodeId :: a -> Int unsafeNodeId a = unsafePerformIO $ do touch a atomicModifyIORef' nextNodeIdRef $ \n -> (succ n, n) #endif --TODO: Figure out why certain things are not 'representational', then make them representational so we can use coerce --type role Hold representational data Hold a = Hold { holdValue :: !(IORef a) , holdInvalidators :: !(IORef [Weak Invalidator]) -- We need to use 'Any' for the next two things, because otherwise Hold inherits a nominal role for its 'a' parameter, and we want to be able to use 'coerce' , holdSubscriber :: !(IORef Any) -- Keeps its subscription alive; for some reason, a regular (or strict) reference to the Subscriber itself wasn't working, so had to use an IORef , holdParent :: !(IORef Any) -- Keeps its parent alive (will be undefined until the hold is initialized --TODO: Probably shouldn't be an IORef #ifdef DEBUG_NODEIDS , holdNodeId :: Int #endif } data EventEnv = EventEnv { eventEnvAssignments :: !(IORef [SomeAssignment]) , eventEnvHoldInits :: !(IORef [SomeHoldInit]) , eventEnvClears :: !(IORef [SomeMaybeIORef]) , eventEnvCurrentHeight :: !(IORef Int) , eventEnvCoincidenceInfos :: !(IORef [SomeCoincidenceInfo]) , eventEnvDelayedMerges :: !(IORef (IntMap [DelayedMerge])) } runEventM :: EventM a -> EventEnv -> IO a runEventM = runReaderT . unEventM askToAssignRef :: EventM (IORef [SomeAssignment]) askToAssignRef = EventM $ asks eventEnvAssignments askHoldInitRef :: EventM (IORef [SomeHoldInit]) askHoldInitRef = EventM $ asks eventEnvHoldInits getCurrentHeight :: EventM Int getCurrentHeight = EventM $ do heightRef <- asks eventEnvCurrentHeight liftIO $ readIORef heightRef putCurrentHeight :: Int -> EventM () putCurrentHeight h = EventM $ do heightRef <- asks eventEnvCurrentHeight liftIO $ writeIORef heightRef h scheduleClear :: IORef (Maybe a) -> EventM () scheduleClear r = EventM $ do clears <- asks eventEnvClears liftIO $ modifyIORef' clears (SomeMaybeIORef r :) scheduleMerge :: Int -> MergeSubscribed a -> EventM () scheduleMerge height subscribed = EventM $ do delayedRef <- asks eventEnvDelayedMerges liftIO $ modifyIORef' delayedRef $ IntMap.insertWith (++) height [DelayedMerge subscribed] emitCoincidenceInfo :: SomeCoincidenceInfo -> EventM () emitCoincidenceInfo sci = EventM $ do ciRef <- asks eventEnvCoincidenceInfos liftIO $ modifyIORef' ciRef (sci:) -- Note: hold cannot examine its event until after the phase is over hold :: a -> Event a -> EventM (Behavior a) hold v0 e = do holdInitRef <- askHoldInitRef liftIO $ do valRef <- newIORef v0 invsRef <- newIORef [] parentRef <- newIORef $ error "hold not yet initialized (parent)" subscriberRef <- newIORef $ error "hold not yet initialized (subscriber)" let h = Hold { holdValue = valRef , holdInvalidators = invsRef , holdSubscriber = subscriberRef , holdParent = parentRef #ifdef DEBUG_NODEIDS , holdNodeId = unsafeNodeId (v0, e) #endif } !s = SubscriberHold h writeIORef subscriberRef $ unsafeCoerce s modifyIORef' holdInitRef (SomeHoldInit e h :) return $ BehaviorHold h subscribeHold :: Event a -> Hold a -> EventM () subscribeHold e h = do toAssignRef <- askToAssignRef !s <- liftIO $ liftM unsafeCoerce $ readIORef $ holdSubscriber h -- This must be performed strictly so that the weak pointer points at the actual item ws <- liftIO $ mkWeakPtrWithDebug s "holdSubscriber" subd <- subscribe e $ WeakSubscriberSimple ws liftIO $ writeIORef (holdParent h) $ unsafeCoerce subd occ <- liftIO $ getEventSubscribedOcc subd case occ of Nothing -> return () Just o -> liftIO $ modifyIORef' toAssignRef (SomeAssignment h o :) --type role BehaviorM representational -- BehaviorM can sample behaviors newtype BehaviorM a = BehaviorM { unBehaviorM :: ReaderT (Maybe (Weak Invalidator, IORef [SomeBehaviorSubscribed])) IO a } deriving (Functor, Applicative, Monad, MonadIO, MonadFix) data BehaviorSubscribed a = BehaviorSubscribedHold (Hold a) | BehaviorSubscribedPull (PullSubscribed a) data SomeBehaviorSubscribed = forall a. SomeBehaviorSubscribed (BehaviorSubscribed a) --type role PullSubscribed representational data PullSubscribed a = PullSubscribed { pullSubscribedValue :: !a , pullSubscribedInvalidators :: !(IORef [Weak Invalidator]) , pullSubscribedOwnInvalidator :: !Invalidator , pullSubscribedParents :: ![SomeBehaviorSubscribed] -- Need to keep parent behaviors alive, or they won't let us know when they're invalidated } --type role Pull representational data Pull a = Pull { pullValue :: !(IORef (Maybe (PullSubscribed a))) , pullCompute :: !(BehaviorM a) } data Invalidator = forall a. InvalidatorPull (Pull a) | forall a. InvalidatorSwitch (SwitchSubscribed a) data RootSubscribed a = RootSubscribed { rootSubscribedSubscribers :: !(IORef [WeakSubscriber a]) , rootSubscribedOccurrence :: !(IORef (Maybe a)) -- Alias to rootOccurrence } data Root a = Root { rootOccurrence :: !(IORef (Maybe a)) -- The currently-firing occurrence of this event , rootSubscribed :: !(IORef (Maybe (RootSubscribed a))) , rootInit :: !(RootTrigger a -> IO (IO ())) } data SomeHoldInit = forall a. SomeHoldInit (Event a) (Hold a) -- EventM can do everything BehaviorM can, plus create holds newtype EventM a = EventM { unEventM :: ReaderT EventEnv IO a } deriving (Functor, Applicative, Monad, MonadFix, MonadIO) -- The environment should be Nothing if we are not in a frame, and Just if we are - in which case it is a list of assignments to be done after the frame is over data PushSubscribed a b = PushSubscribed { pushSubscribedOccurrence :: !(IORef (Maybe b)) -- If the current height is less than our height, this should always be Nothing; during our height, this will get filled in at some point, always before our children are notified; after our height, this will be filled in with the correct value (Nothing if we are not firing, Just if we are) , pushSubscribedHeight :: !(IORef Int) , pushSubscribedSubscribers :: !(IORef [WeakSubscriber b]) , pushSubscribedSelf :: !(Subscriber a) -- Hold this in memory to ensure our WeakReferences don't die , pushSubscribedParent :: !(EventSubscribed a) #ifdef DEBUG_NODEIDS , pushSubscribedNodeId :: Int #endif } data Push a b = Push { pushCompute :: !(a -> EventM (Maybe b)) -- Compute the current firing value; assumes that its parent has been computed , pushParent :: !(Event a) , pushSubscribed :: !(IORef (Maybe (PushSubscribed a b))) --TODO: Can we replace this with an unsafePerformIO thunk? } data MergeSubscribed k = MergeSubscribed { mergeSubscribedOccurrence :: !(IORef (Maybe (DMap k))) , mergeSubscribedAccum :: !(IORef (DMap k)) -- This will accumulate occurrences until our height is reached, at which point it will be transferred to mergeSubscribedOccurrence , mergeSubscribedHeight :: !(IORef Int) , mergeSubscribedSubscribers :: !(IORef [WeakSubscriber (DMap k)]) , mergeSubscribedSelf :: !Any -- Hold all our Subscribers in memory , mergeSubscribedParents :: !(DMap (WrapArg EventSubscribed k)) #ifdef DEBUG_NODEIDS , mergeSubscribedNodeId :: Int #endif } --TODO: DMap sucks; we should really write something better (with a functor for the value as well as the key) data Merge k = Merge { mergeParents :: !(DMap (WrapArg Event k)) , mergeSubscribed :: !(IORef (Maybe (MergeSubscribed k))) --TODO: Can we replace this with an unsafePerformIO thunk? } data FanSubscriberKey k a where FanSubscriberKey :: k a -> FanSubscriberKey k [WeakSubscriber a] instance GEq k => GEq (FanSubscriberKey k) where geq (FanSubscriberKey a) (FanSubscriberKey b) = case geq a b of Nothing -> Nothing Just Refl -> Just Refl instance GCompare k => GCompare (FanSubscriberKey k) where gcompare (FanSubscriberKey a) (FanSubscriberKey b) = case gcompare a b of GLT -> GLT GEQ -> GEQ GGT -> GGT data FanSubscribed k = FanSubscribed { fanSubscribedSubscribers :: !(IORef (DMap (FanSubscriberKey k))) , fanSubscribedParent :: !(EventSubscribed (DMap k)) , fanSubscribedSelf :: !(Subscriber (DMap k)) #ifdef DEBUG_NODEIDS , fanSubscribedNodeId :: Int #endif } data Fan k = Fan { fanParent :: !(Event (DMap k)) , fanSubscribed :: !(IORef (Maybe (FanSubscribed k))) } data SwitchSubscribed a = SwitchSubscribed { switchSubscribedOccurrence :: !(IORef (Maybe a)) , switchSubscribedHeight :: !(IORef Int) , switchSubscribedSubscribers :: !(IORef [WeakSubscriber a]) , switchSubscribedSelf :: !(Subscriber a) , switchSubscribedSelfWeak :: !(IORef (Weak (Subscriber a))) , switchSubscribedOwnInvalidator :: !Invalidator , switchSubscribedOwnWeakInvalidator :: !(IORef (Weak Invalidator)) , switchSubscribedBehaviorParents :: !(IORef [SomeBehaviorSubscribed]) , switchSubscribedParent :: !(Behavior (Event a)) , switchSubscribedCurrentParent :: !(IORef (EventSubscribed a)) #ifdef DEBUG_NODEIDS , switchSubscribedNodeId :: Int #endif } data Switch a = Switch { switchParent :: !(Behavior (Event a)) , switchSubscribed :: !(IORef (Maybe (SwitchSubscribed a))) } data CoincidenceSubscribed a = CoincidenceSubscribed { coincidenceSubscribedOccurrence :: !(IORef (Maybe a)) , coincidenceSubscribedSubscribers :: !(IORef [WeakSubscriber a]) , coincidenceSubscribedHeight :: !(IORef Int) , coincidenceSubscribedOuter :: !(Subscriber (Event a)) , coincidenceSubscribedOuterParent :: !(EventSubscribed (Event a)) , coincidenceSubscribedInnerParent :: !(IORef (Maybe (EventSubscribed a))) #ifdef DEBUG_NODEIDS , coincidenceSubscribedNodeId :: Int #endif } data Coincidence a = Coincidence { coincidenceParent :: !(Event (Event a)) , coincidenceSubscribed :: !(IORef (Maybe (CoincidenceSubscribed a))) } data Box a = Box { unBox :: a } --type WeakSubscriber a = Weak (Subscriber a) data WeakSubscriber a = forall k. GCompare k => WeakSubscriberMerge !(k a) !(Weak (Box (MergeSubscribed k))) --TODO: Can we inline the GCompare? | WeakSubscriberSimple !(Weak (Subscriber a)) showWeakSubscriberType :: WeakSubscriber a -> String showWeakSubscriberType = \case WeakSubscriberMerge _ _ -> "WeakSubscriberMerge" WeakSubscriberSimple _ -> "WeakSubscriberSimple" deRefWeakSubscriber :: WeakSubscriber a -> IO (Maybe (Subscriber a)) deRefWeakSubscriber ws = case ws of WeakSubscriberSimple w -> deRefWeak w WeakSubscriberMerge k w -> liftM (fmap $ SubscriberMerge k . unBox) $ deRefWeak w data Subscriber a = forall b. SubscriberPush !(a -> EventM (Maybe b)) (PushSubscribed a b) | forall k. GCompare k => SubscriberMerge !(k a) (MergeSubscribed k) --TODO: Can we inline the GCompare? | forall k. (GCompare k, a ~ DMap k) => SubscriberFan (FanSubscribed k) | SubscriberHold !(Hold a) | SubscriberSwitch (SwitchSubscribed a) | forall b. a ~ Event b => SubscriberCoincidenceOuter (CoincidenceSubscribed b) | SubscriberCoincidenceInner (CoincidenceSubscribed a) showSubscriberType :: Subscriber a -> String showSubscriberType = \case SubscriberPush _ _ -> "SubscriberPush" SubscriberMerge _ _ -> "SubscriberMerge" SubscriberFan _ -> "SubscriberFan" SubscriberHold _ -> "SubscriberHold" SubscriberSwitch _ -> "SubscriberSwitch" SubscriberCoincidenceOuter _ -> "SubscriberCoincidenceOuter" SubscriberCoincidenceInner _ -> "SubscriberCoincidenceInner" data Event a = EventRoot !(Root a) | EventNever | forall b. EventPush !(Push b a) | forall k. (GCompare k, a ~ DMap k) => EventMerge !(Merge k) | forall k. GCompare k => EventFan !(k a) !(Fan k) | EventSwitch !(Switch a) | EventCoincidence !(Coincidence a) showEventType :: Event a -> String showEventType = \case EventRoot _ -> "EventRoot" EventNever -> "EventNever" EventPush _ -> "EventPush" EventMerge _ -> "EventMerge" EventFan _ _ -> "EventFan" EventSwitch _ -> "EventSwitch" EventCoincidence _ -> "EventCoincidence" data EventSubscribed a = EventSubscribedRoot !(RootSubscribed a) | EventSubscribedNever | forall b. EventSubscribedPush !(PushSubscribed b a) | forall k. (GCompare k, a ~ DMap k) => EventSubscribedMerge !(MergeSubscribed k) | forall k. GCompare k => EventSubscribedFan !(k a) !(FanSubscribed k) | EventSubscribedSwitch !(SwitchSubscribed a) | EventSubscribedCoincidence !(CoincidenceSubscribed a) --type role Behavior representational data Behavior a = BehaviorHold !(Hold a) | BehaviorConst !a | BehaviorPull !(Pull a) -- ResultM can read behaviors and events type ResultM = EventM {-# NOINLINE unsafeNewIORef #-} unsafeNewIORef :: a -> b -> IORef b unsafeNewIORef _ b = unsafePerformIO $ newIORef b instance Functor Event where fmap f = push $ return . Just . f instance Functor Behavior where fmap f = pull . liftM f . readBehaviorTracked {-# NOINLINE push #-} --TODO: If this is helpful, we can get rid of the unsafeNewIORef and use unsafePerformIO directly push :: (a -> EventM (Maybe b)) -> Event a -> Event b push f e = EventPush $ Push { pushCompute = f , pushParent = e , pushSubscribed = unsafeNewIORef (f, e) Nothing --TODO: Does the use of the tuple here create unnecessary overhead? } {-# RULES "push/push" forall f g e. push f (push g e) = push (maybe (return Nothing) f <=< g) e #-} {-# NOINLINE pull #-} pull :: BehaviorM a -> Behavior a pull a = BehaviorPull $ Pull { pullCompute = a , pullValue = unsafeNewIORef a Nothing } {-# RULES "pull/pull" forall a. pull (readBehaviorTracked (pull a)) = pull a #-} {-# NOINLINE switch #-} switch :: Behavior (Event a) -> Event a switch a = EventSwitch $ Switch { switchParent = a , switchSubscribed = unsafeNewIORef a Nothing } {-# RULES "switch/constB" forall e. switch (BehaviorConst e) = e #-} coincidence :: Event (Event a) -> Event a coincidence a = EventCoincidence $ Coincidence { coincidenceParent = a , coincidenceSubscribed = unsafeNewIORef a Nothing } newRoot :: IO (Root a) newRoot = do occRef <- newIORef Nothing subscribedRef <- newIORef Nothing return $ Root { rootOccurrence = occRef , rootSubscribed = subscribedRef , rootInit = const $ return $ return () } propagateAndUpdateSubscribersRef subscribersRef a = do subscribers <- liftIO $ readIORef subscribersRef liftIO $ writeIORef subscribersRef [] stillAlive <- propagate a subscribers liftIO $ modifyIORef' subscribersRef (++stillAlive) -- Propagate the given event occurrence; before cleaning up, run the given action, which may read the state of events and behaviors run :: [DSum RootTrigger] -> ResultM b -> IO b run roots after = do when debugPropagate $ putStrLn "Running an event frame" result <- runFrame $ do forM_ roots $ \(RootTrigger (_, occRef) :=> a) -> do liftIO $ writeIORef occRef $ Just a scheduleClear occRef forM_ roots $ \(RootTrigger (subscribersRef, _) :=> a) -> do propagateAndUpdateSubscribersRef subscribersRef a delayedRef <- EventM $ asks eventEnvDelayedMerges let go = do delayed <- liftIO $ readIORef delayedRef case IntMap.minViewWithKey delayed of Nothing -> return () Just ((currentHeight, current), future) -> do when debugPropagate $ liftIO $ putStrLn $ "Running height " ++ show currentHeight putCurrentHeight currentHeight liftIO $ writeIORef delayedRef future forM_ current $ \d -> case d of DelayedMerge subscribed -> do height <- liftIO $ readIORef $ mergeSubscribedHeight subscribed case height `compare` currentHeight of LT -> error "Somehow a merge's height has been decreased after it was scheduled" GT -> scheduleMerge height subscribed -- The height has been increased (by a coincidence event; TODO: is this the only way?) EQ -> do m <- liftIO $ readIORef $ mergeSubscribedAccum subscribed liftIO $ writeIORef (mergeSubscribedAccum subscribed) DMap.empty --TODO: Assert that m is not empty liftIO $ writeIORef (mergeSubscribedOccurrence subscribed) $ Just m scheduleClear $ mergeSubscribedOccurrence subscribed propagateAndUpdateSubscribersRef (mergeSubscribedSubscribers subscribed) m go go putCurrentHeight maxBound after when debugPropagate $ putStrLn "Done running an event frame" return result data SomeMaybeIORef = forall a. SomeMaybeIORef (IORef (Maybe a)) data SomeAssignment = forall a. SomeAssignment (Hold a) a data DelayedMerge = forall k. DelayedMerge (MergeSubscribed k) debugFinalize :: Bool debugFinalize = False mkWeakPtrWithDebug :: a -> String -> IO (Weak a) mkWeakPtrWithDebug x debugNote = mkWeakPtr x $ if debugFinalize then Just $ putStrLn $ "finalizing: " ++ debugNote else Nothing type WeakList a = [Weak a] --TODO: Is it faster to clean up every time, or to occasionally go through and clean up as needed? traverseAndCleanWeakList_ :: Monad m => (wa -> m (Maybe a)) -> [wa] -> (a -> m ()) -> m [wa] traverseAndCleanWeakList_ deRef ws f = go ws where go [] = return [] go (h:t) = do ma <- deRef h case ma of Just a -> do f a t' <- go t return $ h : t' Nothing -> go t -- | Propagate everything at the current height propagate :: a -> [WeakSubscriber a] -> EventM [WeakSubscriber a] propagate a subscribers = do traverseAndCleanWeakList_ (liftIO . deRefWeakSubscriber) subscribers $ \s -> case s of SubscriberPush compute subscribed -> do when debugPropagate $ liftIO $ putStrLn $ "SubscriberPush" <> showNodeId subscribed occ <- compute a case occ of Nothing -> return () -- No need to write a Nothing back into the Ref Just o -> do liftIO $ writeIORef (pushSubscribedOccurrence subscribed) occ scheduleClear $ pushSubscribedOccurrence subscribed liftIO . writeIORef (pushSubscribedSubscribers subscribed) =<< propagate o =<< liftIO (readIORef (pushSubscribedSubscribers subscribed)) SubscriberMerge k subscribed -> do when debugPropagate $ liftIO $ putStrLn $ "SubscriberMerge" <> showNodeId subscribed oldM <- liftIO $ readIORef $ mergeSubscribedAccum subscribed liftIO $ writeIORef (mergeSubscribedAccum subscribed) $ DMap.insertWith (error "Same key fired multiple times for") k a oldM when (DMap.null oldM) $ do -- Only schedule the firing once height <- liftIO $ readIORef $ mergeSubscribedHeight subscribed --TODO: assertions about height currentHeight <- getCurrentHeight when (height <= currentHeight) $ error $ "Height (" ++ show height ++ ") is not greater than current height (" ++ show currentHeight ++ ")" scheduleMerge height subscribed SubscriberFan subscribed -> do subs <- liftIO $ readIORef $ fanSubscribedSubscribers subscribed when debugPropagate $ liftIO $ putStrLn $ "SubscriberFan" <> showNodeId subscribed <> ": " ++ show (DMap.size subs) ++ " keys subscribed, " ++ show (DMap.size a) ++ " keys firing" --TODO: We need a better DMap intersection; here, we are assuming that the number of firing keys is small and the number of subscribers is large forM_ (DMap.toList a) $ \(k :=> v) -> case DMap.lookup (FanSubscriberKey k) subs of Nothing -> do when debugPropagate $ liftIO $ putStrLn "No subscriber for key" return () Just subsubs -> do _ <- propagate v subsubs --TODO: use the value of this return () --TODO: The following is way too slow to do all the time subs' <- liftIO $ forM (DMap.toList subs) $ ((\(FanSubscriberKey k :=> subsubs) -> do subsubs' <- traverseAndCleanWeakList_ (liftIO . deRefWeakSubscriber) subsubs (const $ return ()) return $ if null subsubs' then Nothing else Just $ FanSubscriberKey k :=> subsubs') :: DSum (FanSubscriberKey k) -> IO (Maybe (DSum (FanSubscriberKey k)))) liftIO $ writeIORef (fanSubscribedSubscribers subscribed) $ DMap.fromDistinctAscList $ catMaybes subs' SubscriberHold h -> do invalidators <- liftIO $ readIORef $ holdInvalidators h when debugPropagate $ liftIO $ putStrLn $ "SubscriberHold" <> showNodeId h <> ": " ++ show (length invalidators) toAssignRef <- askToAssignRef liftIO $ modifyIORef' toAssignRef (SomeAssignment h a :) SubscriberSwitch subscribed -> do when debugPropagate $ liftIO $ putStrLn $ "SubscriberSwitch" <> showNodeId subscribed liftIO $ writeIORef (switchSubscribedOccurrence subscribed) $ Just a scheduleClear $ switchSubscribedOccurrence subscribed subs <- liftIO $ readIORef $ switchSubscribedSubscribers subscribed liftIO . writeIORef (switchSubscribedSubscribers subscribed) =<< propagate a subs SubscriberCoincidenceOuter subscribed -> do when debugPropagate $ liftIO $ putStrLn $ "SubscriberCoincidenceOuter" <> showNodeId subscribed outerHeight <- liftIO $ readIORef $ coincidenceSubscribedHeight subscribed when debugPropagate $ liftIO $ putStrLn $ " outerHeight = " <> show outerHeight (occ, innerHeight, innerSubd) <- subscribeCoincidenceInner a outerHeight subscribed when debugPropagate $ liftIO $ putStrLn $ " isJust occ = " <> show (isJust occ) when debugPropagate $ liftIO $ putStrLn $ " innerHeight = " <> show innerHeight liftIO $ writeIORef (coincidenceSubscribedInnerParent subscribed) $ Just innerSubd scheduleClear $ coincidenceSubscribedInnerParent subscribed case occ of Nothing -> do when (innerHeight > outerHeight) $ liftIO $ do -- If the event fires, it will fire at a later height writeIORef (coincidenceSubscribedHeight subscribed) innerHeight mapM_ invalidateSubscriberHeight =<< readIORef (coincidenceSubscribedSubscribers subscribed) mapM_ recalculateSubscriberHeight =<< readIORef (coincidenceSubscribedSubscribers subscribed) Just o -> do -- Since it's already firing, no need to adjust height liftIO $ writeIORef (coincidenceSubscribedOccurrence subscribed) occ scheduleClear $ coincidenceSubscribedOccurrence subscribed liftIO . writeIORef (coincidenceSubscribedSubscribers subscribed) =<< propagate o =<< liftIO (readIORef (coincidenceSubscribedSubscribers subscribed)) SubscriberCoincidenceInner subscribed -> do when debugPropagate $ liftIO $ putStrLn $ "SubscriberCoincidenceInner" <> showNodeId subscribed liftIO $ writeIORef (coincidenceSubscribedOccurrence subscribed) $ Just a scheduleClear $ coincidenceSubscribedOccurrence subscribed liftIO . writeIORef (coincidenceSubscribedSubscribers subscribed) =<< propagate a =<< liftIO (readIORef (coincidenceSubscribedSubscribers subscribed)) data SomeCoincidenceInfo = forall a. SomeCoincidenceInfo (Weak (Subscriber a)) (Subscriber a) (Maybe (CoincidenceSubscribed a)) -- The CoincidenceSubscriber will be present only if heights need to be reset subscribeCoincidenceInner :: Event a -> Int -> CoincidenceSubscribed a -> EventM (Maybe a, Int, EventSubscribed a) subscribeCoincidenceInner o outerHeight subscribedUnsafe = do let !subInner = SubscriberCoincidenceInner subscribedUnsafe wsubInner <- liftIO $ mkWeakPtrWithDebug subInner "SubscriberCoincidenceInner" innerSubd <- {-# SCC "innerSubd" #-} (subscribe o $ WeakSubscriberSimple wsubInner) innerOcc <- liftIO $ getEventSubscribedOcc innerSubd innerHeight <- liftIO $ readIORef $ eventSubscribedHeightRef innerSubd let height = max innerHeight outerHeight emitCoincidenceInfo $ SomeCoincidenceInfo wsubInner subInner $ if height > outerHeight then Just subscribedUnsafe else Nothing return (innerOcc, height, innerSubd) readBehavior :: Behavior a -> IO a readBehavior b = runBehaviorM (readBehaviorTracked b) Nothing --TODO: Specialize readBehaviorTracked to the Nothing and Just cases runBehaviorM :: BehaviorM a -> Maybe (Weak Invalidator, IORef [SomeBehaviorSubscribed]) -> IO a runBehaviorM a mwi = runReaderT (unBehaviorM a) mwi askInvalidator :: BehaviorM (Maybe (Weak Invalidator)) askInvalidator = liftM (fmap fst) $ BehaviorM ask askParentsRef :: BehaviorM (Maybe (IORef [SomeBehaviorSubscribed])) askParentsRef = liftM (fmap snd) $ BehaviorM ask readBehaviorTracked :: Behavior a -> BehaviorM a readBehaviorTracked b = case b of BehaviorHold h -> do result <- liftIO $ readIORef $ holdValue h askInvalidator >>= mapM_ (\wi -> liftIO $ modifyIORef' (holdInvalidators h) (wi:)) askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (BehaviorSubscribedHold h) :)) liftIO $ touch $ holdSubscriber h return result BehaviorConst a -> return a BehaviorPull p -> do val <- liftIO $ readIORef $ pullValue p case val of Just subscribed -> do askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (BehaviorSubscribedPull subscribed) :)) askInvalidator >>= mapM_ (\wi -> liftIO $ modifyIORef' (pullSubscribedInvalidators subscribed) (wi:)) liftIO $ touch $ pullSubscribedOwnInvalidator subscribed return $ pullSubscribedValue subscribed Nothing -> do let !i = InvalidatorPull p wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorPull" parentsRef <- liftIO $ newIORef [] a <- liftIO $ runReaderT (unBehaviorM $ pullCompute p) $ Just (wi, parentsRef) invsRef <- liftIO . newIORef . maybeToList =<< askInvalidator parents <- liftIO $ readIORef parentsRef let subscribed = PullSubscribed { pullSubscribedValue = a , pullSubscribedInvalidators = invsRef , pullSubscribedOwnInvalidator = i , pullSubscribedParents = parents } liftIO $ writeIORef (pullValue p) $ Just subscribed askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (BehaviorSubscribedPull subscribed) :)) return a readEvent :: Event a -> ResultM (Maybe a) readEvent e = case e of EventRoot r -> liftIO $ readIORef $ rootOccurrence r EventNever -> return Nothing EventPush p -> do subscribed <- getPushSubscribed p liftIO $ do result <- readIORef $ pushSubscribedOccurrence subscribed -- Since ResultM is always called after the final height is reached, this will always be valid touch $ pushSubscribedSelf subscribed return result EventMerge m -> do subscribed <- getMergeSubscribed m liftIO $ do result <- readIORef $ mergeSubscribedOccurrence subscribed touch $ mergeSubscribedSelf subscribed return result EventFan k f -> do parentOcc <- readEvent $ fanParent f return $ DMap.lookup k =<< parentOcc EventSwitch s -> do subscribed <- getSwitchSubscribed s liftIO $ do result <- readIORef $ switchSubscribedOccurrence subscribed touch $ switchSubscribedSelf subscribed touch $ switchSubscribedOwnInvalidator subscribed return result EventCoincidence c -> do subscribed <- getCoincidenceSubscribed c liftIO $ do result <- readIORef $ coincidenceSubscribedOccurrence subscribed touch $ coincidenceSubscribedOuter subscribed --TODO: do we need to touch the inner subscriber? return result -- Always refers to 0 {-# NOINLINE zeroRef #-} zeroRef :: IORef Int zeroRef = unsafePerformIO $ newIORef 0 getEventSubscribed :: Event a -> EventM (EventSubscribed a) getEventSubscribed e = case e of EventRoot r -> liftM EventSubscribedRoot $ getRootSubscribed r EventNever -> return EventSubscribedNever EventPush p -> liftM EventSubscribedPush $ getPushSubscribed p EventFan k f -> liftM (EventSubscribedFan k) $ getFanSubscribed f EventMerge m -> liftM EventSubscribedMerge $ getMergeSubscribed m EventSwitch s -> liftM EventSubscribedSwitch $ getSwitchSubscribed s EventCoincidence c -> liftM EventSubscribedCoincidence $ getCoincidenceSubscribed c debugSubscribe :: Bool debugSubscribe = False subscribeEventSubscribed :: EventSubscribed a -> WeakSubscriber a -> IO () subscribeEventSubscribed es ws = case es of EventSubscribedRoot r -> do when debugSubscribe $ liftIO $ putStrLn $ "subscribeEventSubscribed Root" modifyIORef' (rootSubscribedSubscribers r) (ws:) EventSubscribedNever -> do when debugSubscribe $ liftIO $ putStrLn $ "subscribeEventSubscribed Never" return () EventSubscribedPush subscribed -> do when debugSubscribe $ liftIO $ putStrLn $ "subscribeEventSubscribed Push" modifyIORef' (pushSubscribedSubscribers subscribed) (ws:) EventSubscribedFan k subscribed -> do when debugSubscribe $ liftIO $ putStrLn $ "subscribeEventSubscribed Fan" modifyIORef' (fanSubscribedSubscribers subscribed) $ DMap.insertWith (++) (FanSubscriberKey k) [ws] EventSubscribedMerge subscribed -> do when debugSubscribe $ liftIO $ putStrLn $ "subscribeEventSubscribed Merge" modifyIORef' (mergeSubscribedSubscribers subscribed) (ws:) EventSubscribedSwitch subscribed -> do when debugSubscribe $ liftIO $ putStrLn $ "subscribeEventSubscribed Switch" modifyIORef' (switchSubscribedSubscribers subscribed) (ws:) EventSubscribedCoincidence subscribed -> do when debugSubscribe $ liftIO $ putStrLn $ "subscribeEventSubscribed Coincidence" modifyIORef' (coincidenceSubscribedSubscribers subscribed) (ws:) getEventSubscribedOcc :: EventSubscribed a -> IO (Maybe a) getEventSubscribedOcc es = case es of EventSubscribedRoot r -> readIORef $ rootSubscribedOccurrence r EventSubscribedNever -> return Nothing EventSubscribedPush subscribed -> readIORef $ pushSubscribedOccurrence subscribed EventSubscribedFan k subscribed -> do parentOcc <- getEventSubscribedOcc $ fanSubscribedParent subscribed let occ = DMap.lookup k =<< parentOcc return occ EventSubscribedMerge subscribed -> readIORef $ mergeSubscribedOccurrence subscribed EventSubscribedSwitch subscribed -> readIORef $ switchSubscribedOccurrence subscribed EventSubscribedCoincidence subscribed -> readIORef $ coincidenceSubscribedOccurrence subscribed eventSubscribedHeightRef :: EventSubscribed a -> IORef Int eventSubscribedHeightRef es = case es of EventSubscribedRoot _ -> zeroRef EventSubscribedNever -> zeroRef EventSubscribedPush subscribed -> pushSubscribedHeight subscribed EventSubscribedFan _ subscribed -> eventSubscribedHeightRef $ fanSubscribedParent subscribed EventSubscribedMerge subscribed -> mergeSubscribedHeight subscribed EventSubscribedSwitch subscribed -> switchSubscribedHeight subscribed EventSubscribedCoincidence subscribed -> coincidenceSubscribedHeight subscribed subscribe :: Event a -> WeakSubscriber a -> EventM (EventSubscribed a) subscribe e ws = do subd <- getEventSubscribed e liftIO $ subscribeEventSubscribed subd ws return subd getRootSubscribed :: Root a -> EventM (RootSubscribed a) getRootSubscribed r = do mSubscribed <- liftIO $ readIORef $ rootSubscribed r case mSubscribed of Just subscribed -> return subscribed Nothing -> liftIO $ do subscribersRef <- newIORef [] let !subscribed = RootSubscribed { rootSubscribedOccurrence = rootOccurrence r , rootSubscribedSubscribers = subscribersRef } -- Strangely, init needs the same stuff as a RootSubscribed has, but it must not be the same as the one that everyone's subscribing to, or it'll leak memory uninit <- rootInit r $ RootTrigger (subscribersRef, rootOccurrence r) addFinalizer subscribed $ do -- putStrLn "Uninit root" uninit liftIO $ writeIORef (rootSubscribed r) $ Just subscribed return subscribed -- When getPushSubscribed returns, the PushSubscribed returned will have a fully filled-in getPushSubscribed :: Push a b -> EventM (PushSubscribed a b) getPushSubscribed p = do mSubscribed <- liftIO $ readIORef $ pushSubscribed p case mSubscribed of Just subscribed -> return subscribed Nothing -> do -- Not yet subscribed subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ liftM fromJust $ readIORef $ pushSubscribed p let !s = SubscriberPush (pushCompute p) subscribedUnsafe ws <- liftIO $ mkWeakPtrWithDebug s "SubscriberPush" subd <- subscribe (pushParent p) $ WeakSubscriberSimple ws parentOcc <- liftIO $ getEventSubscribedOcc subd occ <- liftM join $ mapM (pushCompute p) parentOcc occRef <- liftIO $ newIORef occ when (isJust occ) $ scheduleClear occRef subscribersRef <- liftIO $ newIORef [] let subscribed = PushSubscribed { pushSubscribedOccurrence = occRef , pushSubscribedHeight = eventSubscribedHeightRef subd -- Since pushes have the same height as their parents, share the ref , pushSubscribedSubscribers = subscribersRef , pushSubscribedSelf = unsafeCoerce s , pushSubscribedParent = subd #ifdef DEBUG_NODEIDS , pushSubscribedNodeId = unsafeNodeId p #endif } liftIO $ writeIORef (pushSubscribed p) $ Just subscribed return subscribed getMergeSubscribed :: forall k. GCompare k => Merge k -> EventM (MergeSubscribed k) getMergeSubscribed m = {-# SCC "getMergeSubscribed.entire" #-} do mSubscribed <- liftIO $ readIORef $ mergeSubscribed m case mSubscribed of Just subscribed -> return subscribed Nothing -> if DMap.null $ mergeParents m then emptyMergeSubscribed else do subscribedRef <- liftIO $ newIORef $ error "getMergeSubscribed: subscribedRef not yet initialized" subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef let !s = Box subscribedUnsafe ws <- liftIO $ mkWeakPtrWithDebug s "SubscriberMerge" subscribers :: [(Any, Maybe (DSum k), Int, DSum (WrapArg EventSubscribed k))] <- forM (DMap.toList $ mergeParents m) $ {-# SCC "getMergeSubscribed.a" #-} \(WrapArg k :=> e) -> {-# SCC "getMergeSubscribed.a1" #-} do parentSubd <- {-# SCC "getMergeSubscribed.a.parentSubd" #-} subscribe e $ WeakSubscriberMerge k ws parentOcc <- {-# SCC "getMergeSubscribed.a.parentOcc" #-} liftIO $ getEventSubscribedOcc parentSubd height <- {-# SCC "getMergeSubscribed.a.height" #-} liftIO $ readIORef $ eventSubscribedHeightRef parentSubd return $ {-# SCC "getMergeSubscribed.a.returnVal" #-} (unsafeCoerce s :: Any, fmap (k :=>) parentOcc, height, WrapArg k :=> parentSubd) let dm = DMap.fromDistinctAscList $ catMaybes $ map (^._2) subscribers subscriberHeights = map (^._3) subscribers myHeight = if any (==invalidHeight) subscriberHeights --TODO: Replace 'any' with invalidHeight-preserving 'maximum' then invalidHeight else succ $ Prelude.maximum subscriberHeights -- This is safe because the DMap will never be empty here currentHeight <- getCurrentHeight let (occ, accum) = if currentHeight >= myHeight -- If we should have fired by now then (if DMap.null dm then Nothing else Just dm, DMap.empty) else (Nothing, dm) when (not $ DMap.null accum) $ do scheduleMerge myHeight subscribedUnsafe occRef <- liftIO $ newIORef occ when (isJust occ) $ scheduleClear occRef accumRef <- liftIO $ newIORef accum heightRef <- liftIO $ newIORef myHeight subsRef <- liftIO $ newIORef [] let subscribed = MergeSubscribed { mergeSubscribedOccurrence = occRef , mergeSubscribedAccum = accumRef , mergeSubscribedHeight = heightRef , mergeSubscribedSubscribers = subsRef , mergeSubscribedSelf = unsafeCoerce $ map (\(x, _, _, _) -> x) subscribers --TODO: Does lack of strictness make this leak? , mergeSubscribedParents = DMap.fromDistinctAscList $ map (^._4) subscribers #ifdef DEBUG_NODEIDS , mergeSubscribedNodeId = unsafeNodeId m #endif } liftIO $ writeIORef subscribedRef subscribed return subscribed where emptyMergeSubscribed = do --TODO: This should never happen occRef <- liftIO $ newIORef Nothing accumRef <- liftIO $ newIORef DMap.empty subsRef <- liftIO $ newIORef [] return $ MergeSubscribed { mergeSubscribedOccurrence = occRef , mergeSubscribedAccum = accumRef , mergeSubscribedHeight = zeroRef , mergeSubscribedSubscribers = subsRef --TODO: This will definitely leak , mergeSubscribedSelf = unsafeCoerce () , mergeSubscribedParents = DMap.empty #ifdef DEBUG_NODEIDS , mergeSubscribedNodeId = -1 #endif } getFanSubscribed :: GCompare k => Fan k -> EventM (FanSubscribed k) getFanSubscribed f = do mSubscribed <- liftIO $ readIORef $ fanSubscribed f case mSubscribed of Just subscribed -> return subscribed Nothing -> do subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ liftM fromJust $ readIORef $ fanSubscribed f let !sub = SubscriberFan subscribedUnsafe wsub <- liftIO $ mkWeakPtrWithDebug sub "SubscriberFan" subd <- subscribe (fanParent f) $ WeakSubscriberSimple wsub subscribersRef <- liftIO $ newIORef DMap.empty let subscribed = FanSubscribed { fanSubscribedParent = subd , fanSubscribedSubscribers = subscribersRef , fanSubscribedSelf = sub #ifdef DEBUG_NODEIDS , fanSubscribedNodeId = unsafeNodeId f #endif } liftIO $ writeIORef (fanSubscribed f) $ Just subscribed return subscribed getSwitchSubscribed :: Switch a -> EventM (SwitchSubscribed a) getSwitchSubscribed s = do mSubscribed <- liftIO $ readIORef $ switchSubscribed s case mSubscribed of Just subscribed -> return subscribed Nothing -> do subscribedRef <- liftIO $ newIORef $ error "getSwitchSubscribed: subscribed has not yet been created" subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef let !i = InvalidatorSwitch subscribedUnsafe !sub = SubscriberSwitch subscribedUnsafe wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorSwitch" wiRef <- liftIO $ newIORef wi wsub <- liftIO $ mkWeakPtrWithDebug sub "SubscriberSwitch" selfWeakRef <- liftIO $ newIORef wsub parentsRef <- liftIO $ newIORef [] --TODO: This should be unnecessary, because it will always be filled with just the single parent behavior e <- liftIO $ runBehaviorM (readBehaviorTracked (switchParent s)) $ Just (wi, parentsRef) subd <- subscribe e $ WeakSubscriberSimple wsub subdRef <- liftIO $ newIORef subd parentOcc <- liftIO $ getEventSubscribedOcc subd occRef <- liftIO $ newIORef parentOcc when (isJust parentOcc) $ scheduleClear occRef heightRef <- liftIO $ newIORef =<< readIORef (eventSubscribedHeightRef subd) subscribersRef <- liftIO $ newIORef [] let subscribed = SwitchSubscribed { switchSubscribedOccurrence = occRef , switchSubscribedHeight = heightRef , switchSubscribedSubscribers = subscribersRef , switchSubscribedSelf = sub , switchSubscribedSelfWeak = selfWeakRef , switchSubscribedOwnInvalidator = i , switchSubscribedOwnWeakInvalidator = wiRef , switchSubscribedBehaviorParents = parentsRef , switchSubscribedParent = switchParent s , switchSubscribedCurrentParent = subdRef #ifdef DEBUG_NODEIDS , switchSubscribedNodeId = unsafeNodeId s #endif } liftIO $ writeIORef subscribedRef subscribed liftIO $ writeIORef (switchSubscribed s) $ Just subscribed return subscribed getCoincidenceSubscribed :: forall a. Coincidence a -> EventM (CoincidenceSubscribed a) getCoincidenceSubscribed c = do mSubscribed <- liftIO $ readIORef $ coincidenceSubscribed c case mSubscribed of Just subscribed -> return subscribed Nothing -> do subscribedRef <- liftIO $ newIORef $ error "getCoincidenceSubscribed: subscribed has not yet been created" subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef let !subOuter = SubscriberCoincidenceOuter subscribedUnsafe wsubOuter <- liftIO $ mkWeakPtrWithDebug subOuter "subOuter" outerSubd <- subscribe (coincidenceParent c) $ WeakSubscriberSimple wsubOuter outerOcc <- liftIO $ getEventSubscribedOcc outerSubd outerHeight <- liftIO $ readIORef $ eventSubscribedHeightRef outerSubd (occ, height, mInnerSubd) <- case outerOcc of Nothing -> return (Nothing, outerHeight, Nothing) Just o -> do (occ, height, innerSubd) <- subscribeCoincidenceInner o outerHeight subscribedUnsafe return (occ, height, Just innerSubd) occRef <- liftIO $ newIORef occ when (isJust occ) $ scheduleClear occRef heightRef <- liftIO $ newIORef height innerSubdRef <- liftIO $ newIORef mInnerSubd scheduleClear innerSubdRef subscribersRef <- liftIO $ newIORef [] let subscribed = CoincidenceSubscribed { coincidenceSubscribedOccurrence = occRef , coincidenceSubscribedHeight = heightRef , coincidenceSubscribedSubscribers = subscribersRef , coincidenceSubscribedOuter = subOuter , coincidenceSubscribedOuterParent = outerSubd , coincidenceSubscribedInnerParent = innerSubdRef #ifdef DEBUG_NODEIDS , coincidenceSubscribedNodeId = unsafeNodeId c #endif } liftIO $ writeIORef subscribedRef subscribed liftIO $ writeIORef (coincidenceSubscribed c) $ Just subscribed return subscribed merge :: GCompare k => DMap (WrapArg Event k) -> Event (DMap k) merge m = EventMerge $ Merge { mergeParents = m , mergeSubscribed = unsafeNewIORef m Nothing } newtype EventSelector k = EventSelector { select :: forall a. k a -> Event a } fan :: GCompare k => Event (DMap k) -> EventSelector k fan e = let f = Fan { fanParent = e , fanSubscribed = unsafeNewIORef e Nothing } in EventSelector $ \k -> EventFan k f -- | Run an event action outside of a frame runFrame :: EventM a -> IO a runFrame a = do toAssignRef <- newIORef [] -- This should only actually get used when events are firing holdInitRef <- newIORef [] heightRef <- newIORef 0 toClearRef <- newIORef [] coincidenceInfosRef <- newIORef [] delayedRef <- liftIO $ newIORef IntMap.empty result <- flip runEventM (EventEnv toAssignRef holdInitRef toClearRef heightRef coincidenceInfosRef delayedRef) $ do result <- a let runHoldInits = do holdInits <- liftIO $ readIORef holdInitRef if null holdInits then return () else do liftIO $ writeIORef holdInitRef [] forM_ holdInits $ \(SomeHoldInit e h) -> subscribeHold e h runHoldInits runHoldInits -- This must happen before doing the assignments, in case subscribing a Hold causes existing Holds to be read by the newly-propagated events return result toClear <- readIORef toClearRef forM_ toClear $ \(SomeMaybeIORef ref) -> writeIORef ref Nothing toAssign <- readIORef toAssignRef toReconnectRef <- newIORef [] forM_ toAssign $ \(SomeAssignment h v) -> do writeIORef (holdValue h) v writeIORef (holdInvalidators h) =<< invalidate toReconnectRef =<< readIORef (holdInvalidators h) coincidenceInfos <- readIORef coincidenceInfosRef forM_ coincidenceInfos $ \(SomeCoincidenceInfo wsubInner subInner mcs) -> do touch subInner finalize wsubInner mapM_ invalidateCoincidenceHeight mcs toReconnect <- readIORef toReconnectRef forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> do wsub <- readIORef $ switchSubscribedSelfWeak subscribed finalize wsub wi <- readIORef $ switchSubscribedOwnWeakInvalidator subscribed finalize wi let !i = switchSubscribedOwnInvalidator subscribed wi' <- mkWeakPtrWithDebug i "wi'" writeIORef (switchSubscribedBehaviorParents subscribed) [] e <- runBehaviorM (readBehaviorTracked (switchSubscribedParent subscribed)) (Just (wi', switchSubscribedBehaviorParents subscribed)) --TODO: Make sure we touch the pieces of the SwitchSubscribed at the appropriate times let !sub = switchSubscribedSelf subscribed -- Must be done strictly, or the weak pointer will refer to a useless thunk wsub' <- mkWeakPtrWithDebug sub "wsub'" writeIORef (switchSubscribedSelfWeak subscribed) wsub' subd' <- runFrame $ subscribe e $ WeakSubscriberSimple wsub' --TODO: Assert that the event isn't firing --TODO: This should not loop because none of the events should be firing, but still, it is inefficient {- stackTrace <- liftIO $ liftM renderStack $ ccsToStrings =<< (getCCSOf $! switchSubscribedParent subscribed) liftIO $ putStrLn $ (++stackTrace) $ "subd' subscribed to " ++ case e of EventRoot _ -> "EventRoot" EventNever -> "EventNever" _ -> "something else" -} writeIORef (switchSubscribedCurrentParent subscribed) subd' parentHeight <- readIORef $ eventSubscribedHeightRef subd' myHeight <- readIORef $ switchSubscribedHeight subscribed if parentHeight == myHeight then return () else do writeIORef (switchSubscribedHeight subscribed) parentHeight mapM_ invalidateSubscriberHeight =<< readIORef (switchSubscribedSubscribers subscribed) forM_ coincidenceInfos $ \(SomeCoincidenceInfo _ _ mcs) -> mapM_ recalculateCoincidenceHeight mcs forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> do mapM_ recalculateSubscriberHeight =<< readIORef (switchSubscribedSubscribers subscribed) return result invalidHeight :: Int invalidHeight = -1000 invalidateSubscriberHeight :: WeakSubscriber a -> IO () invalidateSubscriberHeight ws = do ms <- deRefWeakSubscriber ws case ms of Nothing -> return () --TODO: cleanup? Just s -> case s of SubscriberPush _ subscribed -> do when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberPush" <> showNodeId subscribed mapM_ invalidateSubscriberHeight =<< readIORef (pushSubscribedSubscribers subscribed) when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberPush" <> showNodeId subscribed <> " done" SubscriberMerge _ subscribed -> do when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberMerge" <> showNodeId subscribed oldHeight <- readIORef $ mergeSubscribedHeight subscribed when (oldHeight /= invalidHeight) $ do writeIORef (mergeSubscribedHeight subscribed) $ invalidHeight mapM_ invalidateSubscriberHeight =<< readIORef (mergeSubscribedSubscribers subscribed) when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberMerge" <> showNodeId subscribed <> " done" SubscriberFan subscribed -> do when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberFan" <> showNodeId subscribed subscribers <- readIORef $ fanSubscribedSubscribers subscribed forM_ (DMap.toList subscribers) $ ((\(FanSubscriberKey _ :=> v) -> mapM_ invalidateSubscriberHeight v) :: DSum (FanSubscriberKey k) -> IO ()) when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberFan" <> showNodeId subscribed <> " done" SubscriberHold _ -> return () SubscriberSwitch subscribed -> do when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed oldHeight <- readIORef $ switchSubscribedHeight subscribed when (oldHeight /= invalidHeight) $ do writeIORef (switchSubscribedHeight subscribed) $ invalidHeight mapM_ invalidateSubscriberHeight =<< readIORef (switchSubscribedSubscribers subscribed) when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed <> " done" SubscriberCoincidenceOuter subscribed -> do when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed invalidateCoincidenceHeight subscribed when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed <> " done" SubscriberCoincidenceInner subscribed -> do when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed invalidateCoincidenceHeight subscribed when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed <> " done" invalidateCoincidenceHeight :: CoincidenceSubscribed a -> IO () invalidateCoincidenceHeight subscribed = do oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed when (oldHeight /= invalidHeight) $ do writeIORef (coincidenceSubscribedHeight subscribed) $ invalidHeight mapM_ invalidateSubscriberHeight =<< readIORef (coincidenceSubscribedSubscribers subscribed) --TODO: The recalculation algorithm seems a bit funky; make sure it doesn't miss stuff or hit stuff twice; also, it should probably be lazy recalculateSubscriberHeight :: WeakSubscriber a -> IO () recalculateSubscriberHeight ws = do ms <- deRefWeakSubscriber ws case ms of Nothing -> return () --TODO: cleanup? Just s -> case s of SubscriberPush _ subscribed -> do when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberPush" <> showNodeId subscribed mapM_ recalculateSubscriberHeight =<< readIORef (pushSubscribedSubscribers subscribed) when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberPush" <> showNodeId subscribed <> " done" SubscriberMerge _ subscribed -> do when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberMerge" <> showNodeId subscribed oldHeight <- readIORef $ mergeSubscribedHeight subscribed when (oldHeight == invalidHeight) $ do height <- calculateMergeHeight subscribed when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: height: " <> show height when (height /= invalidHeight) $ do -- If height == invalidHeight, that means some of the prereqs have not yet been recomputed; when they do recompute, they'll catch this node again --TODO: this is O(n*m), where n is the number of children of this noe and m is the number that have been invalidated writeIORef (mergeSubscribedHeight subscribed) height mapM_ recalculateSubscriberHeight =<< readIORef (mergeSubscribedSubscribers subscribed) when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberMerge" <> showNodeId subscribed <> " done" SubscriberFan subscribed -> do when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberFan" <> showNodeId subscribed subscribers <- readIORef $ fanSubscribedSubscribers subscribed forM_ (DMap.toList subscribers) $ ((\(FanSubscriberKey _ :=> v) -> mapM_ recalculateSubscriberHeight v) :: DSum (FanSubscriberKey k) -> IO ()) when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberFan" <> showNodeId subscribed <> " done" SubscriberHold _ -> return () SubscriberSwitch subscribed -> do when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed oldHeight <- readIORef $ switchSubscribedHeight subscribed when (oldHeight == invalidHeight) $ do height <- calculateSwitchHeight subscribed when (height /= invalidHeight) $ do writeIORef (switchSubscribedHeight subscribed) height mapM_ recalculateSubscriberHeight =<< readIORef (switchSubscribedSubscribers subscribed) when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed <> " done" SubscriberCoincidenceOuter subscribed -> do when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed void $ recalculateCoincidenceHeight subscribed when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed <> " done" SubscriberCoincidenceInner subscribed -> do when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed void $ recalculateCoincidenceHeight subscribed when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed <> " done" recalculateCoincidenceHeight :: CoincidenceSubscribed a -> IO () recalculateCoincidenceHeight subscribed = do oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed when (oldHeight == invalidHeight) $ do height <- calculateCoincidenceHeight subscribed when (height /= invalidHeight) $ do writeIORef (coincidenceSubscribedHeight subscribed) height mapM_ recalculateSubscriberHeight =<< readIORef (coincidenceSubscribedSubscribers subscribed) --TODO: This should probably be mandatory, just like with the merge and switch ones calculateMergeHeight :: MergeSubscribed k -> IO Int calculateMergeHeight subscribed = if DMap.null (mergeSubscribedParents subscribed) then return 0 else do heights <- forM (DMap.toList $ mergeSubscribedParents subscribed) $ \(WrapArg _ :=> es) -> do readIORef $ eventSubscribedHeightRef es return $ if any (== invalidHeight) heights then invalidHeight else succ $ Prelude.maximum heights --TODO: Replace 'any' with invalidHeight-preserving 'maximum' calculateSwitchHeight :: SwitchSubscribed a -> IO Int calculateSwitchHeight subscribed = readIORef . eventSubscribedHeightRef =<< readIORef (switchSubscribedCurrentParent subscribed) calculateCoincidenceHeight :: CoincidenceSubscribed a -> IO Int calculateCoincidenceHeight subscribed = do outerHeight <- readIORef $ eventSubscribedHeightRef $ coincidenceSubscribedOuterParent subscribed innerHeight <- maybe (return 0) (readIORef . eventSubscribedHeightRef) =<< readIORef (coincidenceSubscribedInnerParent subscribed) return $ if outerHeight == invalidHeight || innerHeight == invalidHeight then invalidHeight else max outerHeight innerHeight {- recalculateEventSubscribedHeight :: EventSubscribed a -> IO Int recalculateEventSubscribedHeight es = case es of EventSubscribedRoot _ -> return 0 EventSubscribedNever -> return 0 EventSubscribedPush subscribed -> recalculateEventSubscribedHeight $ pushSubscribedParent subscribed EventSubscribedMerge subscribed -> do oldHeight <- readIORef $ mergeSubscribedHeight subscribed if oldHeight /= invalidHeight then return oldHeight else do height <- calculateMergeHeight subscribed writeIORef (mergeSubscribedHeight subscribed) height return height EventSubscribedFan _ subscribed -> recalculateEventSubscribedHeight $ fanSubscribedParent subscribed EventSubscribedSwitch subscribed -> do oldHeight <- readIORef $ switchSubscribedHeight subscribed if oldHeight /= invalidHeight then return oldHeight else do height <- calculateSwitchHeight subscribed writeIORef (switchSubscribedHeight subscribed) height return height EventSubscribedCoincidence subscribed -> recalculateCoincidenceHeight subscribed -} data SomeSwitchSubscribed = forall a. SomeSwitchSubscribed (SwitchSubscribed a) debugInvalidate :: Bool debugInvalidate = False invalidate :: IORef [SomeSwitchSubscribed] -> WeakList Invalidator -> IO (WeakList Invalidator) invalidate toReconnectRef wis = do forM_ wis $ \wi -> do mi <- deRefWeak wi case mi of Nothing -> do when debugInvalidate $ liftIO $ putStrLn "invalidate Dead" return () --TODO: Should we clean this up here? Just i -> do finalize wi -- Once something's invalidated, it doesn't need to hang around; this will change when some things are strict case i of InvalidatorPull p -> do when debugInvalidate $ liftIO $ putStrLn "invalidate Pull" mVal <- readIORef $ pullValue p forM_ mVal $ \val -> do writeIORef (pullValue p) Nothing writeIORef (pullSubscribedInvalidators val) =<< invalidate toReconnectRef =<< readIORef (pullSubscribedInvalidators val) InvalidatorSwitch subscribed -> do when debugInvalidate $ liftIO $ putStrLn "invalidate Switch" modifyIORef' toReconnectRef (SomeSwitchSubscribed subscribed :) return [] -- Since we always finalize everything, always return an empty list --TODO: There are some things that will need to be re-subscribed every time; we should try to avoid finalizing them -------------------------------------------------------------------------------- -- Reflex integration -------------------------------------------------------------------------------- data Spider instance R.Reflex Spider where newtype Behavior Spider a = SpiderBehavior { unSpiderBehavior :: Behavior a } newtype Event Spider a = SpiderEvent { unSpiderEvent :: Event a } type PullM Spider = BehaviorM type PushM Spider = EventM {-# INLINE never #-} {-# INLINE constant #-} never = SpiderEvent EventNever constant = SpiderBehavior . BehaviorConst push f = SpiderEvent. push f . unSpiderEvent pull = SpiderBehavior . pull merge = SpiderEvent . merge . (unsafeCoerce :: DMap (WrapArg (R.Event Spider) k) -> DMap (WrapArg Event k)) fan e = R.EventSelector $ SpiderEvent . select (fan (unSpiderEvent e)) switch = SpiderEvent . switch . (unsafeCoerce :: Behavior (R.Event Spider a) -> Behavior (Event a)) . unSpiderBehavior coincidence = SpiderEvent . coincidence . (unsafeCoerce :: Event (R.Event Spider a) -> Event (Event a)) . unSpiderEvent instance R.MonadSample Spider SpiderHost where {-# INLINE sample #-} sample = SpiderHost . readBehavior . unSpiderBehavior instance R.MonadHold Spider SpiderHost where hold v0 = SpiderHost . liftM SpiderBehavior . runFrame . hold v0 . unSpiderEvent instance R.MonadSample Spider BehaviorM where {-# INLINE sample #-} sample = readBehaviorTracked . unSpiderBehavior instance R.MonadSample Spider EventM where {-# INLINE sample #-} sample = liftIO . readBehavior . unSpiderBehavior instance R.MonadHold Spider EventM where {-# INLINE hold #-} hold v0 e = SpiderBehavior <$> hold v0 (unSpiderEvent e) newtype RootTrigger a = RootTrigger (IORef [WeakSubscriber a], IORef (Maybe a)) instance R.ReflexHost Spider where type EventTrigger Spider = RootTrigger type EventHandle Spider = R.Event Spider type HostFrame Spider = SpiderHostFrame instance R.MonadReadEvent Spider ResultM where {-# INLINE readEvent #-} readEvent = liftM (fmap return) . readEvent . unSpiderEvent --TODO: Can probably get rid of this now that we're not using it for performEvent instance MonadTypedId EventM where type TypedId EventM = TypedId IO {-# INLINE getTypedId #-} getTypedId = do liftIO getTypedId instance MonadRef EventM where type Ref EventM = Ref IO {-# INLINE newRef #-} {-# INLINE readRef #-} {-# INLINE writeRef #-} {-# INLINE atomicModifyRef #-} newRef = liftIO . newRef readRef = liftIO . readRef writeRef r a = liftIO $ writeRef r a atomicModifyRef r f = liftIO $ atomicModifyRef r f newtype SpiderHost a = SpiderHost { runSpiderHost :: IO a } deriving (Functor, Applicative, Monad, MonadFix, MonadIO) newtype SpiderHostFrame a = SpiderHostFrame { runSpiderHostFrame :: EventM a } deriving (Functor, Applicative, Monad, MonadFix, MonadIO) instance R.MonadSample Spider SpiderHostFrame where sample = SpiderHostFrame . R.sample --TODO: This can cause problems with laziness, so we should get rid of it if we can instance R.MonadHold Spider SpiderHostFrame where {-# INLINE hold #-} hold v0 e = SpiderHostFrame $ R.hold v0 e newEventWithTriggerIO f= do occRef <- newIORef Nothing subscribedRef <- newIORef Nothing let !r = Root { rootOccurrence = occRef , rootSubscribed = subscribedRef , rootInit = f } return $ SpiderEvent $ EventRoot r instance R.MonadReflexCreateTrigger Spider SpiderHost where newEventWithTrigger = SpiderHost . newEventWithTriggerIO instance R.MonadReflexCreateTrigger Spider SpiderHostFrame where newEventWithTrigger = SpiderHostFrame . EventM . liftIO . newEventWithTriggerIO instance R.MonadReflexHost Spider SpiderHost where fireEventsAndRead es a = SpiderHost $ run es a subscribeEvent e = SpiderHost $ do _ <- runFrame $ getEventSubscribed $ unSpiderEvent e --TODO: The result of this should actually be used return e runFrame = SpiderHost . runFrame runHostFrame = SpiderHost . runFrame . runSpiderHostFrame instance MonadRef SpiderHost where type Ref SpiderHost = Ref IO newRef = SpiderHost . newRef readRef = SpiderHost . readRef writeRef r = SpiderHost . writeRef r atomicModifyRef r = SpiderHost . atomicModifyRef r instance MonadRef SpiderHostFrame where type Ref SpiderHostFrame = Ref IO newRef = SpiderHostFrame . newRef readRef = SpiderHostFrame . readRef writeRef r = SpiderHostFrame . writeRef r atomicModifyRef r = SpiderHostFrame . atomicModifyRef r
mightybyte/reflex
src/Reflex/Spider/Internal.hs
bsd-3-clause
65,149
0
37
13,876
15,722
7,642
8,080
-1
-1
{- | A simple priority channel, essentially a priority queue where the producers and consumers are in different threads. A priority channel is unbounded. Instead of reading elements in FIFO order, the consumer reads the lowest-priority element that is currently available, blocking if there are no elements. The interface here is tiny, confined just to uses envisioned in this package. This module should be imported qualified to avoid name clashes. -} module Network.SPDY.Internal.PriorityChan (PriorityChan, newChan, send, receive) where import qualified Control.Concurrent.MSem as MSem import Control.Exception (mask_) import Data.IORef (IORef, newIORef, atomicModifyIORef) import qualified Data.PriorityQueue.FingerTree as FT data PriorityChan p a = PriorityChan { pcSem :: MSem.MSem Int, -- ^ A semaphore that has credits as long as the queue is non-empty. pcIORef :: IORef (FT.PQueue p a) -- ^ The underlying priority queue. } -- | Creates a new, empty priority channel. newChan :: Ord p => IO (PriorityChan p a) newChan = do sem <- MSem.new 0 ref <- newIORef (FT.empty) return PriorityChan { pcSem = sem, pcIORef = ref } -- | Sends an element with a given priority on the channel. The new -- element will appear after all those of lower or equal priority that -- have yet to be received by a consumer. send :: Ord p => p -> a -> PriorityChan p a -> IO () send p x pq = -- note that we force evaluation of the new priority queue in this -- thread mask_ $ do atomicModifyIORef (pcIORef pq) $ \ftpq -> let ftpq' = FT.add p x ftpq in ftpq' `seq` (ftpq', ()) MSem.signal (pcSem pq) -- | Receives the minimum-priority element from the channel, blocking -- until one is available. receive :: Ord p => PriorityChan p a -> IO a receive pq = mask_ (do MSem.wait (pcSem pq) atomicModifyIORef (pcIORef pq) $ \ftpq -> maybe (ftpq, Nothing) (\(x, ftpq') -> (ftpq', Just x)) (FT.minView ftpq)) >>= maybe (error "Didn't block when receiving on an empty priority channel.") return
kcharter/spdy-base
src/Network/SPDY/Internal/PriorityChan.hs
bsd-3-clause
2,190
0
16
550
444
240
204
27
1
module HCSV.Version ( version ) where import Data.List import Data.Version (Version(..)) import qualified Paths_hcsv as P -- | Turn the Cabal-generated Version into a String of the normal form. version :: String version = number++(if null tag then "" else "-" ++ tag) where number = concat $ intersperse "." $ map show $ versionBranch P.version tag = concat $ intersperse "-" $ versionTags P.version
thsutton/hcsv
src/HCSV/Version.hs
bsd-3-clause
433
0
10
98
120
67
53
8
2
module Main where import XMPP import MUC import Translate import Network import Control.Monad import Data.HashTable import List import System.Random import System ( getArgs ) import System.IO usage = "Usage: werewolf user@server [password]" main = withSocketsDo $ do args <- getArgs (username, server, password) <- case args of [us, pwd] -> case break (=='@') us of (u@(_:_), ('@':s)) -> return (u, s, pwd) _ -> error usage [us] -> case break (=='@') us of (u@(_:_), ('@':s)) -> do putStr $ "Password for "++us++": " hFlush stdout hSetEcho stdin False pwd <- getLine hSetEcho stdin True return (u, s, pwd) _ -> error usage _ -> error usage c <- openStream server getStreamStart c runXMPP c $ do startAuth username server password sendPresence handleVersion "Werewolf Bot" "0.1" "HaskellOS" werewolf closeConnection c werewolf :: XMPP () werewolf = do addHandler (isChat `conj` hasBody) listenForJoinRequest True findLanguage :: String -> IO Language findLanguage "sv" = loadLanguage "werewolf.txt.sv" findLanguage "eo" = loadLanguage "werewolf.txt.eo" findLanguage _ = nullLanguage listenForJoinRequest :: XMLElem -> XMPP () listenForJoinRequest msg = do let sender = maybe "" id (getAttr "from" msg) text = maybe "" id (getMessageBody msg) case words text of ["join",langname,room] -> do lang <- liftIO $ findLanguage langname t' <- liftIO $ (translate lang "Joining room ") sendMessage sender (t' ++ room) nick <- liftIO $ (translate lang "werewolfbot") result <- joinGroupchat nick room case result of Nothing -> do t <- liftIO $ translate lang "Error when joining room" sendMessage sender t Just participantList -> inRoom lang nick room participantList _ -> sendMessage sender "I am a werewolf bot. Type 'join lang room@server'." inRoom lang nick room participantList = do t <- liftIO $ (translate lang "Hi, I am the werewolf bot.") sendGroupchatMessage room t gameTable <- liftIO $ new (==) hashString t <- liftIO $ translate lang "To join the game, send 'join' to me privately. List participants with 'who' in public. To start the game, say 'start' in public." sendGroupchatMessage room t beforeGame lang nick room participantList gameTable data PlayerState = Werewolf | Villager deriving (Show, Eq) translateState :: Language -> PlayerState -> IO String translateState lang state = translate lang $ case state of Werewolf -> "werewolf" Villager -> "villager" beforeGame lang nick room participantList gameTable = do msg <- waitForStanza $ matchesBare room `conj` hasBody let sender = maybe "" id (getAttr "from" msg) nick = getResource sender msgtype = maybe "" id (getAttr "type" msg) body = maybe "" id $ getMessageBody msg start <- case msgtype of "chat" -> case body of "join" -> do t <- liftIO $ translate lang " has joined the game." sendGroupchatMessage room (nick ++ t) liftIO $ update gameTable nick Villager return False _ -> do t <- liftIO $ translate lang "You probably meant 'join'." sendGroupchatPrivateMessage nick room t return False "groupchat" -> case body of "who" -> do entries <- liftIO $ toList gameTable t <- case entries of [] -> liftIO $ translate lang "No players yet." _ -> return (unwords $ map fst entries) sendGroupchatMessage room t return False "start" -> do n <- liftIO $ (liftM length) $ toList gameTable if n > 3 then return True else do t <- liftIO $ translate lang "Not enough players." sendGroupchatMessage room t return False _ -> return False _ -> return False if start then startGame lang nick room participantList gameTable else beforeGame lang nick room participantList gameTable startGame :: Language -> String -> String -> (IO [String]) -> HashTable String PlayerState -> XMPP () startGame lang nick room participantList gameTable = do entries <- liftIO $ toList gameTable let nicks = map fst entries nPlayers = length nicks nWerewolves = if nPlayers < 6 then 1 else if nPlayers < 10 then 2 else 3 werewolves <- liftIO $ pickWerewolves nWerewolves nicks --liftIO $ mapM_ (\nick -> update gameTable nick Werewolf) werewolves t <- liftIO $ translate lang "The game is starting. Some of you are werewolves, and some of you are villagers. The werewolves try to kill all the villagers during the night, while the villagers try to execute all the werewolves during the day." sendGroupchatMessage room t mapM_ (\nick -> do t <- liftIO $ translate lang "You are a werewolf. " t' <- case nWerewolves of 1 -> liftIO $ translate lang "There are no other werewolves." _ -> do t'' <- liftIO $ translate lang "The other werewolves are: " return $ t'' ++ unwords (werewolves \\ [nick]) sendGroupchatPrivateMessage nick room (t++t')) werewolves mapM_ (\nick -> do t <- liftIO $ translate lang "You are a villager." sendGroupchatPrivateMessage nick room t) (nicks \\ werewolves) startNight lang nick room participantList werewolves (nicks \\ werewolves) where pickWerewolves :: Int -> [String] -> IO [String] pickWerewolves 0 _ = return [] pickWerewolves n [] = return [] pickWerewolves n nicks = do which <- randomRIO (0,length nicks - 1) let w = nicks !! which rest = nicks \\ [w] ws <- pickWerewolves (n-1) rest return (w:ws) checkVictory [] villagers = Just Villager checkVictory werewolves [] = Just Werewolf checkVictory _ _ = Nothing startNight lang nick room participantList werewolves villagers = do case checkVictory werewolves villagers of Just x -> do t <- liftIO $ translate lang "As the sun sets over the little village, the people realize that there is only one side left. " t' <- liftIO $ translate lang $ case x of Villager -> "The villagers have won!" Werewolf -> "The werewolves have won!" sendGroupchatMessage room (t++t') inRoom lang nick room participantList Nothing -> do t <- liftIO $ translate lang "The villagers, tired after the hard work in the fields, go to bed, and the sun sets. But in the middle of the night, the werewolves wake up!" sendGroupchatMessage room t mapM_ (\nick -> do t <- liftIO $ translate lang "You and the other werewolves vote for a villager to kill by typing 'kill NICK' to me." sendGroupchatPrivateMessage nick room t) werewolves werewolvesChoosing lang nick room participantList werewolves villagers [] werewolvesChoosing :: Language -> String -> String -> (IO [String]) -> [String] -> [String] -> [(String,String)] -> XMPP () werewolvesChoosing lang nick room participantList werewolves villagers choices = do case (werewolves \\ map fst choices, nub (map snd choices)) of -- all werewolves have voted for the same victim. ([], [victim]) -> do t <- liftIO $ translate lang "A scream of pain and agony is heard!" sendGroupchatMessage room t t <- liftIO $ translate lang " has been devoured by the werewolves." sendGroupchatMessage room (victim++t) startDay lang nick room participantList werewolves (villagers \\ [victim]) _ -> do stanza <- waitForStanza $ isGroupchatPrivmsg room `conj` hasBody let sendernick = getResource $ maybe "" id (getAttr "from" stanza) msg = maybe "" id (getMessageBody stanza) if (sendernick `notElem` werewolves) then do t <- liftIO $ translate lang "You are not a werewolf. You are supposed to be sleeping!" sendGroupchatPrivateMessage sendernick room t retry else case msg of 'w':'h':'o':_ -> do t1 <- liftIO $ translate lang "Werewolves:" t2 <- liftIO $ translate lang "Villagers:" t3 <- liftIO $ translate lang "Votes:" t4 <- liftIO $ translate lang "Noone has voted yet." t5 <- liftIO $ translate lang " has voted to kill " let t = t1 ++ "\n" ++ concat (map (++" ") werewolves) ++ t2 ++ "\n" ++ concat (map (++" ") villagers) ++ t3 ++ "\n" ++ case choices of [] -> t4 _ -> concat (map (\(who,whom) -> who ++ t5 ++ whom ++ "\n") choices) sendGroupchatPrivateMessage sendernick room t retry 'k':'i':'l':'l':' ':victim -> if victim `notElem` villagers then do t <- liftIO $ translate lang " is not a villager." sendGroupchatPrivateMessage sendernick room (victim ++ t) retry else do t <- liftIO $ translate lang " has voted to kill " mapM_ (\nick -> sendGroupchatPrivateMessage nick room (sendernick++t++victim)) (werewolves \\ [sendernick]) let choices' = (sendernick, victim):(filter ((/=sendernick).fst) choices) werewolvesChoosing lang nick room participantList werewolves villagers choices' _ -> do t <- liftIO $ translate lang "I don't understand that." sendGroupchatPrivateMessage sendernick room t retry where retry = werewolvesChoosing lang nick room participantList werewolves villagers choices startDay lang nick room participantList werewolves villagers = do case checkVictory werewolves villagers of Just x -> do t <- liftIO $ translate lang "As the sun rises over the little village, the people realize that there is only one side left. " t' <- liftIO $ translate lang $ case x of Villager -> "The villagers have won!" Werewolf -> "The werewolves have won!" sendGroupchatMessage room (t++t') inRoom lang nick room participantList Nothing -> do t <- liftIO $ translate lang "The villagers are outraged over this crime, and want to execute somebody. They gather in the town square to vote about whom to kill. Type 'kill NICK' in public to vote." sendGroupchatMessage room t executionVote lang nick room participantList werewolves villagers [] executionVote lang nick room participantList werewolves villagers choices = do let candidates = nub (map snd choices) candidatesVotes = map (\nick -> (nick, length (filter ((==nick).snd) choices))) candidates candidatesVotesSorted = sortBy (comparing ((0-).snd)) candidatesVotes result = case candidatesVotesSorted of (votedfor, nVotes):_ -> -- majority? if nVotes > ((length werewolves + length villagers) `div` 2) then Just votedfor else Nothing _ -> Nothing case result of Just votedfor -> do t <- liftIO $ translate lang "The villagers have chosen by simple majority to execute " sendGroupchatMessage room (t++votedfor) startNight lang nick room participantList (werewolves \\ [votedfor]) (villagers \\ [votedfor]) Nothing -> if length choices == length werewolves + length villagers then do t <- liftIO $ translate lang "All villagers have cast their vote, but no majority has been reached. The disgruntled villagers go home." sendGroupchatMessage room t startNight lang nick room participantList werewolves villagers else do stanza <- waitForStanza $ matchesBare room `conj` isGroupchatMessage `conj` hasBody let sendernick = getResource $ maybe "" id (getAttr "from" stanza) msg = maybe "" id (getMessageBody stanza) case msg of 'w':'h':'o':_ -> do t1 <- liftIO $ translate lang "Villagers:" t2 <- liftIO $ translate lang "Votes:" t3 <- liftIO $ translate lang "Noone has voted yet." t4 <- liftIO $ translate lang " has voted to kill " let t = t1 ++ "\n" ++ concat (map (++"\n") (sort (werewolves ++ villagers))) ++ t2 ++ "\n" ++ case choices of [] -> t3 _ -> concat (map (\(who,whom) -> who ++ t4 ++ whom ++ "\n") choices) sendGroupchatMessage room t retry 'k':'i':'l':'l':' ':whom -> if sendernick `notElem` werewolves && sendernick `notElem` villagers then do t <- liftIO $ translate lang ": You are not entitled to vote." sendGroupchatMessage room (sendernick++t) retry else if whom `notElem` werewolves && whom `notElem` villagers then do t <- liftIO $ translate lang " is not a villager." sendGroupchatMessage room (whom++t) retry else do t <- liftIO $ translate lang " has voted to kill " sendGroupchatMessage room (sendernick++t++whom) let choices' = (sendernick, whom):(filter ((/=sendernick) . fst) choices) executionVote lang nick room participantList werewolves villagers choices' "status" -> do sendGroupchatMessage room $ "Vote status: " ++ show choices retry _ -> retry where retry = executionVote lang nick room participantList werewolves villagers choices comparing :: Ord b => (a -> b) -> a -> a -> Ordering comparing p x y = compare (p x) (p y)
legoscia/hsxmpp
Werewolf.hs
bsd-3-clause
17,069
0
32
7,296
3,974
1,925
2,049
341
11
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} module FullSimple (TmUnit(..), TyUnit(..), TmAscribe(..), TmTag(..), TyVariant(..), TmFix(..), TmCase(..), TyVar(..), TyString) where import Lib import Text.Parsec hiding (runP) import Text.PrettyPrint hiding (char, space) -- TmUnit data TmUnit e = TmUnit deriving (Functor, Show) parseTmUnit :: NewParser TmUnit fs parseTmUnit e _ = keyword "unit" >> return (In e TmUnit) instance Syntax TmUnit where keywords _ = ["unit"] parseF = parseTmUnit prettyF _ TmUnit = "unit" -- TyUnit data TyUnit e = TyUnit deriving (Functor, Show) parseTyUnit :: NewParser TyUnit fs parseTyUnit e _ = keyword "Unit" >> return (In e TyUnit) instance Syntax TyUnit where keywords _ = ["Unit"] parseF = parseTyUnit prettyF _ TyUnit = "Unit" -- TmAscribe data TmAscribe e = TmAscribe e e deriving (Functor, Show) parseTmAscribe :: NewParser TmAscribe fs parseTmAscribe e p = chainlR (keyword "as" >> p) TmAscribe e p instance Syntax TmAscribe where keywords _ = ["as"] parseF = parseTmAscribe prettyF r (TmAscribe e t) = parens $ r e <+> "as" <+> r t -- TmTag data TmTag e = TmTag String e e deriving (Functor, Show) parseTmTag :: NewParser TmTag fs parseTmTag e p = do keyword "<" l <- parseWord keyword "=" expr <- p keyword ">" keyword "as" typ <- p return $ In e (TmTag l expr typ) instance Syntax TmTag where keywords _ = ["as"] parseF = parseTmTag prettyF r (TmTag l e t) = parens $ "<" <> text l <> "=" <> r e <> ">" <+> "as" <+> r t -- TyVariant data TyVariant e = TyVariant [(String, e)] deriving (Functor, Show) parseTyVariant :: NewParser TyVariant fs parseTyVariant e p = do keyword "<" fs <- pf keyword ">" return $ In e (TyVariant fs) where pf = p1 `sepBy1` keyword "," p1 = do l <- parseWord keyword ":" t <- p return (l, t) instance Syntax TyVariant where parseF = parseTyVariant prettyF r (TyVariant fs) = let gs = map (\(l, t) -> text l <> colon <> r t) fs in "<" <> foldl1 (\a b -> a <> comma <+> b) gs <> ">" -- TmFix data TmFix e = TmFix e deriving (Functor, Show) parseTmFix :: NewParser TmFix fs parseTmFix e p = do keyword "fix" expr <- p return $ In e (TmFix expr) instance Syntax TmFix where keywords _ = ["fix"] parseF = parseTmFix prettyF r (TmFix e) = "fix" <+> parens (r e) -- TmCase data TmCase e = TmCase e [(String, String, e)] deriving (Functor, Show) parseTmCase :: NewParser TmCase fs parseTmCase e p = do keyword "case" expr <- p keyword "of" cs <- pCases return $ In e (TmCase expr cs) where pCases = pCase `sepBy1` keyword "|" pCase = do keyword "<" l <- parseWord keyword "=" x <- parseWord keyword ">" keyword "=>" r <- p return (l, x, r) instance Syntax TmCase where keywords _ = ["case", "of"] parseF = parseTmCase prettyF r (TmCase expr cs) = let gs = map (\(l, x, e) -> "<" <> text l <> "=" <> text x <> ">" <+> "=>" <+> r e) cs in "case" <+> r expr <+> "of" <+> foldl1 (\x y -> x <+> "|" <+> y) gs -- TyVar data TyVar e = TyVar String deriving (Functor, Show) parseTyVar :: NewParser TyVar fs parseTyVar e _ = do w <- parseWordUpper return $ In e (TyVar w) instance Syntax TyVar where parseF = parseTyVar prettyF _ (TyVar v) = text v -- TyString data TyString e = TyString deriving (Functor, Show) parseTyString :: NewParser TyString fs parseTyString e _ = keyword "String" >> return (In e TyString) instance Syntax TyString where keywords _ = ["String"] parseF = parseTyString prettyF _ TyString = "String"
hy-zhang/parser
Haskell/src/FullSimple.hs
bsd-3-clause
4,194
0
19
1,252
1,496
771
725
123
1
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. {-# LANGUAGE GADTs #-} {-# LANGUAGE OverloadedStrings #-} module Duckling.Ordinal.JA.Rules ( rules ) where import Prelude import Data.String import Duckling.Dimensions.Types import Duckling.Numeral.Types (NumeralData (..)) import qualified Duckling.Numeral.Types as TNumeral import Duckling.Ordinal.Helpers import Duckling.Types ruleOrdinalDigits :: Rule ruleOrdinalDigits = Rule { name = "ordinal (digits)" , pattern = [ regex "第" , dimension Numeral ] , prod = \tokens -> case tokens of (_:Token Numeral NumeralData{TNumeral.value = v}:_) -> Just . ordinal $ floor v _ -> Nothing } rules :: [Rule] rules = [ ruleOrdinalDigits ]
facebookincubator/duckling
Duckling/Ordinal/JA/Rules.hs
bsd-3-clause
890
0
17
174
186
114
72
24
2
{-# Language PatternGuards #-} module Blub ( blub , foo , bar ) where import Control.Applicative (r, t, z) import Ugah.Blub ( a , b , c ) import Data.Text as T import Data.Text hiding (Text(A, B, C)) f :: Int -> Int f = (+ 3) r :: Int -> Int r =
dan-t/hsimport
tests/goldenFiles/SymbolTest40.hs
bsd-3-clause
274
1
7
82
104
68
36
-1
-1
module Control.Monad.Trans.Stitch ( StitchT(..) , runStitchT ) where import Stitch.Types import Control.Applicative import Control.Monad.IO.Class import Control.Monad.Trans.Class import Control.Monad.Trans.Writer.Strict import Data.Monoid newtype StitchT m a = StitchT (WriterT Block m a) deriving (Functor, Applicative, Monad, Alternative, MonadIO, MonadTrans) instance (Applicative m, Monoid a) => Monoid (StitchT m a) where mempty = pure mempty a `mappend` b = mappend <$> a <*> b runStitchT :: Monad m => StitchT m a -> m (a, Block) runStitchT (StitchT x) = runWriterT x
bitemyapp/stitch
src/Control/Monad/Trans/Stitch.hs
bsd-3-clause
590
0
8
94
211
119
92
16
1
module Main where import Criterion.Main import ArbitraryLambda import Test.QuickCheck.Gen import Test.QuickCheck.Random import NFDataInstances() import PrettyPrint import Parser import BruijnTerm import TypeCheck import MakeTerm import ExampleBruijn (pair) fixandsized :: Int -> Gen a -> IO a fixandsized size (MkGen g) = return (g fixedseed size) where fixedseed = QCGen (mkTheGen 0) untypeString:: Int -> IO String untypeString size = fmap PrettyPrint.pShow (fixandsized size genUnTyped) typedAST :: Int -> IO (BruijnTerm () ()) typedAST size = fixandsized size (genTyped defaultConf) main :: IO() main = defaultMain [ bgroup "parser" [ env (untypeString 100) $ \str -> bench "random 100" (nf parseString str) , env (untypeString 10000) $ \str -> bench "random 10000" (nf parseString str) ] , bgroup "TypeCheck" [ env (typedAST 100) $ \ast -> bench "random 100" (nf solver ast) , env (typedAST 10000) $ \ast -> bench "random 10000" (nf solver ast) , bench "dub dub ... " $ nf solver (mkLet [("duplicate",lambda "a" $ appl (appl pair (bvar 0)) (bvar 0))] ( foldr1 appl (replicate 12 (bvar 0) ))) ] ]
kwibus/myLang
tests/bench/benchmark.hs
bsd-3-clause
1,152
0
20
224
449
231
218
28
1
{-# LANGUAGE ScopedTypeVariables, DeriveDataTypeable, OverloadedStrings, FlexibleInstances, FlexibleContexts, IncoherentInstances, TypeFamilies, ExistentialQuantification, RankNTypes, ImpredicativeTypes #-} {-# OPTIONS_GHC -fno-warn-orphans #-} -- | A module for shell-like programming in Haskell. -- Shelly's focus is entirely on ease of use for those coming from shell scripting. -- However, it also tries to use modern libraries and techniques to keep things efficient. -- -- The functionality provided by -- this module is (unlike standard Haskell filesystem functionality) -- thread-safe: each Sh maintains its own environment and its own working -- directory. -- -- Recommended usage includes putting the following at the top of your program, -- otherwise you will likely need either type annotations or type conversions -- -- > {-# LANGUAGE OverloadedStrings #-} -- > {-# LANGUAGE ExtendedDefaultRules #-} -- > {-# OPTIONS_GHC -fno-warn-type-defaults #-} -- > import Shelly -- > import qualified Data.Text as T -- > default (T.Text) module Shelly.Lifted ( MonadSh(..), MonadShControl(..), -- This is copied from Shelly.hs, so that we are sure to export the -- exact same set of symbols. Whenever that export list is updated, -- please make the same updates here and implements the corresponding -- lifted functions. -- * Entering Sh. Sh, ShIO, S.shelly, S.shellyNoDir, S.shellyFailDir, sub , silently, verbosely, escaping, print_stdout, print_stderr, print_commands , tracing, errExit , log_stdout_with, log_stderr_with -- * Running external commands. , run, run_, runFoldLines, S.cmd, S.FoldCallback , (-|-), lastStderr, setStdin, lastExitCode , command, command_, command1, command1_ , sshPairs, sshPairs_ , S.ShellCmd(..), S.CmdArg (..) -- * Running commands Using handles , runHandle, runHandles, transferLinesAndCombine, S.transferFoldHandleLines , S.StdHandle(..), S.StdStream(..) -- * Modifying and querying environment. , setenv, get_env, get_env_text, get_env_all, appendToPath -- * Environment directory , cd, chdir, chdir_p, pwd -- * Printing , echo, echo_n, echo_err, echo_n_err, inspect, inspect_err , tag, trace, S.show_command -- * Querying filesystem. , ls, lsT, test_e, test_f, test_d, test_s, test_px, which -- * Filename helpers , absPath, (S.</>), (S.<.>), canonic, canonicalize, relPath, relativeTo , S.hasExt -- * Manipulating filesystem. , mv, rm, rm_f, rm_rf, cp, cp_r, mkdir, mkdir_p, mkdirTree -- * reading/writing Files , readfile, readBinary, writefile, appendfile, touchfile, withTmpDir -- * exiting the program , exit, errorExit, quietExit, terror -- * Exceptions , bracket_sh, catchany, catch_sh, handle_sh, handleany_sh, finally_sh, catches_sh, catchany_sh -- * convert between Text and FilePath , S.toTextIgnore, toTextWarn, FP.fromText -- * Utility Functions , S.whenM, S.unlessM, time, sleep -- * Re-exported for your convenience , liftIO, S.when, S.unless, FilePath, (S.<$>) -- * internal functions for writing extensions , Shelly.Lifted.get, Shelly.Lifted.put -- * find functions , S.find, S.findWhen, S.findFold, S.findDirFilter, S.findDirFilterWhen, S.findFoldDirFilter ) where import qualified Shelly as S import Shelly.Base (Sh(..), ShIO, Text, (>=>), FilePath) import qualified Shelly.Base as S import Control.Monad ( liftM ) import Prelude hiding ( FilePath ) import Data.ByteString ( ByteString ) import Data.Monoid import System.IO ( Handle ) import Data.Tree ( Tree ) import qualified Filesystem.Path.CurrentOS as FP import Control.Exception.Lifted import Control.Exception.Enclosed import Control.Monad.IO.Class import Control.Monad.Trans.Control import Control.Monad.Trans.Identity import Control.Monad.Trans.List import Control.Monad.Trans.Maybe import Control.Monad.Trans.Cont import Control.Monad.Trans.Error import Control.Monad.Trans.Reader import Control.Monad.Trans.State import qualified Control.Monad.Trans.State.Strict as Strict import Control.Monad.Trans.Writer import qualified Control.Monad.Trans.Writer.Strict as Strict import qualified Control.Monad.Trans.RWS as RWS import qualified Control.Monad.Trans.RWS.Strict as Strict class Monad m => MonadSh m where liftSh :: Sh a -> m a instance MonadSh Sh where liftSh = id instance MonadSh m => MonadSh (IdentityT m) where liftSh = IdentityT . liftSh instance MonadSh m => MonadSh (ListT m) where liftSh m = ListT $ do a <- liftSh m return [a] instance MonadSh m => MonadSh (MaybeT m) where liftSh = MaybeT . liftM Just . liftSh instance MonadSh m => MonadSh (ContT r m) where liftSh m = ContT (liftSh m >>=) instance (Error e, MonadSh m) => MonadSh (ErrorT e m) where liftSh m = ErrorT $ do a <- liftSh m return (Right a) instance MonadSh m => MonadSh (ReaderT r m) where liftSh = ReaderT . const . liftSh instance MonadSh m => MonadSh (StateT s m) where liftSh m = StateT $ \s -> do a <- liftSh m return (a, s) instance MonadSh m => MonadSh (Strict.StateT s m) where liftSh m = Strict.StateT $ \s -> do a <- liftSh m return (a, s) instance (Monoid w, MonadSh m) => MonadSh (WriterT w m) where liftSh m = WriterT $ do a <- liftSh m return (a, mempty) instance (Monoid w, MonadSh m) => MonadSh (Strict.WriterT w m) where liftSh m = Strict.WriterT $ do a <- liftSh m return (a, mempty) instance (Monoid w, MonadSh m) => MonadSh (RWS.RWST r w s m) where liftSh m = RWS.RWST $ \_ s -> do a <- liftSh m return (a, s, mempty) instance (Monoid w, MonadSh m) => MonadSh (Strict.RWST r w s m) where liftSh m = Strict.RWST $ \_ s -> do a <- liftSh m return (a, s, mempty) instance MonadSh m => S.ShellCmd (m Text) where cmdAll = (liftSh .) . S.run instance (MonadSh m, s ~ Text, Show s) => S.ShellCmd (m s) where cmdAll = (liftSh .) . S.run instance MonadSh m => S.ShellCmd (m ()) where cmdAll = (liftSh .) . S.run_ class Monad m => MonadShControl m where data ShM m a :: * liftShWith :: ((forall x. m x -> Sh (ShM m x)) -> Sh a) -> m a restoreSh :: ShM m a -> m a instance MonadShControl Sh where newtype ShM Sh a = ShSh a liftShWith f = f $ liftM ShSh restoreSh (ShSh x) = return x {-# INLINE liftShWith #-} {-# INLINE restoreSh #-} instance MonadShControl m => MonadShControl (ListT m) where newtype ShM (ListT m) a = ListTShM (ShM m [a]) liftShWith f = ListT $ liftM return $ liftShWith $ \runInSh -> f $ \k -> liftM ListTShM $ runInSh $ runListT k restoreSh (ListTShM m) = ListT . restoreSh $ m {-# INLINE liftShWith #-} {-# INLINE restoreSh #-} instance MonadShControl m => MonadShControl (MaybeT m) where newtype ShM (MaybeT m) a = MaybeTShM (ShM m (Maybe a)) liftShWith f = MaybeT $ liftM return $ liftShWith $ \runInSh -> f $ \k -> liftM MaybeTShM $ runInSh $ runMaybeT k restoreSh (MaybeTShM m) = MaybeT . restoreSh $ m {-# INLINE liftShWith #-} {-# INLINE restoreSh #-} instance MonadShControl m => MonadShControl (IdentityT m) where newtype ShM (IdentityT m) a = IdentityTShM (ShM m a) liftShWith f = IdentityT $ liftM id $ liftShWith $ \runInSh -> f $ \k -> liftM IdentityTShM $ runInSh $ runIdentityT k restoreSh (IdentityTShM m) = IdentityT . restoreSh $ m {-# INLINE liftShWith #-} {-# INLINE restoreSh #-} instance (MonadShControl m, Monoid w) => MonadShControl (WriterT w m) where newtype ShM (WriterT w m) a = WriterTShM (ShM m (a, w)) liftShWith f = WriterT $ liftM (\x -> (x, mempty)) $ liftShWith $ \runInSh -> f $ \k -> liftM WriterTShM $ runInSh $ runWriterT k restoreSh (WriterTShM m) = WriterT . restoreSh $ m {-# INLINE liftShWith #-} {-# INLINE restoreSh #-} instance (MonadShControl m, Monoid w) => MonadShControl (Strict.WriterT w m) where newtype ShM (Strict.WriterT w m) a = StWriterTShM (ShM m (a, w)) liftShWith f = Strict.WriterT $ liftM (\x -> (x, mempty)) $ liftShWith $ \runInSh -> f $ \k -> liftM StWriterTShM $ runInSh $ Strict.runWriterT k restoreSh (StWriterTShM m) = Strict.WriterT . restoreSh $ m {-# INLINE liftShWith #-} {-# INLINE restoreSh #-} instance (MonadShControl m, Error e) => MonadShControl (ErrorT e m) where newtype ShM (ErrorT e m) a = ErrorTShM (ShM m (Either e a)) liftShWith f = ErrorT $ liftM return $ liftShWith $ \runInSh -> f $ \k -> liftM ErrorTShM $ runInSh $ runErrorT k restoreSh (ErrorTShM m) = ErrorT . restoreSh $ m {-# INLINE liftShWith #-} {-# INLINE restoreSh #-} instance MonadShControl m => MonadShControl (StateT s m) where newtype ShM (StateT s m) a = StateTShM (ShM m (a, s)) liftShWith f = StateT $ \s -> liftM (\x -> (x,s)) $ liftShWith $ \runInSh -> f $ \k -> liftM StateTShM $ runInSh $ runStateT k s restoreSh (StateTShM m) = StateT . const . restoreSh $ m {-# INLINE liftShWith #-} {-# INLINE restoreSh #-} instance MonadShControl m => MonadShControl (Strict.StateT s m) where newtype ShM (Strict.StateT s m) a = StStateTShM (ShM m (a, s)) liftShWith f = Strict.StateT $ \s -> liftM (\x -> (x,s)) $ liftShWith $ \runInSh -> f $ \k -> liftM StStateTShM $ runInSh $ Strict.runStateT k s restoreSh (StStateTShM m) = Strict.StateT . const . restoreSh $ m {-# INLINE liftShWith #-} {-# INLINE restoreSh #-} instance MonadShControl m => MonadShControl (ReaderT r m) where newtype ShM (ReaderT r m) a = ReaderTShM (ShM m a) liftShWith f = ReaderT $ \r -> liftM id $ liftShWith $ \runInSh -> f $ \k -> liftM ReaderTShM $ runInSh $ runReaderT k r restoreSh (ReaderTShM m) = ReaderT . const . restoreSh $ m {-# INLINE liftShWith #-} {-# INLINE restoreSh #-} instance (MonadShControl m, Monoid w) => MonadShControl (RWS.RWST r w s m) where newtype ShM (RWS.RWST r w s m) a = RWSTShM (ShM m (a, s ,w)) liftShWith f = RWS.RWST $ \r s -> liftM (\x -> (x,s,mempty)) $ liftShWith $ \runInSh -> f $ \k -> liftM RWSTShM $ runInSh $ RWS.runRWST k r s restoreSh (RWSTShM m) = RWS.RWST . const . const . restoreSh $ m {-# INLINE liftShWith #-} {-# INLINE restoreSh #-} instance (MonadShControl m, Monoid w) => MonadShControl (Strict.RWST r w s m) where newtype ShM (Strict.RWST r w s m) a = StRWSTShM (ShM m (a, s, w)) liftShWith f = Strict.RWST $ \r s -> liftM (\x -> (x,s,mempty)) $ liftShWith $ \runInSh -> f $ \k -> liftM StRWSTShM $ runInSh $ Strict.runRWST k r s restoreSh (StRWSTShM m) = Strict.RWST . const . const . restoreSh $ m {-# INLINE liftShWith #-} {-# INLINE restoreSh #-} controlSh :: MonadShControl m => ((forall x. m x -> Sh (ShM m x)) -> Sh (ShM m a)) -> m a controlSh = liftShWith >=> restoreSh {-# INLINE controlSh #-} tag :: (MonadShControl m, MonadSh m) => m a -> Text -> m a tag action msg = controlSh $ \runInSh -> S.tag (runInSh action) msg chdir :: MonadShControl m => FilePath -> m a -> m a chdir dir action = controlSh $ \runInSh -> S.chdir dir (runInSh action) chdir_p :: MonadShControl m => FilePath -> m a -> m a chdir_p dir action = controlSh $ \runInSh -> S.chdir_p dir (runInSh action) silently :: MonadShControl m => m a -> m a silently a = controlSh $ \runInSh -> S.silently (runInSh a) verbosely :: MonadShControl m => m a -> m a verbosely a = controlSh $ \runInSh -> S.verbosely (runInSh a) log_stdout_with :: MonadShControl m => (Text -> IO ()) -> m a -> m a log_stdout_with logger a = controlSh $ \runInSh -> S.log_stdout_with logger (runInSh a) log_stderr_with :: MonadShControl m => (Text -> IO ()) -> m a -> m a log_stderr_with logger a = controlSh $ \runInSh -> S.log_stderr_with logger (runInSh a) print_stdout :: MonadShControl m => Bool -> m a -> m a print_stdout shouldPrint a = controlSh $ \runInSh -> S.print_stdout shouldPrint (runInSh a) print_stderr :: MonadShControl m => Bool -> m a -> m a print_stderr shouldPrint a = controlSh $ \runInSh -> S.print_stderr shouldPrint (runInSh a) print_commands :: MonadShControl m => Bool -> m a -> m a print_commands shouldPrint a = controlSh $ \runInSh -> S.print_commands shouldPrint (runInSh a) sub :: MonadShControl m => m a -> m a sub a = controlSh $ \runInSh -> S.sub (runInSh a) trace :: MonadSh m => Text -> m () trace = liftSh . S.trace tracing :: MonadShControl m => Bool -> m a -> m a tracing shouldTrace action = controlSh $ \runInSh -> S.tracing shouldTrace (runInSh action) escaping :: MonadShControl m => Bool -> m a -> m a escaping shouldEscape action = controlSh $ \runInSh -> S.escaping shouldEscape (runInSh action) errExit :: MonadShControl m => Bool -> m a -> m a errExit shouldExit action = controlSh $ \runInSh -> S.errExit shouldExit (runInSh action) (-|-) :: (MonadShControl m, MonadSh m) => m Text -> m b -> m b one -|- two = controlSh $ \runInSh -> do x <- runInSh one runInSh $ restoreSh x >>= \x' -> controlSh $ \runInSh' -> return x' S.-|- runInSh' two withTmpDir :: MonadShControl m => (FilePath -> m a) -> m a withTmpDir action = controlSh $ \runInSh -> S.withTmpDir (fmap runInSh action) time :: MonadShControl m => m a -> m (Double, a) time what = controlSh $ \runInSh -> do (d, a) <- S.time (runInSh what) runInSh $ restoreSh a >>= \x -> return (d, x) toTextWarn :: MonadSh m => FilePath -> m Text toTextWarn = liftSh . toTextWarn transferLinesAndCombine :: MonadIO m => Handle -> (Text -> IO ()) -> m Text transferLinesAndCombine = (liftIO .) . S.transferLinesAndCombine get :: MonadSh m => m S.State get = liftSh S.get put :: MonadSh m => S.State -> m () put = liftSh . S.put catch_sh :: (Exception e) => Sh a -> (e -> Sh a) -> Sh a catch_sh = Control.Exception.Lifted.catch {-# DEPRECATED catch_sh "use Control.Exception.Lifted.catch instead" #-} handle_sh :: (Exception e) => (e -> Sh a) -> Sh a -> Sh a handle_sh = handle {-# DEPRECATED handle_sh "use Control.Exception.Lifted.handle instead" #-} finally_sh :: Sh a -> Sh b -> Sh a finally_sh = finally {-# DEPRECATED finally_sh "use Control.Exception.Lifted.finally instead" #-} bracket_sh :: Sh a -> (a -> Sh b) -> (a -> Sh c) -> Sh c bracket_sh = bracket {-# DEPRECATED bracket_sh "use Control.Exception.Lifted.bracket instead" #-} catches_sh :: Sh a -> [Handler Sh a] -> Sh a catches_sh = catches {-# DEPRECATED catches_sh "use Control.Exception.Lifted.catches instead" #-} catchany_sh :: Sh a -> (SomeException -> Sh a) -> Sh a catchany_sh = catchAny {-# DEPRECATED catchany_sh "use Control.Exception.Enclosed.catchAny instead" #-} handleany_sh :: (SomeException -> Sh a) -> Sh a -> Sh a handleany_sh = handleAny {-# DEPRECATED handleany_sh "use Control.Exception.Enclosed.handleAny instead" #-} cd :: MonadSh m => FilePath -> m () cd = liftSh . S.cd mv :: MonadSh m => FilePath -> FilePath -> m () mv = (liftSh .) . S.mv lsT :: MonadSh m => FilePath -> m [Text] lsT = liftSh . S.lsT pwd :: MonadSh m => m FilePath pwd = liftSh S.pwd exit :: MonadSh m => Int -> m a exit = liftSh . S.exit errorExit :: MonadSh m => Text -> m a errorExit = liftSh . S.errorExit quietExit :: MonadSh m => Int -> m a quietExit = liftSh . S.quietExit terror :: MonadSh m => Text -> m a terror = liftSh . S.terror mkdir :: MonadSh m => FilePath -> m () mkdir = liftSh . S.mkdir mkdir_p :: MonadSh m => FilePath -> m () mkdir_p = liftSh . S.mkdir_p mkdirTree :: MonadSh m => Tree FilePath -> m () mkdirTree = liftSh . S.mkdirTree which :: MonadSh m => FilePath -> m (Maybe FilePath) which = liftSh . S.which test_e :: MonadSh m => FilePath -> m Bool test_e = liftSh . S.test_e test_f :: MonadSh m => FilePath -> m Bool test_f = liftSh . S.test_f test_px :: MonadSh m => FilePath -> m Bool test_px = liftSh . S.test_px rm_rf :: MonadSh m => FilePath -> m () rm_rf = liftSh . S.rm_rf rm_f :: MonadSh m => FilePath -> m () rm_f = liftSh . S.rm_f rm :: MonadSh m => FilePath -> m () rm = liftSh . S.rm setenv :: MonadSh m => Text -> Text -> m () setenv = (liftSh .) . S.setenv appendToPath :: MonadSh m => FilePath -> m () appendToPath = liftSh . S.appendToPath get_env_all :: MonadSh m => m [(String, String)] get_env_all = liftSh S.get_env_all get_env :: MonadSh m => Text -> m (Maybe Text) get_env = liftSh . S.get_env get_env_text :: MonadSh m => Text -> m Text get_env_text = liftSh . S.get_env_text sshPairs_ :: MonadSh m => Text -> [(FilePath, [Text])] -> m () sshPairs_ = (liftSh .) . S.sshPairs_ sshPairs :: MonadSh m => Text -> [(FilePath, [Text])] -> m Text sshPairs = (liftSh .) . S.sshPairs run :: MonadSh m => FilePath -> [Text] -> m Text run = (liftSh .) . S.run command :: MonadSh m => FilePath -> [Text] -> [Text] -> m Text command com args more_args = liftSh $ S.command com args more_args command_ :: MonadSh m => FilePath -> [Text] -> [Text] -> m () command_ com args more_args = liftSh $ S.command_ com args more_args command1 :: MonadSh m => FilePath -> [Text] -> Text -> [Text] -> m Text command1 com args one_arg more_args = liftSh $ S.command1 com args one_arg more_args command1_ :: MonadSh m => FilePath -> [Text] -> Text -> [Text] -> m () command1_ com args one_arg more_args = liftSh $ S.command1_ com args one_arg more_args run_ :: MonadSh m => FilePath -> [Text] -> m () run_ = (liftSh .) . S.run_ runHandle :: MonadShControl m => FilePath -- ^ command -> [Text] -- ^ arguments -> (Handle -> m a) -- ^ stdout handle -> m a runHandle exe args withHandle = controlSh $ \runInSh -> S.runHandle exe args (fmap runInSh withHandle) runHandles :: MonadShControl m => FilePath -- ^ command -> [Text] -- ^ arguments -> [S.StdHandle] -- ^ optionally connect process i/o handles to existing handles -> (Handle -> Handle -> Handle -> m a) -- ^ stdin, stdout and stderr -> m a runHandles exe args reusedHandles withHandles = controlSh $ \runInSh -> S.runHandles exe args reusedHandles (fmap (fmap (fmap runInSh)) withHandles) runFoldLines :: MonadSh m => a -> S.FoldCallback a -> FilePath -> [Text] -> m a runFoldLines start cb exe args = liftSh $ S.runFoldLines start cb exe args lastStderr :: MonadSh m => m Text lastStderr = liftSh S.lastStderr lastExitCode :: MonadSh m => m Int lastExitCode = liftSh S.lastExitCode setStdin :: MonadSh m => Text -> m () setStdin = liftSh . S.setStdin cp_r :: MonadSh m => FilePath -> FilePath -> m () cp_r = (liftSh .) . S.cp_r cp :: MonadSh m => FilePath -> FilePath -> m () cp = (liftSh .) . S.cp writefile :: MonadSh m => FilePath -> Text -> m () writefile = (liftSh .) . S.writefile touchfile :: MonadSh m => FilePath -> m () touchfile = liftSh . S.touchfile appendfile :: MonadSh m => FilePath -> Text -> m () appendfile = (liftSh .) . S.appendfile readfile :: MonadSh m => FilePath -> m Text readfile = liftSh . S.readfile readBinary :: MonadSh m => FilePath -> m ByteString readBinary = liftSh . S.readBinary sleep :: MonadSh m => Int -> m () sleep = liftSh . S.sleep echo, echo_n, echo_err, echo_n_err :: MonadSh m => Text -> m () echo = liftSh . S.echo echo_n = liftSh . S.echo_n echo_err = liftSh . S.echo_err echo_n_err = liftSh . S.echo_n_err relPath :: MonadSh m => FilePath -> m FilePath relPath = liftSh . S.relPath relativeTo :: MonadSh m => FilePath -- ^ anchor path, the prefix -> FilePath -- ^ make this relative to anchor path -> m FilePath relativeTo = (liftSh .) . S.relativeTo canonic :: MonadSh m => FilePath -> m FilePath canonic = liftSh . canonic -- | Obtain a (reasonably) canonic file path to a filesystem object. Based on -- "canonicalizePath" in system-fileio. canonicalize :: MonadSh m => FilePath -> m FilePath canonicalize = liftSh . S.canonicalize absPath :: MonadSh m => FilePath -> m FilePath absPath = liftSh . S.absPath test_d :: MonadSh m => FilePath -> m Bool test_d = liftSh . S.test_d test_s :: MonadSh m => FilePath -> m Bool test_s = liftSh . S.test_s ls :: MonadSh m => FilePath -> m [FilePath] ls = liftSh . S.ls inspect :: (Show s, MonadSh m) => s -> m () inspect = liftSh . S.inspect inspect_err :: (Show s, MonadSh m) => s -> m () inspect_err = liftSh . S.inspect_err catchany :: MonadBaseControl IO m => m a -> (SomeException -> m a) -> m a catchany = Control.Exception.Lifted.catch
adinapoli/Shelly.hs
src/Shelly/Lifted.hs
bsd-3-clause
20,951
0
15
4,891
7,322
3,847
3,475
422
1
{-# LANGUAGE CPP #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE MagicHash #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UnboxedTuples #-} {-# OPTIONS_GHC -fno-warn-missing-methods #-} {-# OPTIONS_GHC -fno-warn-orphans #-} {-# OPTIONS_HADDOCK hide #-} -- | -- Module : Data.Array.Accelerate.Array.Data -- Copyright : [2008..2014] Manuel M T Chakravarty, Gabriele Keller -- [2008..2009] Sean Lee -- [2009..2014] Trevor L. McDonell -- License : BSD3 -- -- Maintainer : Manuel M T Chakravarty <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- This module fixes the concrete representation of Accelerate arrays. We -- allocate all arrays using pinned memory to enable safe direct-access by -- non-Haskell code in multi-threaded code. In particular, we can safely pass -- pointers to an array's payload to foreign code. -- module Data.Array.Accelerate.Array.Data ( -- * Array operations and representations ArrayElt(..), ArrayData, MutableArrayData, runArrayData, ArrayEltR(..), GArrayData(..), -- * Array tuple operations fstArrayData, sndArrayData, pairArrayData, -- * Type macros HTYPE_INT, HTYPE_WORD, HTYPE_LONG, HTYPE_UNSIGNED_LONG, HTYPE_CCHAR, -- * Unique arrays UniqueArray, storableFromUnique, uniqueFromStorable, getUniqueId ) where -- standard libraries import Foreign ( Ptr ) import Foreign.C.Types import Data.Bits import Data.Functor import Data.IORef ( IORef, newIORef, atomicModifyIORef' ) import Data.Typeable ( Typeable ) import Control.Monad #ifdef ACCELERATE_UNSAFE_CHECKS import qualified Data.Array.Base as MArray ( readArray, writeArray ) #else import qualified Data.Array.Base as MArray ( unsafeRead, unsafeWrite ) #endif import Data.Array.Storable.Internals import Foreign.ForeignPtr.Unsafe import Foreign.Storable import System.IO.Unsafe import Data.Array.MArray ( MArray(..) ) import Data.Array.Base ( unsafeNewArray_ ) import Language.Haskell.TH import Prelude -- friends import Data.Array.Accelerate.Type -- Add needed Typeable instance for StorableArray -- deriving instance Typeable StorableArray -- Determine the underlying type of a Haskell CLong or CULong. -- $( runQ [d| type HTYPE_INT = $( case finiteBitSize (undefined::Int) of 32 -> [t| Int32 |] 64 -> [t| Int64 |] _ -> error "I don't know what architecture I am" ) |] ) $( runQ [d| type HTYPE_WORD = $( case finiteBitSize (undefined::Word) of 32 -> [t| Word32 |] 64 -> [t| Word64 |] _ -> error "I don't know what architecture I am" ) |] ) $( runQ [d| type HTYPE_LONG = $( case finiteBitSize (undefined::CLong) of 32 -> [t| Int32 |] 64 -> [t| Int64 |] _ -> error "I don't know what architecture I am" ) |] ) $( runQ [d| type HTYPE_UNSIGNED_LONG = $( case finiteBitSize (undefined::CULong) of 32 -> [t| Word32 |] 64 -> [t| Word64 |] _ -> error "I don't know what architecture I am" ) |] ) $( runQ [d| type HTYPE_CCHAR = $( case isSigned (undefined::CChar) of True -> [t| Int8 |] False -> [t| Word8 |] ) |] ) -- Unique arrays -- ------------- -- |A Uniquely identifiable array. -- -- For the purposes of memory management, we use arrays as keys in a table. For -- this reason we need a way to uniquely identify each array we create. We do -- this by attaching an Int to each array, the value of which we get from a -- global counter that we increment for every array construction. -- data UniqueArray i e = UniqueArray {-# UNPACK #-} !Int {-# UNPACK #-} !(StorableArray i e) -- |Create a unique array from a storable array -- {-# INLINE uniqueFromStorable #-} uniqueFromStorable :: StorableArray i a -> IO (UniqueArray i a) uniqueFromStorable sa = do i <- atomicModifyIORef' counter (\n -> (n+1,n)) return $ UniqueArray i sa -- |Get the storable array backing the unique array -- {-# INLINE storableFromUnique #-} storableFromUnique :: UniqueArray i a -> StorableArray i a storableFromUnique (UniqueArray _ sa) = sa -- |Get the unique identifier associated with the unique array -- {-# INLINE getUniqueId #-} getUniqueId :: UniqueArray i a -> IO Int getUniqueId (UniqueArray n _) = return n instance Storable e => MArray UniqueArray e IO where getBounds (UniqueArray _ sa) = getBounds sa newArray lu i = uniqueFromStorable =<< newArray lu i unsafeNewArray_ lu = uniqueFromStorable =<< unsafeNewArray_ lu newArray_ = unsafeNewArray_ unsafeRead (UniqueArray _ sa) = MArray.unsafeRead sa unsafeWrite (UniqueArray _ sa) = MArray.unsafeWrite sa -- Array representation -- -------------------- -- |Immutable array representation -- type ArrayData e = MutableArrayData e -- |Mutable array representation -- type MutableArrayData e = GArrayData (UniqueArray Int) e -- Array representation in dependence on the element type, but abstracting -- over the basic array type (in particular, abstracting over mutability) -- data family GArrayData :: (* -> *) -> * -> * data instance GArrayData ba () = AD_Unit data instance GArrayData ba Int = AD_Int (ba Int) data instance GArrayData ba Int8 = AD_Int8 (ba Int8) data instance GArrayData ba Int16 = AD_Int16 (ba Int16) data instance GArrayData ba Int32 = AD_Int32 (ba Int32) data instance GArrayData ba Int64 = AD_Int64 (ba Int64) data instance GArrayData ba Word = AD_Word (ba Word) data instance GArrayData ba Word8 = AD_Word8 (ba Word8) data instance GArrayData ba Word16 = AD_Word16 (ba Word16) data instance GArrayData ba Word32 = AD_Word32 (ba Word32) data instance GArrayData ba Word64 = AD_Word64 (ba Word64) data instance GArrayData ba CShort = AD_CShort (ba Int16) data instance GArrayData ba CUShort = AD_CUShort (ba Word16) data instance GArrayData ba CInt = AD_CInt (ba Int32) data instance GArrayData ba CUInt = AD_CUInt (ba Word32) data instance GArrayData ba CLong = AD_CLong (ba HTYPE_LONG) data instance GArrayData ba CULong = AD_CULong (ba HTYPE_UNSIGNED_LONG) data instance GArrayData ba CLLong = AD_CLLong (ba Int64) data instance GArrayData ba CULLong = AD_CULLong (ba Word64) data instance GArrayData ba Float = AD_Float (ba Float) data instance GArrayData ba Double = AD_Double (ba Double) data instance GArrayData ba CFloat = AD_CFloat (ba Float) data instance GArrayData ba CDouble = AD_CDouble (ba Double) data instance GArrayData ba Bool = AD_Bool (ba Word8) data instance GArrayData ba Char = AD_Char (ba Char) data instance GArrayData ba CChar = AD_CChar (ba HTYPE_CCHAR) data instance GArrayData ba CSChar = AD_CSChar (ba Int8) data instance GArrayData ba CUChar = AD_CUChar (ba Word8) data instance GArrayData ba (a, b) = AD_Pair (GArrayData ba a) (GArrayData ba b) deriving instance Typeable GArrayData -- | GADT to reify the 'ArrayElt' class. -- data ArrayEltR a where ArrayEltRunit :: ArrayEltR () ArrayEltRint :: ArrayEltR Int ArrayEltRint8 :: ArrayEltR Int8 ArrayEltRint16 :: ArrayEltR Int16 ArrayEltRint32 :: ArrayEltR Int32 ArrayEltRint64 :: ArrayEltR Int64 ArrayEltRword :: ArrayEltR Word ArrayEltRword8 :: ArrayEltR Word8 ArrayEltRword16 :: ArrayEltR Word16 ArrayEltRword32 :: ArrayEltR Word32 ArrayEltRword64 :: ArrayEltR Word64 ArrayEltRcshort :: ArrayEltR CShort ArrayEltRcushort :: ArrayEltR CUShort ArrayEltRcint :: ArrayEltR CInt ArrayEltRcuint :: ArrayEltR CUInt ArrayEltRclong :: ArrayEltR CLong ArrayEltRculong :: ArrayEltR CULong ArrayEltRcllong :: ArrayEltR CLLong ArrayEltRcullong :: ArrayEltR CULLong ArrayEltRfloat :: ArrayEltR Float ArrayEltRdouble :: ArrayEltR Double ArrayEltRcfloat :: ArrayEltR CFloat ArrayEltRcdouble :: ArrayEltR CDouble ArrayEltRbool :: ArrayEltR Bool ArrayEltRchar :: ArrayEltR Char ArrayEltRcchar :: ArrayEltR CChar ArrayEltRcschar :: ArrayEltR CSChar ArrayEltRcuchar :: ArrayEltR CUChar ArrayEltRpair :: (ArrayElt a, ArrayElt b) => ArrayEltR a -> ArrayEltR b -> ArrayEltR (a,b) -- Array operations -- ---------------- -- -- TLM: do we need to INLINE these functions to get good performance interfacing -- to external libraries, especially Repa? class ArrayElt e where type ArrayPtrs e -- unsafeIndexArrayData :: ArrayData e -> Int -> e ptrsOfArrayData :: ArrayData e -> ArrayPtrs e touchArrayData :: ArrayData e -> IO () -- newArrayData :: Int -> IO (MutableArrayData e) unsafeReadArrayData :: MutableArrayData e -> Int -> IO e unsafeWriteArrayData :: MutableArrayData e -> Int -> e -> IO () unsafeFreezeArrayData :: MutableArrayData e -> IO (ArrayData e) unsafeFreezeArrayData = return ptrsOfMutableArrayData :: MutableArrayData e -> IO (ArrayPtrs e) ptrsOfMutableArrayData = return . ptrsOfArrayData -- arrayElt :: ArrayEltR e instance ArrayElt () where type ArrayPtrs () = () unsafeIndexArrayData AD_Unit i = i `seq` () ptrsOfArrayData AD_Unit = () touchArrayData AD_Unit = return () newArrayData size = size `seq` return AD_Unit unsafeReadArrayData AD_Unit i = i `seq` return () unsafeWriteArrayData AD_Unit i () = i `seq` return () arrayElt = ArrayEltRunit instance ArrayElt Int where type ArrayPtrs Int = Ptr Int unsafeIndexArrayData (AD_Int ba) i = unsafeIndexArray ba i ptrsOfArrayData (AD_Int ba) = uniqueArrayPtr ba touchArrayData (AD_Int ba) = touchUniqueArray ba newArrayData size = liftM AD_Int $ unsafeNewArray_ (0,size-1) unsafeReadArrayData (AD_Int ba) i = unsafeReadArray ba i unsafeWriteArrayData (AD_Int ba) i e = unsafeWriteArray ba i e arrayElt = ArrayEltRint instance ArrayElt Int8 where type ArrayPtrs Int8 = Ptr Int8 unsafeIndexArrayData (AD_Int8 ba) i = unsafeIndexArray ba i ptrsOfArrayData (AD_Int8 ba) = uniqueArrayPtr ba touchArrayData (AD_Int8 ba) = touchUniqueArray ba newArrayData size = liftM AD_Int8 $ unsafeNewArray_ (0,size-1) unsafeReadArrayData (AD_Int8 ba) i = unsafeReadArray ba i unsafeWriteArrayData (AD_Int8 ba) i e = unsafeWriteArray ba i e arrayElt = ArrayEltRint8 instance ArrayElt Int16 where type ArrayPtrs Int16 = Ptr Int16 unsafeIndexArrayData (AD_Int16 ba) i = unsafeIndexArray ba i ptrsOfArrayData (AD_Int16 ba) = uniqueArrayPtr ba touchArrayData (AD_Int16 ba) = touchUniqueArray ba newArrayData size = liftM AD_Int16 $ unsafeNewArray_ (0,size-1) unsafeReadArrayData (AD_Int16 ba) i = unsafeReadArray ba i unsafeWriteArrayData (AD_Int16 ba) i e = unsafeWriteArray ba i e arrayElt = ArrayEltRint16 instance ArrayElt Int32 where type ArrayPtrs Int32 = Ptr Int32 unsafeIndexArrayData (AD_Int32 ba) i = unsafeIndexArray ba i ptrsOfArrayData (AD_Int32 ba) = uniqueArrayPtr ba touchArrayData (AD_Int32 ba) = touchUniqueArray ba newArrayData size = liftM AD_Int32 $ unsafeNewArray_ (0,size-1) unsafeReadArrayData (AD_Int32 ba) i = unsafeReadArray ba i unsafeWriteArrayData (AD_Int32 ba) i e = unsafeWriteArray ba i e arrayElt = ArrayEltRint32 instance ArrayElt Int64 where type ArrayPtrs Int64 = Ptr Int64 unsafeIndexArrayData (AD_Int64 ba) i = unsafeIndexArray ba i ptrsOfArrayData (AD_Int64 ba) = uniqueArrayPtr ba touchArrayData (AD_Int64 ba) = touchUniqueArray ba newArrayData size = liftM AD_Int64 $ unsafeNewArray_ (0,size-1) unsafeReadArrayData (AD_Int64 ba) i = unsafeReadArray ba i unsafeWriteArrayData (AD_Int64 ba) i e = unsafeWriteArray ba i e arrayElt = ArrayEltRint64 instance ArrayElt Word where type ArrayPtrs Word = Ptr Word unsafeIndexArrayData (AD_Word ba) i = unsafeIndexArray ba i ptrsOfArrayData (AD_Word ba) = uniqueArrayPtr ba touchArrayData (AD_Word ba) = touchUniqueArray ba newArrayData size = liftM AD_Word $ unsafeNewArray_ (0,size-1) unsafeReadArrayData (AD_Word ba) i = unsafeReadArray ba i unsafeWriteArrayData (AD_Word ba) i e = unsafeWriteArray ba i e arrayElt = ArrayEltRword instance ArrayElt Word8 where type ArrayPtrs Word8 = Ptr Word8 unsafeIndexArrayData (AD_Word8 ba) i = unsafeIndexArray ba i ptrsOfArrayData (AD_Word8 ba) = uniqueArrayPtr ba touchArrayData (AD_Word8 ba) = touchUniqueArray ba newArrayData size = liftM AD_Word8 $ unsafeNewArray_ (0,size-1) unsafeReadArrayData (AD_Word8 ba) i = unsafeReadArray ba i unsafeWriteArrayData (AD_Word8 ba) i e = unsafeWriteArray ba i e arrayElt = ArrayEltRword8 instance ArrayElt Word16 where type ArrayPtrs Word16 = Ptr Word16 unsafeIndexArrayData (AD_Word16 ba) i = unsafeIndexArray ba i ptrsOfArrayData (AD_Word16 ba) = uniqueArrayPtr ba touchArrayData (AD_Word16 ba) = touchUniqueArray ba newArrayData size = liftM AD_Word16 $ unsafeNewArray_ (0,size-1) unsafeReadArrayData (AD_Word16 ba) i = unsafeReadArray ba i unsafeWriteArrayData (AD_Word16 ba) i e = unsafeWriteArray ba i e arrayElt = ArrayEltRword16 instance ArrayElt Word32 where type ArrayPtrs Word32 = Ptr Word32 unsafeIndexArrayData (AD_Word32 ba) i = unsafeIndexArray ba i ptrsOfArrayData (AD_Word32 ba) = uniqueArrayPtr ba touchArrayData (AD_Word32 ba) = touchUniqueArray ba newArrayData size = liftM AD_Word32 $ unsafeNewArray_ (0,size-1) unsafeReadArrayData (AD_Word32 ba) i = unsafeReadArray ba i unsafeWriteArrayData (AD_Word32 ba) i e = unsafeWriteArray ba i e arrayElt = ArrayEltRword32 instance ArrayElt Word64 where type ArrayPtrs Word64 = Ptr Word64 unsafeIndexArrayData (AD_Word64 ba) i = unsafeIndexArray ba i ptrsOfArrayData (AD_Word64 ba) = uniqueArrayPtr ba touchArrayData (AD_Word64 ba) = touchUniqueArray ba newArrayData size = liftM AD_Word64 $ unsafeNewArray_ (0,size-1) unsafeReadArrayData (AD_Word64 ba) i = unsafeReadArray ba i unsafeWriteArrayData (AD_Word64 ba) i e = unsafeWriteArray ba i e arrayElt = ArrayEltRword64 instance ArrayElt CShort where type ArrayPtrs CShort = Ptr Int16 unsafeIndexArrayData (AD_CShort ba) i = CShort $ unsafeIndexArray ba i ptrsOfArrayData (AD_CShort ba) = uniqueArrayPtr ba touchArrayData (AD_CShort ba) = touchUniqueArray ba newArrayData size = liftM AD_CShort $ unsafeNewArray_ (0,size-1) unsafeReadArrayData (AD_CShort ba) i = CShort <$> unsafeReadArray ba i unsafeWriteArrayData (AD_CShort ba) i (CShort e) = unsafeWriteArray ba i e arrayElt = ArrayEltRcshort instance ArrayElt CUShort where type ArrayPtrs CUShort = Ptr Word16 unsafeIndexArrayData (AD_CUShort ba) i = CUShort $ unsafeIndexArray ba i ptrsOfArrayData (AD_CUShort ba) = uniqueArrayPtr ba touchArrayData (AD_CUShort ba) = touchUniqueArray ba newArrayData size = liftM AD_CUShort $ unsafeNewArray_ (0,size-1) unsafeReadArrayData (AD_CUShort ba) i = CUShort <$> unsafeReadArray ba i unsafeWriteArrayData (AD_CUShort ba) i (CUShort e) = unsafeWriteArray ba i e arrayElt = ArrayEltRcushort instance ArrayElt CInt where type ArrayPtrs CInt = Ptr Int32 unsafeIndexArrayData (AD_CInt ba) i = CInt $ unsafeIndexArray ba i ptrsOfArrayData (AD_CInt ba) = uniqueArrayPtr ba touchArrayData (AD_CInt ba) = touchUniqueArray ba newArrayData size = liftM AD_CInt $ unsafeNewArray_ (0,size-1) unsafeReadArrayData (AD_CInt ba) i = CInt <$> unsafeReadArray ba i unsafeWriteArrayData (AD_CInt ba) i (CInt e) = unsafeWriteArray ba i e arrayElt = ArrayEltRcint instance ArrayElt CUInt where type ArrayPtrs CUInt = Ptr Word32 unsafeIndexArrayData (AD_CUInt ba) i = CUInt $ unsafeIndexArray ba i ptrsOfArrayData (AD_CUInt ba) = uniqueArrayPtr ba touchArrayData (AD_CUInt ba) = touchUniqueArray ba newArrayData size = liftM AD_CUInt $ unsafeNewArray_ (0,size-1) unsafeReadArrayData (AD_CUInt ba) i = CUInt <$> unsafeReadArray ba i unsafeWriteArrayData (AD_CUInt ba) i (CUInt e) = unsafeWriteArray ba i e arrayElt = ArrayEltRcuint instance ArrayElt CLong where type ArrayPtrs CLong = Ptr HTYPE_LONG unsafeIndexArrayData (AD_CLong ba) i = CLong $ unsafeIndexArray ba i ptrsOfArrayData (AD_CLong ba) = uniqueArrayPtr ba touchArrayData (AD_CLong ba) = touchUniqueArray ba newArrayData size = liftM AD_CLong $ unsafeNewArray_ (0,size-1) unsafeReadArrayData (AD_CLong ba) i = CLong <$> unsafeReadArray ba i unsafeWriteArrayData (AD_CLong ba) i (CLong e) = unsafeWriteArray ba i e arrayElt = ArrayEltRclong instance ArrayElt CULong where type ArrayPtrs CULong = Ptr HTYPE_UNSIGNED_LONG unsafeIndexArrayData (AD_CULong ba) i = CULong $ unsafeIndexArray ba i ptrsOfArrayData (AD_CULong ba) = uniqueArrayPtr ba touchArrayData (AD_CULong ba) = touchUniqueArray ba newArrayData size = liftM AD_CULong $ unsafeNewArray_ (0,size-1) unsafeReadArrayData (AD_CULong ba) i = CULong <$> unsafeReadArray ba i unsafeWriteArrayData (AD_CULong ba) i (CULong e) = unsafeWriteArray ba i e arrayElt = ArrayEltRculong instance ArrayElt CLLong where type ArrayPtrs CLLong = Ptr Int64 unsafeIndexArrayData (AD_CLLong ba) i = CLLong $ unsafeIndexArray ba i ptrsOfArrayData (AD_CLLong ba) = uniqueArrayPtr ba touchArrayData (AD_CLLong ba) = touchUniqueArray ba newArrayData size = liftM AD_CLLong $ unsafeNewArray_ (0,size-1) unsafeReadArrayData (AD_CLLong ba) i = CLLong <$> unsafeReadArray ba i unsafeWriteArrayData (AD_CLLong ba) i (CLLong e) = unsafeWriteArray ba i e arrayElt = ArrayEltRcllong instance ArrayElt CULLong where type ArrayPtrs CULLong = Ptr Word64 unsafeIndexArrayData (AD_CULLong ba) i = CULLong $ unsafeIndexArray ba i ptrsOfArrayData (AD_CULLong ba) = uniqueArrayPtr ba touchArrayData (AD_CULLong ba) = touchUniqueArray ba newArrayData size = liftM AD_CULLong $ unsafeNewArray_ (0,size-1) unsafeReadArrayData (AD_CULLong ba) i = CULLong <$> unsafeReadArray ba i unsafeWriteArrayData (AD_CULLong ba) i (CULLong e) = unsafeWriteArray ba i e arrayElt = ArrayEltRcullong instance ArrayElt Float where type ArrayPtrs Float = Ptr Float unsafeIndexArrayData (AD_Float ba) i = unsafeIndexArray ba i ptrsOfArrayData (AD_Float ba) = uniqueArrayPtr ba touchArrayData (AD_Float ba) = touchUniqueArray ba newArrayData size = liftM AD_Float $ unsafeNewArray_ (0,size-1) unsafeReadArrayData (AD_Float ba) i = unsafeReadArray ba i unsafeWriteArrayData (AD_Float ba) i e = unsafeWriteArray ba i e arrayElt = ArrayEltRfloat instance ArrayElt Double where type ArrayPtrs Double = Ptr Double unsafeIndexArrayData (AD_Double ba) i = unsafeIndexArray ba i ptrsOfArrayData (AD_Double ba) = uniqueArrayPtr ba touchArrayData (AD_Double ba) = touchUniqueArray ba newArrayData size = liftM AD_Double $ unsafeNewArray_ (0,size-1) unsafeReadArrayData (AD_Double ba) i = unsafeReadArray ba i unsafeWriteArrayData (AD_Double ba) i e = unsafeWriteArray ba i e arrayElt = ArrayEltRdouble instance ArrayElt CFloat where type ArrayPtrs CFloat = Ptr Float unsafeIndexArrayData (AD_CFloat ba) i = CFloat $ unsafeIndexArray ba i ptrsOfArrayData (AD_CFloat ba) = uniqueArrayPtr ba touchArrayData (AD_CFloat ba) = touchUniqueArray ba newArrayData size = liftM AD_CFloat $ unsafeNewArray_ (0,size-1) unsafeReadArrayData (AD_CFloat ba) i = CFloat <$> unsafeReadArray ba i unsafeWriteArrayData (AD_CFloat ba) i (CFloat e) = unsafeWriteArray ba i e arrayElt = ArrayEltRcfloat instance ArrayElt CDouble where type ArrayPtrs CDouble = Ptr Double unsafeIndexArrayData (AD_CDouble ba) i = CDouble $ unsafeIndexArray ba i ptrsOfArrayData (AD_CDouble ba) = uniqueArrayPtr ba touchArrayData (AD_CDouble ba) = touchUniqueArray ba newArrayData size = liftM AD_CDouble $ unsafeNewArray_ (0,size-1) unsafeReadArrayData (AD_CDouble ba) i = CDouble <$> unsafeReadArray ba i unsafeWriteArrayData (AD_CDouble ba) i (CDouble e) = unsafeWriteArray ba i e arrayElt = ArrayEltRcdouble -- Bool arrays are stored as arrays of bytes. While this is memory inefficient, -- it is better suited to parallel backends than the native Unboxed Bool -- array representation that uses packed bit vectors, as that would require -- atomic operations when writing data necessarily serialising threads. -- instance ArrayElt Bool where type ArrayPtrs Bool = Ptr Word8 unsafeIndexArrayData (AD_Bool ba) i = toBool (unsafeIndexArray ba i) ptrsOfArrayData (AD_Bool ba) = uniqueArrayPtr ba touchArrayData (AD_Bool ba) = touchUniqueArray ba newArrayData size = liftM AD_Bool $ unsafeNewArray_ (0,size-1) unsafeReadArrayData (AD_Bool ba) i = liftM toBool $ unsafeReadArray ba i unsafeWriteArrayData (AD_Bool ba) i e = unsafeWriteArray ba i (fromBool e) arrayElt = ArrayEltRbool {-# INLINE toBool #-} toBool :: Word8 -> Bool toBool 0 = False toBool _ = True {-# INLINE fromBool #-} fromBool :: Bool -> Word8 fromBool True = 1 fromBool False = 0 -- Unboxed Char is stored as a wide character, which is 4-bytes -- instance ArrayElt Char where type ArrayPtrs Char = Ptr Char unsafeIndexArrayData (AD_Char ba) i = unsafeIndexArray ba i ptrsOfArrayData (AD_Char ba) = uniqueArrayPtr ba touchArrayData (AD_Char ba) = touchUniqueArray ba newArrayData size = liftM AD_Char $ unsafeNewArray_ (0,size-1) unsafeReadArrayData (AD_Char ba) i = unsafeReadArray ba i unsafeWriteArrayData (AD_Char ba) i e = unsafeWriteArray ba i e arrayElt = ArrayEltRchar instance ArrayElt CChar where type ArrayPtrs CChar = Ptr HTYPE_CCHAR unsafeIndexArrayData (AD_CChar ba) i = CChar $ unsafeIndexArray ba i ptrsOfArrayData (AD_CChar ba) = uniqueArrayPtr ba touchArrayData (AD_CChar ba) = touchUniqueArray ba newArrayData size = liftM AD_CChar $ unsafeNewArray_ (0,size-1) unsafeReadArrayData (AD_CChar ba) i = CChar <$> unsafeReadArray ba i unsafeWriteArrayData (AD_CChar ba) i (CChar e) = unsafeWriteArray ba i e arrayElt = ArrayEltRcchar instance ArrayElt CSChar where type ArrayPtrs CSChar = Ptr Int8 unsafeIndexArrayData (AD_CSChar ba) i = CSChar $ unsafeIndexArray ba i ptrsOfArrayData (AD_CSChar ba) = uniqueArrayPtr ba touchArrayData (AD_CSChar ba) = touchUniqueArray ba newArrayData size = liftM AD_CSChar $ unsafeNewArray_ (0,size-1) unsafeReadArrayData (AD_CSChar ba) i = CSChar <$> unsafeReadArray ba i unsafeWriteArrayData (AD_CSChar ba) i (CSChar e) = unsafeWriteArray ba i e arrayElt = ArrayEltRcschar instance ArrayElt CUChar where type ArrayPtrs CUChar = Ptr Word8 unsafeIndexArrayData (AD_CUChar ba) i = CUChar $ unsafeIndexArray ba i ptrsOfArrayData (AD_CUChar ba) = uniqueArrayPtr ba touchArrayData (AD_CUChar ba) = touchUniqueArray ba newArrayData size = liftM AD_CUChar $ unsafeNewArray_ (0,size-1) unsafeReadArrayData (AD_CUChar ba) i = CUChar <$> unsafeReadArray ba i unsafeWriteArrayData (AD_CUChar ba) i (CUChar e) = unsafeWriteArray ba i e arrayElt = ArrayEltRcuchar instance (ArrayElt a, ArrayElt b) => ArrayElt (a, b) where type ArrayPtrs (a, b) = (ArrayPtrs a, ArrayPtrs b) unsafeIndexArrayData (AD_Pair a b) i = (unsafeIndexArrayData a i, unsafeIndexArrayData b i) ptrsOfArrayData (AD_Pair a b) = (ptrsOfArrayData a, ptrsOfArrayData b) touchArrayData (AD_Pair a b) = touchArrayData a >> touchArrayData b newArrayData size = do a <- newArrayData size b <- newArrayData size return $ AD_Pair a b unsafeReadArrayData (AD_Pair a b) i = do x <- unsafeReadArrayData a i y <- unsafeReadArrayData b i return (x, y) unsafeWriteArrayData (AD_Pair a b) i (x, y) = do unsafeWriteArrayData a i x unsafeWriteArrayData b i y unsafeFreezeArrayData (AD_Pair a b) = do a' <- unsafeFreezeArrayData a b' <- unsafeFreezeArrayData b return $ AD_Pair a' b' ptrsOfMutableArrayData (AD_Pair a b) = do aptr <- ptrsOfMutableArrayData a bptr <- ptrsOfMutableArrayData b return (aptr, bptr) arrayElt = ArrayEltRpair arrayElt arrayElt -- |Safe combination of creating and fast freezing of array data. -- {-# INLINE runArrayData #-} runArrayData :: ArrayElt e => IO (MutableArrayData e, e) -> (ArrayData e, e) runArrayData st = unsafePerformIO $ do (mad, r) <- st return (mad, r) -- Array tuple operations -- ---------------------- fstArrayData :: ArrayData (a, b) -> ArrayData a fstArrayData (AD_Pair x _) = x sndArrayData :: ArrayData (a, b) -> ArrayData b sndArrayData (AD_Pair _ y) = y pairArrayData :: ArrayData a -> ArrayData b -> ArrayData (a, b) pairArrayData = AD_Pair -- Auxiliary functions -- ------------------- -- Returns the element of an immutable array at the specified index. -- -- This does no bounds checking unless you configured with -funsafe-checks. This -- is usually OK, since the functions that convert from multidimensional to -- linear indexing do bounds checking by default. -- {-# INLINE unsafeIndexArray #-} unsafeIndexArray :: MArray a e IO => a Int e -> Int -> e unsafeIndexArray a i = unsafePerformIO $ unsafeReadArray a i -- Read an element from a mutable array. -- -- This does no bounds checking unless you configured with -funsafe-checks. This -- is usually OK, since the functions that convert from multidimensional to -- linear indexing do bounds checking by default. -- {-# INLINE unsafeReadArray #-} unsafeReadArray :: MArray a e m => a Int e -> Int -> m e #ifdef ACCELERATE_UNSAFE_CHECKS unsafeReadArray = MArray.readArray #else unsafeReadArray = MArray.unsafeRead #endif -- Write an element into a mutable array. -- -- This does no bounds checking unless you configured with -funsafe-checks. This -- is usually OK, since the functions that convert from multidimensional to -- linear indexing do bounds checking by default. -- {-# INLINE unsafeWriteArray #-} unsafeWriteArray :: MArray a e m => a Int e -> Int -> e -> m () #ifdef ACCELERATE_UNSAFE_CHECKS unsafeWriteArray = MArray.writeArray #else unsafeWriteArray = MArray.unsafeWrite #endif -- Keeps a unique array alive. -- {-# INLINE touchUniqueArray #-} touchUniqueArray :: UniqueArray i a -> IO () touchUniqueArray (UniqueArray _ sa) = touchStorableArray sa -- Obtains a pointer to the payload of an unique array. -- {-# INLINE uniqueArrayPtr #-} uniqueArrayPtr :: UniqueArray i a -> Ptr a uniqueArrayPtr (UniqueArray _ (StorableArray _ _ _ fp)) = unsafeForeignPtrToPtr fp -- The global counter that gives new ids for unique arrays. {-# NOINLINE counter #-} counter :: IORef Int counter = unsafePerformIO $ newIORef 0
sjfloat/accelerate
Data/Array/Accelerate/Array/Data.hs
bsd-3-clause
29,251
525
12
7,572
7,105
3,731
3,374
494
1
-- arith2.hs module Arith2 where add :: Int -> Int -> Int add x y = x + y addPF :: Int -> Int -> Int addPF = (+) addOne :: Int -> Int addOne = \x -> x + 1 addOnePF :: Int -> Int addOnePF = (+1) main :: IO () main = do print (0 :: Int) print (add 1 0) print (addOne 0) print (addOnePF 0) print ((addOne . addOne) 0) print ((addOnePF . addOne) 0) print ((addOne . addOnePF) 0) print ((addOnePF . addOnePF) 0) print (negate (addOne 0)) print ((negate . addOne) 0) print ((addOne . addOne . addOne . negate . addOne) 0)
renevp/hello-haskell
src/functionalpatterns/arith2.hs
bsd-3-clause
551
0
14
145
302
152
150
23
1
{-# OPTIONS_GHC -fno-warn-orphans -fno-warn-name-shadowing #-} module Real.Load (readPkgIndex) where import Real.Types import Real.ReadShow () import Text.ParserCombinators.ReadP as ReadP hiding (get) import qualified Text.ParserCombinators.ReadP as Parse import qualified Text.PrettyPrint as Disp import qualified Data.Char as Char (isDigit, isAlphaNum, isSpace) import Text.PrettyPrint hiding (braces) import Data.List import Data.Function (on) import Data.Char as Char (chr, ord, isSpace, isUpper, toLower, isAlphaNum, isDigit) import Data.Maybe import Data.Monoid hiding ((<>)) import Data.Tree as Tree (Tree(..), flatten) import Data.Array (Array, accumArray, bounds, Ix(inRange), (!)) import Data.Bits import Control.Monad import Control.Applicative (Applicative(..)) import Control.Exception import qualified Data.ByteString.Lazy.Char8 as BS import System.FilePath (normalise, splitDirectories) import qualified Codec.Archive.Tar as Tar import qualified Codec.Archive.Tar.Entry as Tar readPkgIndex :: BS.ByteString -> Either String [GenericPackageDescription] readPkgIndex = fmap extractCabalFiles . readTarIndex where extractCabalFiles entries = [ pkgDesc | Tar.Entry { Tar.entryContent = Tar.NormalFile cabalFile _ } <- entries , let ParseOk _ pkgDesc = parsePackageDescription . fromUTF8 . BS.unpack $ cabalFile ] readTarIndex :: BS.ByteString -> Either String [Tar.Entry] readTarIndex indexFileContent = collect [] entries where entries = Tar.read indexFileContent collect es' Tar.Done = Right es' collect es' (Tar.Next e es) = case entry e of Just e' -> collect (e':es') es Nothing -> collect es' es collect _ (Tar.Fail err) = Left (show err) entry e | [_pkgname,versionStr,_] <- splitDirectories (normalise (Tar.entryPath e)) , Just (Version _ []) <- simpleParse versionStr = Just e entry _ = Nothing fromUTF8 :: String -> String fromUTF8 [] = [] fromUTF8 (c:cs) | c <= '\x7F' = c : fromUTF8 cs | c <= '\xBF' = replacementChar : fromUTF8 cs | c <= '\xDF' = twoBytes c cs | c <= '\xEF' = moreBytes 3 0x800 cs (ord c .&. 0xF) | c <= '\xF7' = moreBytes 4 0x10000 cs (ord c .&. 0x7) | c <= '\xFB' = moreBytes 5 0x200000 cs (ord c .&. 0x3) | c <= '\xFD' = moreBytes 6 0x4000000 cs (ord c .&. 0x1) | otherwise = replacementChar : fromUTF8 cs where twoBytes c0 (c1:cs') | ord c1 .&. 0xC0 == 0x80 = let d = ((ord c0 .&. 0x1F) `shiftL` 6) .|. (ord c1 .&. 0x3F) in if d >= 0x80 then chr d : fromUTF8 cs' else replacementChar : fromUTF8 cs' twoBytes _ cs' = replacementChar : fromUTF8 cs' moreBytes :: Int -> Int -> [Char] -> Int -> [Char] moreBytes 1 overlong cs' acc | overlong <= acc && acc <= 0x10FFFF && (acc < 0xD800 || 0xDFFF < acc) && (acc < 0xFFFE || 0xFFFF < acc) = chr acc : fromUTF8 cs' | otherwise = replacementChar : fromUTF8 cs' moreBytes byteCount overlong (cn:cs') acc | ord cn .&. 0xC0 == 0x80 = moreBytes (byteCount-1) overlong cs' ((acc `shiftL` 6) .|. ord cn .&. 0x3F) moreBytes _ _ cs' _ = replacementChar : fromUTF8 cs' replacementChar = '\xfffd' ------------------------------------------------------------------------------ type LineNo = Int data PError = AmbiguousParse String LineNo | NoParse String LineNo | TabsError LineNo | FromString String (Maybe LineNo) deriving (Eq, Show) data PWarning = PWarning String | UTFWarning LineNo String deriving (Eq, Show) data ParseResult a = ParseFailed PError | ParseOk [PWarning] a deriving Show instance Functor ParseResult where fmap _ (ParseFailed err) = ParseFailed err fmap f (ParseOk ws x) = ParseOk ws $ f x instance Applicative ParseResult where pure = return (<*>) = ap instance Monad ParseResult where return = ParseOk [] ParseFailed err >>= _ = ParseFailed err ParseOk ws x >>= f = case f x of ParseFailed err -> ParseFailed err ParseOk ws' x' -> ParseOk (ws'++ws) x' fail s = ParseFailed (FromString s Nothing) catchParseError :: ParseResult a -> (PError -> ParseResult a) -> ParseResult a p@(ParseOk _ _) `catchParseError` _ = p ParseFailed e `catchParseError` k = k e parseFail :: PError -> ParseResult a parseFail = ParseFailed runP :: LineNo -> String -> ReadP a -> String -> ParseResult a runP line fieldname p s = case [ x | (x,"") <- results ] of [a] -> ParseOk (utf8Warnings line fieldname s) a --TODO: what is this double parse thing all about? -- Can't we just do the all isSpace test the first time? [] -> case [ x | (x,ys) <- results, all isSpace ys ] of [a] -> ParseOk (utf8Warnings line fieldname s) a [] -> ParseFailed (NoParse fieldname line) _ -> ParseFailed (AmbiguousParse fieldname line) _ -> ParseFailed (AmbiguousParse fieldname line) where results = readP_to_S p s -- | Parser with simple error reporting newtype ReadE a = ReadE {_runReadE :: String -> Either ErrorMsg a} type ErrorMsg = String instance Functor ReadE where fmap f (ReadE p) = ReadE $ \txt -> case p txt of Right a -> Right (f a) Left err -> Left err utf8Warnings :: LineNo -> String -> String -> [PWarning] utf8Warnings line fieldname s = take 1 [ UTFWarning n fieldname | (n,l) <- zip [line..] (lines s) , '\xfffd' `elem` l ] syntaxError :: LineNo -> String -> ParseResult a syntaxError n s = ParseFailed $ FromString s (Just n) tabsError :: LineNo -> ParseResult a tabsError ln = ParseFailed $ TabsError ln warning :: String -> ParseResult () warning s = ParseOk [PWarning s] () -- | Field descriptor. The parameter @a@ parameterizes over where the field's -- value is stored in. data FieldDescr a = FieldDescr { fieldName :: String , _fieldGet :: a -> Doc , _fieldSet :: LineNo -> String -> a -> ParseResult a -- ^ @fieldSet n str x@ Parses the field value from the given input -- string @str@ and stores the result in @x@ if the parse was -- successful. Otherwise, reports an error on line number @n@. } field :: String -> (a -> Doc) -> ReadP a -> FieldDescr a field name showF readF = FieldDescr name showF (\line val _st -> runP line name readF val) -- Lift a field descriptor storing into an 'a' to a field descriptor storing -- into a 'b'. liftField :: (b -> a) -> (a -> b -> b) -> FieldDescr a -> FieldDescr b liftField get set (FieldDescr name showF parseF) = FieldDescr name (showF . get) (\line str b -> do a <- parseF line str (get b) return (set a b)) -- Parser combinator for simple fields. Takes a field name, a pretty printer, -- a parser function, an accessor, and a setter, returns a FieldDescr over the -- compoid structure. simpleField :: String -> (a -> Doc) -> ReadP a -> (b -> a) -> (a -> b -> b) -> FieldDescr b simpleField name showF readF get set = liftField get set $ field name showF readF commaListField :: String -> (a -> Doc) -> ReadP a -> (b -> [a]) -> ([a] -> b -> b) -> FieldDescr b commaListField name showF readF get set = liftField get set' $ field name (fsep . punctuate comma . map showF) (parseCommaList readF) where set' xs b = set (get b ++ xs) b spaceListField :: String -> (a -> Doc) -> ReadP a -> (b -> [a]) -> ([a] -> b -> b) -> FieldDescr b spaceListField name showF readF get set = liftField get set' $ field name (fsep . map showF) (parseSpaceList readF) where set' xs b = set (get b ++ xs) b listField :: String -> (a -> Doc) -> ReadP a -> (b -> [a]) -> ([a] -> b -> b) -> FieldDescr b listField name showF readF get set = liftField get set' $ field name (fsep . map showF) (parseOptCommaList readF) where set' xs b = set (get b ++ xs) b optsField :: String -> CompilerFlavor -> (b -> [(CompilerFlavor,[String])]) -> ([(CompilerFlavor,[String])] -> b -> b) -> FieldDescr b optsField name flavor get set = liftField (fromMaybe [] . lookup flavor . get) (\opts b -> set (reorder (update flavor opts (get b))) b) $ field name (hsep . map text) (sepBy parseTokenQ' (munch1 isSpace)) where update _ opts l | all null opts = l --empty opts as if no opts update f opts [] = [(f,opts)] update f opts ((f',opts'):rest) | f == f' = (f, opts' ++ opts) : rest | otherwise = (f',opts') : update f opts rest reorder = sortBy (compare `on` fst) boolField :: String -> (b -> Bool) -> (Bool -> b -> b) -> FieldDescr b boolField name get set = liftField get set (FieldDescr name showF readF) where showF = text . show readF line str _ | str == "True" = ParseOk [] True | str == "False" = ParseOk [] False | lstr == "true" = ParseOk [caseWarning] True | lstr == "false" = ParseOk [caseWarning] False | otherwise = ParseFailed (NoParse name line) where lstr = lowercase str caseWarning = PWarning $ "The '" ++ name ++ "' field is case sensitive, use 'True' or 'False'." type UnrecFieldParser a = (String,String) -> a -> Maybe a -- | A default unrecognized field parser which simply returns Nothing, -- i.e. ignores all unrecognized fields, so warnings will be generated. warnUnrec :: UnrecFieldParser a warnUnrec _ _ = Nothing ------------------------------------------------------------------------------ -- The data type for our three syntactic categories data Field = F LineNo String String -- ^ A regular @<property>: <value>@ field | Section LineNo String String [Field] -- ^ A section with a name and possible parameter. The syntactic -- structure is: -- -- @ -- <sectionname> <arg> { -- <field>* -- } -- @ | IfBlock LineNo String [Field] [Field] -- ^ A conditional block with an optional else branch: -- -- @ -- if <condition> { -- <field>* -- } else { -- <field>* -- } -- @ deriving (Show ,Eq) -- for testing lineNo :: Field -> LineNo lineNo (F n _ _) = n lineNo (Section n _ _ _) = n lineNo (IfBlock n _ _ _) = n fName :: Field -> String fName (F _ n _) = n fName (Section _ n _ _) = n fName _ = error "fname: not a field or section" readFields :: String -> ParseResult [Field] readFields input = ifelse =<< mapM (mkField 0) =<< mkTree tokens where ls = (lines . normaliseLineEndings) input tokens = (concatMap tokeniseLine . trimLines) ls normaliseLineEndings :: String -> String normaliseLineEndings [] = [] normaliseLineEndings ('\r':'\n':s) = '\n' : normaliseLineEndings s -- windows normaliseLineEndings ('\r':s) = '\n' : normaliseLineEndings s -- old osx normaliseLineEndings ( c :s) = c : normaliseLineEndings s -- attach line number and determine indentation trimLines :: [String] -> [(LineNo, Indent, HasTabs, String)] trimLines ls = [ (lineno, indent, hastabs, trimTrailing l') | (lineno, l) <- zip [1..] ls , let (sps, l') = span isSpace l indent = length sps hastabs = '\t' `elem` sps , validLine l' ] where validLine ('-':'-':_) = False -- Comment validLine [] = False -- blank line validLine _ = True -- | We parse generically based on indent level and braces '{' '}'. To do that -- we split into lines and then '{' '}' tokens and other spans within a line. data Token = -- | The 'Line' token is for bits that /start/ a line, eg: -- -- > "\n blah blah { blah" -- -- tokenises to: -- -- > [Line n 2 False "blah blah", OpenBracket, Span n "blah"] -- -- so lines are the only ones that can have nested layout, since they -- have a known indentation level. -- -- eg: we can't have this: -- -- > if ... { -- > } else -- > other -- -- because other cannot nest under else, since else doesn't start a line -- so cannot have nested layout. It'd have to be: -- -- > if ... { -- > } -- > else -- > other -- -- but that's not so common, people would normally use layout or -- brackets not both in a single @if else@ construct. -- -- > if ... { foo : bar } -- > else -- > other -- -- this is ok Line LineNo Indent HasTabs String | Span LineNo String -- ^ span in a line, following brackets | OpenBracket LineNo | CloseBracket LineNo type Indent = Int type HasTabs = Bool -- | Tokenise a single line, splitting on '{' '}' and the spans inbetween. -- Also trims leading & trailing space on those spans within the line. tokeniseLine :: (LineNo, Indent, HasTabs, String) -> [Token] tokeniseLine (n0, i, t, l) = case split n0 l of (Span _ l':ss) -> Line n0 i t l' :ss cs -> cs where split _ "" = [] split n s = case span (\c -> c /='}' && c /= '{') s of ("", '{' : s') -> OpenBracket n : split n s' (w , '{' : s') -> mkspan n w (OpenBracket n : split n s') ("", '}' : s') -> CloseBracket n : split n s' (w , '}' : s') -> mkspan n w (CloseBracket n : split n s') (w , _) -> mkspan n w [] mkspan n s ss | null s' = ss | otherwise = Span n s' : ss where s' = trimTrailing (trimLeading s) trimLeading, trimTrailing :: String -> String trimLeading = dropWhile isSpace trimTrailing = reverse . dropWhile isSpace . reverse type SyntaxTree = Tree (LineNo, HasTabs, String) -- | Parse the stream of tokens into a tree of them, based on indent \/ layout mkTree :: [Token] -> ParseResult [SyntaxTree] mkTree toks = layout 0 [] toks >>= \(trees, trailing) -> case trailing of [] -> return trees OpenBracket n:_ -> syntaxError n "mismatched backets, unexpected {" CloseBracket n:_ -> syntaxError n "mismatched backets, unexpected }" -- the following two should never happen: Span n l :_ -> syntaxError n $ "unexpected span: " ++ show l Line n _ _ l :_ -> syntaxError n $ "unexpected line: " ++ show l -- | Parse the stream of tokens into a tree of them, based on indent -- This parse state expect to be in a layout context, though possibly -- nested within a braces context so we may still encounter closing braces. layout :: Indent -- ^ indent level of the parent\/previous line -> [SyntaxTree] -- ^ accumulating param, trees in this level -> [Token] -- ^ remaining tokens -> ParseResult ([SyntaxTree], [Token]) -- ^ collected trees on this level and trailing tokens layout _ a [] = return (reverse a, []) layout i a (s@(Line _ i' _ _):ss) | i' < i = return (reverse a, s:ss) layout i a (Line n _ t l:OpenBracket n':ss) = do (sub, ss') <- braces n' [] ss layout i (Node (n,t,l) sub:a) ss' layout i a (Span n l:OpenBracket n':ss) = do (sub, ss') <- braces n' [] ss layout i (Node (n,False,l) sub:a) ss' -- look ahead to see if following lines are more indented, giving a sub-tree layout i a (Line n i' t l:ss) = do lookahead <- layout (i'+1) [] ss case lookahead of ([], _) -> layout i (Node (n,t,l) [] :a) ss (ts, ss') -> layout i (Node (n,t,l) ts :a) ss' layout _ _ ( OpenBracket n :_) = syntaxError n "unexpected '{'" layout _ a (s@(CloseBracket _):ss) = return (reverse a, s:ss) layout _ _ ( Span n l : _) = syntaxError n $ "unexpected span: " ++ show l -- | Parse the stream of tokens into a tree of them, based on explicit braces -- This parse state expects to find a closing bracket. braces :: LineNo -- ^ line of the '{', used for error messages -> [SyntaxTree] -- ^ accumulating param, trees in this level -> [Token] -- ^ remaining tokens -> ParseResult ([SyntaxTree],[Token]) -- ^ collected trees on this level and trailing tokens braces m a (Line n _ t l:OpenBracket n':ss) = do (sub, ss') <- braces n' [] ss braces m (Node (n,t,l) sub:a) ss' braces m a (Span n l:OpenBracket n':ss) = do (sub, ss') <- braces n' [] ss braces m (Node (n,False,l) sub:a) ss' braces m a (Line n i t l:ss) = do lookahead <- layout (i+1) [] ss case lookahead of ([], _) -> braces m (Node (n,t,l) [] :a) ss (ts, ss') -> braces m (Node (n,t,l) ts :a) ss' braces m a (Span n l:ss) = braces m (Node (n,False,l) []:a) ss braces _ a (CloseBracket _:ss) = return (reverse a, ss) braces n _ [] = syntaxError n $ "opening brace '{'" ++ "has no matching closing brace '}'" braces _ _ (OpenBracket n:_) = syntaxError n "unexpected '{'" -- | Convert the parse tree into the Field AST -- Also check for dodgy uses of tabs in indentation. mkField :: Int -> SyntaxTree -> ParseResult Field mkField d (Node (n,t,_) _) | d >= 1 && t = tabsError n mkField d (Node (n,_,l) ts) = case span (\c -> isAlphaNum c || c == '-') l of ([], _) -> syntaxError n $ "unrecognised field or section: " ++ show l (name, rest) -> case trimLeading rest of (':':rest') -> do let followingLines = concatMap Tree.flatten ts tabs = not (null [()| (_,True,_) <- followingLines ]) if tabs && d >= 1 then tabsError n else return $ F n (map toLower name) (fieldValue rest' followingLines) rest' -> do ts' <- mapM (mkField (d+1)) ts return (Section n (map toLower name) rest' ts') where fieldValue firstLine followingLines = let firstLine' = trimLeading firstLine followingLines' = map (\(_,_,s) -> stripDot s) followingLines allLines | null firstLine' = followingLines' | otherwise = firstLine' : followingLines' in intercalate "\n" allLines stripDot "." = "" stripDot s = s -- | Convert if/then/else 'Section's to 'IfBlock's ifelse :: [Field] -> ParseResult [Field] ifelse [] = return [] ifelse (Section n "if" cond thenpart :Section _ "else" as elsepart:fs) | null cond = syntaxError n "'if' with missing condition" | null thenpart = syntaxError n "'then' branch of 'if' is empty" | not (null as) = syntaxError n "'else' takes no arguments" | null elsepart = syntaxError n "'else' branch of 'if' is empty" | otherwise = do tp <- ifelse thenpart ep <- ifelse elsepart fs' <- ifelse fs return (IfBlock n cond tp ep:fs') ifelse (Section n "if" cond thenpart:fs) | null cond = syntaxError n "'if' with missing condition" | null thenpart = syntaxError n "'then' branch of 'if' is empty" | otherwise = do tp <- ifelse thenpart fs' <- ifelse fs return (IfBlock n cond tp []:fs') ifelse (Section n "else" _ _:_) = syntaxError n "stray 'else' with no preceding 'if'" ifelse (Section n s a fs':fs) = do fs'' <- ifelse fs' fs''' <- ifelse fs return (Section n s a fs'' : fs''') ifelse (f:fs) = do fs' <- ifelse fs return (f : fs') ------------------------------------------------------------------------------ -- |parse a module Real.name parseModuleNameQ :: ReadP ModuleName parseModuleNameQ = parseQuoted parse <++ parse parseFilePathQ :: ReadP FilePath parseFilePathQ = parseTokenQ -- removed until normalise is no longer broken, was: -- liftM normalise parseTokenQ betweenSpaces :: ReadP a -> ReadP a betweenSpaces act = do skipSpaces res <- act skipSpaces return res parseBuildTool :: ReadP Dependency parseBuildTool = do name <- parseBuildToolNameQ ver <- betweenSpaces $ parseVersionRangeQ <++ return AnyVersion return $ Dependency name ver parseBuildToolNameQ :: ReadP PackageName parseBuildToolNameQ = parseQuoted parseBuildToolName <++ parseBuildToolName -- like parsePackageName but accepts symbols in components parseBuildToolName :: ReadP PackageName parseBuildToolName = do ns <- sepBy1 component (ReadP.char '-') return (PackageName (intercalate "-" ns)) where component = do cs <- munch1 (\c -> isAlphaNum c || c == '+' || c == '_') if all isDigit cs then pfail else return cs -- pkg-config allows versions and other letters in package names, -- eg "gtk+-2.0" is a valid pkg-config package _name_. -- It then has a package version number like 2.10.13 parsePkgconfigDependency :: ReadP Dependency parsePkgconfigDependency = do name <- munch1 (\c -> isAlphaNum c || c `elem` "+-._") ver <- betweenSpaces $ parseVersionRangeQ <++ return AnyVersion return $ Dependency (PackageName name) ver parseVersionRangeQ :: ReadP VersionRange parseVersionRangeQ = parseQuoted parse <++ parse parseTestedWithQ :: ReadP (CompilerFlavor,VersionRange) parseTestedWithQ = parseQuoted tw <++ tw where tw :: ReadP (CompilerFlavor,VersionRange) tw = do compiler <- parseCompilerFlavorCompat version <- betweenSpaces $ parse <++ return AnyVersion return (compiler,version) parseCompilerFlavorCompat :: Parse.ReadP CompilerFlavor parseCompilerFlavorCompat = do comp <- Parse.munch1 Char.isAlphaNum when (all Char.isDigit comp) Parse.pfail case lookup comp compilerMap of Just compiler -> return compiler Nothing -> return (OtherCompiler comp) where compilerMap = [ (show compiler, compiler) | compiler <- knownCompilerFlavors , compiler /= YHC ] knownCompilerFlavors :: [CompilerFlavor] knownCompilerFlavors = [GHC, NHC, YHC, Hugs, HBC, Helium, JHC, LHC, UHC] parseLicenseQ :: ReadP License parseLicenseQ = parseQuoted parse <++ parse parseLanguageQ :: ReadP Language parseLanguageQ = parseQuoted parse <++ parse parseExtensionQ :: ReadP Extension parseExtensionQ = parseQuoted parse <++ parse parseHaskellString :: ReadP String parseHaskellString = readS_to_P reads parseTokenQ :: ReadP String parseTokenQ = parseHaskellString <++ munch1 (\x -> not (isSpace x) && x /= ',') parseTokenQ' :: ReadP String parseTokenQ' = parseHaskellString <++ munch1 (not . isSpace) parseSepList :: ReadP b -> ReadP a -- ^The parser for the stuff between commas -> ReadP [a] parseSepList sepr p = sepBy p separator where separator = betweenSpaces sepr parseSpaceList :: ReadP a -- ^The parser for the stuff between commas -> ReadP [a] parseSpaceList p = sepBy p skipSpaces parseCommaList :: ReadP a -- ^The parser for the stuff between commas -> ReadP [a] parseCommaList = parseSepList (ReadP.char ',') parseOptCommaList :: ReadP a -- ^The parser for the stuff between commas -> ReadP [a] parseOptCommaList = parseSepList (optional (ReadP.char ',')) parseQuoted :: ReadP a -> ReadP a parseQuoted = between (ReadP.char '"') (ReadP.char '"') parseFreeText :: ReadP.ReadP String parseFreeText = ReadP.munch (const True) ident :: Parse.ReadP String ident = Parse.munch1 (\c -> Char.isAlphaNum c || c == '_' || c == '-') lowercase :: String -> String lowercase = map Char.toLower -- -------------------------------------------- -- ** Pretty printing showFilePath :: FilePath -> Doc showFilePath = showToken showToken :: String -> Doc showToken str | not (any dodgy str) && not (null str) = text str | otherwise = text (show str) where dodgy c = isSpace c || c == ',' showTestedWith :: (CompilerFlavor,VersionRange) -> Doc showTestedWith (compiler, version) = text (show compiler) <+> disp version -- | Pretty-print free-format text, ensuring that it is vertically aligned, -- and with blank lines replaced by dots for correct re-parsing. showFreeText :: String -> Doc showFreeText "" = empty showFreeText ('\n' :r) = text " " $+$ text "." $+$ showFreeText r showFreeText s = vcat [text (if null l then "." else l) | l <- lines_ s] -- | 'lines_' breaks a string up into a list of strings at newline -- characters. The resulting strings do not contain newlines. lines_ :: String -> [String] lines_ [] = [""] lines_ s = let (l, s') = break (== '\n') s in l : case s' of [] -> [] (_:s'') -> lines_ s'' class Text a where disp :: a -> Disp.Doc parse :: Parse.ReadP a display :: Text a => a -> String display = Disp.renderStyle style . disp where style = Disp.Style { Disp.mode = Disp.PageMode, Disp.lineLength = 79, Disp.ribbonsPerLine = 1.0 } simpleParse :: Text a => String -> Maybe a simpleParse str = case [ p | (p, s) <- Parse.readP_to_S parse str , all Char.isSpace s ] of [] -> Nothing (p:_) -> Just p -- ----------------------------------------------------------------------------- -- Instances for types from the base package instance Text Bool where disp = Disp.text . show parse = Parse.choice [ (Parse.string "True" Parse.+++ Parse.string "true") >> return True , (Parse.string "False" Parse.+++ Parse.string "false") >> return False ] instance Text Version where disp (Version branch _tags) -- Death to version tags!! = Disp.hcat (Disp.punctuate (Disp.char '.') (map Disp.int branch)) parse = do branch <- Parse.sepBy1 digits (Parse.char '.') tags <- Parse.many (Parse.char '-' >> Parse.munch1 Char.isAlphaNum) return (Version branch tags) --TODO: should we ignore the tags? where digits = do first <- Parse.satisfy Char.isDigit if first == '0' then return 0 else do rest <- Parse.munch Char.isDigit return (read (first : rest)) -- ----------------------------------------------------------------------------- instance Text InstalledPackageId where disp (InstalledPackageId str) = text str parse = InstalledPackageId `fmap` Parse.munch1 abi_char where abi_char c = Char.isAlphaNum c || c `elem` ":-_." instance Text ModuleName where disp (ModuleName ms) = Disp.hcat (intersperse (Disp.char '.') (map Disp.text ms)) parse = do ms <- Parse.sepBy1 component (Parse.char '.') return (ModuleName ms) where component = do c <- Parse.satisfy Char.isUpper cs <- Parse.munch validModuleChar return (c:cs) validModuleChar :: Char -> Bool validModuleChar c = Char.isAlphaNum c || c == '_' || c == '\'' instance Text PackageName where disp (PackageName n) = Disp.text n parse = do ns <- Parse.sepBy1 component (Parse.char '-') return (PackageName (intercalate "-" ns)) where component = do cs <- Parse.munch1 Char.isAlphaNum if all Char.isDigit cs then Parse.pfail else return cs -- each component must contain an alphabetic character, to avoid -- ambiguity in identifiers like foo-1 (the 1 is the version number). instance Text PackageId where disp (PackageId n v) = case v of Version [] _ -> disp n -- if no version, don't show version. _ -> disp n <> Disp.char '-' <> disp v parse = do n <- parse v <- (Parse.char '-' >> parse) <++ return (Version [] []) return (PackageId n v) instance Text VersionRange where disp = fst . foldVersionRange' -- precedence: ( Disp.text "-any" , 0 :: Int) (\v -> (Disp.text "==" <> disp v , 0)) (\v -> (Disp.char '>' <> disp v , 0)) (\v -> (Disp.char '<' <> disp v , 0)) (\v -> (Disp.text ">=" <> disp v , 0)) (\v -> (Disp.text "<=" <> disp v , 0)) (\v _ -> (Disp.text "==" <> dispWild v , 0)) (\(r1, p1) (r2, p2) -> (punct 2 p1 r1 <+> Disp.text "||" <+> punct 2 p2 r2 , 2)) (\(r1, p1) (r2, p2) -> (punct 1 p1 r1 <+> Disp.text "&&" <+> punct 1 p2 r2 , 1)) (\(r, p) -> (Disp.parens r, p)) where dispWild (Version b _) = Disp.hcat (Disp.punctuate (Disp.char '.') (map Disp.int b)) <> Disp.text ".*" punct p p' | p < p' = Disp.parens | otherwise = id parse = expr where expr = do Parse.skipSpaces t <- term Parse.skipSpaces (do _ <- Parse.string "||" Parse.skipSpaces e <- expr return (UnionVersionRanges t e) +++ return t) term = do f <- factor Parse.skipSpaces (do _ <- Parse.string "&&" Parse.skipSpaces t <- term return (IntersectVersionRanges f t) +++ return f) factor = Parse.choice $ parens expr : parseAnyVersion : parseWildcardRange : map parseRangeOp rangeOps parseAnyVersion = Parse.string "-any" >> return AnyVersion parseWildcardRange = do _ <- Parse.string "==" Parse.skipSpaces branch <- Parse.sepBy1 digits (Parse.char '.') _ <- Parse.char '.' _ <- Parse.char '*' return (WildcardVersion (Version branch [])) parens p = Parse.between (Parse.char '(' >> Parse.skipSpaces) (Parse.char ')' >> Parse.skipSpaces) (do a <- p Parse.skipSpaces return (VersionRangeParens a)) digits = do first <- Parse.satisfy Char.isDigit if first == '0' then return 0 else do rest <- Parse.munch Char.isDigit return (read (first : rest)) parseRangeOp (s,f) = Parse.string s >> Parse.skipSpaces >> fmap f parse rangeOps = [ ("<", EarlierVersion), ("<=", orEarlierVersion), (">", LaterVersion), (">=", orLaterVersion), ("==", ThisVersion) ] orLaterVersion :: Version -> VersionRange orLaterVersion v = UnionVersionRanges (ThisVersion v) (LaterVersion v) orEarlierVersion :: Version -> VersionRange orEarlierVersion v = UnionVersionRanges (ThisVersion v) (EarlierVersion v) foldVersionRange :: a -- ^ @\"-any\"@ version -> (Version -> a) -- ^ @\"== v\"@ -> (Version -> a) -- ^ @\"> v\"@ -> (Version -> a) -- ^ @\"< v\"@ -> (a -> a -> a) -- ^ @\"_ || _\"@ union -> (a -> a -> a) -- ^ @\"_ && _\"@ intersection -> VersionRange -> a foldVersionRange anyv this later earlier union intersect = fold where fold AnyVersion = anyv fold (ThisVersion v) = this v fold (LaterVersion v) = later v fold (EarlierVersion v) = earlier v fold (WildcardVersion v) = fold (wildcard v) fold (UnionVersionRanges v1 v2) = union (fold v1) (fold v2) fold (IntersectVersionRanges v1 v2) = intersect (fold v1) (fold v2) fold (VersionRangeParens v) = fold v wildcard v = IntersectVersionRanges (orLaterVersion v) (EarlierVersion (wildcardUpperBound v)) foldVersionRange' :: a -- ^ @\"-any\"@ version -> (Version -> a) -- ^ @\"== v\"@ -> (Version -> a) -- ^ @\"> v\"@ -> (Version -> a) -- ^ @\"< v\"@ -> (Version -> a) -- ^ @\">= v\"@ -> (Version -> a) -- ^ @\"<= v\"@ -> (Version -> Version -> a) -- ^ @\"== v.*\"@ wildcard. The -- function is passed the -- inclusive lower bound and the -- exclusive upper bounds of the -- range defined by the wildcard. -> (a -> a -> a) -- ^ @\"_ || _\"@ union -> (a -> a -> a) -- ^ @\"_ && _\"@ intersection -> (a -> a) -- ^ @\"(_)\"@ parentheses -> VersionRange -> a foldVersionRange' anyv this later earlier orLater orEarlier wildcard union intersect parens = fold where fold AnyVersion = anyv fold (ThisVersion v) = this v fold (LaterVersion v) = later v fold (EarlierVersion v) = earlier v fold (UnionVersionRanges (ThisVersion v) (LaterVersion v')) | v==v' = orLater v fold (UnionVersionRanges (LaterVersion v) (ThisVersion v')) | v==v' = orLater v fold (UnionVersionRanges (ThisVersion v) (EarlierVersion v')) | v==v' = orEarlier v fold (UnionVersionRanges (EarlierVersion v) (ThisVersion v')) | v==v' = orEarlier v fold (WildcardVersion v) = wildcard v (wildcardUpperBound v) fold (UnionVersionRanges v1 v2) = union (fold v1) (fold v2) fold (IntersectVersionRanges v1 v2) = intersect (fold v1) (fold v2) fold (VersionRangeParens v) = parens (fold v) wildcardUpperBound :: Version -> Version wildcardUpperBound (Version lowerBound ts) = Version upperBound ts where upperBound = init lowerBound ++ [last lowerBound + 1] asVersionIntervals :: VersionRange -> [VersionInterval] asVersionIntervals = versionIntervals . toVersionIntervals newtype VersionIntervals = VersionIntervals [VersionInterval] deriving (Eq, Show) -- | Inspect the list of version intervals. -- versionIntervals :: VersionIntervals -> [VersionInterval] versionIntervals (VersionIntervals is) = is type VersionInterval = (LowerBound, UpperBound) data LowerBound = LowerBound Version !Bound deriving (Eq, Show) data UpperBound = NoUpperBound | UpperBound Version !Bound deriving (Eq, Show) data Bound = ExclusiveBound | InclusiveBound deriving (Eq, Show) minLowerBound :: LowerBound minLowerBound = LowerBound (Version [0] []) InclusiveBound isVersion0 :: Version -> Bool isVersion0 (Version [0] _) = True isVersion0 _ = False instance Ord LowerBound where LowerBound ver bound <= LowerBound ver' bound' = case compare ver ver' of LT -> True EQ -> not (bound == ExclusiveBound && bound' == InclusiveBound) GT -> False instance Ord UpperBound where _ <= NoUpperBound = True NoUpperBound <= UpperBound _ _ = False UpperBound ver bound <= UpperBound ver' bound' = case compare ver ver' of LT -> True EQ -> not (bound == InclusiveBound && bound' == ExclusiveBound) GT -> False invariant :: VersionIntervals -> Bool invariant (VersionIntervals intervals) = all validInterval intervals && all doesNotTouch' adjacentIntervals where doesNotTouch' :: (VersionInterval, VersionInterval) -> Bool doesNotTouch' ((_,u), (l',_)) = doesNotTouch u l' adjacentIntervals :: [(VersionInterval, VersionInterval)] adjacentIntervals | null intervals = [] | otherwise = zip intervals (tail intervals) checkInvariant :: VersionIntervals -> VersionIntervals checkInvariant is = assert (invariant is) is validVersion :: Version -> Bool validVersion (Version [] _) = False validVersion (Version vs _) = all (>=0) vs validInterval :: (LowerBound, UpperBound) -> Bool validInterval i@(l, u) = validLower l && validUpper u && nonEmpty i where validLower (LowerBound v _) = validVersion v validUpper NoUpperBound = True validUpper (UpperBound v _) = validVersion v -- Check an interval is non-empty -- nonEmpty :: VersionInterval -> Bool nonEmpty (_, NoUpperBound ) = True nonEmpty (LowerBound l lb, UpperBound u ub) = (l < u) || (l == u && lb == InclusiveBound && ub == InclusiveBound) -- Check an upper bound does not intersect, or even touch a lower bound: -- -- ---| or ---) but not ---] or ---) or ---] -- |--- (--- (--- [--- [--- -- doesNotTouch :: UpperBound -> LowerBound -> Bool doesNotTouch NoUpperBound _ = False doesNotTouch (UpperBound u ub) (LowerBound l lb) = u < l || (u == l && ub == ExclusiveBound && lb == ExclusiveBound) -- | Check an upper bound does not intersect a lower bound: -- -- ---| or ---) or ---] or ---) but not ---] -- |--- (--- (--- [--- [--- -- doesNotIntersect :: UpperBound -> LowerBound -> Bool doesNotIntersect NoUpperBound _ = False doesNotIntersect (UpperBound u ub) (LowerBound l lb) = u < l || (u == l && not (ub == InclusiveBound && lb == InclusiveBound)) toVersionIntervals :: VersionRange -> VersionIntervals toVersionIntervals = foldVersionRange ( chkIvl (minLowerBound, NoUpperBound)) (\v -> chkIvl (LowerBound v InclusiveBound, UpperBound v InclusiveBound)) (\v -> chkIvl (LowerBound v ExclusiveBound, NoUpperBound)) (\v -> if isVersion0 v then VersionIntervals [] else chkIvl (minLowerBound, UpperBound v ExclusiveBound)) unionVersionIntervals intersectVersionIntervals where chkIvl interval = checkInvariant (VersionIntervals [interval]) unionVersionIntervals :: VersionIntervals -> VersionIntervals -> VersionIntervals unionVersionIntervals (VersionIntervals is0) (VersionIntervals is'0) = checkInvariant (VersionIntervals (union is0 is'0)) where union is [] = is union [] is' = is' union (i:is) (i':is') = case unionInterval i i' of Left Nothing -> i : union is (i' :is') Left (Just i'') -> union is (i'':is') Right Nothing -> i' : union (i :is) is' Right (Just i'') -> union (i'':is) is' unionInterval :: VersionInterval -> VersionInterval -> Either (Maybe VersionInterval) (Maybe VersionInterval) unionInterval (lower , upper ) (lower', upper') -- Non-intersecting intervals with the left interval ending first | upper `doesNotTouch` lower' = Left Nothing -- Non-intersecting intervals with the right interval first | upper' `doesNotTouch` lower = Right Nothing -- Complete or partial overlap, with the left interval ending first | upper <= upper' = lowerBound `seq` Left (Just (lowerBound, upper')) -- Complete or partial overlap, with the left interval ending first | otherwise = lowerBound `seq` Right (Just (lowerBound, upper)) where lowerBound = min lower lower' intersectVersionIntervals :: VersionIntervals -> VersionIntervals -> VersionIntervals intersectVersionIntervals (VersionIntervals is0) (VersionIntervals is'0) = checkInvariant (VersionIntervals (intersect is0 is'0)) where intersect _ [] = [] intersect [] _ = [] intersect (i:is) (i':is') = case intersectInterval i i' of Left Nothing -> intersect is (i':is') Left (Just i'') -> i'' : intersect is (i':is') Right Nothing -> intersect (i:is) is' Right (Just i'') -> i'' : intersect (i:is) is' intersectInterval :: VersionInterval -> VersionInterval -> Either (Maybe VersionInterval) (Maybe VersionInterval) intersectInterval (lower , upper ) (lower', upper') -- Non-intersecting intervals with the left interval ending first | upper `doesNotIntersect` lower' = Left Nothing -- Non-intersecting intervals with the right interval first | upper' `doesNotIntersect` lower = Right Nothing -- Complete or partial overlap, with the left interval ending first | upper <= upper' = lowerBound `seq` Left (Just (lowerBound, upper)) -- Complete or partial overlap, with the right interval ending first | otherwise = lowerBound `seq` Right (Just (lowerBound, upper')) where lowerBound = max lower lower' instance Text Dependency where disp (Dependency name ver) = disp name <+> disp ver parse = do name <- parse Parse.skipSpaces ver <- parse <++ return AnyVersion Parse.skipSpaces return (Dependency name ver) instance Text License where disp (GPL version) = Disp.text "GPL" <> dispOptVersion version disp (LGPL version) = Disp.text "LGPL" <> dispOptVersion version disp (AGPL version) = Disp.text "AGPL" <> dispOptVersion version disp (Apache version) = Disp.text "Apache" <> dispOptVersion version disp (UnknownLicense other) = Disp.text other disp other = Disp.text (show other) parse = do name <- Parse.munch1 (\c -> Char.isAlphaNum c && c /= '-') version <- Parse.option Nothing (Parse.char '-' >> fmap Just parse) return $! case (name, version :: Maybe Version) of ("GPL", _ ) -> GPL version ("LGPL", _ ) -> LGPL version ("AGPL", _ ) -> AGPL version ("BSD3", Nothing) -> BSD3 ("BSD4", Nothing) -> BSD4 ("MIT", Nothing) -> MIT ("Apache", _ ) -> Apache version ("PublicDomain", Nothing) -> PublicDomain ("AllRightsReserved", Nothing) -> AllRightsReserved ("OtherLicense", Nothing) -> OtherLicense _ -> UnknownLicense $ name ++ maybe "" (('-':) . display) version dispOptVersion :: Maybe Version -> Disp.Doc dispOptVersion Nothing = Disp.empty dispOptVersion (Just v) = Disp.char '-' <> disp v instance Text CompilerFlavor where disp (OtherCompiler name) = Disp.text name disp (HaskellSuite name) = Disp.text name disp NHC = Disp.text "nhc98" disp other = Disp.text (lowercase (show other)) parse = do comp <- Parse.munch1 Char.isAlphaNum when (all Char.isDigit comp) Parse.pfail return (classifyCompilerFlavor comp) classifyCompilerFlavor :: String -> CompilerFlavor classifyCompilerFlavor s = fromMaybe (OtherCompiler s) $ lookup (lowercase s) compilerMap where compilerMap = [ (display compiler, compiler) | compiler <- knownCompilerFlavors ] knownCompilerFlavors :: [CompilerFlavor] knownCompilerFlavors = [GHC, NHC, YHC, Hugs, HBC, Helium, JHC, LHC, UHC] instance Text Language where disp (UnknownLanguage other) = Disp.text other disp other = Disp.text (show other) parse = do lang <- Parse.munch1 Char.isAlphaNum return (classifyLanguage lang) classifyLanguage :: String -> Language classifyLanguage = \str -> case lookup str langTable of Just lang -> lang Nothing -> UnknownLanguage str where langTable = [ (show lang, lang) | lang <- knownLanguages ] knownLanguages :: [Language] knownLanguages = [Haskell98, Haskell2010] instance Text Extension where disp (UnknownExtension other) = Disp.text other disp (EnableExtension ke) = Disp.text (show ke) disp (DisableExtension ke) = Disp.text ("No" ++ show ke) parse = do extension <- Parse.munch1 Char.isAlphaNum return (classifyExtension extension) instance Text KnownExtension where disp ke = Disp.text (show ke) parse = do extension <- Parse.munch1 Char.isAlphaNum case classifyKnownExtension extension of Just ke -> return ke Nothing -> fail ("Can't parse " ++ show extension ++ " as KnownExtension") classifyExtension :: String -> Extension classifyExtension string = case classifyKnownExtension string of Just ext -> EnableExtension ext Nothing -> case string of 'N':'o':string' -> case classifyKnownExtension string' of Just ext -> DisableExtension ext Nothing -> UnknownExtension string _ -> UnknownExtension string -- | 'read' for 'KnownExtension's is really really slow so for the Text -- instance -- what we do is make a simple table indexed off the first letter in the -- extension name. The extension names actually cover the range @'A'-'Z'@ -- pretty densely and the biggest bucket is 7 so it's not too bad. We just do -- a linear search within each bucket. -- -- This gives an order of magnitude improvement in parsing speed, and it'll -- also allow us to do case insensitive matches in future if we prefer. -- classifyKnownExtension :: String -> Maybe KnownExtension classifyKnownExtension "" = Nothing classifyKnownExtension string@(c : _) | inRange (bounds knownExtensionTable) c = lookup string (knownExtensionTable ! c) | otherwise = Nothing knownExtensionTable :: Array Char [(String, KnownExtension)] knownExtensionTable = accumArray (flip (:)) [] ('A', 'Z') [ (head str, (str, extension)) | extension <- [toEnum 0 ..] , let str = show extension ] instance Text BuildType where disp (UnknownBuildType other) = Disp.text other disp other = Disp.text (show other) parse = do name <- Parse.munch1 Char.isAlphaNum return $ case name of "Simple" -> Simple "Configure" -> Configure "Custom" -> Custom "Make" -> Make _ -> UnknownBuildType name instance Text BenchmarkType where disp (BenchmarkTypeExe ver) = text "exitcode-stdio-" <> disp ver disp (BenchmarkTypeUnknown name ver) = text name <> Disp.char '-' <> disp ver parse = stdParse $ \ver name -> case name of "exitcode-stdio" -> BenchmarkTypeExe ver _ -> BenchmarkTypeUnknown name ver stdParse :: Text ver => (ver -> String -> res) -> Parse.ReadP res stdParse f = do cs <- Parse.sepBy1 component (Parse.char '-') _ <- Parse.char '-' ver <- parse let name = intercalate "-" cs return $! f ver (lowercase name) where component = do cs <- Parse.munch1 Char.isAlphaNum if all Char.isDigit cs then Parse.pfail else return cs -- each component must contain an alphabetic character, to avoid -- ambiguity in identifiers like foo-1 (the 1 is the version number). instance Text RepoKind where disp RepoHead = Disp.text "head" disp RepoThis = Disp.text "this" disp (RepoKindUnknown other) = Disp.text other parse = do name <- ident return $ case lowercase name of "head" -> RepoHead "this" -> RepoThis _ -> RepoKindUnknown name instance Text RepoType where disp (OtherRepoType other) = Disp.text other disp other = Disp.text (lowercase (show other)) parse = fmap classifyRepoType ident classifyRepoType :: String -> RepoType classifyRepoType s = fromMaybe (OtherRepoType s) $ lookup (lowercase s) repoTypeMap where repoTypeMap = [ (name, repoType') | repoType' <- knownRepoTypes , name <- display repoType' : repoTypeAliases repoType' ] knownRepoTypes :: [RepoType] knownRepoTypes = [Darcs, Git, SVN, CVS ,Mercurial, GnuArch, Bazaar, Monotone] repoTypeAliases :: RepoType -> [String] repoTypeAliases Bazaar = ["bzr"] repoTypeAliases Mercurial = ["hg"] repoTypeAliases GnuArch = ["arch"] repoTypeAliases _ = [] instance Text Arch where disp (OtherArch name) = Disp.text name disp other = Disp.text (lowercase (show other)) parse = fmap classifyArch ident classifyArch :: String -> Arch classifyArch s = fromMaybe (OtherArch s) $ lookup (lowercase s) archMap where archMap = [ (display arch, arch) | arch <- knownArches ] knownArches :: [Arch] knownArches = [I386, X86_64, PPC, PPC64, Sparc ,Arm, Mips, SH ,IA64, S390 ,Alpha, Hppa, Rs6000 ,M68k, Vax] instance Text OS where disp (OtherOS name) = Disp.text name disp other = Disp.text (lowercase (show other)) parse = fmap classifyOS ident classifyOS :: String -> OS classifyOS s = fromMaybe (OtherOS s) $ lookup (lowercase s) osMap where osMap = [ (name, os) | os <- knownOSs , name <- display os : osAliases os ] knownOSs :: [OS] knownOSs = [Linux, Windows, OSX ,FreeBSD, OpenBSD, NetBSD ,Solaris, AIX, HPUX, IRIX ,HaLVM ,IOS] osAliases :: OS -> [String] osAliases Windows = ["mingw32", "win32"] osAliases _ = [] -- ----------------------------------------------------------------------------- -- The PackageDescription type pkgDescrFieldDescrs :: [FieldDescr PackageDescription] pkgDescrFieldDescrs = [ simpleField "name" disp parse (pkgName.package) (\name pkg -> pkg{package=(package pkg){pkgName=name}}) , simpleField "version" disp parse (pkgVersion.package) (\ver pkg -> pkg{package=(package pkg){pkgVersion=ver}}) , simpleField "cabal-version" (either disp disp) (liftM Left parse +++ liftM Right parse) specVersionRaw (\v pkg -> pkg{specVersionRaw=v}) , simpleField "build-type" (maybe empty disp) (fmap Just parse) buildType (\t pkg -> pkg{buildType=t}) , simpleField "license" disp parseLicenseQ license (\l pkg -> pkg{license=l}) , simpleField "license-file" showFilePath parseFilePathQ licenseFile (\l pkg -> pkg{licenseFile=l}) , simpleField "copyright" showFreeText parseFreeText copyright (\val pkg -> pkg{copyright=val}) , simpleField "maintainer" showFreeText parseFreeText maintainer (\val pkg -> pkg{maintainer=val}) , commaListField "build-depends" disp parse buildDepends (\xs pkg -> pkg{buildDepends=xs}) , simpleField "stability" showFreeText parseFreeText stability (\val pkg -> pkg{stability=val}) , simpleField "homepage" showFreeText parseFreeText homepage (\val pkg -> pkg{homepage=val}) , simpleField "package-url" showFreeText parseFreeText pkgUrl (\val pkg -> pkg{pkgUrl=val}) , simpleField "bug-reports" showFreeText parseFreeText bugReports (\val pkg -> pkg{bugReports=val}) , simpleField "synopsis" showFreeText parseFreeText synopsis (\val pkg -> pkg{synopsis=val}) , simpleField "description" showFreeText parseFreeText description (\val pkg -> pkg{description=val}) , simpleField "category" showFreeText parseFreeText category (\val pkg -> pkg{category=val}) , simpleField "author" showFreeText parseFreeText author (\val pkg -> pkg{author=val}) , listField "tested-with" showTestedWith parseTestedWithQ testedWith (\val pkg -> pkg{testedWith=val}) , listField "data-files" showFilePath parseFilePathQ dataFiles (\val pkg -> pkg{dataFiles=val}) , simpleField "data-dir" showFilePath parseFilePathQ dataDir (\val pkg -> pkg{dataDir=val}) , listField "extra-source-files" showFilePath parseFilePathQ extraSrcFiles (\val pkg -> pkg{extraSrcFiles=val}) , listField "extra-tmp-files" showFilePath parseFilePathQ extraTmpFiles (\val pkg -> pkg{extraTmpFiles=val}) , listField "extra-doc-files" showFilePath parseFilePathQ extraDocFiles (\val pkg -> pkg{extraDocFiles=val}) ] -- | Store any fields beginning with "x-" in the customFields field of -- a PackageDescription. All other fields will generate a warning. storeXFieldsPD :: UnrecFieldParser PackageDescription storeXFieldsPD (f@('x':'-':_),val) pkg = Just pkg{ customFieldsPD = customFieldsPD pkg ++ [(f,val)]} storeXFieldsPD _ _ = Nothing -- --------------------------------------------------------------------------- -- The Library type libFieldDescrs :: [FieldDescr Library] libFieldDescrs = [ listField "exposed-modules" disp parseModuleNameQ exposedModules (\mods lib -> lib{exposedModules=mods}) , boolField "exposed" libExposed (\val lib -> lib{libExposed=val}) ] ++ map biToLib binfoFieldDescrs where biToLib = liftField libBuildInfo (\bi lib -> lib{libBuildInfo=bi}) storeXFieldsLib :: UnrecFieldParser Library storeXFieldsLib (f@('x':'-':_), val) l@(Library { libBuildInfo = bi }) = Just $ l {libBuildInfo = bi{ customFieldsBI = customFieldsBI bi ++ [(f,val)]}} storeXFieldsLib _ _ = Nothing -- --------------------------------------------------------------------------- -- The Executable type executableFieldDescrs :: [FieldDescr Executable] executableFieldDescrs = [ -- note ordering: configuration must come first, for -- showPackageDescription. simpleField "executable" showToken parseTokenQ exeName (\xs exe -> exe{exeName=xs}) , simpleField "main-is" showFilePath parseFilePathQ modulePath (\xs exe -> exe{modulePath=xs}) ] ++ map biToExe binfoFieldDescrs where biToExe = liftField buildInfo (\bi exe -> exe{buildInfo=bi}) storeXFieldsExe :: UnrecFieldParser Executable storeXFieldsExe (f@('x':'-':_), val) e@(Executable { buildInfo = bi }) = Just $ e {buildInfo = bi{ customFieldsBI = (f,val):customFieldsBI bi}} storeXFieldsExe _ _ = Nothing -- --------------------------------------------------------------------------- -- The TestSuite type -- | An intermediate type just used for parsing the test-suite stanza. -- After validation it is converted into the proper 'TestSuite' type. data TestSuiteStanza = TestSuiteStanza { testStanzaTestType :: Maybe TestType, testStanzaMainIs :: Maybe FilePath, testStanzaTestModule :: Maybe ModuleName, testStanzaBuildInfo :: BuildInfo } emptyTestStanza :: TestSuiteStanza emptyTestStanza = TestSuiteStanza Nothing Nothing Nothing mempty testSuiteFieldDescrs :: [FieldDescr TestSuiteStanza] testSuiteFieldDescrs = [ simpleField "type" (maybe empty disp) (fmap Just parse) testStanzaTestType (\x suite -> suite { testStanzaTestType = x }) , simpleField "main-is" (maybe empty showFilePath) (fmap Just parseFilePathQ) testStanzaMainIs (\x suite -> suite { testStanzaMainIs = x }) , simpleField "test-module" (maybe empty disp) (fmap Just parseModuleNameQ) testStanzaTestModule (\x suite -> suite { testStanzaTestModule = x }) ] ++ map biToTest binfoFieldDescrs where biToTest = liftField testStanzaBuildInfo (\bi suite -> suite { testStanzaBuildInfo = bi }) storeXFieldsTest :: UnrecFieldParser TestSuiteStanza storeXFieldsTest (f@('x':'-':_), val) t@(TestSuiteStanza { testStanzaBuildInfo = bi }) = Just $ t {testStanzaBuildInfo = bi{ customFieldsBI = (f,val):customFieldsBI bi}} storeXFieldsTest _ _ = Nothing validateTestSuite :: LineNo -> TestSuiteStanza -> ParseResult TestSuite validateTestSuite line stanza = case testStanzaTestType stanza of Nothing -> return $ emptyTestSuite { testBuildInfo = testStanzaBuildInfo stanza } Just tt@(TestTypeUnknown _ _) -> return emptyTestSuite { testInterface = TestSuiteUnsupported tt, testBuildInfo = testStanzaBuildInfo stanza } Just tt | tt `notElem` knownTestTypes -> return emptyTestSuite { testInterface = TestSuiteUnsupported tt, testBuildInfo = testStanzaBuildInfo stanza } Just tt@(TestTypeExe ver) -> case testStanzaMainIs stanza of Nothing -> syntaxError line (missingField "main-is" tt) Just file -> do when (isJust (testStanzaTestModule stanza)) $ warning (extraField "test-module" tt) return emptyTestSuite { testInterface = TestSuiteExeV10 ver file, testBuildInfo = testStanzaBuildInfo stanza } Just tt@(TestTypeLib ver) -> case testStanzaTestModule stanza of Nothing -> syntaxError line (missingField "test-module" tt) Just module_ -> do when (isJust (testStanzaMainIs stanza)) $ warning (extraField "main-is" tt) return emptyTestSuite { testInterface = TestSuiteLibV09 ver module_, testBuildInfo = testStanzaBuildInfo stanza } where missingField name tt = "The '" ++ name ++ "' field is required for the " ++ display tt ++ " test suite type." extraField name tt = "The '" ++ name ++ "' field is not used for the '" ++ display tt ++ "' test suite type." instance Text TestType where disp (TestTypeExe ver) = text "exitcode-stdio-" <> disp ver disp (TestTypeLib ver) = text "detailed-" <> disp ver disp (TestTypeUnknown name ver) = text name <> Disp.char '-' <> disp ver parse = stdParse $ \ver name -> case name of "exitcode-stdio" -> TestTypeExe ver "detailed" -> TestTypeLib ver _ -> TestTypeUnknown name ver knownTestTypes :: [TestType] knownTestTypes = [ TestTypeExe (Version [1,0] []) , TestTypeLib (Version [0,9] []) ] -- --------------------------------------------------------------------------- -- The Benchmark type -- | An intermediate type just used for parsing the benchmark stanza. -- After validation it is converted into the proper 'Benchmark' type. data BenchmarkStanza = BenchmarkStanza { benchmarkStanzaBenchmarkType :: Maybe BenchmarkType, benchmarkStanzaMainIs :: Maybe FilePath, benchmarkStanzaBenchmarkModule :: Maybe ModuleName, benchmarkStanzaBuildInfo :: BuildInfo } emptyBenchmarkStanza :: BenchmarkStanza emptyBenchmarkStanza = BenchmarkStanza Nothing Nothing Nothing mempty benchmarkFieldDescrs :: [FieldDescr BenchmarkStanza] benchmarkFieldDescrs = [ simpleField "type" (maybe empty disp) (fmap Just parse) benchmarkStanzaBenchmarkType (\x suite -> suite { benchmarkStanzaBenchmarkType = x }) , simpleField "main-is" (maybe empty showFilePath) (fmap Just parseFilePathQ) benchmarkStanzaMainIs (\x suite -> suite { benchmarkStanzaMainIs = x }) ] ++ map biToBenchmark binfoFieldDescrs where biToBenchmark = liftField benchmarkStanzaBuildInfo (\bi suite -> suite { benchmarkStanzaBuildInfo = bi }) storeXFieldsBenchmark :: UnrecFieldParser BenchmarkStanza storeXFieldsBenchmark (f@('x':'-':_), val) t@(BenchmarkStanza { benchmarkStanzaBuildInfo = bi }) = Just $ t {benchmarkStanzaBuildInfo = bi{ customFieldsBI = (f,val):customFieldsBI bi}} storeXFieldsBenchmark _ _ = Nothing validateBenchmark :: LineNo -> BenchmarkStanza -> ParseResult Benchmark validateBenchmark line stanza = case benchmarkStanzaBenchmarkType stanza of Nothing -> return $ emptyBenchmark { benchmarkBuildInfo = benchmarkStanzaBuildInfo stanza } Just tt@(BenchmarkTypeUnknown _ _) -> return emptyBenchmark { benchmarkInterface = BenchmarkUnsupported tt, benchmarkBuildInfo = benchmarkStanzaBuildInfo stanza } Just tt | tt `notElem` knownBenchmarkTypes -> return emptyBenchmark { benchmarkInterface = BenchmarkUnsupported tt, benchmarkBuildInfo = benchmarkStanzaBuildInfo stanza } Just tt@(BenchmarkTypeExe ver) -> case benchmarkStanzaMainIs stanza of Nothing -> syntaxError line (missingField "main-is" tt) Just file -> do when (isJust (benchmarkStanzaBenchmarkModule stanza)) $ warning (extraField "benchmark-module" tt) return emptyBenchmark { benchmarkInterface = BenchmarkExeV10 ver file, benchmarkBuildInfo = benchmarkStanzaBuildInfo stanza } where missingField name tt = "The '" ++ name ++ "' field is required for the " ++ display tt ++ " benchmark type." extraField name tt = "The '" ++ name ++ "' field is not used for the '" ++ display tt ++ "' benchmark type." knownBenchmarkTypes :: [BenchmarkType] knownBenchmarkTypes = [ BenchmarkTypeExe (Version [1,0] []) ] -- --------------------------------------------------------------------------- -- The BuildInfo type binfoFieldDescrs :: [FieldDescr BuildInfo] binfoFieldDescrs = [ boolField "buildable" buildable (\val binfo -> binfo{buildable=val}) , commaListField "build-tools" disp parseBuildTool buildTools (\xs binfo -> binfo{buildTools=xs}) , spaceListField "cpp-options" showToken parseTokenQ' cppOptions (\val binfo -> binfo{cppOptions=val}) , spaceListField "cc-options" showToken parseTokenQ' ccOptions (\val binfo -> binfo{ccOptions=val}) , spaceListField "ld-options" showToken parseTokenQ' ldOptions (\val binfo -> binfo{ldOptions=val}) , commaListField "pkgconfig-depends" disp parsePkgconfigDependency pkgconfigDepends (\xs binfo -> binfo{pkgconfigDepends=xs}) , listField "frameworks" showToken parseTokenQ frameworks (\val binfo -> binfo{frameworks=val}) , listField "c-sources" showFilePath parseFilePathQ cSources (\paths binfo -> binfo{cSources=paths}) , simpleField "default-language" (maybe empty disp) (option Nothing (fmap Just parseLanguageQ)) defaultLanguage (\lang binfo -> binfo{defaultLanguage=lang}) , listField "other-languages" disp parseLanguageQ otherLanguages (\langs binfo -> binfo{otherLanguages=langs}) , listField "default-extensions" disp parseExtensionQ defaultExtensions (\exts binfo -> binfo{defaultExtensions=exts}) , listField "other-extensions" disp parseExtensionQ otherExtensions (\exts binfo -> binfo{otherExtensions=exts}) , listField "extensions" disp parseExtensionQ oldExtensions (\exts binfo -> binfo{oldExtensions=exts}) , listField "extra-libraries" showToken parseTokenQ extraLibs (\xs binfo -> binfo{extraLibs=xs}) , listField "extra-lib-dirs" showFilePath parseFilePathQ extraLibDirs (\xs binfo -> binfo{extraLibDirs=xs}) , listField "includes" showFilePath parseFilePathQ includes (\paths binfo -> binfo{includes=paths}) , listField "install-includes" showFilePath parseFilePathQ installIncludes (\paths binfo -> binfo{installIncludes=paths}) , listField "include-dirs" showFilePath parseFilePathQ includeDirs (\paths binfo -> binfo{includeDirs=paths}) , listField "hs-source-dirs" showFilePath parseFilePathQ hsSourceDirs (\paths binfo -> binfo{hsSourceDirs=paths}) , listField "other-modules" disp parseModuleNameQ otherModules (\val binfo -> binfo{otherModules=val}) , listField "ghc-prof-options" text parseTokenQ ghcProfOptions (\val binfo -> binfo{ghcProfOptions=val}) , listField "ghc-shared-options" text parseTokenQ ghcSharedOptions (\val binfo -> binfo{ghcSharedOptions=val}) , optsField "ghc-options" GHC options (\path binfo -> binfo{options=path}) , optsField "hugs-options" Hugs options (\path binfo -> binfo{options=path}) , optsField "nhc98-options" NHC options (\path binfo -> binfo{options=path}) , optsField "jhc-options" JHC options (\path binfo -> binfo{options=path}) ] ------------------------------------------------------------------------------ flagFieldDescrs :: [FieldDescr Flag] flagFieldDescrs = [ simpleField "description" showFreeText parseFreeText flagDescription (\val fl -> fl{ flagDescription = val }) , boolField "default" flagDefault (\val fl -> fl{ flagDefault = val }) , boolField "manual" flagManual (\val fl -> fl{ flagManual = val }) ] ------------------------------------------------------------------------------ sourceRepoFieldDescrs :: [FieldDescr SourceRepo] sourceRepoFieldDescrs = [ simpleField "type" (maybe empty disp) (fmap Just parse) repoType (\val repo -> repo { repoType = val }) , simpleField "location" (maybe empty showFreeText) (fmap Just parseFreeText) repoLocation (\val repo -> repo { repoLocation = val }) , simpleField "module" (maybe empty showToken) (fmap Just parseTokenQ) repoModule (\val repo -> repo { repoModule = val }) , simpleField "branch" (maybe empty showToken) (fmap Just parseTokenQ) repoBranch (\val repo -> repo { repoBranch = val }) , simpleField "tag" (maybe empty showToken) (fmap Just parseTokenQ) repoTag (\val repo -> repo { repoTag = val }) , simpleField "subdir" (maybe empty showFilePath) (fmap Just parseFilePathQ) repoSubdir (\val repo -> repo { repoSubdir = val }) ] -- --------------------------------------------------------------- -- Parsing mapSimpleFields :: (Field -> ParseResult Field) -> [Field] -> ParseResult [Field] mapSimpleFields f = mapM walk where walk fld@F{} = f fld walk (IfBlock l c fs1 fs2) = do fs1' <- mapM walk fs1 fs2' <- mapM walk fs2 return (IfBlock l c fs1' fs2') walk (Section ln n l fs1) = do fs1' <- mapM walk fs1 return (Section ln n l fs1') -- prop_isMapM fs = mapSimpleFields return fs == return fs -- names of fields that represents dependencies, thus consrca constraintFieldNames :: [String] constraintFieldNames = ["build-depends"] -- Possible refactoring would be to have modifiers be explicit about what -- they add and define an accessor that specifies what the dependencies -- are. This way we would completely reuse the parsing knowledge from the -- field descriptor. parseConstraint :: Field -> ParseResult [Dependency] parseConstraint (F l n v) | n == "build-depends" = runP l n (parseCommaList parse) v parseConstraint f = userBug $ "Constraint was expected (got: " ++ show f ++ ")" {- headerFieldNames :: [String] headerFieldNames = filter (\n -> not (n `elem` constraintFieldNames)) . map fieldName $ pkgDescrFieldDescrs -} libFieldNames :: [String] libFieldNames = map fieldName libFieldDescrs ++ buildInfoNames ++ constraintFieldNames -- exeFieldNames :: [String] -- exeFieldNames = map fieldName executableFieldDescrs -- ++ buildInfoNames buildInfoNames :: [String] buildInfoNames = map fieldName binfoFieldDescrs ++ map fst deprecatedFieldsBuildInfo -- A minimal implementation of the StateT monad transformer to avoid depending -- on the 'mtl' package. newtype StT s m a = StT { runStT :: s -> m (a,s) } instance Functor f => Functor (StT s f) where fmap g (StT f) = StT $ fmap (\(x, s) -> (g x, s)) . f instance (Monad m, Functor m) => Applicative (StT s m) where pure = return (<*>) = ap instance Monad m => Monad (StT s m) where return a = StT (\s -> return (a,s)) StT f >>= g = StT $ \s -> do (a,s') <- f s runStT (g a) s' get :: Monad m => StT s m s get = StT $ \s -> return (s, s) modify :: Monad m => (s -> s) -> StT s m () modify f = StT $ \s -> return ((),f s) lift :: Monad m => m a -> StT s m a lift m = StT $ \s -> m >>= \a -> return (a,s) evalStT :: Monad m => StT s m a -> s -> m a evalStT st s = liftM fst $ runStT st s -- Our monad for parsing a list/tree of fields. -- -- The state represents the remaining fields to be processed. type PM a = StT [Field] ParseResult a -- return look-ahead field or nothing if we're at the end of the file peekField :: PM (Maybe Field) peekField = liftM listToMaybe get -- Unconditionally discard the first field in our state. Will error when it -- reaches end of file. (Yes, that's evil.) skipField :: PM () skipField = modify tail parsePackageDescription :: String -> ParseResult GenericPackageDescription parsePackageDescription file = do -- This function is quite complex because it needs to be able to parse -- both pre-Cabal-1.2 and post-Cabal-1.2 files. Additionally, it contains -- a lot of parser-related noise since we do not want to depend on Parsec. -- -- If we detect an pre-1.2 file we implicitly convert it to post-1.2 -- style. See 'sectionizeFields' below for details about the conversion. fields0 <- readFields file `catchParseError` \err -> let tabs = findIndentTabs file in case err of -- In case of a TabsError report them all at once. TabsError tabLineNo -> reportTabsError -- but only report the ones including and following -- the one that caused the actual error [ t | t@(lineNo',_) <- tabs , lineNo' >= tabLineNo ] _ -> parseFail err let cabalVersionNeeded = head $ [ minVersionBound versionRange | Just versionRange <- [ simpleParse v | F _ "cabal-version" v <- fields0 ] ] ++ [Version [0] []] minVersionBound versionRange = case asVersionIntervals versionRange of [] -> Version [0] [] ((LowerBound version _, _):_) -> version handleFutureVersionParseFailure cabalVersionNeeded $ do let sf = sectionizeFields fields0 -- ensure 1.2 format -- figure out and warn about deprecated stuff (warnings are collected -- inside our parsing monad) fields <- mapSimpleFields deprecField sf -- Our parsing monad takes the not-yet-parsed fields as its state. -- After each successful parse we remove the field from the state -- ('skipField') and move on to the next one. -- -- Things are complicated a bit, because fields take a tree-like -- structure -- they can be sections or "if"/"else" conditionals. flip evalStT fields $ do -- The header consists of all simple fields up to the first section -- (flag, library, executable). header_fields <- getHeader [] -- Parses just the header fields and stores them in a -- 'PackageDescription'. Note that our final result is a -- 'GenericPackageDescription'; for pragmatic reasons we just store -- the partially filled-out 'PackageDescription' inside the -- 'GenericPackageDescription'. pkg <- lift $ parseFields pkgDescrFieldDescrs storeXFieldsPD emptyPackageDescription header_fields -- 'getBody' assumes that the remaining fields only consist of -- flags, lib and exe sections. (repos, flags, mlib, exes, tests, bms) <- getBody warnIfRest -- warn if getBody did not parse up to the last field. -- warn about using old/new syntax with wrong cabal-version: maybeWarnCabalVersion (not $ oldSyntax fields0) pkg checkForUndefinedFlags flags mlib exes tests return $ GenericPackageDescription pkg { sourceRepos = repos } flags mlib exes tests bms where oldSyntax = all isSimpleField reportTabsError tabs = syntaxError (fst (head tabs)) $ "Do not use tabs for indentation (use spaces instead)\n" ++ " Tabs were used at (line,column): " ++ show tabs maybeWarnCabalVersion newsyntax pkg | newsyntax && specVersion pkg < Version [1,2] [] = lift $ warning $ "A package using section syntax must specify at least\n" ++ "'cabal-version: >= 1.2'." maybeWarnCabalVersion newsyntax pkg | not newsyntax && specVersion pkg >= Version [1,2] [] = lift $ warning $ "A package using 'cabal-version: " ++ displaySpecVersion (specVersionRaw pkg) ++ "' must use section syntax. See the Cabal user guide for details." where displaySpecVersion (Left version) = display version displaySpecVersion (Right versionRange) = case asVersionIntervals versionRange of [] {- impossible -} -> display versionRange ((LowerBound version _, _):_) -> display (orLaterVersion version) maybeWarnCabalVersion _ _ = return () specVersion :: PackageDescription -> Version specVersion pkg = case specVersionRaw pkg of Left version -> version Right versionRange -> case asVersionIntervals versionRange of [] -> Version [0] [] ((LowerBound version _, _):_) -> version handleFutureVersionParseFailure cabalVersionNeeded parseBody = (unless versionOk (warning message) >> parseBody) `catchParseError` \parseError -> case parseError of TabsError _ -> parseFail parseError _ | versionOk -> parseFail parseError | otherwise -> fail message where versionOk = cabalVersionNeeded <= cabalVersion message = "This package requires at least Cabal version " ++ display cabalVersionNeeded cabalVersion :: Version cabalVersion = Version [1,16] [] -- "Sectionize" an old-style Cabal file. A sectionized file has: -- -- * all global fields at the beginning, followed by -- -- * all flag declarations, followed by -- -- * an optional library section, and an arbitrary number of executable -- sections (in any order). -- -- The current implementatition just gathers all library-specific fields -- in a library section and wraps all executable stanzas in an executable -- section. sectionizeFields :: [Field] -> [Field] sectionizeFields fs | oldSyntax fs = let -- "build-depends" is a local field now. To be backwards -- compatible, we still allow it as a global field in old-style -- package description files and translate it to a local field by -- adding it to every non-empty section (hdr0, exes0) = break ((=="executable") . fName) fs (hdr, libfs0) = partition (not . (`elem` libFieldNames) . fName) hdr0 (deps, libfs) = partition ((== "build-depends") . fName) libfs0 exes = unfoldr toExe exes0 toExe [] = Nothing toExe (F l e n : r) | e == "executable" = let (efs, r') = break ((=="executable") . fName) r in Just (Section l "executable" n (deps ++ efs), r') toExe _ = cabalBug "unexpected input to 'toExe'" in hdr ++ (if null libfs then [] else [Section (lineNo (head libfs)) "library" "" (deps ++ libfs)]) ++ exes | otherwise = fs isSimpleField F{} = True isSimpleField _ = False -- warn if there's something at the end of the file warnIfRest :: PM () warnIfRest = do s <- get case s of [] -> return () _ -> lift $ warning "Ignoring trailing declarations." -- add line no. -- all simple fields at the beginning of the file are (considered) header -- fields getHeader :: [Field] -> PM [Field] getHeader acc = peekField >>= \mf -> case mf of Just f@F{} -> skipField >> getHeader (f:acc) _ -> return (reverse acc) -- -- body ::= { repo | flag | library | executable | test }+ -- at most one lib -- -- The body consists of an optional sequence of declarations of flags and -- an arbitrary number of executables and at most one library. getBody :: PM ([SourceRepo], [Flag] ,Maybe (CondTree ConfVar [Dependency] Library) ,[(String, CondTree ConfVar [Dependency] Executable)] ,[(String, CondTree ConfVar [Dependency] TestSuite)] ,[(String, CondTree ConfVar [Dependency] Benchmark)]) getBody = peekField >>= \mf -> case mf of Just (Section line_no sec_type sec_label sec_fields) | sec_type == "executable" -> do when (null sec_label) $ lift $ syntaxError line_no "'executable' needs one argument (the executable's name)" exename <- lift $ runP line_no "executable" parseTokenQ sec_label flds <- collectFields parseExeFields sec_fields skipField (repos, flags, lib, exes, tests, bms) <- getBody return (repos, flags, lib, (exename, flds): exes, tests, bms) | sec_type == "test-suite" -> do when (null sec_label) $ lift $ syntaxError line_no "'test-suite' needs one argument (the test suite's name)" testname <- lift $ runP line_no "test" parseTokenQ sec_label flds <- collectFields (parseTestFields line_no) sec_fields -- Check that a valid test suite type has been chosen. A type -- field may be given inside a conditional block, so we must -- check for that before complaining that a type field has not -- been given. The test suite must always have a valid type, so -- we need to check both the 'then' and 'else' blocks, though -- the blocks need not have the same type. let checkTestType ts ct = let ts' = mappend ts $ condTreeData ct -- If a conditional has only a 'then' block and no -- 'else' block, then it cannot have a valid type -- in every branch, unless the type is specified at -- a higher level in the tree. checkComponent (_, _, Nothing) = False -- If a conditional has a 'then' block and an 'else' -- block, both must specify a test type, unless the -- type is specified higher in the tree. checkComponent (_, t, Just e) = checkTestType ts' t && checkTestType ts' e -- Does the current node specify a test type? hasTestType = testInterface ts' /= testInterface emptyTestSuite components = condTreeComponents ct -- If the current level of the tree specifies a type, -- then we are done. If not, then one of the conditional -- branches below the current node must specify a type. -- Each node may have multiple immediate children; we -- only one need one to specify a type because the -- configure step uses 'mappend' to join together the -- results of flag resolution. in hasTestType || any checkComponent components if checkTestType emptyTestSuite flds then do skipField (repos, flags, lib, exes, tests, bms) <- getBody return (repos, flags, lib, exes, (testname, flds) : tests, bms) else lift $ syntaxError line_no $ "Test suite \"" ++ testname ++ "\" is missing required field \"type\" or the field " ++ "is not present in all conditional branches. The " ++ "available test types are: " ++ intercalate ", " (map display knownTestTypes) | sec_type == "benchmark" -> do when (null sec_label) $ lift $ syntaxError line_no "'benchmark' needs one argument (the benchmark's name)" benchname <- lift $ runP line_no "benchmark" parseTokenQ sec_label flds <- collectFields (parseBenchmarkFields line_no) sec_fields -- Check that a valid benchmark type has been chosen. A type -- field may be given inside a conditional block, so we must -- check for that before complaining that a type field has not -- been given. The benchmark must always have a valid type, so -- we need to check both the 'then' and 'else' blocks, though -- the blocks need not have the same type. let checkBenchmarkType ts ct = let ts' = mappend ts $ condTreeData ct -- If a conditional has only a 'then' block and no -- 'else' block, then it cannot have a valid type -- in every branch, unless the type is specified at -- a higher level in the tree. checkComponent (_, _, Nothing) = False -- If a conditional has a 'then' block and an 'else' -- block, both must specify a benchmark type, unless the -- type is specified higher in the tree. checkComponent (_, t, Just e) = checkBenchmarkType ts' t && checkBenchmarkType ts' e -- Does the current node specify a benchmark type? hasBenchmarkType = benchmarkInterface ts' /= benchmarkInterface emptyBenchmark components = condTreeComponents ct -- If the current level of the tree specifies a type, -- then we are done. If not, then one of the conditional -- branches below the current node must specify a type. -- Each node may have multiple immediate children; we -- only one need one to specify a type because the -- configure step uses 'mappend' to join together the -- results of flag resolution. in hasBenchmarkType || any checkComponent components if checkBenchmarkType emptyBenchmark flds then do skipField (repos, flags, lib, exes, tests, bms) <- getBody return (repos, flags, lib, exes, tests, (benchname, flds) : bms) else lift $ syntaxError line_no $ "Benchmark \"" ++ benchname ++ "\" is missing required field \"type\" or the field " ++ "is not present in all conditional branches. The " ++ "available benchmark types are: " ++ intercalate ", " (map display knownBenchmarkTypes) | sec_type == "library" -> do unless (null sec_label) $ lift $ syntaxError line_no "'library' expects no argument" flds <- collectFields parseLibFields sec_fields skipField (repos, flags, lib, exes, tests, bms) <- getBody when (isJust lib) $ lift $ syntaxError line_no "There can only be one library section in a package description." return (repos, flags, Just flds, exes, tests, bms) | sec_type == "flag" -> do when (null sec_label) $ lift $ syntaxError line_no "'flag' needs one argument (the flag's name)" flag <- lift $ parseFields flagFieldDescrs warnUnrec (MkFlag (FlagName (lowercase sec_label)) "" True False) sec_fields skipField (repos, flags, lib, exes, tests, bms) <- getBody return (repos, flag:flags, lib, exes, tests, bms) | sec_type == "source-repository" -> do when (null sec_label) $ lift $ syntaxError line_no $ "'source-repository' needs one argument, " ++ "the repo kind which is usually 'head' or 'this'" kind <- case simpleParse sec_label of Just kind -> return kind Nothing -> lift $ syntaxError line_no $ "could not parse repo kind: " ++ sec_label repo <- lift $ parseFields sourceRepoFieldDescrs warnUnrec SourceRepo { repoKind = kind, repoType = Nothing, repoLocation = Nothing, repoModule = Nothing, repoBranch = Nothing, repoTag = Nothing, repoSubdir = Nothing } sec_fields skipField (repos, flags, lib, exes, tests, bms) <- getBody return (repo:repos, flags, lib, exes, tests, bms) | otherwise -> do lift $ warning $ "Ignoring unknown section type: " ++ sec_type skipField getBody Just f -> do _ <- lift $ syntaxError (lineNo f) $ "Construct not supported at this position: " ++ show f skipField getBody Nothing -> return ([], [], Nothing, [], [], []) -- Extracts all fields in a block and returns a 'CondTree'. -- -- We have to recurse down into conditionals and we treat fields that -- describe dependencies specially. collectFields :: ([Field] -> PM a) -> [Field] -> PM (CondTree ConfVar [Dependency] a) collectFields parser allflds = do let simplFlds = [ F l n v | F l n v <- allflds ] condFlds = [ f | f@IfBlock{} <- allflds ] let (depFlds, dataFlds) = partition isConstraint simplFlds a <- parser dataFlds deps <- liftM concat . mapM (lift . parseConstraint) $ depFlds ifs <- mapM processIfs condFlds return (CondNode a deps ifs) where isConstraint (F _ n _) = n `elem` constraintFieldNames isConstraint _ = False processIfs (IfBlock l c t e) = do cnd <- lift $ runP l "if" parseCondition c t' <- collectFields parser t e' <- case e of [] -> return Nothing es -> do fs <- collectFields parser es return (Just fs) return (cnd, t', e') processIfs _ = cabalBug "processIfs called with wrong field type" parseLibFields :: [Field] -> PM Library parseLibFields = lift . parseFields libFieldDescrs storeXFieldsLib emptyLibrary -- Note: we don't parse the "executable" field here, hence the tail hack. parseExeFields :: [Field] -> PM Executable parseExeFields = lift . parseFields (tail executableFieldDescrs) storeXFieldsExe emptyExecutable parseTestFields :: LineNo -> [Field] -> PM TestSuite parseTestFields line fields = do x <- lift $ parseFields testSuiteFieldDescrs storeXFieldsTest emptyTestStanza fields lift $ validateTestSuite line x parseBenchmarkFields :: LineNo -> [Field] -> PM Benchmark parseBenchmarkFields line fields = do x <- lift $ parseFields benchmarkFieldDescrs storeXFieldsBenchmark emptyBenchmarkStanza fields lift $ validateBenchmark line x checkForUndefinedFlags :: [Flag] -> Maybe (CondTree ConfVar [Dependency] Library) -> [(String, CondTree ConfVar [Dependency] Executable)] -> [(String, CondTree ConfVar [Dependency] TestSuite)] -> PM () checkForUndefinedFlags flags mlib exes tests = do let definedFlags = map flagName flags maybe (return ()) (checkCondTreeFlags definedFlags) mlib mapM_ (checkCondTreeFlags definedFlags . snd) exes mapM_ (checkCondTreeFlags definedFlags . snd) tests checkCondTreeFlags :: [FlagName] -> CondTree ConfVar c a -> PM () checkCondTreeFlags definedFlags ct = do let fv = nub $ freeVars ct unless (all (`elem` definedFlags) fv) $ fail $ "These flags are used without having been defined: " ++ intercalate ", " [ n | FlagName n <- fv \\ definedFlags ] findIndentTabs :: String -> [(Int,Int)] findIndentTabs = concatMap checkLine . zip [1..] . lines where checkLine (lineno, l) = let (indent, _content) = span isSpace l tabCols = map fst . filter ((== '\t') . snd) . zip [0..] addLineNo = map (\col -> (lineno,col)) in addLineNo (tabCols indent) parseCondition :: ReadP (Condition ConfVar) parseCondition = condOr where condOr = sepBy1 condAnd (oper "||") >>= return . foldl1 COr condAnd = sepBy1 cond (oper "&&")>>= return . foldl1 CAnd cond = sp >> (boolLiteral +++ inparens condOr +++ notCond +++ osCond +++ archCond +++ flagCond +++ implCond ) inparens = between (ReadP.char '(' >> sp) (sp >> ReadP.char ')' >> sp) notCond = ReadP.char '!' >> sp >> cond >>= return . CNot osCond = string "os" >> sp >> inparens osIdent >>= return . Var archCond = string "arch" >> sp >> inparens archIdent >>= return . Var flagCond = string "flag" >> sp >> inparens flagIdent >>= return . Var implCond = string "impl" >> sp >> inparens implIdent >>= return . Var boolLiteral = fmap Lit parse archIdent = fmap Arch parse osIdent = fmap OS parse flagIdent = fmap (Flag . FlagName . lowercase) (munch1 isIdentChar) isIdentChar c = isAlphaNum c || c == '_' || c == '-' oper s = sp >> string s >> sp sp = skipSpaces implIdent = do i <- parse vr <- sp >> option AnyVersion parse return $ Impl i vr freeVars :: CondTree ConfVar c a -> [FlagName] freeVars t = [ f | Flag f <- freeVars' t ] where freeVars' (CondNode _ _ ifs) = concatMap compfv ifs compfv (c, ct, mct) = condfv c ++ freeVars' ct ++ maybe [] freeVars' mct condfv c = case c of Var v -> [v] Lit _ -> [] CNot c' -> condfv c' COr c1 c2 -> condfv c1 ++ condfv c2 CAnd c1 c2 -> condfv c1 ++ condfv c2 emptyPackageDescription :: PackageDescription emptyPackageDescription = PackageDescription { package = PackageId (PackageName "") (Version [] []), license = AllRightsReserved, licenseFile = "", specVersionRaw = Right AnyVersion, buildType = Nothing, copyright = "", maintainer = "", author = "", stability = "", testedWith = [], buildDepends = [], homepage = "", pkgUrl = "", bugReports = "", sourceRepos = [], synopsis = "", description = "", category = "", customFieldsPD = [], library = Nothing, executables = [], testSuites = [], benchmarks = [], dataFiles = [], dataDir = "", extraSrcFiles = [], extraTmpFiles = [], extraDocFiles = [] } instance Monoid Library where mempty = Library { exposedModules = mempty, libExposed = True, libBuildInfo = mempty } mappend a b = Library { exposedModules = combine exposedModules, libExposed = libExposed a && libExposed b, -- so False propagates libBuildInfo = combine libBuildInfo } where combine field = field a `mappend` field b emptyLibrary :: Library emptyLibrary = mempty instance Monoid Executable where mempty = Executable { exeName = mempty, modulePath = mempty, buildInfo = mempty } mappend a b = Executable{ exeName = combine' exeName, modulePath = combine modulePath, buildInfo = combine buildInfo } where combine field = field a `mappend` field b combine' field = case (field a, field b) of ("","") -> "" ("", x) -> x (x, "") -> x (x, y) -> error $ "Ambiguous values for executable field: '" ++ x ++ "' and '" ++ y ++ "'" emptyExecutable :: Executable emptyExecutable = mempty instance Monoid TestSuite where mempty = TestSuite { testName = mempty, testInterface = mempty, testBuildInfo = mempty, testEnabled = False } mappend a b = TestSuite { testName = combine' testName, testInterface = combine testInterface, testBuildInfo = combine testBuildInfo, testEnabled = testEnabled a || testEnabled b } where combine field = field a `mappend` field b combine' f = case (f a, f b) of ("", x) -> x (x, "") -> x (x, y) -> error "Ambiguous values for test field: '" ++ x ++ "' and '" ++ y ++ "'" instance Monoid TestSuiteInterface where mempty = TestSuiteUnsupported (TestTypeUnknown mempty (Version [] [])) mappend a (TestSuiteUnsupported _) = a mappend _ b = b emptyTestSuite :: TestSuite emptyTestSuite = mempty instance Monoid Benchmark where mempty = Benchmark { benchmarkName = mempty, benchmarkInterface = mempty, benchmarkBuildInfo = mempty, benchmarkEnabled = False } mappend a b = Benchmark { benchmarkName = combine' benchmarkName, benchmarkInterface = combine benchmarkInterface, benchmarkBuildInfo = combine benchmarkBuildInfo, benchmarkEnabled = benchmarkEnabled a || benchmarkEnabled b } where combine field = field a `mappend` field b combine' f = case (f a, f b) of ("", x) -> x (x, "") -> x (x, y) -> error "Ambiguous values for benchmark field: '" ++ x ++ "' and '" ++ y ++ "'" instance Monoid BenchmarkInterface where mempty = BenchmarkUnsupported (BenchmarkTypeUnknown mempty (Version [] [])) mappend a (BenchmarkUnsupported _) = a mappend _ b = b emptyBenchmark :: Benchmark emptyBenchmark = mempty instance Monoid BuildInfo where mempty = BuildInfo { buildable = True, buildTools = [], cppOptions = [], ccOptions = [], ldOptions = [], pkgconfigDepends = [], frameworks = [], cSources = [], hsSourceDirs = [], otherModules = [], defaultLanguage = Nothing, otherLanguages = [], defaultExtensions = [], otherExtensions = [], oldExtensions = [], extraLibs = [], extraLibDirs = [], includeDirs = [], includes = [], installIncludes = [], options = [], ghcProfOptions = [], ghcSharedOptions = [], customFieldsBI = [], targetBuildDepends = [] } mappend a b = BuildInfo { buildable = buildable a && buildable b, buildTools = combine buildTools, cppOptions = combine cppOptions, ccOptions = combine ccOptions, ldOptions = combine ldOptions, pkgconfigDepends = combine pkgconfigDepends, frameworks = combineNub frameworks, cSources = combineNub cSources, hsSourceDirs = combineNub hsSourceDirs, otherModules = combineNub otherModules, defaultLanguage = combineMby defaultLanguage, otherLanguages = combineNub otherLanguages, defaultExtensions = combineNub defaultExtensions, otherExtensions = combineNub otherExtensions, oldExtensions = combineNub oldExtensions, extraLibs = combine extraLibs, extraLibDirs = combineNub extraLibDirs, includeDirs = combineNub includeDirs, includes = combineNub includes, installIncludes = combineNub installIncludes, options = combine options, ghcProfOptions = combine ghcProfOptions, ghcSharedOptions = combine ghcSharedOptions, customFieldsBI = combine customFieldsBI, targetBuildDepends = combineNub targetBuildDepends } where combine field = field a `mappend` field b combineNub field = nub (combine field) combineMby field = field b `mplus` field a -- | Parse a list of fields, given a list of field descriptions, -- a structure to accumulate the parsed fields, and a function -- that can decide what to do with fields which don't match any -- of the field descriptions. parseFields :: [FieldDescr a] -- ^ descriptions of fields we know how to -- parse -> UnrecFieldParser a -- ^ possibly do something with -- unrecognized fields -> a -- ^ accumulator -> [Field] -- ^ fields to be parsed -> ParseResult a parseFields descrs unrec ini fields = do (a, unknowns) <- foldM (parseField descrs unrec) (ini, []) fields unless (null unknowns) $ warning $ render $ text "Unknown fields:" <+> commaSep (map (\(l,u) -> u ++ " (line " ++ show l ++ ")") (reverse unknowns)) $+$ text "Fields allowed in this section:" $$ nest 4 (commaSep $ map fieldName descrs) return a where commaSep = fsep . punctuate comma . map text parseField :: [FieldDescr a] -- ^ list of parseable fields -> UnrecFieldParser a -- ^ possibly do something with -- unrecognized fields -> (a,[(Int,String)]) -- ^ accumulated result and warnings -> Field -- ^ the field to be parsed -> ParseResult (a, [(Int,String)]) parseField (FieldDescr name _ parser : fields) unrec (a, us) (F line f val) | name == f = parser line val a >>= \a' -> return (a',us) | otherwise = parseField fields unrec (a,us) (F line f val) parseField [] unrec (a,us) (F l f val) = return $ case unrec (f,val) a of -- no fields matched, see if the 'unrec' Just a' -> (a',us) -- function wants to do anything with it Nothing -> (a, (l,f):us) parseField _ _ _ _ = cabalBug "'parseField' called on a non-field" deprecatedFields :: [(String,String)] deprecatedFields = deprecatedFieldsPkgDescr ++ deprecatedFieldsBuildInfo deprecatedFieldsPkgDescr :: [(String,String)] deprecatedFieldsPkgDescr = [ ("other-files", "extra-source-files") ] deprecatedFieldsBuildInfo :: [(String,String)] deprecatedFieldsBuildInfo = [ ("hs-source-dir","hs-source-dirs") ] -- Handle deprecated fields deprecField :: Field -> ParseResult Field deprecField (F line fld val) = do fld' <- case lookup fld deprecatedFields of Nothing -> return fld Just newName -> do warning $ "The field \"" ++ fld ++ "\" is deprecated, please use \"" ++ newName ++ "\"" return newName return (F line fld' val) deprecField _ = cabalBug "'deprecField' called on a non-field" userBug :: String -> a userBug msg = error $ msg ++ ". This is a bug in your .cabal file." cabalBug :: String -> a cabalBug msg = error $ msg ++ ". This is possibly a bug in Cabal.\n" ++ "Please report it to the developers: " ++ "https://github.com/haskell/cabal/issues/new"
thoughtpolice/binary-serialise-cbor
bench/Real/Load.hs
bsd-3-clause
104,030
0
24
33,703
27,263
14,162
13,101
1,863
26
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. {-# LANGUAGE GADTs #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE NoRebindableSyntax #-} module Duckling.Ordinal.MN.Rules ( rules ) where import Data.HashMap.Strict (HashMap) import Data.String import Data.Text (Text) import Prelude import qualified Data.HashMap.Strict as HashMap import qualified Data.Text as Text import Duckling.Dimensions.Types import Duckling.Numeral.Helpers (parseInt) import Duckling.Ordinal.Helpers import Duckling.Regex.Types import Duckling.Types ordinalsFirstthMap :: HashMap Text.Text Int ordinalsFirstthMap = HashMap.fromList [ ( "нэг", 1 ) , ( "хоёр", 2 ) , ( "гурав", 3 ) , ( "дөрөв", 4 ) , ( "тав", 5 ) , ( "зургаа", 6 ) , ( "долоо", 7 ) , ( "найм", 8 ) , ( "ес", 9 ) , ( "арав", 10 ) ] cardinalsMap :: HashMap Text.Text Int cardinalsMap = HashMap.fromList [ ( "арван", 10 ) , ( "хорин", 20 ) , ( "хорь", 20 ) , ( "гучин", 30 ) , ( "гуч", 30 ) , ( "дөчин", 40 ) , ( "дөч", 40 ) , ( "тавин", 50 ) , ( "тавь", 50 ) , ( "жаран", 60 ) , ( "жар", 60 ) , ( "далан", 70 ) , ( "дал", 70 ) , ( "наян", 80 ) , ( "ная", 80 ) , ( "ерэн", 90 ) , ( "ер", 90 ) ] ruleOrdinalsFirstth :: Rule ruleOrdinalsFirstth = Rule { name = "ordinals (first..19th)" , pattern = [ regex "(нэг|хоёр|гурав|дөрөв|тав|зургаа|долоо|найм|ес|арав) ?(дугаар|дүгээр|дахь|дэх)" ] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (match:_)):_) -> ordinal <$> HashMap.lookup (Text.toLower match) ordinalsFirstthMap _ -> Nothing } ruleOrdinal :: Rule ruleOrdinal = Rule { name = "ordinal 10..99" , pattern = [ regex "(арван|хорин|гучин|дөчин|тавин|жаран|далан|наян|ерэн) ?(нэг|хоёр|гурав|дөрөв|тав|зургаа|долоо|найм|ес) ?(дугаар|дүгээр|дахь|дэх)" ] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (m1:_)): Token RegexMatch (GroupMatch (m2:_)): _) -> do dozen <- HashMap.lookup (Text.toLower m1) cardinalsMap unit <- HashMap.lookup (Text.toLower m2) ordinalsFirstthMap Just . ordinal $ dozen + unit _ -> Nothing } -- TODO: Single-word composition (#110) ruleInteger2 :: Rule ruleInteger2 = Rule { name = "integer (20..90)" , pattern = [ regex "(хорь|гуч|дөч|тавь|жар|дал|ная|ер) ?(дугаар|дүгээр|дахь|дэх)" ] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (match:_)):_) -> ordinal <$> HashMap.lookup (Text.toLower match) cardinalsMap _ -> Nothing } ruleOrdinalDigits :: Rule ruleOrdinalDigits = Rule { name = "ordinal (digits)" , pattern = [ regex "0*(\\d+)-?(ын|ийн|р|с|)" ] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (match:_)):_) -> ordinal <$> parseInt match _ -> Nothing } ruleOrdinalDigits2 :: Rule ruleOrdinalDigits2 = Rule { name = "ordinal (digits)" , pattern = [ regex "(?<!\\d|\\.)0*(\\d+)(\\.(?!\\d)| ?(дугаар|дүгээр|дахь|дэх))" ] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (match:_)):_) -> do v <- parseInt match Just $ ordinal v _ -> Nothing } rules :: [Rule] rules = [ ruleOrdinalDigits , ruleOrdinalDigits2 , ruleOrdinal , ruleInteger2 , ruleOrdinalsFirstth ]
facebookincubator/duckling
Duckling/Ordinal/MN/Rules.hs
bsd-3-clause
3,840
0
18
797
974
571
403
104
2
{-# LANGUAGE TupleSections #-} -- | Handle effects. They are most often caused by requests sent by clients -- but sometimes also caused by projectiles or periodically activated items. module Game.LambdaHack.Server.HandleEffectM ( UseResult(..), EffToUse(..), EffApplyFlags(..) , applyItem, cutCalm, kineticEffectAndDestroy, effectAndDestroyAndAddKill , itemEffectEmbedded, highestImpression, dominateFidSfx , dropAllEquippedItems, pickDroppable, consumeItems, dropCStoreItem #ifdef EXPOSE_INTERNAL -- * Internal operations , applyKineticDamage, refillHP, effectAndDestroy, imperishableKit , itemEffectDisco, effectSem , effectBurn, effectExplode, effectRefillHP, effectRefillCalm , effectDominate, dominateFid, effectImpress, effectPutToSleep, effectYell , effectSummon, effectAscend, findStairExit, switchLevels1, switchLevels2 , effectEscape, effectParalyze, paralyze, effectParalyzeInWater , effectInsertMove, effectTeleport, effectCreateItem , effectDestroyItem, effectDropItem, effectConsumeItems , effectRecharge, effectPolyItem, effectRerollItem, effectDupItem , effectIdentify, identifyIid, effectDetect, effectDetectX, effectSendFlying , sendFlyingVector, effectApplyPerfume, effectAtMostOneOf, effectOneOf , effectAndEffect, effectAndEffectSem, effectOrEffect, effectSeqEffect , effectWhen, effectUnless, effectIfThenElse , effectVerbNoLonger, effectVerbMsg, effectVerbMsgFail #endif ) where import Prelude () import Game.LambdaHack.Core.Prelude import Data.Bits (xor) import qualified Data.EnumMap.Strict as EM import qualified Data.EnumSet as ES import qualified Data.HashMap.Strict as HM import Data.Int (Int64) import Data.Key (mapWithKeyM_) import qualified Data.Text as T import Game.LambdaHack.Atomic import Game.LambdaHack.Common.Actor import Game.LambdaHack.Common.ActorState import Game.LambdaHack.Common.Analytics import Game.LambdaHack.Common.Faction import Game.LambdaHack.Common.Item import qualified Game.LambdaHack.Common.ItemAspect as IA import Game.LambdaHack.Common.Kind import Game.LambdaHack.Common.Level import Game.LambdaHack.Common.Misc import Game.LambdaHack.Common.MonadStateRead import Game.LambdaHack.Common.Perception import Game.LambdaHack.Common.Point import Game.LambdaHack.Common.ReqFailure import Game.LambdaHack.Common.State import qualified Game.LambdaHack.Common.Tile as Tile import Game.LambdaHack.Common.Time import Game.LambdaHack.Common.Types import Game.LambdaHack.Common.Vector import Game.LambdaHack.Content.FactionKind import Game.LambdaHack.Content.ItemKind (ItemKind) import qualified Game.LambdaHack.Content.ItemKind as IK import Game.LambdaHack.Content.RuleKind import qualified Game.LambdaHack.Core.Dice as Dice import Game.LambdaHack.Core.Random import Game.LambdaHack.Definition.Ability (ActivationFlag (..)) import qualified Game.LambdaHack.Definition.Ability as Ability import Game.LambdaHack.Definition.Defs import Game.LambdaHack.Server.CommonM import Game.LambdaHack.Server.ItemM import Game.LambdaHack.Server.ItemRev import Game.LambdaHack.Server.MonadServer import Game.LambdaHack.Server.PeriodicM import Game.LambdaHack.Server.ServerOptions import Game.LambdaHack.Server.State -- * Semantics of effects data UseResult = UseDud | UseId | UseUp deriving (Eq, Ord) data EffToUse = EffBare | EffBareAndOnCombine | EffOnCombine deriving Eq data EffApplyFlags = EffApplyFlags { effToUse :: EffToUse , effVoluntary :: Bool , effUseAllCopies :: Bool , effKineticPerformed :: Bool , effActivation :: Ability.ActivationFlag , effMayDestroy :: Bool } applyItem :: MonadServerAtomic m => ActorId -> ItemId -> CStore -> m () applyItem aid iid cstore = do execSfxAtomic $ SfxApply aid iid let c = CActor aid cstore -- Treated as if the actor hit himself with the item as a weapon, -- incurring both the kinetic damage and effect, hence the same call -- as in @reqMelee@. let effApplyFlags = EffApplyFlags { effToUse = EffBareAndOnCombine , effVoluntary = True , effUseAllCopies = False , effKineticPerformed = False , effActivation = ActivationTrigger , effMayDestroy = True } void $ kineticEffectAndDestroy effApplyFlags aid aid aid iid c applyKineticDamage :: MonadServerAtomic m => ActorId -> ActorId -> ItemId -> m Bool applyKineticDamage source target iid = do itemKind <- getsState $ getIidKindServer iid if IK.idamage itemKind == 0 then return False else do -- speedup sb <- getsState $ getActorBody source hurtMult <- getsState $ armorHurtBonus source target totalDepth <- getsState stotalDepth Level{ldepth} <- getLevel (blid sb) dmg <- rndToAction $ castDice ldepth totalDepth $ IK.idamage itemKind let rawDeltaHP = into @Int64 hurtMult * xM dmg `divUp` 100 speedDeltaHP = case btrajectory sb of Just (_, speed) | bproj sb -> - modifyDamageBySpeed rawDeltaHP speed _ -> - rawDeltaHP if speedDeltaHP < 0 then do -- damage the target, never heal refillHP source target speedDeltaHP return True else return False refillHP :: MonadServerAtomic m => ActorId -> ActorId -> Int64 -> m () refillHP source target speedDeltaHP = assert (speedDeltaHP /= 0) $ do tbOld <- getsState $ getActorBody target actorMaxSk <- getsState $ getActorMaxSkills target -- We don't ignore even tiny HP drains, because they can be very weak -- enemy projectiles and so will recur and in total can be deadly -- and also AI should rather be stupidly aggressive than stupidly lethargic. let serious = source /= target && not (bproj tbOld) hpMax = Ability.getSk Ability.SkMaxHP actorMaxSk deltaHP0 | serious && speedDeltaHP < minusM = -- If overfull, at least cut back to max, unless minor drain. min speedDeltaHP (xM hpMax - bhp tbOld) | otherwise = speedDeltaHP deltaHP = if | deltaHP0 > 0 && bhp tbOld > xM 999 -> -- UI limit tenthM -- avoid nop, to avoid loops | deltaHP0 < 0 && bhp tbOld < - xM 999 -> -tenthM | otherwise -> deltaHP0 execUpdAtomic $ UpdRefillHP target deltaHP when serious $ cutCalm target tb <- getsState $ getActorBody target fact <- getsState $ (EM.! bfid tb) . sfactionD when (not (bproj tb) && fhasPointman (gkind fact)) $ -- If leader just lost all HP, change the leader early (not when destroying -- the actor), to let players rescue him, especially if he's slowed -- by the attackers. when (bhp tb <= 0 && bhp tbOld > 0) $ do -- If all other party members dying, leadership will switch -- to one of them, which seems questionable, but it's rare -- and the disruption servers to underline the dire circumstance. electLeader (bfid tb) (blid tb) target mleader <- getsState $ gleader . (EM.! bfid tb) . sfactionD -- If really nobody else in the party, make him the leader back again -- on the oft chance that he gets revived by a projectile, etc. when (isNothing mleader) $ execUpdAtomic $ UpdLeadFaction (bfid tb) Nothing $ Just target cutCalm :: MonadServerAtomic m => ActorId -> m () cutCalm target = do tb <- getsState $ getActorBody target actorMaxSk <- getsState $ getActorMaxSkills target let upperBound = if hpTooLow tb actorMaxSk then 2 -- to trigger domination on next attack, etc. else xM $ Ability.getSk Ability.SkMaxCalm actorMaxSk deltaCalm = min minusM2 (upperBound - bcalm tb) -- HP loss decreases Calm by at least @minusM2@ to avoid "hears something", -- which is emitted when decreasing Calm by @minusM1@. updateCalm target deltaCalm -- Here kinetic damage is applied. This is necessary so that the same -- AI benefit calculation may be used for flinging and for applying items. kineticEffectAndDestroy :: MonadServerAtomic m => EffApplyFlags -> ActorId -> ActorId -> ActorId -> ItemId -> Container -> m UseResult kineticEffectAndDestroy effApplyFlags0@EffApplyFlags{..} killer source target iid c = do bag <- getsState $ getContainerBag c case iid `EM.lookup` bag of Nothing -> error $ "" `showFailure` (source, target, iid, c) Just kit -> do itemFull <- getsState $ itemToFull iid tbOld <- getsState $ getActorBody target localTime <- getsState $ getLocalTime (blid tbOld) let recharged = hasCharge localTime kit -- If neither kinetic hit nor any effect is activated, there's no chance -- the items can be destroyed or even timeout changes, so we abort early. if not recharged then return UseDud else do effKineticPerformed2 <- applyKineticDamage source target iid tb <- getsState $ getActorBody target -- Sometimes victim heals just after we registered it as killed, -- but that's OK, an actor killed two times is similar enough -- to two killed. when (effKineticPerformed2 -- speedup && bhp tb <= 0 && bhp tbOld > 0) $ do sb <- getsState $ getActorBody source arWeapon <- getsState $ (EM.! iid) . sdiscoAspect let killHow | not (bproj sb) = if effVoluntary then KillKineticMelee else KillKineticPush | IA.checkFlag Ability.Blast arWeapon = KillKineticBlast | otherwise = KillKineticRanged addKillToAnalytics killer killHow (bfid tbOld) (btrunk tbOld) let effApplyFlags = effApplyFlags0 { effUseAllCopies = fst kit <= 1 , effKineticPerformed = effKineticPerformed2 } effectAndDestroyAndAddKill effApplyFlags killer source target iid c itemFull effectAndDestroyAndAddKill :: MonadServerAtomic m => EffApplyFlags -> ActorId -> ActorId -> ActorId -> ItemId -> Container -> ItemFull -> m UseResult effectAndDestroyAndAddKill effApplyFlags0@EffApplyFlags{..} killer source target iid c itemFull = do tbOld <- getsState $ getActorBody target triggered <- effectAndDestroy effApplyFlags0 source target iid c itemFull tb <- getsState $ getActorBody target -- Sometimes victim heals just after we registered it as killed, -- but that's OK, an actor killed two times is similar enough to two killed. when (bhp tb <= 0 && bhp tbOld > 0) $ do sb <- getsState $ getActorBody source arWeapon <- getsState $ (EM.! iid) . sdiscoAspect let killHow | not (bproj sb) = if effVoluntary then KillOtherMelee else KillOtherPush | IA.checkFlag Ability.Blast arWeapon = KillOtherBlast | otherwise = KillOtherRanged addKillToAnalytics killer killHow (bfid tbOld) (btrunk tbOld) return triggered effectAndDestroy :: MonadServerAtomic m => EffApplyFlags -> ActorId -> ActorId -> ItemId -> Container -> ItemFull -> m UseResult effectAndDestroy effApplyFlags0@EffApplyFlags{..} source target iid container itemFull@ItemFull{itemDisco, itemKindId, itemKind} = do bag <- getsState $ getContainerBag container let (itemK, itemTimers) = bag EM.! iid effs = case effToUse of EffBare -> if effActivation == ActivationOnSmash then IK.strengthOnSmash itemKind else IK.ieffects itemKind EffBareAndOnCombine -> IK.ieffects itemKind ++ IK.strengthOnCombine itemKind EffOnCombine -> IK.strengthOnCombine itemKind arItem = case itemDisco of ItemDiscoFull itemAspect -> itemAspect _ -> error "effectAndDestroy: server ignorant about an item" timeout = IA.aTimeout arItem lid <- getsState $ lidFromC container localTime <- getsState $ getLocalTime lid let it1 = filter (charging localTime) itemTimers len = length it1 recharged = len < itemK || effActivation `elem` [ActivationOnSmash, ActivationConsume] -- If the item has no charges and the special cases don't apply -- we speed up by shortcutting early, because we don't need to activate -- effects and we know kinetic hit was not performed (no charges to do so -- and in case of @OnSmash@ and @ActivationConsume@, -- only effects are triggered). if not recharged then return UseDud else do let timeoutTurns = timeDeltaScale (Delta timeTurn) timeout newItemTimer = createItemTimer localTime timeoutTurns it2 = if timeout > 0 && recharged then if effActivation == ActivationPeriodic && IA.checkFlag Ability.Fragile arItem then replicate (itemK - length it1) newItemTimer ++ it1 -- copies are spares only; one fires, all discharge else take (itemK - length it1) [newItemTimer] ++ it1 -- copies all fire, turn by turn; <= 1 discharges else itemTimers kit2 = (1, take 1 it2) !_A = assert (len <= itemK `blame` (source, target, iid, container)) () -- We use up the charge even if eventualy every effect fizzles. Tough luck. -- At least we don't destroy the item in such case. -- Also, we ID it regardless. unless (itemTimers == it2) $ execUpdAtomic $ UpdTimeItem iid container itemTimers it2 -- We have to destroy the item before the effect affects the item -- or affects the actor holding it or standing on it (later on we could -- lose track of the item and wouldn't be able to destroy it) . -- This is OK, because we don't remove the item type from various -- item dictionaries, just an individual copy from the container, -- so, e.g., the item can be identified after it's removed. let imperishable = not effMayDestroy || imperishableKit effActivation itemFull unless imperishable $ execUpdAtomic $ UpdLoseItem False iid kit2 container -- At this point, the item is potentially no longer in container -- @container@, therefore beware of assuming so in the code below. triggeredEffect <- itemEffectDisco effApplyFlags0 source target iid itemKindId itemKind container effs sb <- getsState $ getActorBody source let triggered = if effKineticPerformed then UseUp else triggeredEffect mEmbedPos = case container of CEmbed _ p -> Just p _ -> Nothing if | triggered == UseUp && mEmbedPos /= Just (bpos sb) -- treading water, etc. && effActivation `notElem` [ActivationTrigger, ActivationMeleeable] -- do not repeat almost the same msg && (effActivation /= ActivationOnSmash -- only tells condition ends && effActivation /= ActivationPeriodic || not (IA.checkFlag Ability.Condition arItem)) -> do -- Effects triggered; main feedback comes from them, -- but send info so that clients can log it. let verbose = effActivation == ActivationUnderRanged || effActivation == ActivationUnderMelee execSfxAtomic $ SfxItemApplied verbose iid container | triggered /= UseUp && effActivation /= ActivationOnSmash && effActivation /= ActivationPeriodic -- periodic effects repeat and so spam && effActivation `notElem` [ActivationUnderRanged, ActivationUnderMelee] -- and so do effects under attack && not (bproj sb) -- projectiles can be very numerous && isNothing mEmbedPos -> -- embeds may be just flavour -- Announce no effect, which is rare and wastes time, so noteworthy. execSfxAtomic $ SfxMsgFid (bfid sb) $ if any IK.forApplyEffect effs then SfxFizzles iid container -- something didn't work despite promising effects else SfxNothingHappens iid container -- fully expected | otherwise -> return () -- all the spam cases -- If none of item's effects nor a kinetic hit were performed, -- we recreate the item (assuming we deleted the item above). -- Regardless, we don't rewind the time, because some info is gained -- (that the item does not exhibit any effects in the given context). unless (imperishable || triggered == UseUp) $ execUpdAtomic $ UpdSpotItem False iid kit2 container return triggered imperishableKit :: ActivationFlag -> ItemFull -> Bool imperishableKit effActivation itemFull = let arItem = aspectRecordFull itemFull in IA.checkFlag Ability.Durable arItem || effActivation == ActivationPeriodic && not (IA.checkFlag Ability.Fragile arItem) -- The item is triggered exactly once. If there are more copies, -- they are left to be triggered next time. -- If the embed no longer exists at the given position, effect fizzles. itemEffectEmbedded :: MonadServerAtomic m => EffToUse -> Bool -> ActorId -> LevelId -> Point -> ItemId -> m UseResult itemEffectEmbedded effToUse effVoluntary aid lid tpos iid = do embeds2 <- getsState $ getEmbedBag lid tpos -- might have changed due to other embedded items invocations if iid `EM.notMember` embeds2 then return UseDud else do -- First embedded item may move actor to another level, so @lid@ -- may be unequal to @blid sb@. let c = CEmbed lid tpos -- Treated as if the actor hit himself with the embedded item as a weapon, -- incurring both the kinetic damage and effect, hence the same call -- as in @reqMelee@. Information whether this happened due to being pushed -- is preserved, but how did the pushing is lost, so we blame the victim. let effApplyFlags = EffApplyFlags { effToUse , effVoluntary , effUseAllCopies = False , effKineticPerformed = False , effActivation = if effToUse == EffOnCombine then ActivationOnCombine else ActivationEmbed , effMayDestroy = True } kineticEffectAndDestroy effApplyFlags aid aid aid iid c -- | The source actor affects the target actor, with a given item. -- If any of the effects fires up, the item gets identified. -- Even using raw damage (beating the enemy with the magic wand, -- for example) identifies the item. This means a costly @UpdDiscover@ -- is processed for each random timeout weapon hit and for most projectiles, -- but at least not for most explosion particles nor plain organs. -- And if not needed, the @UpdDiscover@ are eventually not sent to clients. -- So, enemy missiles that hit us are no longer mysterious until picked up, -- which is for the better, because the client knows their charging status -- and so can generate accurate messages in the case when not recharged. -- This also means that thrown consumables in flasks sturdy enough to cause -- damage are always identified at hit, even if no effect activated. -- So throwing them at foes is a better identification method than applying. -- -- Note that if we activate a durable non-passive item, e.g., a spiked shield, -- from the ground, it will get identified, which is perfectly fine, -- until we want to add sticky armor that can't be easily taken off -- (and, e.g., has some maluses). itemEffectDisco :: MonadServerAtomic m => EffApplyFlags -> ActorId -> ActorId -> ItemId -> ContentId ItemKind -> ItemKind -> Container -> [IK.Effect] -> m UseResult itemEffectDisco effApplyFlags0@EffApplyFlags{..} source target iid itemKindId itemKind c effs = do urs <- mapM (effectSem effApplyFlags0 source target iid c) effs let ur = case urs of [] -> UseDud -- there was no effects _ -> maximum urs -- Note: @UseId@ suffices for identification, @UseUp@ is not necessary. when (ur >= UseId || effKineticPerformed) $ identifyIid iid c itemKindId itemKind return ur -- | Source actor affects target actor, with a given effect and it strength. -- Both actors are on the current level and can be the same actor. -- The item may or may not still be in the container. effectSem :: MonadServerAtomic m => EffApplyFlags -> ActorId -> ActorId -> ItemId -> Container -> IK.Effect -> m UseResult effectSem effApplyFlags0@EffApplyFlags{..} source target iid c effect = do let recursiveCall = effectSem effApplyFlags0 source target iid c sb <- getsState $ getActorBody source -- @execSfx@ usually comes last in effect semantics, but not always -- and we are likely to introduce more variety. let execSfx = execSfxAtomic $ SfxEffect (bfid sb) target iid effect 0 execSfxSource = execSfxAtomic $ SfxEffect (bfid sb) source iid effect 0 case effect of IK.Burn nDm -> effectBurn nDm source target iid IK.Explode t -> effectExplode execSfx t source target c IK.RefillHP p -> effectRefillHP p source target iid IK.RefillCalm p -> effectRefillCalm execSfx p source target IK.Dominate -> effectDominate source target iid IK.Impress -> effectImpress recursiveCall execSfx source target IK.PutToSleep -> effectPutToSleep execSfx target IK.Yell -> effectYell execSfx target IK.Summon grp nDm -> effectSummon grp nDm iid source target effActivation IK.Ascend p -> effectAscend recursiveCall execSfx p source target c IK.Escape{} -> effectEscape execSfx source target IK.Paralyze nDm -> effectParalyze execSfx nDm source target IK.ParalyzeInWater nDm -> effectParalyzeInWater execSfx nDm source target IK.InsertMove nDm -> effectInsertMove execSfx nDm source target IK.Teleport nDm -> effectTeleport execSfx nDm source target IK.CreateItem mcount store grp tim -> effectCreateItem (Just $ bfid sb) mcount source target (Just iid) store grp tim IK.DestroyItem n k store grp -> effectDestroyItem execSfx n k store target grp IK.ConsumeItems tools raw -> effectConsumeItems execSfx iid target tools raw IK.DropItem n k store grp -> effectDropItem execSfx iid n k store grp target IK.Recharge n dice -> effectRecharge True execSfx iid n dice target IK.Discharge n dice -> effectRecharge False execSfx iid n dice target IK.PolyItem -> effectPolyItem execSfx iid target IK.RerollItem -> effectRerollItem execSfx iid target IK.DupItem -> effectDupItem execSfx iid target IK.Identify -> effectIdentify execSfx iid target IK.Detect d radius -> effectDetect execSfx d radius target c IK.SendFlying tmod -> effectSendFlying execSfx tmod source target c Nothing IK.PushActor tmod -> effectSendFlying execSfx tmod source target c (Just True) IK.PullActor tmod -> effectSendFlying execSfx tmod source target c (Just False) IK.ApplyPerfume -> effectApplyPerfume execSfx target IK.AtMostOneOf l -> effectAtMostOneOf recursiveCall l IK.OneOf l -> effectOneOf recursiveCall l IK.OnSmash _ -> return UseDud -- ignored under normal circumstances IK.OnCombine _ -> return UseDud -- ignored under normal circumstances IK.OnUser eff -> effectSem effApplyFlags0 source source iid c eff IK.NopEffect -> return UseDud -- all there is IK.AndEffect eff1 eff2 -> effectAndEffect recursiveCall source eff1 eff2 IK.OrEffect eff1 eff2 -> effectOrEffect recursiveCall (bfid sb) eff1 eff2 IK.SeqEffect effs -> effectSeqEffect recursiveCall effs IK.When cond eff -> effectWhen recursiveCall source cond eff effActivation IK.Unless cond eff -> effectUnless recursiveCall source cond eff effActivation IK.IfThenElse cond eff1 eff2 -> effectIfThenElse recursiveCall source cond eff1 eff2 effActivation IK.VerbNoLonger{} -> effectVerbNoLonger effUseAllCopies execSfxSource source IK.VerbMsg{} -> effectVerbMsg execSfxSource source IK.VerbMsgFail{} -> effectVerbMsgFail execSfxSource source conditionSem :: MonadServer m => ActorId -> IK.Condition -> ActivationFlag -> m Bool conditionSem source cond effActivation = do sb <- getsState $ getActorBody source return $! case cond of IK.HpLeq n -> bhp sb <= xM n IK.HpGeq n -> bhp sb >= xM n IK.CalmLeq n -> bcalm sb <= xM n IK.CalmGeq n -> bcalm sb >= xM n IK.TriggeredBy activationFlag -> activationFlag == effActivation -- * Individual semantic functions for effects -- ** Burn -- Damage from fire. Not affected by armor. effectBurn :: MonadServerAtomic m => Dice.Dice -> ActorId -> ActorId -> ItemId -> m UseResult effectBurn nDm source target iid = do tb <- getsState $ getActorBody target totalDepth <- getsState stotalDepth Level{ldepth} <- getLevel (blid tb) n0 <- rndToAction $ castDice ldepth totalDepth nDm let n = max 1 n0 -- avoid 0 and negative burn; validated in content anyway deltaHP = - xM n sb <- getsState $ getActorBody source -- Display the effect more accurately. let reportedEffect = IK.Burn $ Dice.intToDice n execSfxAtomic $ SfxEffect (bfid sb) target iid reportedEffect deltaHP refillHP source target deltaHP return UseUp -- ** Explode effectExplode :: MonadServerAtomic m => m () -> GroupName ItemKind -> ActorId -> ActorId -> Container -> m UseResult effectExplode execSfx cgroup source target containerOrigin = do execSfx tb <- getsState $ getActorBody target oxy@(Point x y) <- getsState $ posFromC containerOrigin let itemFreq = [(cgroup, 1)] -- Explosion particles are placed among organs of the victim. -- TODO: when changing this code, perhaps use @containerOrigin@ -- in place of @container@, but then remove @borgan@ from several -- functions that have the store hardwired. container = CActor target COrgan -- Power depth of new items unaffected by number of spawned actors. Level{ldepth} <- getLevel $ blid tb freq <- prepareItemKind 0 ldepth itemFreq m2 <- rollAndRegisterItem False ldepth freq container Nothing acounter <- getsServer $ fromEnum . sacounter let (iid, (ItemFull{itemKind}, (itemK, _))) = fromMaybe (error $ "" `showFailure` cgroup) m2 semiRandom = T.length (IK.idesc itemKind) -- We pick a point at the border, not inside, to have a uniform -- distribution for the points the line goes through at each distance -- from the source. Otherwise, e.g., the points on cardinal -- and diagonal lines from the source would be more common. projectN k10 n = do -- Shape is deterministic for the explosion kind, except that is has -- two variants chosen according to time-dependent @veryRandom@. -- Choice from the variants prevents diagonal or cardinal directions -- being always safe for a given explosion kind. let shapeRandom = k10 `xor` (semiRandom + n) veryRandom = shapeRandom + acounter + acounter `div` 3 fuzz = 5 + shapeRandom `mod` 5 k | n < 16 && n >= 12 = 12 | n < 12 && n >= 8 = 8 | n < 8 && n >= 4 = 4 | otherwise = min n 16 -- fire in groups of 16 including old duds psDir4 = [ Point (x - 12) (y + 12) , Point (x + 12) (y + 12) , Point (x - 12) (y - 12) , Point (x + 12) (y - 12) ] psDir8 = [ Point (x - 12) y , Point (x + 12) y , Point x (y + 12) , Point x (y - 12) ] psFuzz = [ Point (x - 12) $ y + fuzz , Point (x + 12) $ y + fuzz , Point (x - 12) $ y - fuzz , Point (x + 12) $ y - fuzz , flip Point (y - 12) $ x + fuzz , flip Point (y + 12) $ x + fuzz , flip Point (y - 12) $ x - fuzz , flip Point (y + 12) $ x - fuzz ] randomReverse = if even veryRandom then id else reverse ps = take k $ concat $ randomReverse [ zip (repeat True) -- diagonal particles don't reach that far $ take 4 (drop ((k10 + itemK + fuzz) `mod` 4) $ cycle psDir4) , zip (repeat False) -- only some cardinal reach far $ take 4 (drop ((k10 + n) `mod` 4) $ cycle psDir8) ] ++ [zip (repeat True) $ take 8 (drop ((k10 + fuzz) `mod` 8) $ cycle psFuzz)] forM_ ps $ \(centerRaw, tpxy) -> do let center = centerRaw && itemK >= 8 -- if few, keep them regular mfail <- projectFail source target oxy tpxy shapeRandom center iid COrgan True case mfail of Nothing -> return () Just ProjectBlockTerrain -> return () Just ProjectBlockActor -> return () Just failMsg -> execSfxAtomic $ SfxMsgFid (bfid tb) $ SfxUnexpected failMsg tryFlying 0 = return () tryFlying k10 = do -- Explosion particles were placed among organs of the victim: bag2 <- getsState $ borgan . getActorBody target -- We stop bouncing old particles when less than two thirds remain, -- to prevent hoarding explosives to use only in cramped spaces. case EM.lookup iid bag2 of Just (n2, _) | n2 * 2 >= itemK `div` 3 -> do projectN k10 n2 tryFlying $ k10 - 1 _ -> return () -- Some of the particles that fail to take off, bounce off obstacles -- up to 10 times in total, trying to fly in different directions. tryFlying 10 bag3 <- getsState $ borgan . getActorBody target let mn3 = EM.lookup iid bag3 -- Give up and destroy the remaining particles, if any. maybe (return ()) (\kit -> execUpdAtomic $ UpdLoseItem False iid kit container) mn3 return UseUp -- we neglect verifying that at least one projectile got off -- ** RefillHP -- Unaffected by armor. effectRefillHP :: MonadServerAtomic m => Int -> ActorId -> ActorId -> ItemId -> m UseResult effectRefillHP power0 source target iid = do sb <- getsState $ getActorBody source tb <- getsState $ getActorBody target curChalSer <- getsServer $ scurChalSer . soptions fact <- getsState $ (EM.! bfid tb) . sfactionD let power = if power0 <= -1 then power0 else max 1 power0 -- avoid 0 deltaHP = xM power if cfish curChalSer && deltaHP > 0 && fhasUI (gkind fact) && bfid sb /= bfid tb then do execSfxAtomic $ SfxMsgFid (bfid tb) SfxColdFish return UseId else do let reportedEffect = IK.RefillHP power execSfxAtomic $ SfxEffect (bfid sb) target iid reportedEffect deltaHP refillHP source target deltaHP return UseUp -- ** RefillCalm effectRefillCalm :: MonadServerAtomic m => m () -> Int -> ActorId -> ActorId -> m UseResult effectRefillCalm execSfx power0 source target = do tb <- getsState $ getActorBody target actorMaxSk <- getsState $ getActorMaxSkills target let power = if power0 <= -1 then power0 else max 1 power0 -- avoid 0 rawDeltaCalm = xM power calmMax = Ability.getSk Ability.SkMaxCalm actorMaxSk serious = rawDeltaCalm <= minusM2 && source /= target && not (bproj tb) deltaCalm0 | serious = -- if overfull, at least cut back to max min rawDeltaCalm (xM calmMax - bcalm tb) | otherwise = rawDeltaCalm deltaCalm = if | deltaCalm0 > 0 && bcalm tb > xM 999 -> -- UI limit tenthM -- avoid nop, to avoid loops | deltaCalm0 < 0 && bcalm tb < - xM 999 -> -tenthM | otherwise -> deltaCalm0 execSfx updateCalm target deltaCalm return UseUp -- ** Dominate -- The is another way to trigger domination (the normal way is by zeroed Calm). -- Calm is here irrelevant. The other conditions are the same. effectDominate :: MonadServerAtomic m => ActorId -> ActorId -> ItemId -> m UseResult effectDominate source target iid = do sb <- getsState $ getActorBody source tb <- getsState $ getActorBody target if | bproj tb -> return UseDud | bfid tb == bfid sb -> return UseDud -- accidental hit; ignore | otherwise -> do fact <- getsState $ (EM.! bfid tb) . sfactionD hiImpression <- highestImpression tb let permitted = case hiImpression of Nothing -> False -- no impression, no domination Just (hiImpressionFid, hiImpressionK) -> hiImpressionFid == bfid sb -- highest impression needs to be by us && (fhasPointman (gkind fact) || hiImpressionK >= 10) -- to tame/hack animal/robot, impress them a lot first if permitted then do b <- dominateFidSfx source target iid (bfid sb) return $! if b then UseUp else UseDud else do execSfxAtomic $ SfxMsgFid (bfid sb) $ SfxUnimpressed target when (source /= target) $ execSfxAtomic $ SfxMsgFid (bfid tb) $ SfxUnimpressed target return UseDud highestImpression :: MonadServerAtomic m => Actor -> m (Maybe (FactionId, Int)) highestImpression tb = do getKind <- getsState $ flip getIidKindServer getItem <- getsState $ flip getItemBody let isImpression iid = maybe False (> 0) $ lookup IK.S_IMPRESSED $ IK.ifreq $ getKind iid impressions = EM.filterWithKey (\iid _ -> isImpression iid) $ borgan tb f (_, (k, _)) = k maxImpression = maximumBy (comparing f) $ EM.assocs impressions if EM.null impressions then return Nothing else case jfid $ getItem $ fst maxImpression of Nothing -> return Nothing Just fid -> assert (fid /= bfid tb) $ return $ Just (fid, fst $ snd maxImpression) dominateFidSfx :: MonadServerAtomic m => ActorId -> ActorId -> ItemId -> FactionId -> m Bool dominateFidSfx source target iid fid = do tb <- getsState $ getActorBody target let !_A = assert (not $ bproj tb) () -- Actors that don't move freely can't be dominated, for otherwise, -- when they are the last survivors, they could get stuck and the game -- wouldn't end. Also, they are a hassle to guide through the dungeon. canTra <- getsState $ canTraverse target -- Being pushed protects from domination, for simplicity. -- A possible interesting exploit, but much help from content would be needed -- to make it practical. if isNothing (btrajectory tb) && canTra && bhp tb > 0 then do let execSfx = execSfxAtomic $ SfxEffect fid target iid IK.Dominate 0 execSfx -- if actor ours, possibly the last occasion to see him dominateFid fid source target -- If domination resulted in game over, the message won't be seen -- before the end game screens, but at least it will be seen afterwards -- and browsable in history while inside subsequent game, revealing -- the cause of the previous game over. Better than no message at all. execSfx -- see the actor as theirs, unless position not visible return True else return False dominateFid :: MonadServerAtomic m => FactionId -> ActorId -> ActorId -> m () dominateFid fid source target = do tb0 <- getsState $ getActorBody target -- Game over deduced very early, so no further animation nor message -- will appear before game end screens. This is good in that our last actor -- that yielded will still be on screen when end game messages roll. -- This is bad in that last enemy actor that got dominated by us -- may not be on screen and we have no clue how we won until -- we see history in the next game. Even worse if our ally dominated -- the enemy actor. Then we may never learn. Oh well, that's realism. deduceKilled target electLeader (bfid tb0) (blid tb0) target -- Drop all items so that domiation is not too nasty, especially -- if the dominated hero runs off or teleports away with gold -- or starts hitting with the most potent artifact weapon in the game. -- Drop items while still of the original faction -- to mark them on the map for other party members to collect. dropAllEquippedItems target tb0 tb <- getsState $ getActorBody target actorMaxSk <- getsState $ getActorMaxSkills target getKind <- getsState $ flip getIidKindServer let isImpression iid = maybe False (> 0) $ lookup IK.S_IMPRESSED $ IK.ifreq $ getKind iid dropAllImpressions = EM.filterWithKey (\iid _ -> not $ isImpression iid) borganNoImpression = dropAllImpressions $ borgan tb -- Actor is not pushed nor projectile, so @sactorTime@ suffices. btime <- getsServer $ fromJust . lookupActorTime (bfid tb) (blid tb) target . sactorTime execUpdAtomic $ UpdLoseActor target tb let maxCalm = Ability.getSk Ability.SkMaxCalm actorMaxSk maxHp = Ability.getSk Ability.SkMaxHP actorMaxSk bNew = tb { bfid = fid , bcalm = max (xM 10) $ xM maxCalm `div` 2 , bhp = min (xM maxHp) $ bhp tb + xM 10 , borgan = borganNoImpression} modifyServer $ \ser -> ser {sactorTime = updateActorTime fid (blid tb) target btime $ sactorTime ser} execUpdAtomic $ UpdSpotActor target bNew -- Focus on the dominated actor, by making him a leader. setFreshLeader fid target factionD <- getsState sfactionD let inGame fact2 = case gquit fact2 of Nothing -> True Just Status{stOutcome=Camping} -> True _ -> False gameOver = not $ any inGame $ EM.elems factionD -- Avoid the spam of identifying items, if game over. unless gameOver $ do -- Add some nostalgia for the old faction. void $ effectCreateItem (Just $ bfid tb) (Just 10) source target Nothing COrgan IK.S_IMPRESSED IK.timerNone -- Identify organs that won't get identified by use. getKindId <- getsState $ flip getIidKindIdServer let discoverIf (iid, cstore) = do let itemKindId = getKindId iid c = CActor target cstore assert (cstore /= CGround) $ discoverIfMinorEffects c iid itemKindId aic = (btrunk tb, COrgan) : filter ((/= btrunk tb) . fst) (getCarriedIidCStore tb) mapM_ discoverIf aic -- | Drop all actor's equipped items. dropAllEquippedItems :: MonadServerAtomic m => ActorId -> Actor -> m () dropAllEquippedItems aid b = mapActorCStore_ CEqp (void <$$> dropCStoreItem False False CEqp aid b maxBound) b -- ** Impress effectImpress :: MonadServerAtomic m => (IK.Effect -> m UseResult) -> m () -> ActorId -> ActorId -> m UseResult effectImpress recursiveCall execSfx source target = do sb <- getsState $ getActorBody source tb <- getsState $ getActorBody target if | bproj tb -> return UseDud | bfid tb == bfid sb -> -- Unimpress wrt others, but only once. The recursive Sfx suffices. recursiveCall $ IK.DropItem 1 1 COrgan IK.S_IMPRESSED | otherwise -> do -- Actors that don't move freely and so are stupid, can't be impressed. canTra <- getsState $ canTraverse target if canTra then do unless (bhp tb <= 0) execSfx -- avoid spam just before death effectCreateItem (Just $ bfid sb) (Just 1) source target Nothing COrgan IK.S_IMPRESSED IK.timerNone else return UseDud -- no message, because common and not crucial -- ** PutToSleep effectPutToSleep :: MonadServerAtomic m => m () -> ActorId -> m UseResult effectPutToSleep execSfx target = do tb <- getsState $ getActorBody target if | bproj tb -> return UseDud | bwatch tb `elem` [WSleep, WWake] -> return UseDud -- can't increase sleep | otherwise -> do actorMaxSk <- getsState $ getActorMaxSkills target if not $ canSleep actorMaxSk then return UseId -- no message about the cause, so at least ID else do let maxCalm = xM $ Ability.getSk Ability.SkMaxCalm actorMaxSk deltaCalm = maxCalm - bcalm tb when (deltaCalm > 0) $ updateCalm target deltaCalm -- max Calm, but asleep vulnerability execSfx case bwatch tb of WWait n | n > 0 -> do nAll <- removeConditionSingle IK.S_BRACED target let !_A = assert (nAll == 0) () return () _ -> return () -- Forced sleep. No check if the actor can sleep naturally. addSleep target return UseUp -- ** Yell -- This is similar to 'reqYell', but also mentions that the actor is startled, -- because, presumably, he yells involuntarily. It doesn't wake him up -- via Calm instantly, just like yelling in a dream not always does. effectYell :: MonadServerAtomic m => m () -> ActorId -> m UseResult effectYell execSfx target = do tb <- getsState $ getActorBody target if bhp tb <= 0 then -- avoid yelling corpses return UseDud -- the yell never manifested else do unless (bproj tb) execSfx execSfxAtomic $ SfxTaunt False target when (not (bproj tb) && deltaBenign (bcalmDelta tb)) $ execUpdAtomic $ UpdRefillCalm target minusM return UseUp -- ** Summon -- Note that the Calm expended doesn't depend on the number of actors summoned. effectSummon :: MonadServerAtomic m => GroupName ItemKind -> Dice.Dice -> ItemId -> ActorId -> ActorId -> ActivationFlag -> m UseResult effectSummon grp nDm iid source target effActivation = do -- Obvious effect, nothing announced. sb <- getsState $ getActorBody source tb <- getsState $ getActorBody target sMaxSk <- getsState $ getActorMaxSkills source tMaxSk <- getsState $ getActorMaxSkills target totalDepth <- getsState stotalDepth Level{ldepth, lbig} <- getLevel (blid tb) nFriends <- getsState $ length . friendRegularAssocs (bfid sb) (blid sb) discoAspect <- getsState sdiscoAspect power0 <- rndToAction $ castDice ldepth totalDepth nDm fact <- getsState $ (EM.! bfid sb) . sfactionD let arItem = discoAspect EM.! iid power = max power0 1 -- KISS, always at least one summon -- We put @source@ instead of @target@ and @power@ instead of dice -- to make the message more accurate. effect = IK.Summon grp $ Dice.intToDice power durable = IA.checkFlag Ability.Durable arItem warnBothActors warning = unless (bproj sb) $ do execSfxAtomic $ SfxMsgFid (bfid sb) warning when (source /= target) $ execSfxAtomic $ SfxMsgFid (bfid tb) warning deltaCalm = - xM 30 -- Verify Calm only at periodic activations or if the item is durable. -- Otherwise summon uses up the item, which prevents summoning getting -- out of hand. I don't verify Calm otherwise, to prevent an exploit -- via draining one's calm on purpose when an item with good activation -- has a nasty summoning side-effect (the exploit still works on durables). if | bproj tb || source /= target && not (isFoe (bfid sb) fact (bfid tb)) -> return UseDud -- hitting friends or projectiles to summon is too cheap | (effActivation == ActivationPeriodic || durable) && not (bproj sb) && (bcalm sb < - deltaCalm || not (calmEnough sb sMaxSk)) -> do warnBothActors $ SfxSummonLackCalm source return UseId | nFriends >= 20 -> do -- We assume the actor tries to summon his teammates or allies. -- As he repeats such summoning, he is going to bump into this limit. -- If he summons others, see the next condition. warnBothActors $ SfxSummonTooManyOwn source return UseId | EM.size lbig >= 200 -> do -- lower than the 300 limit for spawning -- Even if the actor summons foes, he is prevented from exploiting it -- too many times and stopping natural monster spawning on the level -- (e.g., by filling the level with harmless foes). warnBothActors $ SfxSummonTooManyAll source return UseId | otherwise -> do unless (bproj sb) $ updateCalm source deltaCalm localTime <- getsState $ getLocalTime (blid tb) -- Make sure summoned actors start acting after the victim. let actorTurn = ticksPerMeter $ gearSpeed tMaxSk targetTime = timeShift localTime actorTurn afterTime = timeShift targetTime $ Delta timeClip -- Mark as summoned to prevent immediate chain summoning. -- Summon from current depth, not deeper due to many spawns already. anySummoned <- addManyActors True 0 [(grp, 1)] (blid tb) afterTime (Just $ bpos tb) power if anySummoned then do execSfxAtomic $ SfxEffect (bfid sb) source iid effect 0 return UseUp else do -- We don't display detailed warnings when @addAnyActor@ fails, -- e.g., because the actor groups can't be generated on a given level. -- However, we at least don't claim any summoning happened -- and we offer a general summoning failure messages. warnBothActors $ SfxSummonFailure source return UseId -- ** Ascend -- Note that projectiles can be teleported, too, for extra fun. effectAscend :: MonadServerAtomic m => (IK.Effect -> m UseResult) -> m () -> Bool -> ActorId -> ActorId -> Container -> m UseResult effectAscend recursiveCall execSfx up source target container = do b1 <- getsState $ getActorBody target pos <- getsState $ posFromC container let lid1 = blid b1 destinations <- getsState $ whereTo lid1 pos up . sdungeon sb <- getsState $ getActorBody source actorMaxSk <- getsState $ getActorMaxSkills target if | source /= target && Ability.getSk Ability.SkMove actorMaxSk <= 0 -> do execSfxAtomic $ SfxMsgFid (bfid sb) SfxTransImpossible when (source /= target) $ execSfxAtomic $ SfxMsgFid (bfid b1) SfxTransImpossible return UseId | actorWaits b1 && source /= target -> do execSfxAtomic $ SfxMsgFid (bfid sb) $ SfxBracedImmune target when (source /= target) $ execSfxAtomic $ SfxMsgFid (bfid b1) $ SfxBracedImmune target return UseId | null destinations -> do execSfxAtomic $ SfxMsgFid (bfid sb) SfxLevelNoMore when (source /= target) $ execSfxAtomic $ SfxMsgFid (bfid b1) SfxLevelNoMore -- We keep it useful even in shallow dungeons. recursiveCall $ IK.Teleport 30 -- powerful teleport | otherwise -> do (lid2, pos2) <- rndToAction $ oneOf destinations execSfx mbtime_bOld <- getsServer $ lookupActorTime (bfid b1) lid1 target . sactorTime mbtimeTraj_bOld <- getsServer $ lookupActorTime (bfid b1) lid1 target . strajTime pos3 <- findStairExit (bfid sb) up lid2 pos2 let switch1 = void $ switchLevels1 (target, b1) switch2 = do -- Make the initiator of the stair move the leader, -- to let him clear the stairs for others to follow. let mlead = if bproj b1 then Nothing else Just target -- Move the actor to where the inhabitants were, if any. switchLevels2 lid2 pos3 (target, b1) mbtime_bOld mbtimeTraj_bOld mlead -- The actor will be added to the new level, -- but there can be other actors at his new position. inhabitants <- getsState $ posToAidAssocs pos3 lid2 case inhabitants of (_, b2) : _ | not $ bproj b1 -> do -- Alert about the switch. execSfxAtomic $ SfxMsgFid (bfid sb) SfxLevelPushed -- Only tell one pushed player, even if many actors, because then -- they are projectiles, so not too important. when (source /= target) $ execSfxAtomic $ SfxMsgFid (bfid b2) SfxLevelPushed -- Move the actor out of the way. switch1 -- Move the inhabitants out of the way and to where the actor was. let moveInh inh = do -- Preserve the old leader, since the actor is pushed, -- so possibly has nothing worhwhile to do on the new level -- (and could try to switch back, if made a leader, -- leading to a loop). mbtime_inh <- getsServer $ lookupActorTime (bfid (snd inh)) lid2 (fst inh) . sactorTime mbtimeTraj_inh <- getsServer $ lookupActorTime (bfid (snd inh)) lid2 (fst inh) . strajTime inhMLead <- switchLevels1 inh switchLevels2 lid1 (bpos b1) inh mbtime_inh mbtimeTraj_inh inhMLead mapM_ moveInh inhabitants -- Move the actor to his destination. switch2 _ -> do -- no inhabitants or the stair-taker a projectile switch1 switch2 return UseUp findStairExit :: MonadStateRead m => FactionId -> Bool -> LevelId -> Point -> m Point findStairExit side moveUp lid pos = do COps{coTileSpeedup} <- getsState scops fact <- getsState $ (EM.! side) . sfactionD lvl <- getLevel lid let defLanding = uncurry Vector $ if moveUp then (1, 0) else (-1, 0) center = uncurry Vector $ if moveUp then (-1, 0) else (1, 0) (mvs2, mvs1) = break (== defLanding) moves mvs = center : filter (/= center) (mvs1 ++ mvs2) ps = filter (Tile.isWalkable coTileSpeedup . (lvl `at`)) $ map (shift pos) mvs posOcc :: State -> Int -> Point -> Bool posOcc s k p = case posToAidAssocs p lid s of [] -> k == 0 (_, b) : _ | bproj b -> k == 3 (_, b) : _ | isFoe side fact (bfid b) -> k == 1 -- non-proj foe _ -> k == 2 -- moving a non-projectile friend unocc <- getsState posOcc case concatMap (\k -> filter (unocc k) ps) [0..3] of [] -> error $ "" `showFailure` ps posRes : _ -> return posRes switchLevels1 :: MonadServerAtomic m => (ActorId, Actor) -> m (Maybe ActorId) switchLevels1 (aid, bOld) = do let side = bfid bOld mleader <- getsState $ gleader . (EM.! side) . sfactionD -- Prevent leader pointing to a non-existing actor. mlead <- if not (bproj bOld) && isJust mleader then do execUpdAtomic $ UpdLeadFaction side mleader Nothing return mleader -- outside of a client we don't know the real tgt of aid, hence fst else return Nothing -- Remove the actor from the old level. -- Onlookers see somebody disappear suddenly. -- @UpdDestroyActor@ is too loud, so use @UpdLoseActor@ instead. execUpdAtomic $ UpdLoseActor aid bOld return mlead switchLevels2 ::MonadServerAtomic m => LevelId -> Point -> (ActorId, Actor) -> Maybe Time -> Maybe Time -> Maybe ActorId -> m () switchLevels2 lidNew posNew (aid, bOld) mbtime_bOld mbtimeTraj_bOld mlead = do let lidOld = blid bOld side = bfid bOld let !_A = assert (lidNew /= lidOld `blame` "stairs looped" `swith` lidNew) () -- Sync actor's items' timeouts with the new local time of the level. -- We need to sync organs and equipment due to periodic activations, -- but also due to timeouts after use, e.g., for some weapons -- (they recharge also in the stash; however, this doesn't encourage -- micromanagement for periodic items, because the timeout is randomised -- upon move to equipment). -- -- We don't rebase timeouts for items in stash, because they are -- used by many actors on levels with different local times, -- so there is no single rebase that would match all. -- This is not a big problem: after a single use by an actor the timeout is -- set to his current local time, so further uses by that actor have -- not anomalously short or long recharge times. If the recharge time -- is very long, the player has an option of moving the item away from stash -- and back, to reset the timeout. An abuse is possible when recently -- used item is put from equipment to stash and at once used on another level -- taking advantage of local time difference, but this only works once -- and using the item back again at the original level makes the recharge -- time longer, in turn. timeOld <- getsState $ getLocalTime lidOld timeLastActive <- getsState $ getLocalTime lidNew let delta = timeLastActive `timeDeltaToFrom` timeOld computeNewTimeout :: ItemQuant -> ItemQuant computeNewTimeout (k, it) = (k, map (shiftItemTimer delta) it) rebaseTimeout :: ItemBag -> ItemBag rebaseTimeout = EM.map computeNewTimeout bNew = bOld { blid = lidNew , bpos = posNew , boldpos = Just posNew -- new level, new direction , borgan = rebaseTimeout $ borgan bOld , beqp = rebaseTimeout $ beqp bOld } shiftByDelta = (`timeShift` delta) -- Sync the actor time with the level time. -- This time shift may cause a double move of a foe of the same speed, -- but this is OK --- the foe didn't have a chance to move -- before, because the arena went inactive, so he moves now one more time. maybe (return ()) (\btime_bOld -> modifyServer $ \ser -> ser {sactorTime = updateActorTime (bfid bNew) lidNew aid (shiftByDelta btime_bOld) $ sactorTime ser}) mbtime_bOld maybe (return ()) (\btime_bOld -> modifyServer $ \ser -> ser {strajTime = updateActorTime (bfid bNew) lidNew aid (shiftByDelta btime_bOld) $ strajTime ser}) mbtimeTraj_bOld -- Materialize the actor at the new location. -- Onlookers see somebody appear suddenly. The actor himself -- sees new surroundings and has to reset his perception. execUpdAtomic $ UpdSpotActor aid bNew forM_ mlead $ -- The leader is fresh in the sense that he's on a new level -- and so doesn't have up to date Perception. setFreshLeader side -- ** Escape -- | The faction leaves the dungeon. effectEscape :: MonadServerAtomic m => m () -> ActorId -> ActorId -> m UseResult effectEscape execSfx source target = do -- Obvious effect, nothing announced. sb <- getsState $ getActorBody source tb <- getsState $ getActorBody target let fid = bfid tb fact <- getsState $ (EM.! fid) . sfactionD if | bproj tb -> return UseDud -- basically a misfire | not (fcanEscape $ gkind fact) -> do execSfxAtomic $ SfxMsgFid (bfid sb) SfxEscapeImpossible when (source /= target) $ execSfxAtomic $ SfxMsgFid (bfid tb) SfxEscapeImpossible return UseId | otherwise -> do execSfx deduceQuits (bfid tb) $ Status Escape (fromEnum $ blid tb) Nothing return UseUp -- ** Paralyze -- | Advance target actor time by this many time clips. Not by actor moves, -- to hurt fast actors more. effectParalyze :: MonadServerAtomic m => m () -> Dice.Dice -> ActorId -> ActorId -> m UseResult effectParalyze execSfx nDm source target = do tb <- getsState $ getActorBody target if bproj tb then return UseDud -- shortcut for speed else paralyze execSfx nDm source target paralyze :: MonadServerAtomic m => m () -> Dice.Dice -> ActorId -> ActorId -> m UseResult paralyze execSfx nDm source target = do tb <- getsState $ getActorBody target totalDepth <- getsState stotalDepth Level{ldepth} <- getLevel (blid tb) power0 <- rndToAction $ castDice ldepth totalDepth nDm let power = max power0 1 -- KISS, avoid special case actorStasis <- getsServer sactorStasis if ES.member target actorStasis then do sb <- getsState $ getActorBody source execSfxAtomic $ SfxMsgFid (bfid sb) SfxStasisProtects when (source /= target) $ execSfxAtomic $ SfxMsgFid (bfid tb) SfxStasisProtects return UseId else do execSfx let t = timeDeltaScale (Delta timeClip) power -- Only the normal time, not the trajectory time, is affected. modifyServer $ \ser -> ser { sactorTime = ageActor (bfid tb) (blid tb) target t $ sactorTime ser , sactorStasis = ES.insert target (sactorStasis ser) } -- actor's time warped, so he is in stasis, -- immune to further warps return UseUp -- ** ParalyzeInWater -- | Advance target actor time by this many time clips. Not by actor moves, -- to hurt fast actors more. Due to water, so resistable. effectParalyzeInWater :: MonadServerAtomic m => m () -> Dice.Dice -> ActorId -> ActorId -> m UseResult effectParalyzeInWater execSfx nDm source target = do tb <- getsState $ getActorBody target if bproj tb then return UseDud else do -- shortcut for speed actorMaxSk <- getsState $ getActorMaxSkills target let swimmingOrFlying = max (Ability.getSk Ability.SkSwimming actorMaxSk) (Ability.getSk Ability.SkFlying actorMaxSk) if Dice.supDice nDm > swimmingOrFlying then paralyze execSfx nDm source target -- no help at all else -- fully resisted -- Don't spam: -- sb <- getsState $ getActorBody source -- execSfxAtomic $ SfxMsgFid (bfid sb) SfxWaterParalysisResisted return UseId -- ** InsertMove -- | Give target actor the given number of tenths of extra move. Don't give -- an absolute amount of time units, to benefit slow actors more. effectInsertMove :: MonadServerAtomic m => m () -> Dice.Dice -> ActorId -> ActorId -> m UseResult effectInsertMove execSfx nDm source target = do tb <- getsState $ getActorBody target actorMaxSk <- getsState $ getActorMaxSkills target totalDepth <- getsState stotalDepth Level{ldepth} <- getLevel (blid tb) actorStasis <- getsServer sactorStasis power0 <- rndToAction $ castDice ldepth totalDepth nDm let power = max power0 1 -- KISS, avoid special case actorTurn = ticksPerMeter $ gearSpeed actorMaxSk t = timeDeltaScale (timeDeltaPercent actorTurn 10) (-power) if | bproj tb -> return UseDud -- shortcut for speed | ES.member target actorStasis -> do sb <- getsState $ getActorBody source execSfxAtomic $ SfxMsgFid (bfid sb) SfxStasisProtects when (source /= target) $ execSfxAtomic $ SfxMsgFid (bfid tb) SfxStasisProtects return UseId | otherwise -> do execSfx -- Only the normal time, not the trajectory time, is affected. modifyServer $ \ser -> ser { sactorTime = ageActor (bfid tb) (blid tb) target t $ sactorTime ser , sactorStasis = ES.insert target (sactorStasis ser) } -- actor's time warped, so he is in stasis, -- immune to further warps return UseUp -- ** Teleport -- | Teleport the target actor. -- Note that projectiles can be teleported, too, for extra fun. effectTeleport :: MonadServerAtomic m => m () -> Dice.Dice -> ActorId -> ActorId -> m UseResult effectTeleport execSfx nDm source target = do sb <- getsState $ getActorBody source tb <- getsState $ getActorBody target actorMaxSk <- getsState $ getActorMaxSkills target if | source /= target && Ability.getSk Ability.SkMove actorMaxSk <= 0 -> do execSfxAtomic $ SfxMsgFid (bfid sb) SfxTransImpossible when (source /= target) $ execSfxAtomic $ SfxMsgFid (bfid tb) SfxTransImpossible return UseId | source /= target && actorWaits tb -> do -- immune only against not own effects, to enable teleport -- as beneficial's necklace drawback; also consistent -- with sleep not protecting execSfxAtomic $ SfxMsgFid (bfid sb) $ SfxBracedImmune target when (source /= target) $ execSfxAtomic $ SfxMsgFid (bfid tb) $ SfxBracedImmune target return UseId | otherwise -> do COps{coTileSpeedup} <- getsState scops totalDepth <- getsState stotalDepth lvl@Level{ldepth} <- getLevel (blid tb) range <- rndToAction $ castDice ldepth totalDepth nDm let spos = bpos tb dMinMax !delta !pos = let d = chessDist spos pos in d >= range - delta && d <= range + delta dist !delta !pos _ = dMinMax delta pos mtpos <- rndToAction $ findPosTry 200 lvl (\p !t -> Tile.isWalkable coTileSpeedup t && not (Tile.isNoActor coTileSpeedup t) && not (occupiedBigLvl p lvl) && not (occupiedProjLvl p lvl)) [ dist 1 , dist $ 1 + range `div` 9 , dist $ 1 + range `div` 7 , dist $ 1 + range `div` 5 , dist 5 , dist 7 , dist 9 ] case mtpos of Nothing -> do -- really very rare, so debug debugPossiblyPrint "Server: effectTeleport: failed to find any free position" execSfxAtomic $ SfxMsgFid (bfid sb) SfxTransImpossible when (source /= target) $ execSfxAtomic $ SfxMsgFid (bfid tb) SfxTransImpossible return UseId Just tpos -> do execSfx execUpdAtomic $ UpdMoveActor target spos tpos return UseUp -- ** CreateItem effectCreateItem :: MonadServerAtomic m => Maybe FactionId -> Maybe Int -> ActorId -> ActorId -> Maybe ItemId -> CStore -> GroupName ItemKind -> IK.TimerDice -> m UseResult effectCreateItem jfidRaw mcount source target miidOriginal store grp tim = do tb <- getsState $ getActorBody target if bproj tb && store == COrgan -- other stores OK not to lose possible loot then return UseDud -- don't make a projectile hungry, etc. else do cops <- getsState scops sb <- getsState $ getActorBody source actorMaxSk <- getsState $ getActorMaxSkills target totalDepth <- getsState stotalDepth lvlTb <- getLevel (blid tb) let -- If the number of items independent of depth in @mcount@, -- make also the timer, the item kind choice and aspects -- independent of depth, via fixing the generation depth of the item -- to @totalDepth@. Prime example of provided @mcount@ is crafting. -- TODO: base this on a resource that can be consciously spent, -- not on a skill that grows over time or that only one actor -- maxes out and so needs to always be chosen for crafting. -- See https://www.reddit.com/r/roguelikedev/comments/phukcq/game_design_question_how_to_base_item_generation/ depth = if isJust mcount then totalDepth else ldepth lvlTb fscale unit nDm = do k0 <- rndToAction $ castDice depth totalDepth nDm let k = max 1 k0 -- KISS, don't freak out if dice permit 0 return $! timeDeltaScale unit k fgame = fscale (Delta timeTurn) factor nDm = do -- A bit added to make sure length 1 effect doesn't randomly -- end, or not, before the end of first turn, which would make, -- e.g., hasting, useless. This needs to be higher than 10% -- to compensate for overhead of animals, etc. (no leaders). let actorTurn = timeDeltaPercent (ticksPerMeter $ gearSpeed actorMaxSk) 111 fscale actorTurn nDm delta <- IK.foldTimer (return $ Delta timeZero) fgame factor tim let c = CActor target store bagBefore <- getsState $ getBodyStoreBag tb store uniqueSet <- getsServer suniqueSet -- Power depth of new items unaffected by number of spawned actors, so 0. let freq = newItemKind cops uniqueSet [(grp, 1)] depth totalDepth 0 m2 <- rollItemAspect freq depth case m2 of NoNewItem -> return UseDud -- e.g., unique already generated NewItem _ itemKnownRaw itemFullRaw (kRaw, itRaw) -> do -- Avoid too many different item identifiers (one for each faction) -- for blasts or common item generating tiles. Conditions are -- allowed to be duplicated, because they provide really useful info -- (perpetrator). However, if timer is none, they are not duplicated -- to make sure that, e.g., poisons stack with each other regardless -- of perpetrator and we don't get "no longer poisoned" message -- while still poisoned due to another faction. With timed aspects, -- e.g., slowness, the message is less misleading, and it's interesting -- that I'm twice slower due to aspects from two factions and not -- as deadly as being poisoned at twice the rate from two factions. let jfid = if store == COrgan && not (IK.isTimerNone tim) || grp == IK.S_IMPRESSED then jfidRaw else Nothing ItemKnown kindIx arItem _ = itemKnownRaw (itemKnown, itemFull) = ( ItemKnown kindIx arItem jfid , itemFullRaw {itemBase = (itemBase itemFullRaw) {jfid}} ) itemRev <- getsServer sitemRev let mquant = case HM.lookup itemKnown itemRev of Nothing -> Nothing Just iid -> (iid,) <$> iid `EM.lookup` bagBefore case mquant of Just (iid, (_, afterIt@(timer : rest))) | not $ IK.isTimerNone tim -> do -- Already has such items and timer change requested, so only increase -- the timer of the first item by the delta, but don't create items. let newIt = shiftItemTimer delta timer : rest if afterIt /= newIt then do execUpdAtomic $ UpdTimeItem iid c afterIt newIt -- It's hard for the client to tell this timer change from charge -- use, timer reset on pickup, etc., so we create the msg manually. -- Sending to both involved factions lets the player notice -- both the extensions he caused and suffered. Other faction causing -- that on themselves or on others won't be noticed. TMI. execSfxAtomic $ SfxMsgFid (bfid sb) $ SfxTimerExtended target iid store delta when (bfid sb /= bfid tb) $ execSfxAtomic $ SfxMsgFid (bfid tb) $ SfxTimerExtended target iid store delta return UseUp else return UseDud -- probably incorrect content, but let it be _ -> do localTime <- getsState $ getLocalTime (blid tb) let newTimer = createItemTimer localTime delta extraIt k = if IK.isTimerNone tim then itRaw -- don't break @applyPeriodicLevel@ else replicate k newTimer -- randomized and overwritten in @registerItem@ -- if an organ or created in equipment kitNew = case mcount of Just itemK -> (itemK, extraIt itemK) Nothing -> (kRaw, extraIt kRaw) case miidOriginal of Just iidOriginal | store /= COrgan -> execSfxAtomic $ SfxMsgFid (bfid tb) $ SfxItemYield iidOriginal (fst kitNew) (blid tb) _ -> return () -- No such items or some items, but void delta, so create items. -- If it's, e.g., a periodic poison, the new items will stack with any -- already existing items. iid <- registerItem True (itemFull, kitNew) itemKnown c -- If created not on the ground, ID it, because it won't be on pickup. -- If ground and stash coincide, unindentified item enters stash, -- so will be identified when equipped, used or dropped -- and picked again. if isJust mcount -- not a random effect, so probably crafting && not (IA.isHumanTrinket (itemKind itemFull)) then execUpdAtomic $ UpdDiscover c iid (itemKindId itemFull) arItem else when (store /= CGround) $ discoverIfMinorEffects c iid (itemKindId itemFull) return UseUp -- ** DestroyItem -- | Make the target actor destroy items in a store from the given group. -- The item that caused the effect itself is *not* immune, because often -- the item needs to destroy itself, e.g., to model wear and tear. -- In such a case, the item may need to be identified, in a container, -- when it no longer exists, at least in the container. This is OK. -- Durable items are not immune, unlike the tools in @ConsumeItems@. effectDestroyItem :: MonadServerAtomic m => m () -> Int -> Int -> CStore -> ActorId -> GroupName ItemKind -> m UseResult effectDestroyItem execSfx ngroup kcopy store target grp = do tb <- getsState $ getActorBody target is <- allGroupItems store grp target if null is then return UseDud else do execSfx urs <- mapM (uncurry (dropCStoreItem True True store target tb kcopy)) (take ngroup is) return $! case urs of [] -> UseDud -- there was no effects _ -> maximum urs -- | Drop a single actor's item (though possibly multiple copies). -- Note that if there are multiple copies, at most one explodes -- to avoid excessive carnage and UI clutter (let's say, -- the multiple explosions interfere with each other or perhaps -- larger quantities of explosives tend to be packaged more safely). -- Note also that @OnSmash@ effects are activated even if item discharged. dropCStoreItem :: MonadServerAtomic m => Bool -> Bool -> CStore -> ActorId -> Actor -> Int -> ItemId -> ItemQuant -> m UseResult dropCStoreItem verbose destroy store aid b kMax iid (k, _) = do let c = CActor aid store bag0 <- getsState $ getContainerBag c -- @OnSmash@ effects of previous items may remove next items, so better check. if iid `EM.notMember` bag0 then return UseDud else do itemFull <- getsState $ itemToFull iid let arItem = aspectRecordFull itemFull fragile = IA.checkFlag Ability.Fragile arItem durable = IA.checkFlag Ability.Durable arItem isDestroyed = destroy || bproj b && (bhp b <= 0 && not durable || fragile) || store == COrgan -- just as organs are destroyed at death -- but also includes conditions if isDestroyed then do let effApplyFlags = EffApplyFlags { effToUse = EffBare -- the embed could be combined at this point but @iid@ cannot , effVoluntary = True -- we don't know if it's effVoluntary, so we conservatively assume -- it is and we blame @aid@ , effUseAllCopies = kMax >= k , effKineticPerformed = False , effActivation = ActivationOnSmash , effMayDestroy = True } void $ effectAndDestroyAndAddKill effApplyFlags aid aid aid iid c itemFull -- One copy was destroyed (or none if the item was discharged), -- so let's mop up. bag <- getsState $ getContainerBag c maybe (return ()) (\(k1, it) -> do let destroyedSoFar = k - k1 k2 = min (kMax - destroyedSoFar) k1 kit2 = (k2, take k2 it) -- Don't spam if the effect already probably made noise -- and also the number could be surprising to the player. verbose2 = verbose && k1 == k when (k2 > 0) $ execUpdAtomic $ UpdDestroyItem verbose2 iid (itemBase itemFull) kit2 c) (EM.lookup iid bag) return UseUp else do cDrop <- pickDroppable False aid b -- drop over fog, etc. mvCmd <- generalMoveItem verbose iid (min kMax k) (CActor aid store) cDrop mapM_ execUpdAtomic mvCmd return UseUp pickDroppable :: MonadStateRead m => Bool -> ActorId -> Actor -> m Container pickDroppable respectNoItem aid b = do cops@COps{coTileSpeedup} <- getsState scops lvl <- getLevel (blid b) let validTile t = not (respectNoItem && Tile.isNoItem coTileSpeedup t) if validTile $ lvl `at` bpos b then return $! CActor aid CGround else do let ps = nearbyFreePoints cops lvl validTile (bpos b) return $! case filter (adjacent $ bpos b) $ take 8 ps of [] -> CActor aid CGround -- fallback; still correct, though not ideal pos : _ -> CFloor (blid b) pos -- ** ConsumeItems -- | Make the target actor destroy the given items, if all present, -- or none at all, if any is missing. To be used in crafting. -- The item that caused the effect itself is not considered (any copies). effectConsumeItems :: MonadServerAtomic m => m () -> ItemId -> ActorId -> [(Int, GroupName ItemKind)] -> [(Int, GroupName ItemKind)] -> m UseResult effectConsumeItems execSfx iidOriginal target tools0 raw0 = do kitAssG <- getsState $ kitAssocs target [CGround] let kitAss = listToolsToConsume kitAssG [] -- equipment too dangerous to use is = filter ((/= iidOriginal) . fst . snd) kitAss grps0 = map (\(x, y) -> (False, x, y)) tools0 -- apply if durable ++ map (\(x, y) -> (True, x, y)) raw0 -- destroy always (bagsToLose3, iidsToApply3, grps3) = foldl' subtractIidfromGrps (EM.empty, [], grps0) is if null grps3 then do execSfx consumeItems target bagsToLose3 iidsToApply3 return UseUp else return UseDud consumeItems :: MonadServerAtomic m => ActorId -> EM.EnumMap CStore ItemBag -> [(CStore, (ItemId, ItemFull))] -> m () consumeItems target bagsToLose iidsToApply = do COps{coitem} <- getsState scops tb <- getsState $ getActorBody target arTrunk <- getsState $ (EM.! btrunk tb) . sdiscoAspect let isBlast = IA.checkFlag Ability.Blast arTrunk identifyStoreBag store bag = mapM_ (identifyStoreIid store) $ EM.keys bag identifyStoreIid store iid = do discoAspect2 <- getsState sdiscoAspect -- might have changed due to embedded items invocations itemKindId <- getsState $ getIidKindIdServer iid let arItem = discoAspect2 EM.! iid c = CActor target store itemKind = okind coitem itemKindId unless (IA.isHumanTrinket itemKind) $ -- a hack execUpdAtomic $ UpdDiscover c iid itemKindId arItem -- We don't invoke @OnSmash@ effects, so we avoid the risk -- of the first removed item displacing the actor, destroying -- or scattering some pending items ahead of time, etc. -- The embed should provide any requisite fireworks instead. forM_ (EM.assocs bagsToLose) $ \(store, bagToLose) -> unless (EM.null bagToLose) $ do identifyStoreBag store bagToLose -- Not @UpdLoseItemBag@, to be verbose. -- The bag is small, anyway. let c = CActor target store itemD <- getsState sitemD mapWithKeyM_ (\iid kit -> do let verbose = not isBlast -- no spam item = itemD EM.! iid execUpdAtomic $ UpdDestroyItem verbose iid item kit c) bagToLose -- But afterwards we do apply normal effects of durable items, -- even if the actor or other items displaced in the process, -- as long as a number of the items is still there. -- So if a harmful double-purpose tool-component is both to be used -- and destroyed, it will be lost, but at least it won't harm anybody. let applyItemIfPresent (store, (iid, itemFull)) = do let c = CActor target store bag <- getsState $ getContainerBag c when (iid `EM.member` bag) $ do execSfxAtomic $ SfxApply target iid -- Treated as if the actor only activated the item on himself, -- without kinetic damage, to avoid the exploit of wearing armor -- when using tools or transforming terrain. -- Also, timeouts of the item ignored to prevent exploit -- by discharging the item before using it. let effApplyFlags = EffApplyFlags { effToUse = EffBare -- crafting not intended , effVoluntary = True , effUseAllCopies = False , effKineticPerformed = False , effActivation = ActivationConsume , effMayDestroy = False } void $ effectAndDestroyAndAddKill effApplyFlags target target target iid c itemFull mapM_ applyItemIfPresent iidsToApply -- ** DropItem -- | Make the target actor drop items in a store from the given group. -- The item that caused the effect itself is immune (any copies). effectDropItem :: MonadServerAtomic m => m () -> ItemId -> Int -> Int -> CStore -> GroupName ItemKind -> ActorId -> m UseResult effectDropItem execSfx iidOriginal ngroup kcopy store grp target = do tb <- getsState $ getActorBody target fact <- getsState $ (EM.! bfid tb) . sfactionD isRaw <- allGroupItems store grp target curChalSer <- getsServer $ scurChalSer . soptions factionD <- getsState sfactionD let is = filter ((/= iidOriginal) . fst) isRaw if | bproj tb || null is -> return UseDud | ngroup == maxBound && kcopy == maxBound && store `elem` [CStash, CEqp] && fhasGender (gkind fact) -- hero in Allure's decontamination chamber && (cdiff curChalSer == 1 -- at lowest difficulty for its faction && any (fhasUI . gkind . snd) (filter (\(fi, fa) -> isFriend fi fa (bfid tb)) (EM.assocs factionD)) || cdiff curChalSer == difficultyBound && any (fhasUI . gkind . snd) (filter (\(fi, fa) -> isFoe fi fa (bfid tb)) (EM.assocs factionD))) -> {- A hardwired hack, because AI heroes don't cope with Allure's decontamination chamber; beginners may struggle too, so this is trigered by difficulty. - AI heroes don't switch leader to the hero past laboratory to equip weapons from stash between the in-lab hero picks up the loot pile and himself enters the decontamination chamber - the items of the last actor would be lost anyway, unless AI is taught the foolproof solution of this puzzle, which is yet a bit more specific than the two abilities above -} return UseUp | otherwise -> do unless (store == COrgan) execSfx urs <- mapM (uncurry (dropCStoreItem True False store target tb kcopy)) (take ngroup is) return $! case urs of [] -> UseDud -- there was no effects _ -> maximum urs -- ** Recharge and Discharge effectRecharge :: forall m. MonadServerAtomic m => Bool -> m () -> ItemId -> Int -> Dice.Dice -> ActorId -> m UseResult effectRecharge reducingCooldown execSfx iidOriginal n0 dice target = do tb <- getsState $ getActorBody target if bproj tb then return UseDud else do -- slows down, but rarely any effect localTime <- getsState $ getLocalTime (blid tb) totalDepth <- getsState stotalDepth Level{ldepth} <- getLevel $ blid tb power <- rndToAction $ castDice ldepth totalDepth dice let timeUnit = if reducingCooldown then absoluteTimeNegate timeClip else timeClip delta = timeDeltaScale (Delta timeUnit) power localTimer = createItemTimer localTime (Delta timeZero) addToCooldown :: CStore -> (Int, UseResult) -> (ItemId, ItemFullKit) -> m (Int, UseResult) addToCooldown _ (0, ur) _ = return (0, ur) addToCooldown store (n, ur) (iid, (_, (k0, itemTimers0))) = do let itemTimers = filter (charging localTime) itemTimers0 kt = length itemTimers lenToShift = min n $ if reducingCooldown then kt else k0 - kt (itToShift, itToKeep) = if reducingCooldown then splitAt lenToShift itemTimers else (replicate lenToShift localTimer, itemTimers) -- No problem if this overcharges; equivalent to pruned timer. it2 = map (shiftItemTimer delta) itToShift ++ itToKeep if itemTimers0 == it2 then return (n, ur) else do let c = CActor target store execUpdAtomic $ UpdTimeItem iid c itemTimers0 it2 return (n - lenToShift, UseUp) selectWeapon i@(iid, (itemFull, _)) (weapons, others) = let arItem = aspectRecordFull itemFull in if | IA.aTimeout arItem == 0 || iid == iidOriginal -> (weapons, others) | IA.checkFlag Ability.Meleeable arItem -> (i : weapons, others) | otherwise -> (weapons, i : others) partitionWeapon = foldr selectWeapon ([],[]) ignoreCharges = True -- handled above depending on @reducingCooldown@ benefits = Nothing -- only raw damage counts (client knows benefits) sortWeapons ass = map (\(_, _, _, _, iid, itemFullKit) -> (iid, itemFullKit)) $ strongestMelee ignoreCharges benefits localTime ass eqpAss <- getsState $ kitAssocs target [CEqp] let (eqpAssWeapons, eqpAssOthers) = partitionWeapon eqpAss organAss <- getsState $ kitAssocs target [COrgan] let (organAssWeapons, organAssOthers) = partitionWeapon organAss (nEqpWeapons, urEqpWeapons) <- foldM (addToCooldown CEqp) (n0, UseDud) $ sortWeapons eqpAssWeapons (nOrganWeapons, urOrganWeapons) <- foldM (addToCooldown COrgan) (nEqpWeapons, urEqpWeapons) $ sortWeapons organAssWeapons (nEqpOthers, urEqpOthers) <- foldM (addToCooldown CEqp) (nOrganWeapons, urOrganWeapons) eqpAssOthers (_nOrganOthers, urOrganOthers) <- foldM (addToCooldown COrgan) (nEqpOthers, urEqpOthers) organAssOthers if urOrganOthers == UseDud then return UseDud else do execSfx return UseUp -- ** PolyItem -- Can't apply to the item itself (any copies). effectPolyItem :: MonadServerAtomic m => m () -> ItemId -> ActorId -> m UseResult effectPolyItem execSfx iidOriginal target = do tb <- getsState $ getActorBody target let cstore = CGround kitAss <- getsState $ kitAssocs target [cstore] case filter ((/= iidOriginal) . fst) kitAss of [] -> do execSfxAtomic $ SfxMsgFid (bfid tb) SfxPurposeNothing -- Do not spam the source actor player about the failures. return UseId (iid, ( itemFull@ItemFull{itemBase, itemKindId, itemKind} , (itemK, itemTimer) )) : _ -> do let arItem = aspectRecordFull itemFull maxCount = Dice.supDice $ IK.icount itemKind if | IA.checkFlag Ability.Unique arItem -> do execSfxAtomic $ SfxMsgFid (bfid tb) SfxPurposeUnique return UseId | maybe True (<= 0) $ lookup IK.COMMON_ITEM $ IK.ifreq itemKind -> do execSfxAtomic $ SfxMsgFid (bfid tb) SfxPurposeNotCommon return UseId | itemK < maxCount -> do execSfxAtomic $ SfxMsgFid (bfid tb) $ SfxPurposeTooFew maxCount itemK return UseId | otherwise -> do -- Only the required number of items is used up, not all of them. let c = CActor target cstore kit = (maxCount, take maxCount itemTimer) execSfx identifyIid iid c itemKindId itemKind execUpdAtomic $ UpdDestroyItem True iid itemBase kit c effectCreateItem (Just $ bfid tb) Nothing target target Nothing cstore IK.COMMON_ITEM IK.timerNone -- ** RerollItem -- Can't apply to the item itself (any copies). effectRerollItem :: forall m . MonadServerAtomic m => m () -> ItemId -> ActorId -> m UseResult effectRerollItem execSfx iidOriginal target = do COps{coItemSpeedup} <- getsState scops tb <- getsState $ getActorBody target let cstore = CGround -- if ever changed, call @discoverIfMinorEffects@ kitAss <- getsState $ kitAssocs target [cstore] case filter ((/= iidOriginal) . fst) kitAss of [] -> do execSfxAtomic $ SfxMsgFid (bfid tb) SfxRerollNothing -- Do not spam the source actor player about the failures. return UseId (iid, ( ItemFull{ itemBase, itemKindId, itemKind , itemDisco=ItemDiscoFull itemAspect } , (_, itemTimer) )) : _ -> if IA.kmConst $ getKindMean itemKindId coItemSpeedup then do execSfxAtomic $ SfxMsgFid (bfid tb) SfxRerollNotRandom return UseId else do let c = CActor target cstore kit = (1, take 1 itemTimer) -- prevent micromanagement freq = pure (IK.HORROR, itemKindId, itemKind) execSfx identifyIid iid c itemKindId itemKind execUpdAtomic $ UpdDestroyItem False iid itemBase kit c totalDepth <- getsState stotalDepth let roll100 :: Int -> m (ItemKnown, ItemFull) roll100 n = do -- Not only rerolled, but at highest depth possible, -- resulting in highest potential for bonuses. m2 <- rollItemAspect freq totalDepth case m2 of NoNewItem -> error "effectRerollItem: can't create rerolled item" NewItem _ itemKnown@(ItemKnown _ ar2 _) itemFull _ -> if ar2 == itemAspect && n > 0 then roll100 (n - 1) else return (itemKnown, itemFull) (itemKnown, itemFull) <- roll100 100 void $ registerItem True (itemFull, kit) itemKnown c return UseUp _ -> error "effectRerollItem: server ignorant about an item" -- ** DupItem -- Can't apply to the item itself (any copies). effectDupItem :: MonadServerAtomic m => m () -> ItemId -> ActorId -> m UseResult effectDupItem execSfx iidOriginal target = do tb <- getsState $ getActorBody target let cstore = CGround -- beware of other options, e.g., creating in eqp -- and not setting timeout to a random value kitAss <- getsState $ kitAssocs target [cstore] case filter ((/= iidOriginal) . fst) kitAss of [] -> do execSfxAtomic $ SfxMsgFid (bfid tb) SfxDupNothing -- Do not spam the source actor player about the failures. return UseId (iid, ( itemFull@ItemFull{itemKindId, itemKind} , _ )) : _ -> do let arItem = aspectRecordFull itemFull if | IA.checkFlag Ability.Unique arItem -> do execSfxAtomic $ SfxMsgFid (bfid tb) SfxDupUnique return UseId | maybe False (> 0) $ lookup IK.VALUABLE $ IK.ifreq itemKind -> do execSfxAtomic $ SfxMsgFid (bfid tb) SfxDupValuable return UseId | otherwise -> do let c = CActor target cstore execSfx identifyIid iid c itemKindId itemKind let slore = IA.loreFromContainer arItem c modifyServer $ \ser -> ser {sgenerationAn = EM.adjust (EM.insertWith (+) iid 1) slore (sgenerationAn ser)} execUpdAtomic $ UpdCreateItem True iid (itemBase itemFull) quantSingle c return UseUp -- ** Identify effectIdentify :: MonadServerAtomic m => m () -> ItemId -> ActorId -> m UseResult effectIdentify execSfx iidOriginal target = do COps{coItemSpeedup} <- getsState scops discoAspect <- getsState sdiscoAspect -- The actor that causes the application does not determine what item -- is identifiable, becuase it's the target actor that identifies -- his possesions. tb <- getsState $ getActorBody target sClient <- getsServer $ (EM.! bfid tb) . sclientStates let tryFull store as = case as of [] -> return False (iid, _) : rest | iid == iidOriginal -> tryFull store rest -- don't id itself (iid, ItemFull{itemBase, itemKindId, itemKind}) : rest -> do let arItem = discoAspect EM.! iid kindIsKnown = case jkind itemBase of IdentityObvious _ -> True IdentityCovered ix _ -> ix `EM.member` sdiscoKind sClient if iid `EM.member` sdiscoAspect sClient -- already fully identified || IA.isHumanTrinket itemKind -- hack; keep them non-identified || store == CGround && IA.onlyMinorEffects arItem itemKind -- will be identified when picked up, so don't bother || IA.kmConst (getKindMean itemKindId coItemSpeedup) && kindIsKnown -- constant aspects and known kind; no need to identify further; -- this should normally not be needed, since clients should -- identify such items for free then tryFull store rest else do let c = CActor target store execSfx identifyIid iid c itemKindId itemKind return True tryStore stores = case stores of [] -> do execSfxAtomic $ SfxMsgFid (bfid tb) SfxIdentifyNothing return UseId -- the message tells it's ID effect store : rest -> do allAssocs <- getsState $ fullAssocs target [store] go <- tryFull store allAssocs if go then return UseUp else tryStore rest tryStore [CGround, CStash, CEqp] -- The item need not be in the container. It's used for a message only. identifyIid :: MonadServerAtomic m => ItemId -> Container -> ContentId ItemKind -> ItemKind -> m () identifyIid iid c itemKindId itemKind = unless (IA.isHumanTrinket itemKind) $ do discoAspect <- getsState sdiscoAspect execUpdAtomic $ UpdDiscover c iid itemKindId $ discoAspect EM.! iid -- ** Detect effectDetect :: MonadServerAtomic m => m () -> IK.DetectKind -> Int -> ActorId -> Container -> m UseResult effectDetect execSfx d radius target container = do COps{coitem, coTileSpeedup} <- getsState scops b <- getsState $ getActorBody target lvl <- getLevel $ blid b sClient <- getsServer $ (EM.! bfid b) . sclientStates let lvlClient = (EM.! blid b) . sdungeon $ sClient s <- getState getKind <- getsState $ flip getIidKindServer factionD <- getsState sfactionD let lootPredicate p = p `EM.member` lfloor lvl || (case posToBigAssoc p (blid b) s of Nothing -> False Just (_, body) -> let belongings = EM.keys (beqp body) -- shared stash ignored in any belongingIsLoot belongings) || any embedHasLoot (EM.keys $ getEmbedBag (blid b) p s) itemKindIsLoot = isNothing . lookup IK.UNREPORTED_INVENTORY . IK.ifreq belongingIsLoot iid = itemKindIsLoot $ getKind iid embedHasLoot iid = any effectHasLoot $ IK.ieffects $ getKind iid reported acc _ _ itemKind = acc && itemKindIsLoot itemKind effectHasLoot (IK.CreateItem _ cstore grp _) = cstore `elem` [CGround, CStash, CEqp] && ofoldlGroup' coitem grp reported True effectHasLoot IK.PolyItem = True effectHasLoot IK.RerollItem = True effectHasLoot IK.DupItem = True effectHasLoot (IK.AtMostOneOf l) = any effectHasLoot l effectHasLoot (IK.OneOf l) = any effectHasLoot l effectHasLoot (IK.OnSmash eff) = effectHasLoot eff effectHasLoot (IK.OnUser eff) = effectHasLoot eff effectHasLoot (IK.AndEffect eff1 eff2) = effectHasLoot eff1 || effectHasLoot eff2 effectHasLoot (IK.OrEffect eff1 eff2) = effectHasLoot eff1 || effectHasLoot eff2 effectHasLoot (IK.SeqEffect effs) = any effectHasLoot effs effectHasLoot (IK.When _ eff) = effectHasLoot eff effectHasLoot (IK.Unless _ eff) = effectHasLoot eff effectHasLoot (IK.IfThenElse _ eff1 eff2) = effectHasLoot eff1 || effectHasLoot eff2 effectHasLoot _ = False stashPredicate p = any (onStash p) $ EM.assocs factionD onStash p (fid, fact) = case gstash fact of Just (lid, pos) -> pos == p && lid == blid b && fid /= bfid b Nothing -> False (predicate, action) = case d of IK.DetectAll -> (const True, const $ return False) IK.DetectActor -> ((`EM.member` lbig lvl), const $ return False) IK.DetectLoot -> (lootPredicate, const $ return False) IK.DetectExit -> let (ls1, ls2) = lstair lvl in ((`elem` ls1 ++ ls2 ++ lescape lvl), const $ return False) IK.DetectHidden -> let predicateH p = let tClient = lvlClient `at` p tServer = lvl `at` p in Tile.isHideAs coTileSpeedup tServer && tClient /= tServer -- the actor searches only tiles he doesn't know already, -- preventing misleading messages (and giving less information -- to eavesdropping parties) revealEmbed p = do embeds <- getsState $ getEmbedBag (blid b) p unless (EM.null embeds) $ execUpdAtomic $ UpdSpotItemBag True (CEmbed (blid b) p) embeds actionH l = do pos <- getsState $ posFromC container let f p = when (p /= pos) $ do let t = lvl `at` p execUpdAtomic $ UpdSearchTile target p t -- This is safe searching; embedded items -- are not triggered, but they are revealed. revealEmbed p case EM.lookup p $ lentry lvl of Nothing -> return () Just entry -> execUpdAtomic $ UpdSpotEntry (blid b) [(p, entry)] mapM_ f l return $! not $ null l in (predicateH, actionH) IK.DetectEmbed -> ((`EM.member` lembed lvl), const $ return False) IK.DetectStash -> (stashPredicate, const $ return False) effectDetectX d predicate action execSfx radius target -- This is not efficient at all, so optimize iff detection is added -- to periodic organs or common periodic items or often activated embeds. effectDetectX :: MonadServerAtomic m => IK.DetectKind -> (Point -> Bool) -> ([Point] -> m Bool) -> m () -> Int -> ActorId -> m UseResult effectDetectX d predicate action execSfx radius target = do COps{corule=RuleContent{rWidthMax, rHeightMax}} <- getsState scops b <- getsState $ getActorBody target sperFidOld <- getsServer sperFid let perOld = sperFidOld EM.! bfid b EM.! blid b Point x0 y0 = bpos b perList = filter predicate [ Point x y | y <- [max 0 (y0 - radius) .. min (rHeightMax - 1) (y0 + radius)] , x <- [max 0 (x0 - radius) .. min (rWidthMax - 1) (x0 + radius)] ] extraPer = emptyPer {psight = PerVisible $ ES.fromDistinctAscList perList} inPer = diffPer extraPer perOld unless (nullPer inPer) $ do -- Perception is modified on the server and sent to the client -- together with all the revealed info. let perNew = addPer inPer perOld fper = EM.adjust (EM.insert (blid b) perNew) (bfid b) modifyServer $ \ser -> ser {sperFid = fper $ sperFid ser} execSendPer (bfid b) (blid b) emptyPer inPer perNew pointsModified <- action perList if not (nullPer inPer) || pointsModified then do execSfx -- Perception is reverted. This is necessary to ensure save and restore -- doesn't change game state. unless (nullPer inPer) $ do modifyServer $ \ser -> ser {sperFid = sperFidOld} execSendPer (bfid b) (blid b) inPer emptyPer perOld else execSfxAtomic $ SfxMsgFid (bfid b) $ SfxVoidDetection d return UseUp -- even if nothing spotted, in itself it's still useful data -- ** SendFlying -- | Send the target actor flying like a projectile. If the actors are adjacent, -- the vector is directed outwards, if no, inwards, if it's the same actor, -- boldpos is used, if it can't, a random outward vector of length 10 -- is picked. effectSendFlying :: MonadServerAtomic m => m () -> IK.ThrowMod -> ActorId -> ActorId -> Container -> Maybe Bool -> m UseResult effectSendFlying execSfx IK.ThrowMod{..} source target container modePush = do v <- sendFlyingVector source target container modePush sb <- getsState $ getActorBody source tb <- getsState $ getActorBody target let eps = 0 fpos = bpos tb `shift` v isEmbed = case container of CEmbed{} -> True _ -> False if bhp tb <= 0 -- avoid dragging around corpses || bproj tb && isEmbed then -- flying projectiles can't slip on the floor return UseDud -- the impact never manifested else if actorWaits tb && source /= target && isNothing (btrajectory tb) then do execSfxAtomic $ SfxMsgFid (bfid sb) $ SfxBracedImmune target when (source /= target) $ execSfxAtomic $ SfxMsgFid (bfid tb) $ SfxBracedImmune target return UseUp -- waste it to prevent repeated throwing at immobile actors else do case bresenhamsLineAlgorithm eps (bpos tb) fpos of Nothing -> error $ "" `showFailure` (fpos, tb) Just [] -> error $ "projecting from the edge of level" `showFailure` (fpos, tb) Just (pos : rest) -> do weightAssocs <- getsState $ fullAssocs target [CEqp, COrgan] let weight = sum $ map (IK.iweight . itemKind . snd) weightAssocs path = bpos tb : pos : rest (trajectory, (speed, _)) = -- Note that the @ThrowMod@ aspect of the actor's trunk is ignored. computeTrajectory weight throwVelocity throwLinger path ts = Just (trajectory, speed) -- Old and new trajectories are not added; the old one is replaced. if btrajectory tb == ts then return UseId -- e.g., actor is too heavy; but a jerk is noticeable else do execSfx execUpdAtomic $ UpdTrajectory target (btrajectory tb) ts -- If propeller is a projectile, it pushes involuntarily, -- so its originator is to blame. -- However, we can't easily see whether a pushed non-projectile actor -- pushed another due to colliding or voluntarily, so we assign -- blame to him. originator <- if bproj sb then getsServer $ EM.findWithDefault source source . strajPushedBy else return source modifyServer $ \ser -> ser {strajPushedBy = EM.insert target originator $ strajPushedBy ser} -- In case of pre-existing pushing, don't touch the time -- so that the pending @advanceTimeTraj@ can do its job -- (it will, because non-empty trajectory is here set, unless, e.g., -- subsequent effects from the same item change the trajectory). when (isNothing $ btrajectory tb) $ do -- Set flying time to almost now, so that the push happens ASAP, -- because it's the first one, so almost no delay is needed. localTime <- getsState $ getLocalTime (blid tb) -- But add a slight overhead to avoid displace-slide loops -- of 3 actors in a line. However, add even more overhead -- to normal actor move, so that it doesn't manage to land -- a hit before it flies away safely. let overheadTime = timeShift localTime (Delta timeClip) doubleClip = timeDeltaScale (Delta timeClip) 2 modifyServer $ \ser -> ser { strajTime = updateActorTime (bfid tb) (blid tb) target overheadTime $ strajTime ser , sactorTime = ageActor (bfid tb) (blid tb) target doubleClip $ sactorTime ser } return UseUp sendFlyingVector :: MonadServerAtomic m => ActorId -> ActorId -> Container -> Maybe Bool -> m Vector sendFlyingVector source target container modePush = do sb <- getsState $ getActorBody source if source == target then do pos <- getsState $ posFromC container lid <- getsState $ lidFromC container let (start, end) = -- Without the level the pushing stair trap moved actor back upstairs. if bpos sb /= pos && blid sb == lid then (bpos sb, pos) else (fromMaybe (bpos sb) (boldpos sb), bpos sb) if start == end then rndToAction $ do z <- randomR (-10, 10) oneOf [Vector 10 z, Vector (-10) z, Vector z 10, Vector z (-10)] else do let pushV = vectorToFrom end start pullV = vectorToFrom start end return $! case modePush of Just True -> pushV Just False -> pullV Nothing -> pushV else do tb <- getsState $ getActorBody target let pushV = vectorToFrom (bpos tb) (bpos sb) pullV = vectorToFrom (bpos sb) (bpos tb) return $! case modePush of Just True -> pushV Just False -> pullV Nothing | adjacent (bpos sb) (bpos tb) -> pushV Nothing -> pullV -- ** ApplyPerfume effectApplyPerfume :: MonadServerAtomic m => m () -> ActorId -> m UseResult effectApplyPerfume execSfx target = do tb <- getsState $ getActorBody target Level{lsmell} <- getLevel $ blid tb unless (EM.null lsmell) $ do execSfx let f p fromSm = execUpdAtomic $ UpdAlterSmell (blid tb) p fromSm timeZero mapWithKeyM_ f lsmell return UseUp -- even if no smell before, the perfume is noticeable -- ** AtMostOneOf effectAtMostOneOf :: MonadServerAtomic m => (IK.Effect -> m UseResult) -> [IK.Effect] -> m UseResult effectAtMostOneOf recursiveCall l = do chosen <- rndToAction $ oneOf l recursiveCall chosen -- no @execSfx@, because the individual effect sents it -- ** OneOf effectOneOf :: MonadServerAtomic m => (IK.Effect -> m UseResult) -> [IK.Effect] -> m UseResult effectOneOf recursiveCall l = do shuffled <- rndToAction $ shuffle l let f eff result = do ur <- recursiveCall eff -- We stop at @UseId@ activation and in this ways avoid potentially -- many calls to fizzling effects that only spam a failure message -- and ID the item. if ur == UseDud then result else return ur foldr f (return UseDud) shuffled -- no @execSfx@, because the individual effect sents it -- ** AndEffect effectAndEffect :: forall m. MonadServerAtomic m => (IK.Effect -> m UseResult) -> ActorId -> IK.Effect -> IK.Effect -> m UseResult effectAndEffect recursiveCall source [email protected]{} eff2 = do -- So far, this is the only idiom used for crafting. If others appear, -- either formalize it by a specialized crafting effect constructor -- or add here and to effect printing code. sb <- getsState $ getActorBody source curChalSer <- getsServer $ scurChalSer . soptions fact <- getsState $ (EM.! bfid sb) . sfactionD if cgoods curChalSer && fhasUI (gkind fact) then do execSfxAtomic $ SfxMsgFid (bfid sb) SfxReadyGoods return UseId else effectAndEffectSem recursiveCall eff1 eff2 effectAndEffect recursiveCall _ eff1 eff2 = effectAndEffectSem recursiveCall eff1 eff2 effectAndEffectSem :: forall m. MonadServerAtomic m => (IK.Effect -> m UseResult) -> IK.Effect -> IK.Effect -> m UseResult effectAndEffectSem recursiveCall eff1 eff2 = do ur1 <- recursiveCall eff1 if ur1 == UseUp then recursiveCall eff2 else return ur1 -- No @execSfx@, because individual effects sent them. -- ** OrEffect effectOrEffect :: forall m. MonadServerAtomic m => (IK.Effect -> m UseResult) -> FactionId -> IK.Effect -> IK.Effect -> m UseResult effectOrEffect recursiveCall fid eff1 eff2 = do curChalSer <- getsServer $ scurChalSer . soptions fact <- getsState $ (EM.! fid) . sfactionD case eff1 of IK.AndEffect IK.ConsumeItems{} _ | cgoods curChalSer && fhasUI (gkind fact) -> do -- Stop forbidden crafting ASAP to avoid spam. execSfxAtomic $ SfxMsgFid fid SfxReadyGoods return UseId _ -> do ur1 <- recursiveCall eff1 if ur1 == UseUp then return UseUp else recursiveCall eff2 -- no @execSfx@, because individual effects sent them -- ** SeqEffect effectSeqEffect :: forall m. MonadServerAtomic m => (IK.Effect -> m UseResult) -> [IK.Effect] -> m UseResult effectSeqEffect recursiveCall effs = do mapM_ (void <$> recursiveCall) effs return UseUp -- no @execSfx@, because individual effects sent them -- ** When effectWhen :: forall m. MonadServerAtomic m => (IK.Effect -> m UseResult) -> ActorId -> IK.Condition -> IK.Effect -> ActivationFlag -> m UseResult effectWhen recursiveCall source cond eff effActivation = do go <- conditionSem source cond effActivation if go then recursiveCall eff else return UseDud -- ** Unless effectUnless :: forall m. MonadServerAtomic m => (IK.Effect -> m UseResult) -> ActorId -> IK.Condition -> IK.Effect -> ActivationFlag -> m UseResult effectUnless recursiveCall source cond eff effActivation = do go <- conditionSem source cond effActivation if not go then recursiveCall eff else return UseDud -- ** IfThenElse effectIfThenElse :: forall m. MonadServerAtomic m => (IK.Effect -> m UseResult) -> ActorId -> IK.Condition -> IK.Effect -> IK.Effect -> ActivationFlag -> m UseResult effectIfThenElse recursiveCall source cond eff1 eff2 effActivation = do c <- conditionSem source cond effActivation if c then recursiveCall eff1 else recursiveCall eff2 -- ** VerbNoLonger effectVerbNoLonger :: MonadServerAtomic m => Bool -> m () -> ActorId -> m UseResult effectVerbNoLonger effUseAllCopies execSfx source = do b <- getsState $ getActorBody source when (effUseAllCopies -- @UseUp@ ensures that if all used, all destroyed && not (bproj b)) -- no spam when projectiles activate execSfx -- announce that all copies have run out (or whatever message) return UseUp -- help to destroy the copy, even if not all used up -- ** VerbMsg effectVerbMsg :: MonadServerAtomic m => m () -> ActorId -> m UseResult effectVerbMsg execSfx source = do b <- getsState $ getActorBody source unless (bproj b) execSfx -- don't spam when projectiles activate return UseUp -- announcing always successful and this helps -- to destroy the item -- ** VerbMsgFail effectVerbMsgFail :: MonadServerAtomic m => m () -> ActorId -> m UseResult effectVerbMsgFail execSfx source = do b <- getsState $ getActorBody source unless (bproj b) execSfx -- don't spam when projectiles activate return UseId -- not @UseDud@ so that @OneOf@ doesn't ignore it
LambdaHack/LambdaHack
engine-src/Game/LambdaHack/Server/HandleEffectM.hs
bsd-3-clause
107,894
4
31
30,782
25,343
12,522
12,821
-1
-1
{-# LANGUAGE FlexibleContexts #-} import Call import Audiovisual.Deck as Deck import Control.Monad.State.Strict import Control.Lens main = runCallDefault $ do music <- prepareMusic "assets/Monoidal Purity.wav" playMusic music stand type Music = Instance (StateT (Deck Stereo) IO) IO prepareMusic :: Call => FilePath -> IO Music prepareMusic path = do wav <- readWAVE path i <- new $ variable $ source .~ sampleSource wav $ Deck.empty linkAudio $ \dt n -> i .- playback dt n return i playMusic :: Music -> IO () playMusic m = m .- playing .= True
fumieval/rhythm-game-tutorial
src/music-only.hs
bsd-3-clause
564
0
11
108
199
98
101
18
1
---------------------------------------------------------------------------- -- | -- Module : Import1NoListImport2WithListChildrenWildcardsReexportModule.ImportCausesImportCycle -- Copyright : (c) Sergey Vinokurov 2018 -- License : BSD3-style (see LICENSE) -- Maintainer : [email protected] ---------------------------------------------------------------------------- module ImportCausesImportCycle where import CausesImportCycle
sergv/tags-server
test-data/0012resolve_reexport_import_cycles/import1NoListImport2WithListChildrenWildcardsReexportModule/ImportCausesImportCycle.hs
bsd-3-clause
449
0
3
48
14
12
2
2
0
{-# LANGUAGE OverloadedStrings, Safe #-} module Evalso.Cruncher.Language.Clojure (clojure) where import Evalso.Cruncher.Language (Language (..)) -- TODO: Improve Clojure runtime speeds. I've not managed <15s in the sandbox. -@duckinator clojure :: Language clojure = Language { _codeFilename = "program.clj" , _compileCommand = Nothing , _compileTimeout = Nothing , _runCommand = [ "java", "-client", "-XX:+TieredCompilation", "-XX:TieredStopAtLevel=1", "-Xbootclasspath/a:/usr/share/java/clojure.jar", "clojure.main", "program.clj" ] , _runTimeout = 20 , _codemirror = "clojure" , _rpm = "clojure" , _displayName = "Clojure" }
eval-so/cruncher
src/Evalso/Cruncher/Language/Clojure.hs
bsd-3-clause
681
0
7
127
111
74
37
20
1
{- Copyright © 2007-2012 Gracjan Polak Copyright © 2012-2016 Ömer Sinan Ağacan Copyright © 2017-2019 Albert Krewinkel Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -} {-| Module : Foreign.Lua Copyright : © 2007–2012 Gracjan Polak, 2012–2016 Ömer Sinan Ağacan, 2017-2019 Albert Krewinkel License : MIT Maintainer : Albert Krewinkel <[email protected]> Stability : beta Portability : non-portable (depends on GHC) Bindings, functions, and utilities enabling the integration of a Lua interpreter into a haskell project. Basic access to the Lua API is provided by '@Foreign.Lua.Core@'. -} module Foreign.Lua ( -- * Core module Foreign.Lua.Core -- * Receiving values from Lua stack (Lua → Haskell) , Peekable (..) , peekEither , peekList , peekKeyValuePairs , peekRead , peekAny -- * Pushing values to Lua stack (Haskell → Lua) , Pushable (..) , pushList , pushAny -- * Calling Functions , PreCFunction , HaskellFunction , ToHaskellFunction (..) , toHaskellFunction , callFunc , newCFunction , freeCFunction , pushHaskellFunction , registerHaskellFunction -- * Utility functions and types , run , runEither , getglobal' , setglobal' , raiseError , Optional (Optional, fromOptional) -- ** Retrieving values , popValue -- ** Modules , requirehs , preloadhs , create , addfield , addfunction ) where import Prelude hiding (compare, concat) import Foreign.Lua.Core import Foreign.Lua.FunctionCalling import Foreign.Lua.Module import Foreign.Lua.Types import Foreign.Lua.Userdata ( pushAny, peekAny ) import Foreign.Lua.Util
tarleb/hslua
src/Foreign/Lua.hs
mit
2,649
0
5
508
188
130
58
41
0
{-# LANGUAGE ScopedTypeVariables, CPP, BangPatterns, RankNTypes #-} #if __GLASGOW_HASKELL__ >= 701 {-# LANGUAGE Unsafe #-} #endif {-# OPTIONS_HADDOCK hide #-} -- | Copyright : (c) 2010 - 2011 Simon Meier -- License : BSD3-style (see LICENSE) -- -- Maintainer : Simon Meier <[email protected]> -- Stability : unstable, private -- Portability : GHC -- -- *Warning:* this module is internal. If you find that you need it then please -- contact the maintainers and explain what you are trying to do and discuss -- what you would need in the public API. It is important that you do this as -- the module may not be exposed at all in future releases. -- -- Core types and functions for the 'Builder' monoid and its generalization, -- the 'Put' monad. -- -- The design of the 'Builder' monoid is optimized such that -- -- 1. buffers of arbitrary size can be filled as efficiently as possible and -- -- 2. sequencing of 'Builder's is as cheap as possible. -- -- We achieve (1) by completely handing over control over writing to the buffer -- to the 'BuildStep' implementing the 'Builder'. This 'BuildStep' is just told -- the start and the end of the buffer (represented as a 'BufferRange'). Then, -- the 'BuildStep' can write to as big a prefix of this 'BufferRange' in any -- way it desires. If the 'BuildStep' is done, the 'BufferRange' is full, or a -- long sequence of bytes should be inserted directly, then the 'BuildStep' -- signals this to its caller using a 'BuildSignal'. -- -- We achieve (2) by requiring that every 'Builder' is implemented by a -- 'BuildStep' that takes a continuation 'BuildStep', which it calls with the -- updated 'BufferRange' after it is done. Therefore, only two pointers have -- to be passed in a function call to implement concatenation of 'Builder's. -- Moreover, many 'Builder's are completely inlined, which enables the compiler -- to sequence them without a function call and with no boxing at all. -- -- This design gives the implementation of a 'Builder' full access to the 'IO' -- monad. Therefore, utmost care has to be taken to not overwrite anything -- outside the given 'BufferRange's. Moreover, further care has to be taken to -- ensure that 'Builder's and 'Put's are referentially transparent. See the -- comments of the 'builder' and 'put' functions for further information. -- Note that there are /no safety belts/ at all, when implementing a 'Builder' -- using an 'IO' action: you are writing code that might enable the next -- buffer-overflow attack on a Haskell server! -- module Data.ByteString.Builder.Internal ( -- * Buffer management Buffer(..) , BufferRange(..) , newBuffer , bufferSize , byteStringFromBuffer , ChunkIOStream(..) , buildStepToCIOS , ciosUnitToLazyByteString , ciosToLazyByteString -- * Build signals and steps , BuildSignal , BuildStep , finalBuildStep , done , bufferFull , insertChunk , fillWithBuildStep -- * The Builder monoid , Builder , builder , runBuilder , runBuilderWith -- ** Primitive combinators , empty , append , flush , ensureFree -- , sizedChunksInsert , byteStringCopy , byteStringInsert , byteStringThreshold , lazyByteStringCopy , lazyByteStringInsert , lazyByteStringThreshold , shortByteString , maximalCopySize , byteString , lazyByteString -- ** Execution , toLazyByteStringWith , AllocationStrategy , safeStrategy , untrimmedStrategy , customStrategy , L.smallChunkSize , L.defaultChunkSize , L.chunkOverhead -- * The Put monad , Put , put , runPut -- ** Execution , putToLazyByteString , putToLazyByteStringWith , hPut -- ** Conversion to and from Builders , putBuilder , fromPut -- -- ** Lifting IO actions -- , putLiftIO ) where import Control.Arrow (second) import Control.Applicative (Applicative(..), (<$>)) -- import Control.Exception (return) import Data.Monoid import qualified Data.ByteString as S import qualified Data.ByteString.Internal as S import qualified Data.ByteString.Lazy.Internal as L import qualified Data.ByteString.Short.Internal as Sh #if __GLASGOW_HASKELL__ >= 611 import qualified GHC.IO.Buffer as IO (Buffer(..), newByteBuffer) import GHC.IO.Handle.Internals (wantWritableHandle, flushWriteBuffer) import GHC.IO.Handle.Types (Handle__, haByteBuffer, haBufferMode) import System.IO (hFlush, BufferMode(..)) import Data.IORef #else import qualified Data.ByteString.Lazy as L #endif import System.IO (Handle) #if MIN_VERSION_base(4,4,0) #if MIN_VERSION_base(4,7,0) import Foreign #else import Foreign hiding (unsafeForeignPtrToPtr) #endif import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr) import System.IO.Unsafe (unsafeDupablePerformIO) #else import Foreign import GHC.IO (unsafeDupablePerformIO) #endif ------------------------------------------------------------------------------ -- Buffers ------------------------------------------------------------------------------ -- | A range of bytes in a buffer represented by the pointer to the first byte -- of the range and the pointer to the first byte /after/ the range. data BufferRange = BufferRange {-# UNPACK #-} !(Ptr Word8) -- First byte of range {-# UNPACK #-} !(Ptr Word8) -- First byte /after/ range -- | A 'Buffer' together with the 'BufferRange' of free bytes. The filled -- space starts at offset 0 and ends at the first free byte. data Buffer = Buffer {-# UNPACK #-} !(ForeignPtr Word8) {-# UNPACK #-} !BufferRange -- | Combined size of the filled and free space in the buffer. {-# INLINE bufferSize #-} bufferSize :: Buffer -> Int bufferSize (Buffer fpbuf (BufferRange _ ope)) = ope `minusPtr` unsafeForeignPtrToPtr fpbuf -- | Allocate a new buffer of the given size. {-# INLINE newBuffer #-} newBuffer :: Int -> IO Buffer newBuffer size = do fpbuf <- S.mallocByteString size let pbuf = unsafeForeignPtrToPtr fpbuf return $! Buffer fpbuf (BufferRange pbuf (pbuf `plusPtr` size)) -- | Convert the filled part of a 'Buffer' to a strict 'S.ByteString'. {-# INLINE byteStringFromBuffer #-} byteStringFromBuffer :: Buffer -> S.ByteString byteStringFromBuffer (Buffer fpbuf (BufferRange op _)) = S.PS fpbuf 0 (op `minusPtr` unsafeForeignPtrToPtr fpbuf) --- | Prepend the filled part of a 'Buffer' to a lazy 'L.ByteString' --- trimming it if necessary. {-# INLINE trimmedChunkFromBuffer #-} trimmedChunkFromBuffer :: AllocationStrategy -> Buffer -> L.ByteString -> L.ByteString trimmedChunkFromBuffer (AllocationStrategy _ _ trim) buf k | S.null bs = k | trim (S.length bs) (bufferSize buf) = L.Chunk (S.copy bs) k | otherwise = L.Chunk bs k where bs = byteStringFromBuffer buf ------------------------------------------------------------------------------ -- Chunked IO Stream ------------------------------------------------------------------------------ -- | A stream of chunks that are constructed in the 'IO' monad. -- -- This datatype serves as the common interface for the buffer-by-buffer -- execution of a 'BuildStep' by 'buildStepToCIOS'. Typical users of this -- interface are 'ciosToLazyByteString' or iteratee-style libraries like -- @enumerator@. data ChunkIOStream a = Finished Buffer a -- ^ The partially filled last buffer together with the result. | Yield1 S.ByteString (IO (ChunkIOStream a)) -- ^ Yield a /non-empty/ strict 'S.ByteString'. -- | A smart constructor for yielding one chunk that ignores the chunk if -- it is empty. {-# INLINE yield1 #-} yield1 :: S.ByteString -> IO (ChunkIOStream a) -> IO (ChunkIOStream a) yield1 bs cios | S.null bs = cios | otherwise = return $ Yield1 bs cios -- | Convert a @'ChunkIOStream' ()@ to a lazy 'L.ByteString' using -- 'unsafeDupablePerformIO'. {-# INLINE ciosUnitToLazyByteString #-} ciosUnitToLazyByteString :: AllocationStrategy -> L.ByteString -> ChunkIOStream () -> L.ByteString ciosUnitToLazyByteString strategy k = go where go (Finished buf _) = trimmedChunkFromBuffer strategy buf k go (Yield1 bs io) = L.Chunk bs $ unsafeDupablePerformIO (go <$> io) -- | Convert a 'ChunkIOStream' to a lazy tuple of the result and the written -- 'L.ByteString' using 'unsafeDupablePerformIO'. {-# INLINE ciosToLazyByteString #-} ciosToLazyByteString :: AllocationStrategy -> (a -> (b, L.ByteString)) -> ChunkIOStream a -> (b, L.ByteString) ciosToLazyByteString strategy k = go where go (Finished buf x) = second (trimmedChunkFromBuffer strategy buf) $ k x go (Yield1 bs io) = second (L.Chunk bs) $ unsafeDupablePerformIO (go <$> io) ------------------------------------------------------------------------------ -- Build signals ------------------------------------------------------------------------------ -- | 'BuildStep's may be called *multiple times* and they must not rise an -- async. exception. type BuildStep a = BufferRange -> IO (BuildSignal a) -- | 'BuildSignal's abstract signals to the caller of a 'BuildStep'. There are -- three signals: 'done', 'bufferFull', or 'insertChunks signals data BuildSignal a = Done {-# UNPACK #-} !(Ptr Word8) a | BufferFull {-# UNPACK #-} !Int {-# UNPACK #-} !(Ptr Word8) (BuildStep a) | InsertChunk {-# UNPACK #-} !(Ptr Word8) S.ByteString (BuildStep a) -- | Signal that the current 'BuildStep' is done and has computed a value. {-# INLINE done #-} done :: Ptr Word8 -- ^ Next free byte in current 'BufferRange' -> a -- ^ Computed value -> BuildSignal a done = Done -- | Signal that the current buffer is full. {-# INLINE bufferFull #-} bufferFull :: Int -- ^ Minimal size of next 'BufferRange'. -> Ptr Word8 -- ^ Next free byte in current 'BufferRange'. -> BuildStep a -- ^ 'BuildStep' to run on the next 'BufferRange'. This 'BuildStep' -- may assume that it is called with a 'BufferRange' of at least the -- required minimal size; i.e., the caller of this 'BuildStep' must -- guarantee this. -> BuildSignal a bufferFull = BufferFull -- | Signal that a 'S.ByteString' chunk should be inserted directly. {-# INLINE insertChunk #-} insertChunk :: Ptr Word8 -- ^ Next free byte in current 'BufferRange' -> S.ByteString -- ^ Chunk to insert. -> BuildStep a -- ^ 'BuildStep' to run on next 'BufferRange' -> BuildSignal a insertChunk op bs = InsertChunk op bs -- | Fill a 'BufferRange' using a 'BuildStep'. {-# INLINE fillWithBuildStep #-} fillWithBuildStep :: BuildStep a -- ^ Build step to use for filling the 'BufferRange'. -> (Ptr Word8 -> a -> IO b) -- ^ Handling the 'done' signal -> (Ptr Word8 -> Int -> BuildStep a -> IO b) -- ^ Handling the 'bufferFull' signal -> (Ptr Word8 -> S.ByteString -> BuildStep a -> IO b) -- ^ Handling the 'insertChunk' signal -> BufferRange -- ^ Buffer range to fill. -> IO b -- ^ Value computed while filling this 'BufferRange'. fillWithBuildStep step fDone fFull fChunk !br = do signal <- step br case signal of Done op x -> fDone op x BufferFull minSize op nextStep -> fFull op minSize nextStep InsertChunk op bs nextStep -> fChunk op bs nextStep ------------------------------------------------------------------------------ -- The 'Builder' monoid ------------------------------------------------------------------------------ -- | 'Builder's denote sequences of bytes. -- They are 'Monoid's where -- 'mempty' is the zero-length sequence and -- 'mappend' is concatenation, which runs in /O(1)/. newtype Builder = Builder (forall r. BuildStep r -> BuildStep r) -- | Construct a 'Builder'. In contrast to 'BuildStep's, 'Builder's are -- referentially transparent. {-# INLINE builder #-} builder :: (forall r. BuildStep r -> BuildStep r) -- ^ A function that fills a 'BufferRange', calls the continuation with -- the updated 'BufferRange' once its done, and signals its caller how -- to proceed using 'done', 'bufferFull', or 'insertChunk'. -- -- This function must be referentially transparent; i.e., calling it -- multiple times with equally sized 'BufferRange's must result in the -- same sequence of bytes being written. If you need mutable state, -- then you must allocate it anew upon each call of this function. -- Moroever, this function must call the continuation once its done. -- Otherwise, concatenation of 'Builder's does not work. Finally, this -- function must write to all bytes that it claims it has written. -- Otherwise, the resulting 'Builder' is not guaranteed to be -- referentially transparent and sensitive data might leak. -> Builder builder = Builder -- | The final build step that returns the 'done' signal. finalBuildStep :: BuildStep () finalBuildStep !(BufferRange op _) = return $ Done op () -- | Run a 'Builder' with the 'finalBuildStep'. {-# INLINE runBuilder #-} runBuilder :: Builder -- ^ 'Builder' to run -> BuildStep () -- ^ 'BuildStep' that writes the byte stream of this -- 'Builder' and signals 'done' upon completion. runBuilder b = runBuilderWith b finalBuildStep -- | Run a 'Builder'. {-# INLINE runBuilderWith #-} runBuilderWith :: Builder -- ^ 'Builder' to run -> BuildStep a -- ^ Continuation 'BuildStep' -> BuildStep a runBuilderWith (Builder b) = b -- | The 'Builder' denoting a zero-length sequence of bytes. This function is -- only exported for use in rewriting rules. Use 'mempty' otherwise. {-# INLINE[1] empty #-} empty :: Builder empty = Builder id -- | Concatenate two 'Builder's. This function is only exported for use in rewriting -- rules. Use 'mappend' otherwise. {-# INLINE[1] append #-} append :: Builder -> Builder -> Builder append (Builder b1) (Builder b2) = Builder $ b1 . b2 instance Monoid Builder where {-# INLINE mempty #-} mempty = empty {-# INLINE mappend #-} mappend = append {-# INLINE mconcat #-} mconcat = foldr mappend mempty -- | Flush the current buffer. This introduces a chunk boundary. {-# INLINE flush #-} flush :: Builder flush = builder step where step k !(BufferRange op _) = return $ insertChunk op S.empty k ------------------------------------------------------------------------------ -- Put ------------------------------------------------------------------------------ -- | A 'Put' action denotes a computation of a value that writes a stream of -- bytes as a side-effect. 'Put's are strict in their side-effect; i.e., the -- stream of bytes will always be written before the computed value is -- returned. -- -- 'Put's are a generalization of 'Builder's. The typical use case is the -- implementation of an encoding that might fail (e.g., an interface to the -- 'zlib' compression library or the conversion from Base64 encoded data to -- 8-bit data). For a 'Builder', the only way to handle and report such a -- failure is ignore it or call 'error'. In contrast, 'Put' actions are -- expressive enough to allow reportng and handling such a failure in a pure -- fashion. -- -- @'Put' ()@ actions are isomorphic to 'Builder's. The functions 'putBuilder' -- and 'fromPut' convert between these two types. Where possible, you should -- use 'Builder's, as sequencing them is slightly cheaper than sequencing -- 'Put's because they do not carry around a computed value. newtype Put a = Put { unPut :: forall r. (a -> BuildStep r) -> BuildStep r } -- | Construct a 'Put' action. In contrast to 'BuildStep's, 'Put's are -- referentially transparent in the sense that sequencing the same 'Put' -- multiple times yields every time the same value with the same side-effect. {-# INLINE put #-} put :: (forall r. (a -> BuildStep r) -> BuildStep r) -- ^ A function that fills a 'BufferRange', calls the continuation with -- the updated 'BufferRange' and its computed value once its done, and -- signals its caller how to proceed using 'done', 'bufferFull', or -- 'insertChunk' signals. -- -- This function must be referentially transparent; i.e., calling it -- multiple times with equally sized 'BufferRange's must result in the -- same sequence of bytes being written and the same value being -- computed. If you need mutable state, then you must allocate it anew -- upon each call of this function. Moroever, this function must call -- the continuation once its done. Otherwise, monadic sequencing of -- 'Put's does not work. Finally, this function must write to all bytes -- that it claims it has written. Otherwise, the resulting 'Put' is -- not guaranteed to be referentially transparent and sensitive data -- might leak. -> Put a put = Put -- | Run a 'Put'. {-# INLINE runPut #-} runPut :: Put a -- ^ Put to run -> BuildStep a -- ^ 'BuildStep' that first writes the byte stream of -- this 'Put' and then yields the computed value using -- the 'done' signal. runPut (Put p) = p $ \x (BufferRange op _) -> return $ Done op x instance Functor Put where fmap f p = Put $ \k -> unPut p (\x -> k (f x)) {-# INLINE fmap #-} -- | Synonym for '<*' from 'Applicative'; used in rewriting rules. {-# INLINE[1] ap_l #-} ap_l :: Put a -> Put b -> Put a ap_l (Put a) (Put b) = Put $ \k -> a (\a' -> b (\_ -> k a')) -- | Synonym for '*>' from 'Applicative' and '>>' from 'Monad'; used in -- rewriting rules. {-# INLINE[1] ap_r #-} ap_r :: Put a -> Put b -> Put b ap_r (Put a) (Put b) = Put $ \k -> a (\_ -> b k) instance Applicative Put where {-# INLINE pure #-} pure x = Put $ \k -> k x {-# INLINE (<*>) #-} Put f <*> Put a = Put $ \k -> f (\f' -> a (\a' -> k (f' a'))) #if MIN_VERSION_base(4,2,0) {-# INLINE (<*) #-} (<*) = ap_l {-# INLINE (*>) #-} (*>) = ap_r #endif instance Monad Put where {-# INLINE return #-} return x = Put $ \k -> k x {-# INLINE (>>=) #-} Put m >>= f = Put $ \k -> m (\m' -> unPut (f m') k) {-# INLINE (>>) #-} (>>) = ap_r -- Conversion between Put and Builder ------------------------------------- -- | Run a 'Builder' as a side-effect of a @'Put' ()@ action. {-# INLINE[1] putBuilder #-} putBuilder :: Builder -> Put () putBuilder (Builder b) = Put $ \k -> b (k ()) -- | Convert a @'Put' ()@ action to a 'Builder'. {-# INLINE fromPut #-} fromPut :: Put () -> Builder fromPut (Put p) = Builder $ \k -> p (\_ -> k) -- We rewrite consecutive uses of 'putBuilder' such that the append of the -- involved 'Builder's is used. This can significantly improve performance, -- when the bound-checks of the concatenated builders are fused. -- ap_l rules {-# RULES "ap_l/putBuilder" forall b1 b2. ap_l (putBuilder b1) (putBuilder b2) = putBuilder (append b1 b2) "ap_l/putBuilder/assoc_r" forall b1 b2 (p :: Put a). ap_l (putBuilder b1) (ap_l (putBuilder b2) p) = ap_l (putBuilder (append b1 b2)) p "ap_l/putBuilder/assoc_l" forall (p :: Put a) b1 b2. ap_l (ap_l p (putBuilder b1)) (putBuilder b2) = ap_l p (putBuilder (append b1 b2)) #-} -- ap_r rules {-# RULES "ap_r/putBuilder" forall b1 b2. ap_r (putBuilder b1) (putBuilder b2) = putBuilder (append b1 b2) "ap_r/putBuilder/assoc_r" forall b1 b2 (p :: Put a). ap_r (putBuilder b1) (ap_r (putBuilder b2) p) = ap_r (putBuilder (append b1 b2)) p "ap_r/putBuilder/assoc_l" forall (p :: Put a) b1 b2. ap_r (ap_r p (putBuilder b1)) (putBuilder b2) = ap_r p (putBuilder (append b1 b2)) #-} -- combined ap_l/ap_r rules {-# RULES "ap_l/ap_r/putBuilder/assoc_r" forall b1 b2 (p :: Put a). ap_l (putBuilder b1) (ap_r (putBuilder b2) p) = ap_l (putBuilder (append b1 b2)) p "ap_r/ap_l/putBuilder/assoc_r" forall b1 b2 (p :: Put a). ap_r (putBuilder b1) (ap_l (putBuilder b2) p) = ap_l (putBuilder (append b1 b2)) p "ap_l/ap_r/putBuilder/assoc_l" forall (p :: Put a) b1 b2. ap_l (ap_r p (putBuilder b1)) (putBuilder b2) = ap_r p (putBuilder (append b1 b2)) "ap_r/ap_l/putBuilder/assoc_l" forall (p :: Put a) b1 b2. ap_r (ap_l p (putBuilder b1)) (putBuilder b2) = ap_r p (putBuilder (append b1 b2)) #-} -- Lifting IO actions --------------------- {- -- | Lift an 'IO' action to a 'Put' action. {-# INLINE putLiftIO #-} putLiftIO :: IO a -> Put a putLiftIO io = put $ \k br -> io >>= (`k` br) -} ------------------------------------------------------------------------------ -- Executing a Put directly on a buffered Handle ------------------------------------------------------------------------------ -- | Run a 'Put' action redirecting the produced output to a 'Handle'. -- -- The output is buffered using the 'Handle's associated buffer. If this -- buffer is too small to execute one step of the 'Put' action, then -- it is replaced with a large enough buffer. hPut :: forall a. Handle -> Put a -> IO a #if __GLASGOW_HASKELL__ >= 611 hPut h p = do fillHandle 1 (runPut p) where fillHandle :: Int -> BuildStep a -> IO a fillHandle !minFree step = do next <- wantWritableHandle "hPut" h fillHandle_ next where -- | We need to return an inner IO action that is executed outside -- the lock taken on the Handle for two reasons: -- -- 1. GHC.IO.Handle.Internals mentions in "Note [async]" that -- we should never do any side-effecting operations before -- an interuptible operation that may raise an async. exception -- as long as we are inside 'wantWritableHandle' and the like. -- We possibly run the interuptible 'flushWriteBuffer' right at -- the start of 'fillHandle', hence entering it a second time is -- not safe, as it could lead to a 'BuildStep' being run twice. -- -- FIXME (SM): Adapt this function or at least its documentation, -- as it is OK to run a 'BuildStep' twice. We dropped this -- requirement in favor of being able to use -- 'unsafeDupablePerformIO' and the speed improvement that it -- brings. -- -- 2. We use the 'S.hPut' function to also write to the handle. -- This function tries to take the same lock taken by -- 'wantWritableHandle'. Therefore, we cannot call 'S.hPut' -- inside 'wantWritableHandle'. -- fillHandle_ :: Handle__ -> IO (IO a) fillHandle_ h_ = do makeSpace =<< readIORef refBuf fillBuffer =<< readIORef refBuf where refBuf = haByteBuffer h_ freeSpace buf = IO.bufSize buf - IO.bufR buf makeSpace buf | IO.bufSize buf < minFree = do flushWriteBuffer h_ s <- IO.bufState <$> readIORef refBuf IO.newByteBuffer minFree s >>= writeIORef refBuf | freeSpace buf < minFree = flushWriteBuffer h_ | otherwise = #if __GLASGOW_HASKELL__ >= 613 return () #else -- required for ghc-6.12 flushWriteBuffer h_ #endif fillBuffer buf | freeSpace buf < minFree = error $ unlines [ "Data.ByteString.Builder.Internal.hPut: internal error." , " Not enough space after flush." , " required: " ++ show minFree , " free: " ++ show (freeSpace buf) ] | otherwise = do let !br = BufferRange op (pBuf `plusPtr` IO.bufSize buf) res <- fillWithBuildStep step doneH fullH insertChunkH br touchForeignPtr fpBuf return res where fpBuf = IO.bufRaw buf pBuf = unsafeForeignPtrToPtr fpBuf op = pBuf `plusPtr` IO.bufR buf {-# INLINE updateBufR #-} updateBufR op' = do let !off' = op' `minusPtr` pBuf !buf' = buf {IO.bufR = off'} writeIORef refBuf buf' doneH op' x = do updateBufR op' -- We must flush if this Handle is set to NoBuffering. -- If it is set to LineBuffering, be conservative and -- flush anyway (we didn't check for newlines in the data). -- Flushing must happen outside this 'wantWriteableHandle' -- due to the possible async. exception. case haBufferMode h_ of BlockBuffering _ -> return $ return x _line_or_no_buffering -> return $ hFlush h >> return x fullH op' minSize nextStep = do updateBufR op' return $ fillHandle minSize nextStep -- 'fillHandle' will flush the buffer (provided there is -- really less than 'minSize' space left) before executing -- the 'nextStep'. insertChunkH op' bs nextStep = do updateBufR op' return $ do S.hPut h bs fillHandle 1 nextStep #else hPut h p = go =<< buildStepToCIOS strategy (runPut p) where strategy = untrimmedStrategy L.smallChunkSize L.defaultChunkSize go (Finished buf x) = S.hPut h (byteStringFromBuffer buf) >> return x go (Yield1 bs io) = S.hPut h bs >> io >>= go #endif -- | Execute a 'Put' and return the computed result and the bytes -- written during the computation as a lazy 'L.ByteString'. -- -- This function is strict in the computed result and lazy in the writing of -- the bytes. For example, given -- -- @ --infinitePut = sequence_ (repeat (putBuilder (word8 1))) >> return 0 -- @ -- -- evaluating the expression -- -- @ --fst $ putToLazyByteString infinitePut -- @ -- -- does not terminate, while evaluating the expression -- -- @ --L.head $ snd $ putToLazyByteString infinitePut -- @ -- -- does terminate and yields the value @1 :: Word8@. -- -- An illustrative example for these strictness properties is the -- implementation of Base64 decoding (<http://en.wikipedia.org/wiki/Base64>). -- -- @ --type DecodingState = ... -- --decodeBase64 :: 'S.ByteString' -> DecodingState -> 'Put' (Maybe DecodingState) --decodeBase64 = ... -- @ -- -- The above function takes a strict 'S.ByteString' supposed to represent -- Base64 encoded data and the current decoding state. -- It writes the decoded bytes as the side-effect of the 'Put' and returns the -- new decoding state, if the decoding of all data in the 'S.ByteString' was -- successful. The checking if the strict 'S.ByteString' represents Base64 -- encoded data and the actual decoding are fused. This makes the common case, -- where all data represents Base64 encoded data, more efficient. It also -- implies that all data must be decoded before the final decoding -- state can be returned. 'Put's are intended for implementing such fused -- checking and decoding/encoding, which is reflected in their strictness -- properties. {-# NOINLINE putToLazyByteString #-} putToLazyByteString :: Put a -- ^ 'Put' to execute -> (a, L.ByteString) -- ^ Result and lazy 'L.ByteString' -- written as its side-effect putToLazyByteString = putToLazyByteStringWith (safeStrategy L.smallChunkSize L.defaultChunkSize) (\x -> (x, L.Empty)) -- | Execute a 'Put' with a buffer-allocation strategy and a continuation. For -- example, 'putToLazyByteString' is implemented as follows. -- -- @ --putToLazyByteString = 'putToLazyByteStringWith' -- ('safeStrategy' 'L.smallChunkSize' 'L.defaultChunkSize') (\x -> (x, L.empty)) -- @ -- {-# INLINE putToLazyByteStringWith #-} putToLazyByteStringWith :: AllocationStrategy -- ^ Buffer allocation strategy to use -> (a -> (b, L.ByteString)) -- ^ Continuation to use for computing the final result and the tail of -- its side-effect (the written bytes). -> Put a -- ^ 'Put' to execute -> (b, L.ByteString) -- ^ Resulting lazy 'L.ByteString' putToLazyByteStringWith strategy k p = ciosToLazyByteString strategy k $ unsafeDupablePerformIO $ buildStepToCIOS strategy (runPut p) ------------------------------------------------------------------------------ -- ByteString insertion / controlling chunk boundaries ------------------------------------------------------------------------------ -- Raw memory ------------- -- | Ensure that there are at least 'n' free bytes for the following 'Builder'. {-# INLINE ensureFree #-} ensureFree :: Int -> Builder ensureFree minFree = builder step where step k br@(BufferRange op ope) | ope `minusPtr` op < minFree = return $ bufferFull minFree op k | otherwise = k br -- | Copy the bytes from a 'BufferRange' into the output stream. wrappedBytesCopyStep :: BufferRange -- ^ Input 'BufferRange'. -> BuildStep a -> BuildStep a wrappedBytesCopyStep !(BufferRange ip0 ipe) k = go ip0 where go !ip !(BufferRange op ope) | inpRemaining <= outRemaining = do copyBytes op ip inpRemaining let !br' = BufferRange (op `plusPtr` inpRemaining) ope k br' | otherwise = do copyBytes op ip outRemaining let !ip' = ip `plusPtr` outRemaining return $ bufferFull 1 ope (go ip') where outRemaining = ope `minusPtr` op inpRemaining = ipe `minusPtr` ip -- Strict ByteStrings ------------------------------------------------------------------------------ -- | Construct a 'Builder' that copies the strict 'S.ByteString's, if it is -- smaller than the treshold, and inserts it directly otherwise. -- -- For example, @byteStringThreshold 1024@ copies strict 'S.ByteString's whose size -- is less or equal to 1kb, and inserts them directly otherwise. This implies -- that the average chunk-size of the generated lazy 'L.ByteString' may be as -- low as 513 bytes, as there could always be just a single byte between the -- directly inserted 1025 byte, strict 'S.ByteString's. -- {-# INLINE byteStringThreshold #-} byteStringThreshold :: Int -> S.ByteString -> Builder byteStringThreshold maxCopySize = \bs -> builder $ step bs where step !bs@(S.PS _ _ len) !k br@(BufferRange !op _) | len <= maxCopySize = byteStringCopyStep bs k br | otherwise = return $ insertChunk op bs k -- | Construct a 'Builder' that copies the strict 'S.ByteString'. -- -- Use this function to create 'Builder's from smallish (@<= 4kb@) -- 'S.ByteString's or if you need to guarantee that the 'S.ByteString' is not -- shared with the chunks generated by the 'Builder'. -- {-# INLINE byteStringCopy #-} byteStringCopy :: S.ByteString -> Builder byteStringCopy = \bs -> builder $ byteStringCopyStep bs {-# INLINE byteStringCopyStep #-} byteStringCopyStep :: S.ByteString -> BuildStep a -> BuildStep a byteStringCopyStep (S.PS ifp ioff isize) !k0 br0@(BufferRange op ope) -- Ensure that the common case is not recursive and therefore yields -- better code. | op' <= ope = do copyBytes op ip isize touchForeignPtr ifp k0 (BufferRange op' ope) | otherwise = do wrappedBytesCopyStep (BufferRange ip ipe) k br0 where op' = op `plusPtr` isize ip = unsafeForeignPtrToPtr ifp `plusPtr` ioff ipe = ip `plusPtr` isize k br = do touchForeignPtr ifp -- input consumed: OK to release here k0 br -- | Construct a 'Builder' that always inserts the strict 'S.ByteString' -- directly as a chunk. -- -- This implies flushing the output buffer, even if it contains just -- a single byte. You should therefore use 'byteStringInsert' only for large -- (@> 8kb@) 'S.ByteString's. Otherwise, the generated chunks are too -- fragmented to be processed efficiently afterwards. -- {-# INLINE byteStringInsert #-} byteStringInsert :: S.ByteString -> Builder byteStringInsert = \bs -> builder $ \k (BufferRange op _) -> return $ insertChunk op bs k -- Short bytestrings ------------------------------------------------------------------------------ -- | Construct a 'Builder' that copies the 'SH.ShortByteString'. -- {-# INLINE shortByteString #-} shortByteString :: Sh.ShortByteString -> Builder shortByteString = \sbs -> builder $ shortByteStringCopyStep sbs -- | Copy the bytes from a 'SH.ShortByteString' into the output stream. {-# INLINE shortByteStringCopyStep #-} shortByteStringCopyStep :: Sh.ShortByteString -- ^ Input 'SH.ShortByteString'. -> BuildStep a -> BuildStep a shortByteStringCopyStep !sbs k = go 0 (Sh.length sbs) where go !ip !ipe !(BufferRange op ope) | inpRemaining <= outRemaining = do Sh.copyToPtr sbs ip op inpRemaining let !br' = BufferRange (op `plusPtr` inpRemaining) ope k br' | otherwise = do Sh.copyToPtr sbs ip op outRemaining let !ip' = ip + outRemaining return $ bufferFull 1 ope (go ip' ipe) where outRemaining = ope `minusPtr` op inpRemaining = ipe - ip -- Lazy bytestrings ------------------------------------------------------------------------------ -- | Construct a 'Builder' that uses the thresholding strategy of 'byteStringThreshold' -- for each chunk of the lazy 'L.ByteString'. -- {-# INLINE lazyByteStringThreshold #-} lazyByteStringThreshold :: Int -> L.ByteString -> Builder lazyByteStringThreshold maxCopySize = L.foldrChunks (\bs b -> byteStringThreshold maxCopySize bs `mappend` b) mempty -- TODO: We could do better here. Currently, Large, Small, Large, leads to -- an unnecessary copy of the 'Small' chunk. -- | Construct a 'Builder' that copies the lazy 'L.ByteString'. -- {-# INLINE lazyByteStringCopy #-} lazyByteStringCopy :: L.ByteString -> Builder lazyByteStringCopy = L.foldrChunks (\bs b -> byteStringCopy bs `mappend` b) mempty -- | Construct a 'Builder' that inserts all chunks of the lazy 'L.ByteString' -- directly. -- {-# INLINE lazyByteStringInsert #-} lazyByteStringInsert :: L.ByteString -> Builder lazyByteStringInsert = L.foldrChunks (\bs b -> byteStringInsert bs `mappend` b) mempty -- | Create a 'Builder' denoting the same sequence of bytes as a strict -- 'S.ByteString'. -- The 'Builder' inserts large 'S.ByteString's directly, but copies small ones -- to ensure that the generated chunks are large on average. -- {-# INLINE byteString #-} byteString :: S.ByteString -> Builder byteString = byteStringThreshold maximalCopySize -- | Create a 'Builder' denoting the same sequence of bytes as a lazy -- 'S.ByteString'. -- The 'Builder' inserts large chunks of the lazy 'L.ByteString' directly, -- but copies small ones to ensure that the generated chunks are large on -- average. -- {-# INLINE lazyByteString #-} lazyByteString :: L.ByteString -> Builder lazyByteString = lazyByteStringThreshold maximalCopySize -- FIXME: also insert the small chunk for [large,small,large] directly. -- Perhaps it makes even sense to concatenate the small chunks in -- [large,small,small,small,large] and insert them directly afterwards to avoid -- unnecessary buffer spilling. Hmm, but that uncontrollably increases latency -- => no good! -- | The maximal size of a 'S.ByteString' that is copied. -- @2 * 'L.smallChunkSize'@ to guarantee that on average a chunk is of -- 'L.smallChunkSize'. maximalCopySize :: Int maximalCopySize = 2 * L.smallChunkSize ------------------------------------------------------------------------------ -- Builder execution ------------------------------------------------------------------------------ -- | A buffer allocation strategy for executing 'Builder's. -- The strategy -- -- > 'AllocationStrategy' firstBufSize bufSize trim -- -- states that the first buffer is of size @firstBufSize@, all following buffers -- are of size @bufSize@, and a buffer of size @n@ filled with @k@ bytes should -- be trimmed iff @trim k n@ is 'True'. data AllocationStrategy = AllocationStrategy (Maybe (Buffer, Int) -> IO Buffer) {-# UNPACK #-} !Int (Int -> Int -> Bool) -- | Create a custom allocation strategy. See the code for 'safeStrategy' and -- 'untrimmedStrategy' for examples. {-# INLINE customStrategy #-} customStrategy :: (Maybe (Buffer, Int) -> IO Buffer) -- ^ Buffer allocation function. If 'Nothing' is given, then a new first -- buffer should be allocated. If @'Just' (oldBuf, minSize)@ is given, -- then a buffer with minimal size 'minSize' must be returned. The -- strategy may reuse the 'oldBuffer', if it can guarantee that this -- referentially transparent and 'oldBuffer' is large enough. -> Int -- ^ Default buffer size. -> (Int -> Int -> Bool) -- ^ A predicate @trim used allocated@ returning 'True', if the buffer -- should be trimmed before it is returned. -> AllocationStrategy customStrategy = AllocationStrategy -- | Sanitize a buffer size; i.e., make it at least the size of an 'Int'. {-# INLINE sanitize #-} sanitize :: Int -> Int sanitize = max (sizeOf (undefined :: Int)) -- | Use this strategy for generating lazy 'L.ByteString's whose chunks are -- discarded right after they are generated. For example, if you just generate -- them to write them to a network socket. {-# INLINE untrimmedStrategy #-} untrimmedStrategy :: Int -- ^ Size of the first buffer -> Int -- ^ Size of successive buffers -> AllocationStrategy -- ^ An allocation strategy that does not trim any of the -- filled buffers before converting it to a chunk untrimmedStrategy firstSize bufSize = AllocationStrategy nextBuffer (sanitize bufSize) (\_ _ -> False) where {-# INLINE nextBuffer #-} nextBuffer Nothing = newBuffer $ sanitize firstSize nextBuffer (Just (_, minSize)) = newBuffer minSize -- | Use this strategy for generating lazy 'L.ByteString's whose chunks are -- likely to survive one garbage collection. This strategy trims buffers -- that are filled less than half in order to avoid spilling too much memory. {-# INLINE safeStrategy #-} safeStrategy :: Int -- ^ Size of first buffer -> Int -- ^ Size of successive buffers -> AllocationStrategy -- ^ An allocation strategy that guarantees that at least half -- of the allocated memory is used for live data safeStrategy firstSize bufSize = AllocationStrategy nextBuffer (sanitize bufSize) trim where trim used size = 2 * used < size {-# INLINE nextBuffer #-} nextBuffer Nothing = newBuffer $ sanitize firstSize nextBuffer (Just (_, minSize)) = newBuffer minSize -- | /Heavy inlining./ Execute a 'Builder' with custom execution parameters. -- -- This function is inlined despite its heavy code-size to allow fusing with -- the allocation strategy. For example, the default 'Builder' execution -- function 'toLazyByteString' is defined as follows. -- -- @ -- {-\# NOINLINE toLazyByteString \#-} -- toLazyByteString = -- toLazyByteStringWith ('safeStrategy' 'L.smallChunkSize' 'L.defaultChunkSize') L.empty -- @ -- -- where @L.empty@ is the zero-length lazy 'L.ByteString'. -- -- In most cases, the parameters used by 'toLazyByteString' give good -- performance. A sub-performing case of 'toLazyByteString' is executing short -- (<128 bytes) 'Builder's. In this case, the allocation overhead for the first -- 4kb buffer and the trimming cost dominate the cost of executing the -- 'Builder'. You can avoid this problem using -- -- >toLazyByteStringWith (safeStrategy 128 smallChunkSize) L.empty -- -- This reduces the allocation and trimming overhead, as all generated -- 'L.ByteString's fit into the first buffer and there is no trimming -- required, if more than 64 bytes and less than 128 bytes are written. -- {-# INLINE toLazyByteStringWith #-} toLazyByteStringWith :: AllocationStrategy -- ^ Buffer allocation strategy to use -> L.ByteString -- ^ Lazy 'L.ByteString' to use as the tail of the generated lazy -- 'L.ByteString' -> Builder -- ^ 'Builder' to execute -> L.ByteString -- ^ Resulting lazy 'L.ByteString' toLazyByteStringWith strategy k b = ciosUnitToLazyByteString strategy k $ unsafeDupablePerformIO $ buildStepToCIOS strategy (runBuilder b) -- | Convert a 'BuildStep' to a 'ChunkIOStream' stream by executing it on -- 'Buffer's allocated according to the given 'AllocationStrategy'. {-# INLINE buildStepToCIOS #-} buildStepToCIOS :: AllocationStrategy -- ^ Buffer allocation strategy to use -> BuildStep a -- ^ 'BuildStep' to execute -> IO (ChunkIOStream a) buildStepToCIOS !(AllocationStrategy nextBuffer bufSize trim) = \step -> nextBuffer Nothing >>= fill step where fill !step !buf@(Buffer fpbuf br@(BufferRange _ pe)) = do res <- fillWithBuildStep step doneH fullH insertChunkH br touchForeignPtr fpbuf return res where pbuf = unsafeForeignPtrToPtr fpbuf doneH op' x = return $ Finished (Buffer fpbuf (BufferRange op' pe)) x fullH op' minSize nextStep = wrapChunk op' $ const $ nextBuffer (Just (buf, max minSize bufSize)) >>= fill nextStep insertChunkH op' bs nextStep = wrapChunk op' $ \isEmpty -> yield1 bs $ -- Checking for empty case avoids allocating 'n-1' empty -- buffers for 'n' insertChunkH right after each other. if isEmpty then fill nextStep buf else do buf' <- nextBuffer (Just (buf, bufSize)) fill nextStep buf' -- Wrap and yield a chunk, trimming it if necesary {-# INLINE wrapChunk #-} wrapChunk !op' mkCIOS | chunkSize == 0 = mkCIOS True | trim chunkSize size = do bs <- S.create chunkSize $ \pbuf' -> copyBytes pbuf' pbuf chunkSize -- FIXME: We could reuse the trimmed buffer here. return $ Yield1 bs (mkCIOS False) | otherwise = return $ Yield1 (S.PS fpbuf 0 chunkSize) (mkCIOS False) where chunkSize = op' `minusPtr` pbuf size = pe `minusPtr` pbuf
jwiegley/ghc-release
libraries/bytestring/Data/ByteString/Builder/Internal.hs
gpl-3.0
43,305
0
21
10,587
5,476
3,030
2,446
441
3
{-# OPTIONS_GHC -fno-warn-orphans #-} -- | -- Copyright : (c) 2011 Simon Meier -- License : GPL v3 (see LICENSE) -- -- Maintainer : Simon Meier <[email protected]> -- -- 'Document' class allowing to have different interpretations of the -- HughesPJ pretty-printing combinators. module Text.PrettyPrint.Class ( Doc , Document(..) , isEmpty , render , renderStyle , defaultStyle , P.Style(..) , P.Mode(..) , ($--$) , emptyDoc , (<>) , semi , colon , comma , space , equals , lparen , rparen , lbrack , rbrack , lbrace , rbrace , int , integer , float , double , rational , quotes , doubleQuotes , parens , brackets , braces , hang , punctuate -- * Additional combinators , nestBetween , nestShort , nestShort' , nestShortNonEmpty , nestShortNonEmpty' , fixedWidthText , symbol , numbered , numbered' ) where import Control.DeepSeq (NFData(..)) import Data.List (intersperse) import Extension.Data.Monoid ((<>)) import Extension.Prelude (flushRight) import qualified Text.PrettyPrint.HughesPJ as P infixr 6 <-> infixl 5 $$, $-$, $--$ newtype Doc = Doc { getPrettyLibraryDoc :: P.Doc } isEmpty :: Doc -> Bool isEmpty (Doc d) = P.isEmpty d render :: Doc -> String render (Doc d) = P.render d renderStyle :: P.Style -> Doc -> String renderStyle s (Doc d) = P.renderStyle s d -- emptyDoc = P.empty -- (<>) = (P.<>) class (Monoid d, NFData d) => Document d where char :: Char -> d text :: String -> d zeroWidthText :: String -> d (<->) :: d -> d -> d hcat :: [d] -> d hsep :: [d] -> d ($$) :: d -> d -> d ($-$) :: d -> d -> d vcat :: [d] -> d sep :: [d] -> d cat :: [d] -> d fsep :: [d] -> d fcat :: [d] -> d nest :: Int -> d -> d caseEmptyDoc :: d -> d -> d -> d -- | The default 'P.Style'. defaultStyle :: P.Style defaultStyle = P.style -- | The empty document. emptyDoc :: Document d => d emptyDoc = mempty -- | Vertical concatentation of two documents with an empty line in between. ($--$) :: Document d => d -> d -> d d1 $--$ d2 = caseEmptyDoc d2 (caseEmptyDoc d1 (d1 $-$ text "" $-$ d2) d2) d1 semi, colon, comma, space, equals, lparen, rparen, lbrack, rbrack, lbrace, rbrace :: Document d => d semi = char ';' colon = char ':' comma = char ',' space = char ' ' equals = char '=' lparen = char '(' rparen = char ')' lbrack = char '[' rbrack = char ']' lbrace = char '{' rbrace = char '}' int :: Document d => Int -> d int n = text (show n) integer :: Document d => Integer -> d integer n = text (show n) float :: Document d => Float -> d float n = text (show n) double :: Document d => Double -> d double n = text (show n) rational :: Document d => Rational -> d rational n = text (show n) quotes, doubleQuotes, parens, brackets, braces :: Document d => d -> d quotes p = char '\'' <> p <> char '\'' doubleQuotes p = char '"' <> p <> char '"' parens p = char '(' <> p <> char ')' brackets p = char '[' <> p <> char ']' braces p = char '{' <> p <> char '}' hang :: Document d => d -> Int -> d -> d hang d1 n d2 = sep [d1, nest n d2] punctuate :: Document d => d -> [d] -> [d] punctuate _ [] = [] punctuate p (d:ds) = go d ds where go d' [] = [d'] go d' (e:es) = (d' <> p) : go e es ------------------------------------------------------------------------------ -- The 'Document' instance for 'Text.PrettyPrint.Doc' ------------------------------------------------------------------------------ -- Must be removed for GHC 7.10, needed before instance NFData Doc where rnf = rnf . P.render . getPrettyLibraryDoc instance Document Doc where char = Doc . P.char text = Doc . P.text zeroWidthText = Doc . P.zeroWidthText (<->) (Doc d1) (Doc d2) = Doc $ (P.<+>) d1 d2 hcat = Doc . P.hcat . map getPrettyLibraryDoc hsep = Doc . P.hsep . map getPrettyLibraryDoc ($$) (Doc d1) (Doc d2) = Doc $ (P.$$) d1 d2 ($-$) (Doc d1) (Doc d2) = Doc $ (P.$+$) d1 d2 vcat = Doc . P.vcat . map getPrettyLibraryDoc sep = Doc . P.sep . map getPrettyLibraryDoc cat = Doc . P.cat . map getPrettyLibraryDoc fsep = Doc . P.fsep . map getPrettyLibraryDoc fcat = Doc . P.fcat . map getPrettyLibraryDoc nest i (Doc d) = Doc $ P.nest i d caseEmptyDoc yes no (Doc d) = if P.isEmpty d then yes else no instance Monoid Doc where mempty = Doc $ P.empty mappend (Doc d1) (Doc d2) = Doc $ (P.<>) d1 d2 ------------------------------------------------------------------------------ -- Additional combinators ------------------------------------------------------------------------------ -- | Nest a document surrounded by a leading and a finishing document breaking -- lead, body, and finish onto separate lines, if they don't fit on a single -- line. nestBetween :: Document d => Int -- ^ Indent of body -> d -- ^ Leading document -> d -- ^ Finishing document -> d -- ^ Body document -> d nestBetween n l r x = sep [l, nest n x, r] -- | Nest a document surrounded by a leading and a finishing document with an -- non-compulsory break between lead and body. nestShort :: Document d => Int -- ^ Indent of body -> d -- ^ Leading document -> d -- ^ Finishing document -> d -- ^ Body document -> d nestShort n lead finish body = sep [lead $$ nest n body, finish] -- | Nest document between two strings and indent body by @length lead + 1@. nestShort' :: Document d => String -> String -> d -> d nestShort' lead finish = nestShort (length lead + 1) (text lead) (text finish) -- | Like 'nestShort' but doesn't print the lead and finish, if the document is -- empty. nestShortNonEmpty :: Document d => Int -> d -> d -> d -> d nestShortNonEmpty n lead finish body = caseEmptyDoc emptyDoc (nestShort n lead finish body) body -- | Like 'nestShort'' but doesn't print the lead and finish, if the document is -- empty. nestShortNonEmpty' :: Document d => String -> String -> d -> d nestShortNonEmpty' lead finish = nestShortNonEmpty (length lead + 1) (text lead) (text finish) -- | Output text with a fixed width: if it is smaller then nothing happens, -- otherwise care is taken to make the text appear having the given width. fixedWidthText :: Document d => Int -> String -> d fixedWidthText n cs | length cs <= n = text cs | otherwise = text as <> zeroWidthText bs where (as,bs) = splitAt n cs -- | Print string as symbol having width 1. symbol :: Document d => String -> d symbol = fixedWidthText 1 -- | Number a list of documents that are vertically separated by the given -- separator. numbered :: Document d => d -> [d] -> d numbered _ [] = emptyDoc numbered vsep ds = foldr1 ($-$) $ intersperse vsep $ map pp $ zip [(1::Int)..] ds where n = length ds nWidth = length (show n) pp (i, d) = text (flushRight nWidth (show i)) <> d -- | Number a list of documents with numbers terminated by "." and vertically -- separate using an empty line. numbered' :: Document d => [d] -> d numbered' = numbered (text "") . map (text ". " <>)
kelnage/tamarin-prover
lib/utils/src/Text/PrettyPrint/Class.hs
gpl-3.0
7,404
0
12
1,997
2,287
1,238
1,049
178
2
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.ElasticBeanstalk.DeleteApplication -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Deletes the specified application along with all associated versions and -- configurations. The application versions will not be deleted from your -- Amazon S3 bucket. -- -- You cannot delete an application that has a running environment. -- -- /See:/ <http://docs.aws.amazon.com/elasticbeanstalk/latest/api/API_DeleteApplication.html AWS API Reference> for DeleteApplication. module Network.AWS.ElasticBeanstalk.DeleteApplication ( -- * Creating a Request deleteApplication , DeleteApplication -- * Request Lenses , daTerminateEnvByForce , daApplicationName -- * Destructuring the Response , deleteApplicationResponse , DeleteApplicationResponse ) where import Network.AWS.ElasticBeanstalk.Types import Network.AWS.ElasticBeanstalk.Types.Product import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | This documentation target is not reported in the API reference. -- -- /See:/ 'deleteApplication' smart constructor. data DeleteApplication = DeleteApplication' { _daTerminateEnvByForce :: !(Maybe Bool) , _daApplicationName :: !Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'DeleteApplication' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'daTerminateEnvByForce' -- -- * 'daApplicationName' deleteApplication :: Text -- ^ 'daApplicationName' -> DeleteApplication deleteApplication pApplicationName_ = DeleteApplication' { _daTerminateEnvByForce = Nothing , _daApplicationName = pApplicationName_ } -- | When set to true, running environments will be terminated before -- deleting the application. daTerminateEnvByForce :: Lens' DeleteApplication (Maybe Bool) daTerminateEnvByForce = lens _daTerminateEnvByForce (\ s a -> s{_daTerminateEnvByForce = a}); -- | The name of the application to delete. daApplicationName :: Lens' DeleteApplication Text daApplicationName = lens _daApplicationName (\ s a -> s{_daApplicationName = a}); instance AWSRequest DeleteApplication where type Rs DeleteApplication = DeleteApplicationResponse request = postQuery elasticBeanstalk response = receiveNull DeleteApplicationResponse' instance ToHeaders DeleteApplication where toHeaders = const mempty instance ToPath DeleteApplication where toPath = const "/" instance ToQuery DeleteApplication where toQuery DeleteApplication'{..} = mconcat ["Action" =: ("DeleteApplication" :: ByteString), "Version" =: ("2010-12-01" :: ByteString), "TerminateEnvByForce" =: _daTerminateEnvByForce, "ApplicationName" =: _daApplicationName] -- | /See:/ 'deleteApplicationResponse' smart constructor. data DeleteApplicationResponse = DeleteApplicationResponse' deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'DeleteApplicationResponse' with the minimum fields required to make a request. -- deleteApplicationResponse :: DeleteApplicationResponse deleteApplicationResponse = DeleteApplicationResponse'
fmapfmapfmap/amazonka
amazonka-elasticbeanstalk/gen/Network/AWS/ElasticBeanstalk/DeleteApplication.hs
mpl-2.0
3,905
0
11
721
450
274
176
61
1
{-# LANGUAGE OverloadedStrings #-} module NLP.LTAG.Earlye5.Test4 where import Control.Applicative ((<$>), (<*>)) import Control.Monad (void) import qualified Control.Monad.State.Strict as E import qualified Data.IntMap as I import qualified Data.Set as S import Data.List (sortBy) import Data.Ord (comparing) import qualified Pipes as P import qualified Pipes.Prelude as P import qualified NLP.FeatureStructure.Tree as FS import qualified NLP.FeatureStructure.AVM as A import NLP.LTAG.Tree2 import NLP.LTAG.Rule import NLP.LTAG.Earley5 --------------------------------------------------------------------- -- AVM utilities --------------------------------------------------------------------- type FN = FS.FN String String String -- | An empty feature tree. empty :: FN empty = A.avm A.empty -- | Red attribute value. red :: FN red = A.avm $ A.feat "col" "red" -- | Black attribute value. black :: FN black = A.avm $ A.feat "col" "black" -- | Variable 'x' color. colX :: FN colX = A.avm $ A.feat "col" "?x" -- colX = A.avm $ A.feat "col" $ A.empty --------------------------------------------------------------------- -- Grammar --------------------------------------------------------------------- type Tr = Tree String String String String String type AuxTr = AuxTree String String String String String alpha :: Tr alpha = INode "S" colX empty [ LNode "p" , INode "Z" empty empty [ INode "X" empty colX [ LNode "e" ] ] , LNode "q" ] beta1 :: AuxTr beta1 = AuxTree (INode "X" red red [ LNode "a" , INode "X" colX empty [ INode "Q" empty colX [ INode "X" black black [] , LNode "a" ] ] ] ) [1,0,0] beta2 :: AuxTr beta2 = AuxTree (INode "X" red red [ LNode "b" , INode "X" empty empty [ INode "X" black black [] , LNode "b" ] ] ) [1,0] testGram :: [String] -> IO () testGram sent = do rs <- flip E.evalStateT 0 $ P.toListM $ do mapM_ (treeRules True) [alpha] mapM_ (auxRules True) [beta1, beta2] let gram = S.fromList $ map compile rs void $ earley gram sent
kawu/tag-vanilla
src/NLP/TAG/Vanilla/Earley5/Test4.hs
bsd-2-clause
2,183
0
14
527
614
345
269
56
1