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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE OverloadedStrings #-}
module Main ( main ) where
import Control.Error.Util (hush)
import Control.Monad (void, when)
import Control.Monad.State (StateT, liftIO, get, runStateT, modify)
import Data.Aeson (decode)
import qualified Data.Char as Char
import qualified Data.Configurator as Conf
import Data.Maybe (mapMaybe)
import qualified Data.Text.Lazy as T
import qualified Data.Text.Lazy.Encoding as T
import qualified Data.Text.Lazy.IO as T
import qualified Database.SQLite.Simple as DB
import Database.SQLite.Simple (NamedParam((:=)))
import Paths_Dikunt
import Prelude hiding (Word, words)
import System.Environment (getArgs)
import System.IO (stdout, stdin, hSetBuffering, BufferMode(..))
import System.Random (randomRs, newStdGen)
import qualified Text.Parsec as P
import qualified Text.Parsec.Number as P
import qualified Types.BotTypes as BT
{- | The type replacements are stored under in the database. -}
data Replacement = Replacement Int T.Text T.Text deriving (Show)
instance DB.FromRow Replacement where
fromRow = Replacement <$> DB.field <*> DB.field <*> DB.field
instance DB.ToRow Replacement where
toRow (Replacement id_ word replacement) = DB.toRow (id_, word, replacement)
type BotNick = String
type Word = String
type Probability = Double
{- | Lines from stdin are parsed to this structure which represents a request to
- the plugin. -}
data Request
= HelpRequest BotNick
| AddReplacement BotNick Word String
| SetProbability Probability
| WordSequence [Word]
main :: IO ()
main = do
(botnick:_) <- getArgs
hSetBuffering stdout LineBuffering
hSetBuffering stdin LineBuffering
-- Load configuration.
configName <- getDataFileName "data/dikunt.config"
config <- Conf.load [ Conf.Required configName ]
replacerProb <- Conf.require config "wordreplacer-probability"
randoms <- randomRs (0.0, 1.0) <$> newStdGen
requests <- parseRequests botnick <$> T.hGetContents stdin
dbFile <- getDataFileName "data/WordReplacerData.db"
DB.withConnection dbFile (\c -> do
initDatabase c
handleRequests c replacerProb (zip randoms requests))
{- | Handle a list of requests by performing the action requested. -}
handleRequests :: DB.Connection
-- ^ Database connection.
-> Probability
-- ^ Initial probability of replacing.
-> [(Probability, Request)]
-- ^ Connections together with the probability of writing message.
-> IO ()
handleRequests conn initProb reqs =
void $ runStateT (mapM_ handleRequest reqs) initialState
where
initialState = (initProb, conn)
{- | State we run the wordreplacer in. The state contains a database connection
- and the current probability. Words are only replaced if a generated number is
- lower than the current probability. -}
type WordReplacerState a = StateT (Probability, DB.Connection) IO a
{- | Handle a single request. -}
handleRequest :: (Probability, Request)
-- ^ The request and the probability that the request should be served.
-> WordReplacerState ()
handleRequest (_, HelpRequest botnick) =
handleHelp botnick
handleRequest (_, AddReplacement botnick word withString) =
handleAdd botnick word withString
handleRequest (_, SetProbability newProb) =
handleSetProbability newProb
handleRequest (prob , WordSequence words) =
handleWordReplacement words prob
{- | Add a replacement to the database if the word is not the nickname of the
- bot. -}
handleAdd :: BotNick
-- ^ Nickname of bot.
-> Word
-- ^ Word to replace.
-> String
-- ^ String to replace with.
-> WordReplacerState ()
handleAdd botnick word replacement
| map Char.toLower botnick == map Char.toLower word =
liftIO $ putStrLn "Din naughty dreng"
| otherwise = do
conn <- getConnection
liftIO $ insertReplacement conn word replacement
liftIO $ putStrLn ("Fra nu af ved jeg at " ++ word ++ " er det samme som "
++ replacement)
{- | Print help message. -}
handleHelp :: BotNick
-- ^ Nickname of Dikunt bot.
-> WordReplacerState ()
handleHelp nick = liftIO $ sequence_
[ putStrLn $ nick ++ ": wordreplacer add <word1>=<word2> - add word1=word2 "
++ "to database"
, putStrLn $ nick ++ ": wordreplacer set probability <d> - set the "
++ "probability of writing replacements"
, putStrLn $ nick ++ ": wordreplacer help - display this message"
, putStrLn "otherwise replaces words from database in messages"
]
{- | Set the current probability in the state. -}
handleSetProbability :: Probability
-- ^ The new probability.
-> WordReplacerState ()
handleSetProbability newprob = do
setProbability newprob
liftIO $ putStrLn "Sandsynlighed er sat!"
{- | Look up each word in the database and find replacements. -}
handleWordReplacement :: [Word]
-- ^ Words to find and output replacements for.
-> Probability
-- ^ The probability of printing the replacements.
-> WordReplacerState ()
handleWordReplacement words prob = do
threshold <- getCurrentProbability
conn <- getConnection
replacements <- liftIO $ getReplacements conn words
when ((not . null) replacements && prob < threshold) $
liftIO (T.putStrLn $ replacementString (head replacements))
where
replacementString (Replacement _ w rep) = T.concat
["Jeg tror ikke du mener " , w , " men " , rep]
{- | Parse requests to the plugin from a text string. A new potential request
- is assumed to be on each line. -}
parseRequests :: BotNick
-- ^ The nickname of the bot.
-> T.Text
-- ^ The text to parse requests from.
-> [Request]
parseRequests botnick =
mapMaybe parseRequest . mapMaybe (decode . T.encodeUtf8) . T.lines
where
parseRequest (BT.ServerPrivMsg _ _ msg) =
hush $ P.parse (request botnick) "" (BT.getMessage msg)
parseRequest _ = Nothing
{- | Type to use when parsing requests. -}
type RequestParser a = P.Parsec String () a
{- | Parse a request from a line of text. A request is one of HelpRequest,
- AddReplacement, SetProbability or WordSequence. -}
request :: BotNick
-- ^ The nickname of the bot.
-> RequestParser Request
request botnick = P.choice requestTypes <* P.eof
where
requestTypes = map P.try
[ helpRequest botnick
, addReplacementRequest botnick
, setProbabilityRequest botnick
, wordListRequest
]
{- | Parse a help request. -}
helpRequest :: BotNick
-- ^ Nickname of the bot.
-> RequestParser Request
helpRequest botnick = stringToken (botnick ++ ": ")
*> stringToken "wordreplacer " *> stringToken "help"
*> return (HelpRequest botnick)
{- | Parse a request to add a replacement. -}
addReplacementRequest :: BotNick
-- ^ Nickname of the bot.
-> RequestParser Request
addReplacementRequest botnick = do
void $ stringToken (botnick ++ ": ")
void $ stringToken "wordreplacer "
void $ stringToken "add "
word <- P.many1 (P.noneOf " \n\t=")
replacement <- trim <$> (P.char '=' *> P.many1 P.anyChar)
return $ AddReplacement botnick word replacement
{- | Parse a request to set the current probability. -}
setProbabilityRequest :: BotNick
-- ^ Nickname of the bot.
-> RequestParser Request
setProbabilityRequest botnick = do
void $ stringToken (botnick ++ ": ")
void $ stringToken "wordreplacer "
void $ stringToken "set "
void $ stringToken "probability "
newprob <- P.floating
if newprob >= 0.0 && newprob <= 1.0
then return $ SetProbability newprob
else P.unexpected "Probability should be between 0 and 1"
{- | Parses anything to a list of words separated by spaces and special
- characters. -}
wordListRequest :: RequestParser Request
wordListRequest = WordSequence <$> token (word `P.sepBy` separator)
where
word = P.many1 $ P.noneOf " \n\t.:?!()[]{},"
separator = P.many1 $ P.oneOf " \n\t.:?!()[]{},"
{- | Initialize a database by creating it if it does not exist. -}
initDatabase :: DB.Connection
-- ^ Connection to database to initialize.
-> IO ()
initDatabase conn =
DB.execute_ conn "CREATE TABLE IF NOT EXISTS replacements \
\(id INTEGER PRIMARY KEY, word TEXT UNIQUE, replacement TEXT)"
{- | Insert or replace a replacement in the database of replacements. -}
insertReplacement :: DB.Connection
-- ^ Database connection.
-> Word
-- ^ Word to replace.
-> String
-- ^ String to replace with.
-> IO ()
insertReplacement conn word replacement =
DB.executeNamed conn "INSERT OR REPLACE INTO replacements \
\(word, replacement) VALUES (:word, :replacement)"
[":word" := map Char.toLower word, ":replacement" := replacement]
{- | Get list of all replacements for words given. The function looks up each
- word in the database and concatenates the result. -}
getReplacements :: DB.Connection
-- ^ Database connection.
-> [Word]
-- ^ List of words to find replacements for.
-> IO [Replacement]
getReplacements conn words = concat <$> mapM getReplacement words
where
getReplacement word = DB.queryNamed conn "SELECT id, word, replacement \
\FROM replacements WHERE word = :word COLLATE NOCASE"
[":word" := word] :: IO [Replacement]
{- | Get the current probability from the state. -}
getCurrentProbability :: WordReplacerState Probability
getCurrentProbability = fst <$> get
{- | Get the database connection from the state. -}
getConnection :: WordReplacerState DB.Connection
getConnection = snd <$> get
{- | Set the probability in the state. -}
setProbability :: Probability
-- ^ The new probability.
-> WordReplacerState ()
setProbability newprob = modify (\(_, conn) -> (newprob, conn))
{- | Skips space on both sides of the parser. -}
token :: RequestParser a
-- ^ Parser to skip spaces around.
-> RequestParser a
token tok = P.spaces *> tok <* P.spaces
{- | Parses the string given and skips all whitespace around it. -}
stringToken :: String
-- ^ String to parse.
-> RequestParser String
stringToken = token . P.string
{- | Remove trailing whitespace and whitespace before string. -}
trim :: String
-- ^ String to trim.
-> String
trim = f . f
where
f = reverse . dropWhile Char.isSpace
| bus000/Dikunt | plugins/WordReplacer/Main.hs | bsd-3-clause | 10,292 | 0 | 14 | 2,178 | 2,100 | 1,114 | 986 | 184 | 2 |
{-# LANGUAGE NamedFieldPuns #-}
{- |
Module : Mongo.Pid.Removal
Description : Get Pid from Name
Copyright : (c) Plow Technology 2014
License : MIT
Maintainer : [email protected]
Stability : unstable
Portability : portable
<Uses a name to grab the pid to remove old pid alarms from mongo>
-}
{-# LANGUAGE OverloadedStrings, NoImplicitPrelude ,RecordWildCards #-}
module Mongo.Pid.Removal (removeMissingAlarms) where
import BasicPrelude hiding (delete)
import Persist.Mongo.Settings
import Database.Persist
import Data.Aeson
import Data.Traversable
import qualified Data.Set as S
removeMissingAlarms :: Either String MongoDBConf -> IO ()
removeMissingAlarms (Left st) = putStrLn "Missing mongo config" >> print st
removeMissingAlarms (Right mdbc) = do
(joinKeys,alarmEntityKeys,alarmnames,locationNames) <- runDBConf mdbc $ do
alarms <- selectList [] []
let pidlist = concat $ alarmPids.entityVal <$> alarms
otclist <- selectList [OnpingTagCombinedPid <-. (Just <$> pidlist)] []
let badPidSet = makeCheckSets pidlist (catMaybes $ (onpingTagCombinedPid.entityVal <$> otclist))
let badPidLst = S.toList badPidSet
let filteredAlarms = filterAlarmByPids badPidLst <$> alarms
let filteredAlarmEntities = (catMaybes filteredAlarms)
let alarmentitykeys = entityKey <$> filteredAlarmEntities
joinkeys <- selectKeysList [AlarmJoinsAlarmId <-. alarmentitykeys] []
let alarmnames = alarmName.entityVal <$> filteredAlarmEntities
alarmjoins <- selectList [AlarmJoinsId <-. joinkeys] []
let locationids = alarmJoinsLocationId.entityVal <$> alarmjoins
locationentitys <- selectList [LocationId <-. locationids] []
let locationNames = locationName.entityVal <$> locationentitys
--void $ traverse (delete.entityKey) (filteredAlarmEntities)
--void $ traverse delete joinkeys
return(joinkeys,alarmentitykeys,alarmnames,locationNames)
--putStrLn $ show.encode $ joinKeys
--putStrLn $ show.encode $ alarmEntityKeys
putStrLn $ "Alarm Names Below:"
putStrLn $ show.encode $ alarmnames
putStrLn $ " "
putStrLn $ "Location Names Below:"
putStrLn $ show.encode $ locationNames
filterAlarmByPids :: [Int] -> (Entity Alarm) -> Maybe (Entity Alarm)
filterAlarmByPids pids a@(Entity _ (Alarm {
alarmPids })) = const a <$> listToMaybe
[p2 | p1 <- pids, p2 <- alarmPids, p1 == p2]
makeCheckSets ::(Eq a, Ord a) => [a] -> [a] -> (S.Set a)
makeCheckSets l1 l2 = let s1 = S.fromList l1
s2 = S.fromList l2
in (S.difference s1 s2)
| plow-technologies/mongo-pid-removal | src/Mongo/Pid/Removal.hs | bsd-3-clause | 3,380 | 0 | 19 | 1,285 | 650 | 329 | 321 | 41 | 1 |
{-# LANGUAGE FlexibleContexts, DeriveDataTypeable #-}
{-- | Parser for the lambda AST built of parsec. Converts to an intermediate format for antiexpressions -}
module Language.Lambda.Untyped.Parser where
import Text.Parsec
import Text.Parsec.Language
import Text.Parsec.Token
import Language.Lambda.Untyped.Syntax
import Data.Functor.Identity
import Data.List
import Data.Data
type M = Identity
data MetaExpr s = MVar (MetaSym s)
| MApp (MetaExpr s) (MetaExpr s)
| MLam (MetaSym s) (MetaExpr s)
| AntiExpr String
| AntiVar String
deriving(Show, Eq, Data, Typeable)
data MetaSym s = S s
| AntiSym String
deriving(Show, Eq, Data, Typeable)
type Output s = MetaExpr s
type SymParser u s = ParsecT String u M s
top_expr :: SymParser u s -> ParsecT String u M (Output s)
top_expr sp = do
spaces
e <- parse_expr sp
spaces
eof
return e
parse_expr :: SymParser u s -> ParsecT String u M (Output s)
parse_expr sp = try (parse_aexpr sp)
<|> try (parse_lambda sp)
<|> try parse_anti_expr
parse_aexpr :: SymParser u s -> ParsecT String u M (Output s)
parse_aexpr sp = try (parse_app sp)
<|> try (parse_atom sp)
parse_anti_expr :: ParsecT String u M (Output s)
parse_anti_expr = do
_ <- string "$"
i <- (identifier haskell)
return $ AntiExpr i
parse_lambda :: SymParser u s -> ParsecT String u M (Output s)
parse_lambda sp = do
_ <- char '\\'
spaces
sym <- (p_sym sp) <?> "lambda argument"
_ <- char '.'
spaces
expr <- (parse_expr sp) <?> "lambda expression"
return $ MLam sym expr
parse_app :: SymParser u s -> ParsecT String u M (Output s)
parse_app sp = do
expr_0 <- (parse_atom sp) <?> "first apply argument"
spaces
as <- sepBy1 (parse_atom sp) spaces <?> "other apply arguments"
return $ foldl' MApp expr_0 as
parse_atom :: SymParser u s -> ParsecT String u M (Output s)
parse_atom sp = try (parens' (parse_expr sp))
<|> try (parse_var sp)
<|> try parse_anti_expr
parse_var sp = try (parse_var' sp) <|> parse_anti_var
parse_var' :: SymParser u s -> ParsecT String u M (Output s)
parse_var' sp = do
spaces
sym <- (p_sym sp) <?> "Var symbol"
return $ MVar sym
parse_anti_var = do
spaces
_ <- string "*"
i <- (identifier haskell)
return $ AntiVar i
p_sym :: SymParser u s -> ParsecT String u M (MetaSym s)
p_sym sp = try (S `fmap` sp) <|> try parse_anti_sym
parse_anti_sym :: ParsecT String u M (MetaSym s)
parse_anti_sym = do
_ <- string "^"
i <- (identifier haskell)
return $ AntiSym i
parse_sym :: ParsecT String u M Sym
parse_sym = many1 (alphaNum <|> char '_') <?> "symbol"
parens' :: Stream s m Char => ParsecT s u m b -> ParsecT s u m b
parens' p = do
_ <- char '('
e <- p
_ <- char ')'
return e
meta_to_expr :: MetaExpr s -> GExpr s
meta_to_expr (MVar (S x)) = Var x
meta_to_expr (MApp x y) = App (meta_to_expr x) (meta_to_expr y)
meta_to_expr (MLam (S x) y) = Lam x (meta_to_expr y)
meta_to_expr _ = error "meta_to_expr should not be used if the MetaExpr tree has AntiExpr"
to_meta :: GExpr s -> MetaExpr s
to_meta (Var x) = MVar (S x)
to_meta (App x y) = MApp (to_meta x) (to_meta y)
to_meta (Lam x y) = MLam (S x) (to_meta y)
| jfischoff/LambdaPrettyQuote | src/Language/Lambda/Untyped/Parser.hs | bsd-3-clause | 3,423 | 0 | 11 | 936 | 1,296 | 629 | 667 | 94 | 1 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE RankNTypes #-}
-- | UPDATE operations on the wallet-spec state
module Cardano.Wallet.Kernel.DB.Spec.Update (
-- * Errors
NewPendingFailed(..)
, NewForeignFailed(..)
, ApplyBlockFailed(..)
-- * Updates
, newPending
, newForeign
, cancelPending
, applyBlock
, applyBlockPartial
, switchToFork
-- * Testing
, observableRollbackUseInTestsOnly
) where
import Universum hiding ((:|))
import Control.Lens (lazy, _Just)
import qualified Data.Map.Strict as Map
import Data.SafeCopy (base, deriveSafeCopy)
import qualified Data.Set as Set
import Formatting (bprint, build, (%))
import qualified Formatting.Buildable
import Serokell.Util (listJsonIndent)
import Serokell.Util.Text (listBuilderJSON)
import Test.QuickCheck (Arbitrary (..), elements)
import qualified Pos.Chain.Block as Core
import Pos.Chain.Txp (TxIn, Utxo)
import qualified Pos.Chain.Txp as Txp
import qualified Pos.Core as Core
import Pos.Core.Chrono (NewestFirst (..), OldestFirst (..))
import Cardano.Wallet.Kernel.DB.BlockContext
import Cardano.Wallet.Kernel.DB.BlockMeta
import Cardano.Wallet.Kernel.DB.InDb
import Cardano.Wallet.Kernel.DB.Spec
import Cardano.Wallet.Kernel.DB.Spec.Pending (Pending)
import qualified Cardano.Wallet.Kernel.DB.Spec.Pending as Pending
import Cardano.Wallet.Kernel.DB.Spec.Read
import Cardano.Wallet.Kernel.DB.Util.AcidState
import Cardano.Wallet.Kernel.NodeStateAdaptor (SecurityParameter (..))
import Cardano.Wallet.Kernel.PrefilterTx (PrefilteredBlock (..))
import qualified Cardano.Wallet.Kernel.Util.Core as Core
import qualified Cardano.Wallet.Kernel.Util.Strict as Strict
import qualified Cardano.Wallet.Kernel.Util.StrictList as SL
import Cardano.Wallet.Kernel.Util.StrictNonEmpty (StrictNonEmpty (..))
import qualified Cardano.Wallet.Kernel.Util.StrictNonEmpty as SNE
import UTxO.Util (liftNewestFirst)
{-------------------------------------------------------------------------------
Errors
-------------------------------------------------------------------------------}
-- | Errors thrown by 'newPending'
data NewPendingFailed =
-- | Some inputs are not in the wallet utxo
NewPendingInputsUnavailable (InDb (Set Txp.TxIn))
deriveSafeCopy 1 'base ''NewPendingFailed
instance Buildable NewPendingFailed where
build (NewPendingInputsUnavailable (InDb inputs)) =
bprint ("NewPendingInputsUnavailable { inputs = " % listJsonIndent 4 % " }") (Set.toList inputs)
-- NOTE(adn) Short-circuiting the rabbit-hole with this instance by generating
-- an empty set, thus avoiding the extra dependency on @cardano-sl-core-test@.
instance Arbitrary NewPendingFailed where
arbitrary = pure . NewPendingInputsUnavailable . InDb $ mempty
data NewForeignFailed =
-- | Foreign transactions are not allowed spend from this wallet
NewForeignInputsAvailable (InDb (Set Txp.TxIn))
deriveSafeCopy 1 'base ''NewForeignFailed
instance Buildable NewForeignFailed where
build (NewForeignInputsAvailable (InDb inputs)) =
bprint ("NewForeignInputsAvailable { inputs = " % listJsonIndent 4 % " }") (Set.toList inputs)
-- TODO: See comments for the 'Arbitrary' instance for 'NewPendingFailed'
instance Arbitrary NewForeignFailed where
arbitrary = pure . NewForeignInputsAvailable . InDb $ mempty
-- | Errors thrown by 'applyBlock'
data ApplyBlockFailed =
-- | The block we're trying to apply does not fit onto the previous
--
-- This indicates that the wallet has fallen behind the node (for example,
-- when the node informs the wallet of a block but the wallet gets
-- shut down before it gets a chance to process it).
--
-- We record the context of the block we're trying to apply and the
-- context of the most recent checkpoint.
ApplyBlockNotSuccessor BlockContext (Maybe BlockContext)
deriveSafeCopy 1 'base ''ApplyBlockFailed
instance Buildable ApplyBlockFailed where
build (ApplyBlockNotSuccessor context checkpoint) = bprint
("ApplyBlockNotSuccessor "
% "{ context: " % build
% ", checkpoint: " % build
% "}"
)
context
checkpoint
instance Buildable [ApplyBlockFailed] where
build = listBuilderJSON
instance Arbitrary ApplyBlockFailed where
arbitrary = elements []
{-------------------------------------------------------------------------------
Wallet spec mandated updates
-------------------------------------------------------------------------------}
-- | Insert new pending transaction into the specified wallet
--
-- NOTE: Transactions to be inserted must be fully constructed and signed; we do
-- not offer input selection at this layer. Instead, callers must get a snapshot
-- of the database, construct a transaction asynchronously, and then finally
-- submit the transaction. It is of course possible that the state of the
-- database has changed at this point, possibly making the generated transaction
-- invalid; 'newPending' therefore returns whether or not the transaction could
-- be inserted. If this fails, the process must be started again. This is
-- important for a number of reasons:
--
-- * Input selection may be an expensive computation, and we don't want to
-- lock the database while input selection is ongoing.
-- * Transactions may be signed off-site (on a different machine or on a
-- a specialized hardware device).
-- * We do not actually have access to the key storage inside the DB layer
-- (and do not store private keys) so we cannot actually sign transactions.
newPending :: forall c. IsCheckpoint c
=> InDb Txp.TxAux
-> Update' NewPendingFailed (Checkpoints c) ()
newPending (InDb tx) = do
checkpoints <- get
let (_available, unavailable) =
cpCheckAvailable (Core.txIns tx) (checkpoints ^. currentCheckpoint)
if Set.null unavailable
then put $ insertPending checkpoints
else throwError $ NewPendingInputsUnavailable (InDb unavailable)
where
insertPending :: Checkpoints c -> Checkpoints c
insertPending = currentPending %~ Pending.insert tx
-- | Insert new foreign transaction
--
-- For foreign transactions we expect /none/ of the inputs to belong to the
-- wallet. We may wish to relax this requirement later (or indeed get rid of
-- the difference between these two pending sets altogether), but for now this
-- strict separation makes it easier to see what's going on and limits the
-- impact this has on the reasoning in the wallet spec.
newForeign :: forall c. IsCheckpoint c
=> InDb Txp.TxAux
-> Update' NewForeignFailed (Checkpoints c) ()
newForeign (InDb tx) = do
checkpoints <- get
let (available, _unavailable) =
cpCheckAvailable (Core.txIns tx) (checkpoints ^. currentCheckpoint)
if Set.null available
then put $ insertForeign checkpoints
else throwError $ NewForeignInputsAvailable (InDb available)
where
insertForeign :: Checkpoints c -> Checkpoints c
insertForeign = currentForeign %~ Pending.insert tx
-- | Cancel the input set of cancelled transactions from @all@ the 'Checkpoints'
-- of an 'Account'.
cancelPending :: forall c. IsCheckpoint c
=> Set Txp.TxId
-> Checkpoints c -> Checkpoints c
cancelPending txids = liftCheckpoints $ map (cpPending %~ Pending.delete txids)
-- | Apply the prefiltered block to the specified wallet
--
-- Additionally returns the set of transactions removed from pending.
applyBlock :: SecurityParameter
-> PrefilteredBlock
-> Update' ApplyBlockFailed
(Checkpoints Checkpoint)
(Set Txp.TxId)
applyBlock (SecurityParameter k) pb = do
checkpoints@(Checkpoints ls) <- get
let current = checkpoints ^. currentCheckpoint
utxo = current ^. checkpointUtxo . fromDb
balance = current ^. checkpointUtxoBalance . fromDb
(utxo', balance') = updateUtxo pb (utxo, balance)
(pending', rem1) = updatePending (pfbInputs pb) (current ^. checkpointPending)
blockMeta' = updateBlockMeta pb (current ^. checkpointBlockMeta)
(foreign', rem2) = updatePending (pfbForeignInputs pb) (current ^. checkpointForeign)
if (pfbContext pb) `blockContextSucceeds` (current ^. checkpointContext . lazy) then do
put $ Checkpoints . takeNewest k . NewestFirst $ Checkpoint {
_checkpointUtxo = InDb utxo'
, _checkpointUtxoBalance = InDb balance'
, _checkpointPending = pending'
, _checkpointBlockMeta = blockMeta'
, _checkpointForeign = foreign'
, _checkpointContext = Strict.Just $ pfbContext pb
} SNE.<| getNewestFirst ls
return $ Set.unions [rem1, rem2]
else
throwError $ ApplyBlockNotSuccessor
(pfbContext pb)
(current ^. checkpointContext . lazy)
-- | Like 'applyBlock', but to a list of partial checkpoints instead
--
-- NOTE: Unlike 'applyBlock', we do /NOT/ throw away partial checkpoints. If
-- we did, it might be impossible for the historical checkpoints to ever
-- catch up with the current ones.
applyBlockPartial :: PrefilteredBlock
-> Update' ApplyBlockFailed
(Checkpoints PartialCheckpoint)
(Set Txp.TxId)
applyBlockPartial pb = do
checkpoints@(Checkpoints ls) <- get
let current = checkpoints ^. currentCheckpoint
utxo = current ^. pcheckpointUtxo . fromDb
balance = current ^. pcheckpointUtxoBalance . fromDb
(utxo', balance') = updateUtxo pb (utxo, balance)
(pending', rem1) = updatePending (pfbInputs pb) (current ^. pcheckpointPending)
blockMeta' = updateLocalBlockMeta pb (current ^. pcheckpointBlockMeta)
(foreign', rem2) = updatePending (pfbForeignInputs pb) (current ^. pcheckpointForeign)
if (pfbContext pb) `blockContextSucceeds` (current ^. cpContext . lazy) then do
put $ Checkpoints $ NewestFirst $ PartialCheckpoint {
_pcheckpointUtxo = InDb utxo'
, _pcheckpointUtxoBalance = InDb balance'
, _pcheckpointPending = pending'
, _pcheckpointBlockMeta = blockMeta'
, _pcheckpointForeign = foreign'
, _pcheckpointContext = pfbContext pb
} SNE.<| getNewestFirst ls
return $ Set.unions [rem1, rem2]
else
throwError $ ApplyBlockNotSuccessor
(pfbContext pb)
(current ^. cpContext . lazy)
-- | Rollback
--
-- For the base case, see section "Rollback -- Omitting checkpoints" in the
-- formal specification.
--
-- NOTE: Rollback is currently only supported for wallets that are fully up
-- to date. Hence, we only support full checkpoints here.
--
-- Additionally returns the set of pending transactions that got reintroduced,
-- so that the submission layer can start sending those out again.
--
-- This is an internal function only, and not exported. See 'switchToFork'.
rollback :: Update' e (Checkpoints Checkpoint) Pending
rollback = state $ \case
Checkpoints (NewestFirst (c :| SL.Nil)) -> (Pending.empty,
Checkpoints . NewestFirst $ c :| SL.Nil)
Checkpoints (NewestFirst (c :| SL.Cons c' cs)) ->
(Pending.union
((c' ^. cpPending) Pending.\\ (c ^. cpPending))
((c' ^. cpForeign) Pending.\\ (c ^. cpForeign)),
Checkpoints . NewestFirst $ (c' & cpPending %~ Pending.union (c ^. cpPending)
& cpForeign %~ Pending.union (c ^. cpForeign)) :| cs)
-- | Observable rollback, used in testing only
--
-- See 'switchToFork' for production use.
observableRollbackUseInTestsOnly :: Update' e (Checkpoints Checkpoint) Pending
observableRollbackUseInTestsOnly = rollback
-- | Switch to a fork
--
-- Since rollback is only supported on wallets that are up to date wrt to
-- the underlying node, the same goes for 'switchToFork'.
--
-- Additionally returns the set of transactions that got introduced reintroduced
-- (to the rollback) and the transactions that got removed from pending
-- (since they are new confirmed).
switchToFork :: SecurityParameter
-> Maybe Core.HeaderHash -- ^ Roll back until we meet this block.
-> OldestFirst [] PrefilteredBlock -- ^ Blocks to apply
-> Update' ApplyBlockFailed
(Checkpoints Checkpoint)
(Pending, Set Txp.TxId)
switchToFork k oldest blocksToApply = do
-- Unless we are already at 'oldest', roll back until we find it.
curCtx <- use currentContext
reintroduced <- if curCtx ^? _Just . bcHash . fromDb /= oldest
then rollbacks Pending.empty
else return Pending.empty
-- Now apply the blocks for new fork.
applyBlocks reintroduced Set.empty (getOldestFirst blocksToApply)
where
rollbacks :: Pending -- Accumulator: reintroduced pending transactions
-> Update' e
(Checkpoints Checkpoint)
Pending
rollbacks !accNew = do
curCtx <- use currentContext
reintroduced <- rollback
let acc = Pending.union accNew reintroduced
prev = do ctx <- curCtx
prevMain <- ctx ^. bcPrevMain . lazy
return $ prevMain ^. fromDb
case (prev == oldest, prev) of
(True, _) -> return acc -- We rolled back everything we needed to.
(False, Nothing) -> return acc -- The checkpoints began after the fork point.
(False, Just _) -> rollbacks acc -- Keep going
applyBlocks :: Pending -- Accumulator: reintroduced pending transactions
-> Set Txp.TxId -- Accumulator: removed pending transactions
-> [PrefilteredBlock]
-> Update' ApplyBlockFailed
(Checkpoints Checkpoint)
(Pending, Set Txp.TxId)
applyBlocks !accNew !accRem [] = return (accNew, accRem)
applyBlocks !accNew !accRem (b:bs) = do
removed <- applyBlock k b
applyBlocks (Pending.delete removed accNew)
(Set.union removed accRem)
bs
{-------------------------------------------------------------------------------
Internal auxiliary
-------------------------------------------------------------------------------}
updateBlockMeta :: PrefilteredBlock -> BlockMeta -> BlockMeta
updateBlockMeta = flip appendBlockMeta . pfbMeta
updateLocalBlockMeta :: PrefilteredBlock -> LocalBlockMeta -> LocalBlockMeta
updateLocalBlockMeta = flip appendLocalBlockMeta . pfbMeta
-- | Update (utxo,balance) with the given prefiltered block
updateUtxo :: PrefilteredBlock -> (Utxo, Core.Coin) -> (Utxo, Core.Coin)
updateUtxo PrefilteredBlock{..} (utxo, balance) =
(utxo', balance')
where
-- See wallet spec figure 6 (Wallet with prefiltering):
--
-- * pfbOutputs corresponds to what the spec calls utxo^+ / txouts_b
-- * pfbInputs corresponds to what the spec calls txins_b
extendedInputs = Set.union pfbInputs pfbForeignInputs
utxoUnion = Map.union utxo pfbOutputs
utxoMin = utxoUnion `Core.utxoRestrictToInputs` extendedInputs
utxo' = utxoUnion `Core.utxoRemoveInputs` extendedInputs
balance' = Core.unsafeIntegerToCoin $
Core.coinToInteger balance
+ Core.utxoBalance pfbOutputs
- Core.utxoBalance utxoMin
-- | Update the pending transactions with the given prefiltered block
--
-- Returns the set of transactions that got removed from the pending set.
updatePending :: Set TxIn -> Pending -> (Pending, Set Txp.TxId)
updatePending inputs = Pending.removeInputs inputs
takeNewest :: Int -> NewestFirst StrictNonEmpty a -> NewestFirst StrictNonEmpty a
takeNewest = liftNewestFirst . SNE.take
| input-output-hk/pos-haskell-prototype | wallet/src/Cardano/Wallet/Kernel/DB/Spec/Update.hs | mit | 16,318 | 0 | 18 | 3,951 | 2,909 | 1,611 | 1,298 | -1 | -1 |
module Grammatik.CF.Chomsky.Generate where
import Grammatik.CF.Chomsky.Type
import Autolib.FiniteMap
import Control.Monad ( guard )
import Data.List ( nub )
main :: Ord a
=> Chomsky a -> [[ String ]]
main ch = let Just ws = lookupFM ( creation ch ) ( start ch ) in ws
-- | compute terminal words derivable from symbol
-- collect words of equal length into groups:
-- lookupFM ( creation ch ) v !! k = list of all words derivable
-- from variable v of length k
creation :: Ord a
=> Chomsky a -> FiniteMap a [[String]]
creation ch =
let sigma = nub $ map fst $ rules ch
fm = listToFM $ do
v <- sigma
let words k = nub $
if k <= 0 then [ "" | v == start ch && eps ch ]
else if k == 1 then do
( v', Left c ) <- rules ch
guard $ v' == v
return [ c ]
else do
( v', Right ( x, y ) ) <- rules ch
guard $ v' == v
l <- [ 1 .. k -1 ]
let r = k - l
let Just wls = lookupFM fm x
Just wrs = lookupFM fm y
wl <- wls !! l
wr <- wrs !! r
return $ wl ++ wr
return ( v, map words [ 0 .. ] )
in fm
| Erdwolf/autotool-bonn | src/Grammatik/CF/Chomsky/Generate.hs | gpl-2.0 | 1,429 | 12 | 11 | 685 | 417 | 220 | 197 | 32 | 3 |
{-# LANGUAGE GeneralizedNewtypeDeriving, RankNTypes, TemplateHaskell #-}
{-# LANGUAGE DerivingVia #-}
module Revision.Deltum.Transaction
( Transaction, run
, Store(..), onStoreM
, Changes, fork, merge
, lookupBS, lookup
, insertBS, insert
, delete, deleteIRef
, readIRef, writeIRef
, isEmpty
, irefExists
, newIRef, newKey
, assocDataRef, assocDataRefDef
, fromIRef
, mkPropertyFromIRef
) where
import Control.Applicative ((<|>))
import qualified Control.Lens as Lens
import Control.Monad.Trans.Reader (ReaderT, runReaderT)
import qualified Control.Monad.Trans.Reader as Reader
import Control.Monad.Trans.State (StateT, runStateT)
import qualified Control.Monad.Trans.State as State
import Data.Binary.Extended (encodeS, decodeS)
import qualified Data.Map as Map
import qualified Data.Monoid as Monoid
import Data.Property (Property, MkProperty')
import qualified Data.Property as Property
import Data.UUID.Types (UUID)
import qualified Data.UUID.Utils as UUIDUtils
import Revision.Deltum.IRef (IRef)
import qualified Revision.Deltum.IRef as IRef
import Revision.Deltum.Rev.Change (Key, Value)
import Lamdu.Prelude hiding (lookup)
type ChangesMap = Map Key (Maybe Value)
-- 't' is a phantom-type tag meant to make sure you run Transactions
-- with the right store
data Store m = Store
{ storeNewKey :: m Key
, storeLookup :: Key -> m (Maybe Value)
, storeAtomicWrite :: [(Key, Maybe Value)] -> m ()
}
onStoreM :: (forall a. m a -> n a) -> Store m -> Store n
onStoreM f x = x
{ storeNewKey = f $ storeNewKey x
, storeLookup = f . storeLookup x
, storeAtomicWrite = f . storeAtomicWrite x
}
data Askable m = Askable
{ _aStore :: Store m
, -- | The base is the set of changes we inherited from a parent
-- transaction (in a fork) that we do NOT apply when merging the
-- forked transaction.
-- This in contrast to the Stateful ChangesMap that starts empty
-- in the fork and is applied when the fork is merged.
_aBase :: ChangesMap
}
Lens.makeLenses ''Askable
-- Define transformer stack:
newtype Transaction m a =
Transaction (ReaderT (Askable m) (StateT ChangesMap m) a)
deriving stock Generic
deriving newtype (Functor, Applicative, Monad)
deriving (Semigroup, Monoid) via Monoid.Ap (Transaction m) a
type T = Transaction
liftAskable :: ReaderT (Askable m) (StateT ChangesMap m) a -> T m a
liftAskable = Transaction
liftChangesMap :: Monad m => StateT ChangesMap m a -> T m a
liftChangesMap = liftAskable . lift
liftInner :: Monad m => m a -> T m a
liftInner = Transaction . lift . lift
getStore :: Monad m => T m (Store m)
getStore = Lens.view aStore & liftAskable
getBase :: Monad m => T m ChangesMap
getBase = Lens.view aBase & liftAskable
run :: Monad m => Store m -> T m a -> m a
run store (Transaction transaction) = do
(res, changes) <-
transaction
& (`runReaderT` Askable store mempty)
& (`runStateT` mempty)
storeAtomicWrite store (changes ^@.. Lens.itraversed)
pure res
newtype Changes = Changes ChangesMap
-- | Fork the given transaction into its own space. Unless the
-- transaction is later "merged" into the main transaction, its
-- changes will not be committed anywhere.
fork :: Monad m => T m a -> T m (a, Changes)
fork (Transaction discardableTrans) = do
changes <- liftChangesMap State.get
-- Map.union is left-biased, so changes correctly override base:
askable <- liftAskable Reader.ask <&> aBase %~ Map.union changes
discardableTrans
& (`runReaderT` askable)
& (`runStateT` mempty)
& liftInner
<&> _2 %~ Changes
merge :: Monad m => Changes -> T m ()
merge (Changes changes) =
liftChangesMap . State.modify $ Map.union changes
isEmpty :: Monad m => T m Bool
isEmpty = liftChangesMap (State.gets Map.null)
lookupBS :: Monad m => UUID -> T m (Maybe Value)
lookupBS uuid = do
base <- getBase
changes <- liftChangesMap State.get
case Map.lookup uuid changes <|> Map.lookup uuid base of
Nothing -> do
store <- getStore
liftInner $ storeLookup store uuid
Just res -> pure res
insertBS :: Monad m => UUID -> ByteString -> T m ()
insertBS key = liftChangesMap . State.modify . Map.insert key . Just
delete :: Monad m => UUID -> T m ()
delete key = liftChangesMap . State.modify . Map.insert key $ Nothing
lookup :: (Monad m, Binary a) => UUID -> T m (Maybe a)
lookup = (fmap . fmap) decodeS . lookupBS
insert :: (Monad m, Binary a) => UUID -> a -> T m ()
insert key = insertBS key . encodeS
writeUUID :: (Monad m, Binary a) => UUID -> a -> T m ()
writeUUID = insert
uuidExists :: Monad m => UUID -> T m Bool
uuidExists = fmap (Lens.has Lens._Just) . lookupBS
readUUIDMb :: (Monad m, Binary a) => T m a -> UUID -> T m a
readUUIDMb nothingCase uuid =
maybe nothingCase pure =<< lookup uuid
readUUID :: (Monad m, Binary a) => UUID -> T m a
readUUID uuid = readUUIDMb failure uuid
where
failure = error $ "Inexistent uuid: " ++ show uuid ++ " referenced"
deleteIRef :: Monad m => IRef m a -> T m ()
deleteIRef = delete . IRef.uuid
readIRef :: (Monad m, Binary a) => IRef m a -> T m a
readIRef = readUUID . IRef.uuid
irefExists :: Monad m => IRef m a -> T m Bool
irefExists = uuidExists . IRef.uuid
writeIRef :: (Monad m, Binary a) => IRef m a -> a -> T m ()
writeIRef = writeUUID . IRef.uuid
newKey :: Monad m => T m Key
newKey = liftInner . storeNewKey =<< getStore
newIRef :: (Monad m, Binary a) => a -> T m (IRef m a)
newIRef val = do
newUUID <- newKey
insert newUUID val
pure $ IRef.unsafeFromUUID newUUID
---------- Properties:
fromIRef :: (Monad m, Binary a) => IRef m a -> T m (Property (T m) a)
fromIRef iref = flip Property.Property (writeIRef iref) <$> readIRef iref
mkPropertyFromIRef :: (Monad m, Binary a) => IRef m a -> MkProperty' (T m) a
mkPropertyFromIRef = Property.MkProperty . fromIRef
assocDataRef :: (Binary a, Monad m) => ByteString -> UUID -> MkProperty' (T m) (Maybe a)
assocDataRef str uuid =
lookup assocUUID <&> (`Property.Property` set) & Property.MkProperty
where
assocUUID = UUIDUtils.augment str uuid
set Nothing = delete assocUUID
set (Just x) = writeUUID assocUUID x
assocDataRefDef ::
(Eq a, Binary a, Monad m) => a -> ByteString -> UUID -> MkProperty' (T m) a
assocDataRefDef def str uuid =
assocDataRef str uuid
& Property.prop %~ Property.pureCompose (fromMaybe def) f
where
f x
| x == def = Nothing
| otherwise = Just x
| lamdu/lamdu | src/Revision/Deltum/Transaction.hs | gpl-3.0 | 6,690 | 0 | 13 | 1,571 | 2,255 | 1,184 | 1,071 | -1 | -1 |
{-# 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.EC2.CreatePlacementGroup
-- 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)
--
-- Creates a placement group that you launch cluster instances into. You
-- must give the group a name that\'s unique within the scope of your
-- account.
--
-- For more information about placement groups and cluster instances, see
-- <http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using_cluster_computing.html Cluster Instances>
-- in the /Amazon Elastic Compute Cloud User Guide/.
--
-- /See:/ <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-CreatePlacementGroup.html AWS API Reference> for CreatePlacementGroup.
module Network.AWS.EC2.CreatePlacementGroup
(
-- * Creating a Request
createPlacementGroup
, CreatePlacementGroup
-- * Request Lenses
, cpgDryRun
, cpgGroupName
, cpgStrategy
-- * Destructuring the Response
, createPlacementGroupResponse
, CreatePlacementGroupResponse
) where
import Network.AWS.EC2.Types
import Network.AWS.EC2.Types.Product
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | /See:/ 'createPlacementGroup' smart constructor.
data CreatePlacementGroup = CreatePlacementGroup'
{ _cpgDryRun :: !(Maybe Bool)
, _cpgGroupName :: !Text
, _cpgStrategy :: !PlacementStrategy
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'CreatePlacementGroup' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cpgDryRun'
--
-- * 'cpgGroupName'
--
-- * 'cpgStrategy'
createPlacementGroup
:: Text -- ^ 'cpgGroupName'
-> PlacementStrategy -- ^ 'cpgStrategy'
-> CreatePlacementGroup
createPlacementGroup pGroupName_ pStrategy_ =
CreatePlacementGroup'
{ _cpgDryRun = Nothing
, _cpgGroupName = pGroupName_
, _cpgStrategy = pStrategy_
}
-- | Checks whether you have the required permissions for the action, without
-- actually making the request, and provides an error response. If you have
-- the required permissions, the error response is 'DryRunOperation'.
-- Otherwise, it is 'UnauthorizedOperation'.
cpgDryRun :: Lens' CreatePlacementGroup (Maybe Bool)
cpgDryRun = lens _cpgDryRun (\ s a -> s{_cpgDryRun = a});
-- | A name for the placement group.
--
-- Constraints: Up to 255 ASCII characters
cpgGroupName :: Lens' CreatePlacementGroup Text
cpgGroupName = lens _cpgGroupName (\ s a -> s{_cpgGroupName = a});
-- | The placement strategy.
cpgStrategy :: Lens' CreatePlacementGroup PlacementStrategy
cpgStrategy = lens _cpgStrategy (\ s a -> s{_cpgStrategy = a});
instance AWSRequest CreatePlacementGroup where
type Rs CreatePlacementGroup =
CreatePlacementGroupResponse
request = postQuery eC2
response = receiveNull CreatePlacementGroupResponse'
instance ToHeaders CreatePlacementGroup where
toHeaders = const mempty
instance ToPath CreatePlacementGroup where
toPath = const "/"
instance ToQuery CreatePlacementGroup where
toQuery CreatePlacementGroup'{..}
= mconcat
["Action" =: ("CreatePlacementGroup" :: ByteString),
"Version" =: ("2015-04-15" :: ByteString),
"DryRun" =: _cpgDryRun, "GroupName" =: _cpgGroupName,
"Strategy" =: _cpgStrategy]
-- | /See:/ 'createPlacementGroupResponse' smart constructor.
data CreatePlacementGroupResponse =
CreatePlacementGroupResponse'
deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'CreatePlacementGroupResponse' with the minimum fields required to make a request.
--
createPlacementGroupResponse
:: CreatePlacementGroupResponse
createPlacementGroupResponse = CreatePlacementGroupResponse'
| fmapfmapfmap/amazonka | amazonka-ec2/gen/Network/AWS/EC2/CreatePlacementGroup.hs | mpl-2.0 | 4,418 | 0 | 11 | 829 | 526 | 321 | 205 | 70 | 1 |
{-| PyValue contains instances for the 'PyValue' typeclass.
The typeclass 'PyValue' converts Haskell values to Python values.
This module contains instances of this typeclass for several generic
types. These instances are used in the Haskell to Python generation
of opcodes and constants, for example.
-}
{-
Copyright (C) 2013 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
{-# LANGUAGE ExistentialQuantification #-}
module Ganeti.PyValue
( PyValue(..)
, PyValueEx(..)
) where
import Data.Char (isAscii, isPrint, ord)
import Data.List (intercalate)
import Data.Map (Map)
import Data.ByteString (ByteString)
import Text.Printf (printf)
import qualified Data.ByteString.Char8 as BC8 (foldr)
import qualified Data.Map as Map
import qualified Data.Set as Set (toList)
import Ganeti.BasicTypes
-- * PyValue represents data types convertible to Python
-- | Converts Haskell values into Python values
--
-- This is necessary for the default values of opcode parameters and
-- return values. For example, if a default value or return type is a
-- Data.Map, then it must be shown as a Python dictioanry.
class PyValue a where
showValue :: a -> String
showValueList :: [a] -> String
showValueList xs = "[" ++ intercalate "," (map showValue xs) ++ "]"
instance PyValue Bool where
showValue = show
instance PyValue Int where
showValue = show
instance PyValue Integer where
showValue = show
instance PyValue Double where
showValue = show
instance PyValue Char where
showValue = show
showValueList = show
-- (Byte)String show output does not work out of the box as a Python
-- string/bytes literal, especially when special characters are involved.
-- For instance, show ByteString.Char8.pack "\x03" yields "\ETX", which means
-- something completely different in Python. Thus, we need to implement our own
-- showValue, which does the following:
-- * escapes double quotes
-- * leaves all printable ASCII characters intact
-- * encodes all other characters in \xYZ form
instance PyValue ByteString where
showValue bs =
"b'" ++ (BC8.foldr (\c acc -> formatChar c ++ acc) "" bs) ++ "'"
where
formatChar x
| x == '\\' = "\\\\"
| x == '\'' = "\\\'"
| isAscii x && isPrint x = [x]
| otherwise = (printf "\\x%02x" $ ord x)
instance (PyValue a, PyValue b) => PyValue (a, b) where
showValue (x, y) = "(" ++ showValue x ++ "," ++ showValue y ++ ")"
instance (PyValue a, PyValue b, PyValue c) => PyValue (a, b, c) where
showValue (x, y, z) =
"(" ++
showValue x ++ "," ++
showValue y ++ "," ++
showValue z ++
")"
instance PyValue a => PyValue [a] where
showValue = showValueList
instance (PyValue k, PyValue a) => PyValue (Map k a) where
showValue mp =
"{" ++ intercalate ", " (map showPair (Map.assocs mp)) ++ "}"
where showPair (k, x) = showValue k ++ ":" ++ showValue x
instance PyValue a => PyValue (ListSet a) where
showValue = showValue . Set.toList . unListSet
-- * PyValue represents an unspecified value convertible to Python
-- | Encapsulates Python default values
data PyValueEx = forall a. PyValue a => PyValueEx a
instance PyValue PyValueEx where
showValue (PyValueEx x) = showValue x
| ganeti/ganeti | src/Ganeti/PyValue.hs | bsd-2-clause | 4,431 | 0 | 13 | 826 | 752 | 408 | 344 | 56 | 0 |
{-# LANGUAGE PatternGuards, ViewPatterns #-}
module Idris.Elab.Record(elabRecord) where
import Idris.AbsSyntax
import Idris.Docstrings
import Idris.Error
import Idris.Delaborate
import Idris.Imports
import Idris.Elab.Term
import Idris.Coverage
import Idris.DataOpts
import Idris.Providers
import Idris.Primitives
import Idris.Inliner
import Idris.PartialEval
import Idris.DeepSeq
import Idris.Output (iputStrLn, pshow, iWarn, sendHighlighting)
import IRTS.Lang
import Idris.ParseExpr (tryFullExpr)
import Idris.Elab.Type
import Idris.Elab.Data
import Idris.Elab.Utils
import Idris.Core.TT
import Idris.Core.Evaluate
import Idris.Elab.Data
import Data.Maybe
import Data.List
import Control.Monad
-- | Elaborate a record declaration
elabRecord :: ElabInfo
-> ElabWhat
-> (Docstring (Either Err PTerm)) -- ^ The documentation for the whole declaration
-> SyntaxInfo -> FC -> DataOpts
-> Name -- ^ The name of the type being defined
-> FC -- ^ The precise source location of the tycon name
-> [(Name, FC, Plicity, PTerm)] -- ^ Parameters
-> [(Name, Docstring (Either Err PTerm))] -- ^ Parameter Docs
-> [(Maybe (Name, FC), Plicity, PTerm, Maybe (Docstring (Either Err PTerm)))] -- ^ Fields
-> Maybe (Name, FC) -- ^ Constructor Name
-> (Docstring (Either Err PTerm)) -- ^ Constructor Doc
-> SyntaxInfo -- ^ Constructor SyntaxInfo
-> Idris ()
elabRecord info what doc rsyn fc opts tyn nfc params paramDocs fields cname cdoc csyn
= do logElab 1 $ "Building data declaration for " ++ show tyn
-- Type constructor
let tycon = generateTyConType params
logElab 1 $ "Type constructor " ++ showTmImpls tycon
-- Data constructor
dconName <- generateDConName (fmap fst cname)
let dconTy = generateDConType params fieldsWithNameAndDoc
logElab 1 $ "Data constructor: " ++ showTmImpls dconTy
-- Build data declaration for elaboration
logElab 1 $ foldr (++) "" $ intersperse "\n" (map show dconsArgDocs)
let datadecl = case what of
ETypes -> PLaterdecl tyn NoFC tycon
_ -> PDatadecl tyn NoFC tycon [(cdoc, dconsArgDocs, dconName, NoFC, dconTy, fc, [])]
elabData info rsyn doc paramDocs fc opts datadecl
-- Keep track of the record
let parameters = [(n,pt) | (n, _, _, pt) <- params]
let projections = [n | (n, _, _, _, _) <- fieldsWithName]
addRecord tyn (RI parameters dconName projections)
addIBC (IBCRecord tyn)
when (what /= ETypes) $ do
logElab 1 $ "fieldsWithName " ++ show fieldsWithName
logElab 1 $ "fieldsWIthNameAndDoc " ++ show fieldsWithNameAndDoc
elabRecordFunctions info rsyn fc tyn paramsAndDoc fieldsWithNameAndDoc dconName target
sendHighlighting $
[(nfc, AnnName tyn Nothing Nothing Nothing)] ++
maybe [] (\(_, cnfc) -> [(cnfc, AnnName dconName Nothing Nothing Nothing)]) cname ++
[(ffc, AnnBoundName fn False) | (fn, ffc, _, _, _) <- fieldsWithName]
where
-- | Generates a type constructor.
generateTyConType :: [(Name, FC, Plicity, PTerm)] -> PTerm
generateTyConType ((n, nfc, p, t) : rest) = PPi p (nsroot n) nfc t (generateTyConType rest)
generateTyConType [] = (PType fc)
-- | Generates a name for the data constructor if none was specified.
generateDConName :: Maybe Name -> Idris Name
generateDConName (Just n) = return $ expandNS csyn n
generateDConName Nothing = uniqueName (expandNS csyn $ sMN 0 ("Mk" ++ (show (nsroot tyn))))
where
uniqueName :: Name -> Idris Name
uniqueName n = do i <- getIState
case lookupTyNameExact n (tt_ctxt i) of
Just _ -> uniqueName (nextName n)
Nothing -> return n
-- | Generates the data constructor type.
generateDConType :: [(Name, FC, Plicity, PTerm)] -> [(Name, FC, Plicity, PTerm, a)] -> PTerm
generateDConType ((n, nfc, _, t) : ps) as = PPi impl (nsroot n) NoFC t (generateDConType ps as)
generateDConType [] ((n, _, p, t, _) : as) = PPi p (nsroot n) NoFC t (generateDConType [] as)
generateDConType [] [] = target
-- | The target for the constructor and projection functions. Also the source of the update functions.
target :: PTerm
target = PApp fc (PRef fc [] tyn) $ map (uncurry asPRefArg) [(p, n) | (n, _, p, _) <- params]
paramsAndDoc :: [(Name, FC, Plicity, PTerm, Docstring (Either Err PTerm))]
paramsAndDoc = pad params paramDocs
where
pad :: [(Name, FC, Plicity, PTerm)] -> [(Name, Docstring (Either Err PTerm))] -> [(Name, FC, Plicity, PTerm, Docstring (Either Err PTerm))]
pad ((n, fc, p, t) : rest) docs
= let d = case lookup n docs of
Just d' -> d
Nothing -> emptyDocstring
in (n, fc, p, t, d) : (pad rest docs)
pad _ _ = []
dconsArgDocs :: [(Name, Docstring (Either Err PTerm))]
dconsArgDocs = paramDocs ++ (dcad fieldsWithName)
where
dcad :: [(Name, FC, Plicity, PTerm, Maybe (Docstring (Either Err PTerm)))] -> [(Name, Docstring (Either Err PTerm))]
dcad ((n, _, _, _, (Just d)) : rest) = ((nsroot n), d) : (dcad rest)
dcad (_ : rest) = dcad rest
dcad [] = []
fieldsWithName :: [(Name, FC, Plicity, PTerm, Maybe (Docstring (Either Err PTerm)))]
fieldsWithName = fwn [] fields
where
fwn :: [Name] -> [(Maybe (Name, FC), Plicity, PTerm, Maybe (Docstring (Either Err PTerm)))] -> [(Name, FC, Plicity, PTerm, Maybe (Docstring (Either Err PTerm)))]
fwn ns ((n, p, t, d) : rest)
= let nn = case n of
Just n' -> n'
Nothing -> newName ns baseName
withNS = expandNS rsyn (fst nn)
in (withNS, snd nn, p, t, d) : (fwn (fst nn : ns) rest)
fwn _ _ = []
baseName = (sUN "__pi_arg", NoFC)
newName :: [Name] -> (Name, FC) -> (Name, FC)
newName ns (n, nfc)
| n `elem` ns = newName ns (nextName n, nfc)
| otherwise = (n, nfc)
fieldsWithNameAndDoc :: [(Name, FC, Plicity, PTerm, Docstring (Either Err PTerm))]
fieldsWithNameAndDoc = fwnad fieldsWithName
where
fwnad :: [(Name, FC, Plicity, PTerm, Maybe (Docstring (Either Err PTerm)))] -> [(Name, FC, Plicity, PTerm, Docstring (Either Err PTerm))]
fwnad ((n, nfc, p, t, d) : rest)
= let doc = fromMaybe emptyDocstring d
in (n, nfc, p, t, doc) : (fwnad rest)
fwnad [] = []
elabRecordFunctions :: ElabInfo -> SyntaxInfo -> FC
-> Name -- ^ Record type name
-> [(Name, FC, Plicity, PTerm, Docstring (Either Err PTerm))] -- ^ Parameters
-> [(Name, FC, Plicity, PTerm, Docstring (Either Err PTerm))] -- ^ Fields
-> Name -- ^ Constructor Name
-> PTerm -- ^ Target type
-> Idris ()
elabRecordFunctions info rsyn fc tyn params fields dconName target
= do logElab 1 $ "Elaborating helper functions for record " ++ show tyn
logElab 1 $ "Fields: " ++ show fieldNames
logElab 1 $ "Params: " ++ show paramNames
-- The elaborated constructor type for the data declaration
i <- getIState
ttConsTy <-
case lookupTyExact dconName (tt_ctxt i) of
Just as -> return as
Nothing -> tclift $ tfail $ At fc (Elaborating "record " tyn Nothing (InternalMsg "It seems like the constructor for this record has disappeared. :( \n This is a bug. Please report."))
-- The arguments to the constructor
let constructorArgs = getArgTys ttConsTy
logElab 1 $ "Cons args: " ++ show constructorArgs
logElab 1 $ "Free fields: " ++ show (filter (not . isFieldOrParam') constructorArgs)
-- If elaborating the constructor has resulted in some new implicit fields we make projection functions for them.
let freeFieldsForElab = map (freeField i) (filter (not . isFieldOrParam') constructorArgs)
-- The parameters for elaboration with their documentation
-- Parameter functions are all prefixed with "param_".
let paramsForElab = [((nsroot n), (paramName n), impl, t, d) | (n, _, _, t, d) <- params] -- zipParams i params paramDocs]
-- The fields (written by the user) with their documentation.
let userFieldsForElab = [((nsroot n), n, p, t, d) | (n, nfc, p, t, d) <- fields]
-- All things we need to elaborate projection functions for, together with a number denoting their position in the constructor.
let projectors = [(n, n', p, t, d, i) | ((n, n', p, t, d), i) <- zip (freeFieldsForElab ++ paramsForElab ++ userFieldsForElab) [0..]]
-- Build and elaborate projection functions
elabProj dconName projectors
logElab 1 $ "Dependencies: " ++ show fieldDependencies
logElab 1 $ "Depended on: " ++ show dependedOn
-- All things we need to elaborate update functions for, together with a number denoting their position in the constructor.
let updaters = [(n, n', p, t, d, i) | ((n, n', p, t, d), i) <- zip (paramsForElab ++ userFieldsForElab) [0..]]
-- Build and elaborate update functions
elabUp dconName updaters
where
-- | Creates a PArg from a plicity and a name where the term is a Placeholder.
placeholderArg :: Plicity -> Name -> PArg
placeholderArg p n = asArg p (nsroot n) Placeholder
-- | Root names of all fields in the current record declarations
fieldNames :: [Name]
fieldNames = [nsroot n | (n, _, _, _, _) <- fields]
paramNames :: [Name]
paramNames = [nsroot n | (n, _, _, _, _) <- params]
isFieldOrParam :: Name -> Bool
isFieldOrParam n = n `elem` (fieldNames ++ paramNames)
isFieldOrParam' :: (Name, a) -> Bool
isFieldOrParam' = isFieldOrParam . fst
isField :: Name -> Bool
isField = flip elem fieldNames
isField' :: (Name, a, b, c, d, f) -> Bool
isField' (n, _, _, _, _, _) = isField n
fieldTerms :: [PTerm]
fieldTerms = [t | (_, _, _, t, _) <- fields]
-- Delabs the TT to PTerm
-- This is not good.
-- However, for machine generated implicits, there seems to be no PTerm available.
-- Is there a better way to do this without building the setters and getters as TT?
freeField :: IState -> (Name, TT Name) -> (Name, Name, Plicity, PTerm, Docstring (Either Err PTerm))
freeField i arg = let nameInCons = fst arg -- The name as it appears in the constructor
nameFree = expandNS rsyn (freeName $ fst arg) -- The name prefixed with "free_"
plicity = impl -- All free fields are implicit as they are machine generated
fieldType = delab i (snd arg) -- The type of the field
doc = emptyDocstring -- No docmentation for machine generated fields
in (nameInCons, nameFree, plicity, fieldType, doc)
freeName :: Name -> Name
freeName (UN n) = sUN ("free_" ++ str n)
freeName (MN i n) = sMN i ("free_" ++ str n)
freeName (NS n s) = NS (freeName n) s
freeName n = n
-- | Zips together parameters with their documentation. If no documentation for a given field exists, an empty docstring is used.
zipParams :: IState -> [(Name, Plicity, PTerm)] -> [(Name, Docstring (Either Err PTerm))] -> [(Name, PTerm, Docstring (Either Err PTerm))]
zipParams i ((n, _, t) : rest) ((_, d) : rest') = (n, t, d) : (zipParams i rest rest')
zipParams i ((n, _, t) : rest) [] = (n, t, emptyDoc) : (zipParams i rest [])
where emptyDoc = annotCode (tryFullExpr rsyn i) emptyDocstring
zipParams _ [] [] = []
paramName :: Name -> Name
paramName (UN n) = sUN ("param_" ++ str n)
paramName (MN i n) = sMN i ("param_" ++ str n)
paramName (NS n s) = NS (paramName n) s
paramName n = n
-- | Elaborate the projection functions.
elabProj :: Name -> [(Name, Name, Plicity, PTerm, Docstring (Either Err PTerm), Int)] -> Idris ()
elabProj cn fs = let phArgs = map (uncurry placeholderArg) [(p, n) | (n, _, p, _, _, _) <- fs]
elab = \(n, n', p, t, doc, i) ->
-- Use projections in types
do let t' = projectInType [(m, m') | (m, m', _, _, _, _) <- fs
-- Parameters are already in scope, so just use them
, not (m `elem` paramNames)] t
elabProjection info n n' p t' doc rsyn fc target cn phArgs fieldNames i
in mapM_ elab fs
-- | Elaborate the update functions.
elabUp :: Name -> [(Name, Name, Plicity, PTerm, Docstring (Either Err PTerm), Int)] -> Idris ()
elabUp cn fs = let args = map (uncurry asPRefArg) [(p, n) | (n, _, p, _, _, _) <- fs]
elab = \(n, n', p, t, doc, i) -> elabUpdate info n n' p t doc rsyn fc target cn args fieldNames i (optionalSetter n)
in mapM_ elab fs
-- | Decides whether a setter should be generated for a field or not.
optionalSetter :: Name -> Bool
optionalSetter n = n `elem` dependedOn
-- | A map from a field name to the other fields it depends on.
fieldDependencies :: [(Name, [Name])]
fieldDependencies = map (uncurry fieldDep) [(n, t) | (n, _, _, t, _) <- fields ++ params]
where
fieldDep :: Name -> PTerm -> (Name, [Name])
fieldDep n t = ((nsroot n), paramNames ++ fieldNames `intersect` allNamesIn t)
-- | A list of fields depending on another field.
dependentFields :: [Name]
dependentFields = filter depends fieldNames
where
depends :: Name -> Bool
depends n = case lookup n fieldDependencies of
Just xs -> not $ null xs
Nothing -> False
-- | A list of fields depended on by other fields.
dependedOn :: [Name]
dependedOn = concat ((catMaybes (map (\x -> lookup x fieldDependencies) fieldNames)))
-- | Creates and elaborates a projection function.
elabProjection :: ElabInfo
-> Name -- ^ Name of the argument in the constructor
-> Name -- ^ Projection Name
-> Plicity -- ^ Projection Plicity
-> PTerm -- ^ Projection Type
-> (Docstring (Either Err PTerm)) -- ^ Projection Documentation
-> SyntaxInfo -- ^ Projection SyntaxInfo
-> FC -> PTerm -- ^ Projection target type
-> Name -- ^ Data constructor tame
-> [PArg] -- ^ Placeholder Arguments to constructor
-> [Name] -- ^ All Field Names
-> Int -- ^ Argument Index
-> Idris ()
elabProjection info cname pname plicity projTy pdoc psyn fc targetTy cn phArgs fnames index
= do logElab 1 $ "Generating Projection for " ++ show pname
let ty = generateTy
logElab 1 $ "Type of " ++ show pname ++ ": " ++ show ty
let lhs = generateLhs
logElab 1 $ "LHS of " ++ show pname ++ ": " ++ showTmImpls lhs
let rhs = generateRhs
logElab 1 $ "RHS of " ++ show pname ++ ": " ++ showTmImpls rhs
rec_elabDecl info EAll info ty
let clause = PClause fc pname lhs [] rhs []
rec_elabDecl info EAll info $ PClauses fc [] pname [clause]
where
-- | The type of the projection function.
generateTy :: PDecl
generateTy = PTy pdoc [] psyn fc [] pname NoFC $
PPi expl recName NoFC targetTy projTy
-- | The left hand side of the projection function.
generateLhs :: PTerm
generateLhs = let args = lhsArgs index phArgs
in PApp fc (PRef fc [] pname) [pexp (PApp fc (PRef fc [] cn) args)]
where
lhsArgs :: Int -> [PArg] -> [PArg]
lhsArgs 0 (_ : rest) = (asArg plicity (nsroot cname) (PRef fc [] pname_in)) : rest
lhsArgs i (x : rest) = x : (lhsArgs (i-1) rest)
lhsArgs _ [] = []
-- | The "_in" name. Used for the lhs.
pname_in :: Name
pname_in = rootname -- in_name rootname
rootname :: Name
rootname = nsroot cname
-- | The right hand side of the projection function.
generateRhs :: PTerm
generateRhs = PRef fc [] pname_in
-- | Creates and elaborates an update function.
-- If 'optional' is true, we will not fail if we can't elaborate the update function.
elabUpdate :: ElabInfo
-> Name -- ^ Name of the argument in the constructor
-> Name -- ^ Field Name
-> Plicity -- ^ Field Plicity
-> PTerm -- ^ Field Type
-> (Docstring (Either Err PTerm)) -- ^ Field Documentation
-> SyntaxInfo -- ^ Field SyntaxInfo
-> FC -> PTerm -- ^ Projection Source Type
-> Name -- ^ Data Constructor Name
-> [PArg] -- ^ Arguments to constructor
-> [Name] -- ^ All fields
-> Int -- ^ Argument Index
-> Bool -- ^ Optional
-> Idris ()
elabUpdate info cname pname plicity pty pdoc psyn fc sty cn args fnames i optional
= do logElab 1 $ "Generating Update for " ++ show pname
let ty = generateTy
logElab 1 $ "Type of " ++ show set_pname ++ ": " ++ show ty
let lhs = generateLhs
logElab 1 $ "LHS of " ++ show set_pname ++ ": " ++ showTmImpls lhs
let rhs = generateRhs
logElab 1 $ "RHS of " ++ show set_pname ++ ": " ++ showTmImpls rhs
let clause = PClause fc set_pname lhs [] rhs []
idrisCatch (do rec_elabDecl info EAll info ty
rec_elabDecl info EAll info $ PClauses fc [] set_pname [clause])
(\err -> logElab 1 $ "Could not generate update function for " ++ show pname)
{-if optional
then logElab 1 $ "Could not generate update function for " ++ show pname
else tclift $ tfail $ At fc (Elaborating "record update function " pname err)) -}
where
-- | The type of the update function.
generateTy :: PDecl
generateTy = PTy pdoc [] psyn fc [] set_pname NoFC $
PPi expl (nsroot pname) NoFC pty $
PPi expl recName NoFC sty (substInput sty)
where substInput = substMatches [(cname, PRef fc [] (nsroot pname))]
-- | The "_set" name.
set_pname :: Name
set_pname = set_name pname
set_name :: Name -> Name
set_name (UN n) = sUN ("set_" ++ str n)
set_name (MN i n) = sMN i ("set_" ++ str n)
set_name (NS n s) = NS (set_name n) s
set_name n = n
-- | The left-hand side of the update function.
generateLhs :: PTerm
generateLhs = PApp fc (PRef fc [] set_pname) [pexp $ PRef fc [] pname_in, pexp constructorPattern]
where
constructorPattern :: PTerm
constructorPattern = PApp fc (PRef fc [] cn) args
-- | The "_in" name.
pname_in :: Name
pname_in = in_name rootname
rootname :: Name
rootname = nsroot pname
-- | The right-hand side of the update function.
generateRhs :: PTerm
generateRhs = PApp fc (PRef fc [] cn) (newArgs i args)
where
newArgs :: Int -> [PArg] -> [PArg]
newArgs 0 (_ : rest) = (asArg plicity (nsroot cname) (PRef fc [] pname_in)) : rest
newArgs i (x : rest) = x : (newArgs (i-1) rest)
newArgs _ [] = []
-- | Post-fixes a name with "_in".
in_name :: Name -> Name
in_name (UN n) = sMN 0 (str n ++ "_in")
in_name (MN i n) = sMN i (str n ++ "_in")
in_name (NS n s) = NS (in_name n) s
in_name n = n
-- | Creates a PArg with a given plicity, name, and term.
asArg :: Plicity -> Name -> PTerm -> PArg
asArg (Imp os _ _ _) n t = PImp 0 False os n t
asArg (Exp os _ _) n t = PExp 0 os n t
asArg (Constraint os _) n t = PConstraint 0 os n t
asArg (TacImp os _ s) n t = PTacImplicit 0 os n s t
-- | Machine name "rec".
recName :: Name
recName = sMN 0 "rec"
recRef = PRef emptyFC [] recName
projectInType :: [(Name, Name)] -> PTerm -> PTerm
projectInType xs = mapPT st
where
st :: PTerm -> PTerm
st (PRef fc hls n)
| Just pn <- lookup n xs = PApp fc (PRef fc hls pn) [pexp recRef]
st t = t
-- | Creates an PArg from a plicity and a name where the term is a PRef.
asPRefArg :: Plicity -> Name -> PArg
asPRefArg p n = asArg p (nsroot n) $ PRef emptyFC [] (nsroot n)
| aaronc/Idris-dev | src/Idris/Elab/Record.hs | bsd-3-clause | 20,611 | 437 | 22 | 6,180 | 6,332 | 3,445 | 2,887 | 322 | 14 |
-----------------------------------------------------------------------------
-- |
-- License : BSD-3-Clause
-- Maintainer : Oleg Grenrus <[email protected]>
--
-- The Github Repo Contents API, as documented at
-- <https://developer.github.com/v3/repos/contents/>
module GitHub.Endpoints.Repos.Contents (
-- * Querying contents
contentsForR,
readmeForR,
archiveForR,
-- ** Create
createFileR,
-- ** Update
updateFileR,
-- ** Delete
deleteFileR,
module GitHub.Data
) where
import GitHub.Data
import GitHub.Internal.Prelude
import Prelude ()
import Data.Maybe (maybeToList)
import qualified Data.Text.Encoding as TE
import Network.URI (URI)
contentsForR
:: Name Owner
-> Name Repo
-> Text -- ^ file or directory
-> Maybe Text -- ^ Git commit
-> Request k Content
contentsForR user repo path ref =
query ["repos", toPathPart user, toPathPart repo, "contents", path] qs
where
qs = maybe [] (\r -> [("ref", Just . TE.encodeUtf8 $ r)]) ref
readmeForR :: Name Owner -> Name Repo -> Request k Content
readmeForR user repo =
query ["repos", toPathPart user, toPathPart repo, "readme"] []
-- | Get archive link.
-- See <https://developer.github.com/v3/repos/contents/#get-archive-link>
archiveForR
:: Name Owner
-> Name Repo
-> ArchiveFormat -- ^ The type of archive to retrieve
-> Maybe Text -- ^ Git commit
-> GenRequest 'MtRedirect rw URI
archiveForR user repo format ref = Query path []
where
path = ["repos", toPathPart user, toPathPart repo, toPathPart format] <> maybeToList ref
-- | Create a file.
-- See <https://developer.github.com/v3/repos/contents/#create-a-file>
createFileR
:: Name Owner
-> Name Repo
-> CreateFile
-> Request 'RW ContentResult
createFileR user repo body =
command Put ["repos", toPathPart user, toPathPart repo, "contents", createFilePath body] (encode body)
-- | Update a file.
-- See <https://developer.github.com/v3/repos/contents/#update-a-file>
updateFileR
:: Name Owner
-> Name Repo
-> UpdateFile
-> Request 'RW ContentResult
updateFileR user repo body =
command Put ["repos", toPathPart user, toPathPart repo, "contents", updateFilePath body] (encode body)
-- | Delete a file.
-- See <https://developer.github.com/v3/repos/contents/#delete-a-file>
deleteFileR
:: Name Owner
-> Name Repo
-> DeleteFile
-> GenRequest 'MtUnit 'RW ()
deleteFileR user repo body =
Command Delete ["repos", toPathPart user, toPathPart repo, "contents", deleteFilePath body] (encode body)
| jwiegley/github | src/GitHub/Endpoints/Repos/Contents.hs | bsd-3-clause | 2,607 | 0 | 14 | 531 | 618 | 332 | 286 | -1 | -1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE StandaloneDeriving #-}
-----------------------------------------------------------------------------
-- |
-- Module : DieHard
-- Copyright : (C) 2017, ATS Advanced Telematic Systems GmbH
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer : Stevan Andjelkovic <[email protected]>
-- Stability : provisional
-- Portability : non-portable (GHC extensions)
--
-- This module contains a solution to the water jug puzzle featured in
-- /Die Hard 3/.
--
-----------------------------------------------------------------------------
module DieHard
( Command(..)
, Model(..)
, initModel
, transitions
, prop_dieHard
) where
import Data.Kind
(Type)
import GHC.Generics
(Generic, Generic1)
import Prelude
import Test.QuickCheck
(Gen, Property, oneof, (===))
import Test.QuickCheck.Monadic
(monadicIO)
import Test.StateMachine
import qualified Test.StateMachine.Types.Rank2 as Rank2
------------------------------------------------------------------------
-- The problem is to measure exactly 4 liters of water given a 3- and
-- 5-liter jug.
-- We start of defining the different actions that are allowed:
data Command (r :: Type -> Type)
= FillBig -- Fill the 5-liter jug.
| FillSmall -- Fill the 3-liter jug.
| EmptyBig -- Empty the 5-liter jug.
| EmptySmall
| SmallIntoBig -- Pour the contents of the 3-liter jug
-- into 5-liter jug.
| BigIntoSmall
deriving stock (Eq, Show, Generic1)
deriving anyclass (Rank2.Functor, Rank2.Foldable, Rank2.Traversable, CommandNames)
data Response (r :: Type -> Type) = Done
deriving stock (Show, Generic1)
deriving anyclass (Rank2.Foldable)
------------------------------------------------------------------------
-- The model (or state) keeps track of what amount of water is in the
-- two jugs.
data Model (r :: Type -> Type) = Model
{ bigJug :: Int
, smallJug :: Int
} deriving stock (Show, Eq, Generic)
deriving anyclass instance ToExpr (Model Concrete)
initModel :: Model r
initModel = Model 0 0
------------------------------------------------------------------------
-- There are no pre-conditions for our actions. That simply means that
-- any action can happen at any state.
preconditions :: Model Symbolic -> Command Symbolic -> Logic
preconditions _ _ = Top
-- The transitions describe how the actions change the state.
transitions :: Model r -> Command r -> Response r -> Model r
transitions m FillBig _ = m { bigJug = 5 }
transitions m FillSmall _ = m { smallJug = 3 }
transitions m EmptyBig _ = m { bigJug = 0 }
transitions m EmptySmall _ = m { smallJug = 0 }
transitions (Model big small) SmallIntoBig _ =
let big' = min 5 (big + small) in
Model { bigJug = big'
, smallJug = small - (big' - big) }
transitions (Model big small) BigIntoSmall _ =
let small' = min 3 (big + small) in
Model { bigJug = big - (small' - small)
, smallJug = small'
}
-- The post-condition is used in a bit of a funny way. Recall that we
-- want to find a series of actions that leads to the big jug containing
-- 4 liters. So the idea is to state an invariant saying that the big
-- jug is NOT equal to 4 after we performed any action. If we happen to
-- find a series of actions where this is not true, i.e. the big jug
-- actually does contain 4 liters, then a minimal counter example will
-- be presented -- this will be our solution.
postconditions :: Model Concrete -> Command Concrete -> Response Concrete -> Logic
postconditions s c r = bigJug (transitions s c r) ./= 4
------------------------------------------------------------------------
-- The generator of actions is simple, with equal distribution pick an
-- action.
generator :: Model Symbolic -> Maybe (Gen (Command Symbolic))
generator _ = Just $ oneof
[ return FillBig
, return FillSmall
, return EmptyBig
, return EmptySmall
, return SmallIntoBig
, return BigIntoSmall
]
-- There's nothing to shrink.
shrinker :: Model r -> Command r -> [Command r]
shrinker _ _ = []
------------------------------------------------------------------------
-- We are not modelling an actual program here, so there's no semantics
-- for our actions. We are merely doing model checking.
semantics :: Command Concrete -> IO (Response Concrete)
semantics _ = return Done
mock :: Model Symbolic -> Command Symbolic -> GenSym (Response Symbolic)
mock _ _ = return Done
------------------------------------------------------------------------
-- Finally we have all the pieces needed to get the sequential property!
-- To make the code fit on a line, we first group all things related to
-- generation and execution of programs respectively.
sm :: StateMachine Model Command IO Response
sm = StateMachine initModel transitions preconditions postconditions
Nothing generator shrinker semantics mock noCleanup
prop_dieHard :: Property
prop_dieHard = forAllCommands sm Nothing $ \cmds -> monadicIO $ do
(hist, _model, res) <- runCommands sm cmds
prettyCommands sm hist (checkCommandNames cmds (res === Ok))
-- If we run @quickCheck prop_dieHard@ we get:
--
-- @
-- *** Failed! Falsifiable (after 43 tests and 4 shrinks):
-- Commands
-- { unCommands =
-- [ Command FillBig (fromList [])
-- , Command BigIntoSmall (fromList [])
-- , Command EmptySmall (fromList [])
-- , Command BigIntoSmall (fromList [])
-- , Command FillBig (fromList [])
-- , Command BigIntoSmall (fromList [])
-- ]
-- }
--
-- Model {bigJug = 0,smallJug = 0}
--
-- == FillBig ==> Done [ 0 ]
--
-- Model {bigJug = -0 +5
-- ,smallJug = 0}
--
-- == BigIntoSmall ==> Done [ 0 ]
--
-- Model {bigJug = -5 +2
-- ,smallJug = -0 +3}
--
-- == EmptySmall ==> Done [ 0 ]
--
-- Model {bigJug = 2
-- ,smallJug = -3 +0}
--
-- == BigIntoSmall ==> Done [ 0 ]
--
-- Model {bigJug = -2 +0
-- ,smallJug = -0 +2}
--
-- == FillBig ==> Done [ 0 ]
--
-- Model {bigJug = -0 +5
-- ,smallJug = 2}
--
-- == BigIntoSmall ==> Done [ 0 ]
--
-- Model {bigJug = -5 +4
-- ,smallJug = -2 +3}
--
-- PostconditionFailed "PredicateC (4 :== 4)" /= Ok
-- @
--
-- The counterexample is our solution.
| advancedtelematic/quickcheck-state-machine-model | test/DieHard.hs | bsd-3-clause | 6,644 | 0 | 14 | 1,508 | 1,042 | 606 | 436 | 82 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_HADDOCK show-extensions #-}
-- |
-- Module : Yi.Keymap.Vim.VisualMap
-- License : GPL-2
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- I'm a module waiting for some kind soul to give me a commentary!
module Yi.Keymap.Vim.VisualMap ( defVisualMap ) where
import Control.Applicative ((<$), (<$>))
import Control.Lens ((.=))
import Control.Monad (forM_, void)
import Data.Char (ord)
import Data.List (group)
import Data.Maybe (fromJust)
import qualified Data.Text as T (unpack)
import Yi.Buffer.Adjusted hiding (Insert)
import Yi.Editor
import Yi.Keymap.Vim.Common
import Yi.Keymap.Vim.Operator (VimOperator (..), opDelete, stringToOperator)
import Yi.Keymap.Vim.StateUtils
import Yi.Keymap.Vim.StyledRegion (StyledRegion (StyledRegion), transformCharactersInRegionB)
import Yi.Keymap.Vim.Tag (gotoTag)
import Yi.Keymap.Vim.Utils (matchFromBool, mkChooseRegisterBinding, mkMotionBinding)
import Yi.MiniBuffer (spawnMinibufferE)
import Yi.Monad (whenM)
import qualified Yi.Rope as R (toText)
import Yi.Tag (Tag (Tag))
import Yi.Utils (SemiNum ((-~)))
defVisualMap :: [VimOperator] -> [VimBinding]
defVisualMap operators =
[escBinding, motionBinding, changeVisualStyleBinding, setMarkBinding]
++ [chooseRegisterBinding]
++ operatorBindings operators ++ digitBindings ++ [replaceBinding, switchEdgeBinding]
++ [insertBinding, exBinding, shiftDBinding]
++ [tagJumpBinding]
escAction :: EditorM RepeatToken
escAction = do
resetCountE
clrStatus
withCurrentBuffer $ do
setVisibleSelection False
putRegionStyle Inclusive
switchModeE Normal
return Drop
escBinding :: VimBinding
escBinding = VimBindingE f
where f evs (VimState { vsMode = (Visual _) }) = escAction <$
matchFromBool (evs `elem` ["<Esc>", "<C-c>"])
f _ _ = NoMatch
exBinding :: VimBinding
exBinding = VimBindingE f
where f ":" (VimState { vsMode = (Visual _) }) = WholeMatch $ do
void $ spawnMinibufferE ":" id
withCurrentBuffer $ writeN "'<,'>"
switchModeE Ex
return Finish
f _ _ = NoMatch
digitBindings :: [VimBinding]
digitBindings = zeroBinding : fmap mkDigitBinding ['1' .. '9']
zeroBinding :: VimBinding
zeroBinding = VimBindingE f
where f "0" (VimState { vsMode = (Visual _) }) = WholeMatch $ do
currentState <- getEditorDyn
case vsCount currentState of
Just c -> do
setCountE (10 * c)
return Continue
Nothing -> do
withCurrentBuffer moveToSol
resetCountE
setStickyEolE False
return Continue
f _ _ = NoMatch
setMarkBinding :: VimBinding
setMarkBinding = VimBindingE (f . T.unpack . _unEv)
where f "m" (VimState { vsMode = (Visual _) }) = PartialMatch
f ('m':c:[]) (VimState { vsMode = (Visual _) }) = WholeMatch $ do
withCurrentBuffer $ setNamedMarkHereB [c]
return Continue
f _ _ = NoMatch
changeVisualStyleBinding :: VimBinding
changeVisualStyleBinding = VimBindingE f
where f evs (VimState { vsMode = (Visual _) })
| evs `elem` ["v", "V", "<C-v>"]
= WholeMatch $ do
currentMode <- fmap vsMode getEditorDyn
let newStyle = case evs of
"v" -> Inclusive
"V" -> LineWise
"<C-v>" -> Block
_ -> error "Just silencing false positive warning."
newMode = Visual newStyle
if newMode == currentMode
then escAction
else do
modifyStateE $ \s -> s { vsMode = newMode }
withCurrentBuffer $ do
putRegionStyle newStyle
rectangleSelectionA .= (Block == newStyle)
setVisibleSelection True
return Finish
f _ _ = NoMatch
mkDigitBinding :: Char -> VimBinding
mkDigitBinding c = VimBindingE (f . T.unpack . _unEv)
where f [c'] (VimState { vsMode = (Visual _) }) | c == c'
= WholeMatch $ do
modifyStateE mutate
return Continue
f _ _ = NoMatch
mutate vs@(VimState {vsCount = Nothing}) = vs { vsCount = Just d }
mutate vs@(VimState {vsCount = Just count}) = vs { vsCount = Just $ count * 10 + d }
d = ord c - ord '0'
motionBinding :: VimBinding
motionBinding = mkMotionBinding Continue $
\m -> case m of
Visual _ -> True
_ -> False
regionOfSelectionB :: BufferM Region
regionOfSelectionB = savingPointB $ do
start <- getSelectionMarkPointB
stop <- pointB
return $! mkRegion start stop
operatorBindings :: [VimOperator] -> [VimBinding]
operatorBindings operators = fmap mkOperatorBinding $ operators ++ visualOperators
where visualOperators = fmap synonymOp
[ ("x", "d")
, ("s", "c")
, ("S", "c")
, ("C", "c")
, ("~", "g~")
, ("Y", "y")
, ("u", "gu")
, ("U", "gU")
]
synonymOp (newName, existingName) =
VimOperator newName . operatorApplyToRegionE . fromJust
. stringToOperator operators $ existingName
chooseRegisterBinding :: VimBinding
chooseRegisterBinding = mkChooseRegisterBinding $
\s -> case s of
(VimState { vsMode = (Visual _) }) -> True
_ -> False
shiftDBinding :: VimBinding
shiftDBinding = VimBindingE (f . T.unpack . _unEv)
where f "D" (VimState { vsMode = (Visual _) }) = WholeMatch $ do
(Visual style) <- vsMode <$> getEditorDyn
reg <- withCurrentBuffer regionOfSelectionB
case style of
Block -> withCurrentBuffer $ do
(start, lengths) <- shapeOfBlockRegionB reg
moveTo start
startCol <- curCol
forM_ (reverse [0 .. length lengths - 1]) $ \l -> do
moveTo start
void $ lineMoveRel l
whenM (fmap (== startCol) curCol) deleteToEol
leftOnEol
_ -> do
reg' <- withCurrentBuffer $ convertRegionToStyleB reg LineWise
reg'' <- withCurrentBuffer $ mkRegionOfStyleB (regionStart reg')
(regionEnd reg' -~ Size 1)
Exclusive
void $ operatorApplyToRegionE opDelete 1 $ StyledRegion LineWise reg''
resetCountE
switchModeE Normal
return Finish
f _ _ = NoMatch
mkOperatorBinding :: VimOperator -> VimBinding
mkOperatorBinding op = VimBindingE f
where
f evs (VimState { vsMode = (Visual _) }) =
action <$ evs `matchesString` Ev (_unOp $ operatorName op)
f _ _ = NoMatch
action = do
(Visual style) <- vsMode <$> getEditorDyn
region <- withCurrentBuffer regionOfSelectionB
count <- getCountE
token <- operatorApplyToRegionE op count $ StyledRegion style region
resetCountE
clrStatus
withCurrentBuffer $ do
setVisibleSelection False
putRegionStyle Inclusive
return token
replaceBinding :: VimBinding
replaceBinding = VimBindingE (f . T.unpack . _unEv)
where f evs (VimState { vsMode = (Visual _) }) =
case evs of
"r" -> PartialMatch
('r':c:[]) -> WholeMatch $ do
(Visual style) <- vsMode <$> getEditorDyn
region <- withCurrentBuffer regionOfSelectionB
withCurrentBuffer $ transformCharactersInRegionB (StyledRegion style region)
(\x -> if x == '\n' then x else c)
switchModeE Normal
return Finish
_ -> NoMatch
f _ _ = NoMatch
switchEdgeBinding :: VimBinding
switchEdgeBinding = VimBindingE (f . T.unpack . _unEv)
where f [c] (VimState { vsMode = (Visual _) }) | c `elem` ['o', 'O']
= WholeMatch $ do
(Visual style) <- vsMode <$> getEditorDyn
withCurrentBuffer $ do
here <- pointB
there <- getSelectionMarkPointB
(here', there') <- case (c, style) of
('O', Block) -> flipRectangleB here there
(_, _) -> return (there, here)
moveTo here'
setSelectionMarkPointB there'
return Continue
f _ _ = NoMatch
insertBinding :: VimBinding
insertBinding = VimBindingE (f . T.unpack . _unEv)
where f evs (VimState { vsMode = (Visual _) }) | evs `elem` group "IA"
= WholeMatch $ do
(Visual style) <- vsMode <$> getEditorDyn
region <- withCurrentBuffer regionOfSelectionB
cursors <- withCurrentBuffer $ case evs of
"I" -> leftEdgesOfRegionB style region
"A" -> rightEdgesOfRegionB style region
_ -> error "Just silencing ghc's false positive warning."
case cursors of
(mainCursor : _) -> withCurrentBuffer (moveTo mainCursor)
modifyStateE $ \s -> s { vsSecondaryCursors = drop 1 cursors }
switchModeE $ Insert (head evs)
return Continue
f _ _ = NoMatch
tagJumpBinding :: VimBinding
tagJumpBinding = VimBindingY (f . T.unpack . _unEv)
where f "<C-]>" (VimState { vsMode = (Visual _) })
= WholeMatch $ do
tag <- Tag . R.toText <$> withCurrentBuffer
(regionOfSelectionB >>= readRegionB)
withEditor $ switchModeE Normal
gotoTag tag 0 Nothing
return Finish
f _ _ = NoMatch
| TOSPIO/yi | src/library/Yi/Keymap/Vim/VisualMap.hs | gpl-2.0 | 11,009 | 0 | 23 | 4,369 | 2,793 | 1,441 | 1,352 | 232 | 6 |
{-# 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.AutoScaling.UpdateAutoScalingGroup
-- 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.
-- | Updates the configuration for the specified 'AutoScalingGroup'.
--
-- To update an Auto Scaling group with a launch configuration that has the 'InstanceMonitoring' flag set to 'False', you must first ensure that collection of group metrics is
-- disabled. Otherwise, calls to 'UpdateAutoScalingGroup' will fail. If you have
-- previously enabled group metrics collection, you can disable collection of
-- all group metrics by calling 'DisableMetricsCollection'.
--
-- The new settings are registered upon the completion of this call. Any
-- launch configuration settings take effect on any triggers after this call
-- returns. Scaling activities that are currently in progress aren't affected.
--
-- If a new value is specified for /MinSize/ without specifying the value for /DesiredCapacity/, and if the new /MinSize/ is larger than the current size of the Auto Scaling
-- group, there will be an implicit call to 'SetDesiredCapacity' to set the group
-- to the new /MinSize/.
--
-- If a new value is specified for /MaxSize/ without specifying the value for /DesiredCapacity/, and the new /MaxSize/ is smaller than the current size of the Auto Scaling
-- group, there will be an implicit call to 'SetDesiredCapacity' to set the group
-- to the new /MaxSize/.
--
-- All other optional parameters are left unchanged if not passed in the
-- request.
--
--
--
-- <http://docs.aws.amazon.com/AutoScaling/latest/APIReference/API_UpdateAutoScalingGroup.html>
module Network.AWS.AutoScaling.UpdateAutoScalingGroup
(
-- * Request
UpdateAutoScalingGroup
-- ** Request constructor
, updateAutoScalingGroup
-- ** Request lenses
, uasgAutoScalingGroupName
, uasgAvailabilityZones
, uasgDefaultCooldown
, uasgDesiredCapacity
, uasgHealthCheckGracePeriod
, uasgHealthCheckType
, uasgLaunchConfigurationName
, uasgMaxSize
, uasgMinSize
, uasgPlacementGroup
, uasgTerminationPolicies
, uasgVPCZoneIdentifier
-- * Response
, UpdateAutoScalingGroupResponse
-- ** Response constructor
, updateAutoScalingGroupResponse
) where
import Network.AWS.Prelude
import Network.AWS.Request.Query
import Network.AWS.AutoScaling.Types
import qualified GHC.Exts
data UpdateAutoScalingGroup = UpdateAutoScalingGroup
{ _uasgAutoScalingGroupName :: Text
, _uasgAvailabilityZones :: List1 "member" Text
, _uasgDefaultCooldown :: Maybe Int
, _uasgDesiredCapacity :: Maybe Int
, _uasgHealthCheckGracePeriod :: Maybe Int
, _uasgHealthCheckType :: Maybe Text
, _uasgLaunchConfigurationName :: Maybe Text
, _uasgMaxSize :: Maybe Int
, _uasgMinSize :: Maybe Int
, _uasgPlacementGroup :: Maybe Text
, _uasgTerminationPolicies :: List "member" Text
, _uasgVPCZoneIdentifier :: Maybe Text
} deriving (Eq, Ord, Read, Show)
-- | 'UpdateAutoScalingGroup' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'uasgAutoScalingGroupName' @::@ 'Text'
--
-- * 'uasgAvailabilityZones' @::@ 'NonEmpty' 'Text'
--
-- * 'uasgDefaultCooldown' @::@ 'Maybe' 'Int'
--
-- * 'uasgDesiredCapacity' @::@ 'Maybe' 'Int'
--
-- * 'uasgHealthCheckGracePeriod' @::@ 'Maybe' 'Int'
--
-- * 'uasgHealthCheckType' @::@ 'Maybe' 'Text'
--
-- * 'uasgLaunchConfigurationName' @::@ 'Maybe' 'Text'
--
-- * 'uasgMaxSize' @::@ 'Maybe' 'Int'
--
-- * 'uasgMinSize' @::@ 'Maybe' 'Int'
--
-- * 'uasgPlacementGroup' @::@ 'Maybe' 'Text'
--
-- * 'uasgTerminationPolicies' @::@ ['Text']
--
-- * 'uasgVPCZoneIdentifier' @::@ 'Maybe' 'Text'
--
updateAutoScalingGroup :: Text -- ^ 'uasgAutoScalingGroupName'
-> NonEmpty Text -- ^ 'uasgAvailabilityZones'
-> UpdateAutoScalingGroup
updateAutoScalingGroup p1 p2 = UpdateAutoScalingGroup
{ _uasgAutoScalingGroupName = p1
, _uasgAvailabilityZones = withIso _List1 (const id) p2
, _uasgLaunchConfigurationName = Nothing
, _uasgMinSize = Nothing
, _uasgMaxSize = Nothing
, _uasgDesiredCapacity = Nothing
, _uasgDefaultCooldown = Nothing
, _uasgHealthCheckType = Nothing
, _uasgHealthCheckGracePeriod = Nothing
, _uasgPlacementGroup = Nothing
, _uasgVPCZoneIdentifier = Nothing
, _uasgTerminationPolicies = mempty
}
-- | The name of the Auto Scaling group.
uasgAutoScalingGroupName :: Lens' UpdateAutoScalingGroup Text
uasgAutoScalingGroupName =
lens _uasgAutoScalingGroupName
(\s a -> s { _uasgAutoScalingGroupName = a })
-- | One or more Availability Zones for the group.
uasgAvailabilityZones :: Lens' UpdateAutoScalingGroup (NonEmpty Text)
uasgAvailabilityZones =
lens _uasgAvailabilityZones (\s a -> s { _uasgAvailabilityZones = a })
. _List1
-- | The amount of time, in seconds, after a scaling activity completes before
-- another scaling activity can start. For more information, see <http://docs.aws.amazon.com/AutoScaling/latest/DeveloperGuide/Cooldown.html UnderstandingAuto Scaling Cooldowns>.
uasgDefaultCooldown :: Lens' UpdateAutoScalingGroup (Maybe Int)
uasgDefaultCooldown =
lens _uasgDefaultCooldown (\s a -> s { _uasgDefaultCooldown = a })
-- | The number of EC2 instances that should be running in the Auto Scaling group.
-- This value must be greater than or equal to the minimum size of the group and
-- less than or equal to the maximum size of the group.
uasgDesiredCapacity :: Lens' UpdateAutoScalingGroup (Maybe Int)
uasgDesiredCapacity =
lens _uasgDesiredCapacity (\s a -> s { _uasgDesiredCapacity = a })
-- | The amount of time, in second, that Auto Scaling waits before checking the
-- health status of an instance. The grace period begins when the instance
-- passes System Status and the Instance Status checks from Amazon EC2. For more
-- information, see <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeInstanceStatus.html DescribeInstanceStatus>.
uasgHealthCheckGracePeriod :: Lens' UpdateAutoScalingGroup (Maybe Int)
uasgHealthCheckGracePeriod =
lens _uasgHealthCheckGracePeriod
(\s a -> s { _uasgHealthCheckGracePeriod = a })
-- | The type of health check for the instances in the Auto Scaling group. The
-- health check type can either be 'EC2' for Amazon EC2 or 'ELB' for Elastic Load
-- Balancing.
uasgHealthCheckType :: Lens' UpdateAutoScalingGroup (Maybe Text)
uasgHealthCheckType =
lens _uasgHealthCheckType (\s a -> s { _uasgHealthCheckType = a })
-- | The name of the launch configuration.
uasgLaunchConfigurationName :: Lens' UpdateAutoScalingGroup (Maybe Text)
uasgLaunchConfigurationName =
lens _uasgLaunchConfigurationName
(\s a -> s { _uasgLaunchConfigurationName = a })
-- | The maximum size of the Auto Scaling group.
uasgMaxSize :: Lens' UpdateAutoScalingGroup (Maybe Int)
uasgMaxSize = lens _uasgMaxSize (\s a -> s { _uasgMaxSize = a })
-- | The minimum size of the Auto Scaling group.
uasgMinSize :: Lens' UpdateAutoScalingGroup (Maybe Int)
uasgMinSize = lens _uasgMinSize (\s a -> s { _uasgMinSize = a })
-- | The name of the placement group into which you'll launch your instances, if
-- any. For more information, see <http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/placement-groups.html Placement Groups>.
uasgPlacementGroup :: Lens' UpdateAutoScalingGroup (Maybe Text)
uasgPlacementGroup =
lens _uasgPlacementGroup (\s a -> s { _uasgPlacementGroup = a })
-- | A standalone termination policy or a list of termination policies used to
-- select the instance to terminate. The policies are executed in the order that
-- they are listed.
--
-- For more information, see <http://docs.aws.amazon.com/AutoScaling/latest/DeveloperGuide/us-termination-policy.html Choosing a Termination Policy for Your AutoScaling Group> in the /Auto Scaling Developer Guide/.
uasgTerminationPolicies :: Lens' UpdateAutoScalingGroup [Text]
uasgTerminationPolicies =
lens _uasgTerminationPolicies (\s a -> s { _uasgTerminationPolicies = a })
. _List
-- | The subnet identifier for the Amazon VPC connection, if applicable. You can
-- specify several subnets in a comma-separated list.
--
-- When you specify 'VPCZoneIdentifier' with 'AvailabilityZones', ensure that the
-- subnets' Availability Zones match the values you specify for 'AvailabilityZones'
-- .
--
-- For more information, see <http://docs.aws.amazon.com/AutoScaling/latest/DeveloperGuide/autoscalingsubnets.html Auto Scaling and Amazon VPC> in the /Auto ScalingDeveloper Guide/.
uasgVPCZoneIdentifier :: Lens' UpdateAutoScalingGroup (Maybe Text)
uasgVPCZoneIdentifier =
lens _uasgVPCZoneIdentifier (\s a -> s { _uasgVPCZoneIdentifier = a })
data UpdateAutoScalingGroupResponse = UpdateAutoScalingGroupResponse
deriving (Eq, Ord, Read, Show, Generic)
-- | 'UpdateAutoScalingGroupResponse' constructor.
updateAutoScalingGroupResponse :: UpdateAutoScalingGroupResponse
updateAutoScalingGroupResponse = UpdateAutoScalingGroupResponse
instance ToPath UpdateAutoScalingGroup where
toPath = const "/"
instance ToQuery UpdateAutoScalingGroup where
toQuery UpdateAutoScalingGroup{..} = mconcat
[ "AutoScalingGroupName" =? _uasgAutoScalingGroupName
, "AvailabilityZones" =? _uasgAvailabilityZones
, "DefaultCooldown" =? _uasgDefaultCooldown
, "DesiredCapacity" =? _uasgDesiredCapacity
, "HealthCheckGracePeriod" =? _uasgHealthCheckGracePeriod
, "HealthCheckType" =? _uasgHealthCheckType
, "LaunchConfigurationName" =? _uasgLaunchConfigurationName
, "MaxSize" =? _uasgMaxSize
, "MinSize" =? _uasgMinSize
, "PlacementGroup" =? _uasgPlacementGroup
, "TerminationPolicies" =? _uasgTerminationPolicies
, "VPCZoneIdentifier" =? _uasgVPCZoneIdentifier
]
instance ToHeaders UpdateAutoScalingGroup
instance AWSRequest UpdateAutoScalingGroup where
type Sv UpdateAutoScalingGroup = AutoScaling
type Rs UpdateAutoScalingGroup = UpdateAutoScalingGroupResponse
request = post "UpdateAutoScalingGroup"
response = nullResponse UpdateAutoScalingGroupResponse
| romanb/amazonka | amazonka-autoscaling/gen/Network/AWS/AutoScaling/UpdateAutoScalingGroup.hs | mpl-2.0 | 11,333 | 0 | 10 | 2,229 | 1,189 | 718 | 471 | 127 | 1 |
{-# LANGUAGE NamedFieldPuns, RecordWildCards #-}
-- | The tar index cache provides generic support for caching a tarball's
-- TarIndex; this is used by various other modules.
module Distribution.Server.Features.TarIndexCache (
TarIndexCacheFeature(..)
, initTarIndexCacheFeature
) where
import Control.Exception (throwIO)
import Data.Serialize (runGetLazy, runPutLazy)
import Data.SafeCopy (safeGet, safePut)
import Distribution.Server.Framework
import Distribution.Server.Framework.BlobStorage
import Distribution.Server.Framework.BackupRestore
import Distribution.Server.Features.TarIndexCache.State
import Distribution.Server.Features.Users
import Distribution.Server.Packages.Types (PkgTarball(..))
import Data.TarIndex
import Distribution.Server.Util.ServeTarball (constructTarIndex)
import qualified Data.Map as Map
import Data.Aeson (toJSON)
data TarIndexCacheFeature = TarIndexCacheFeature {
tarIndexCacheFeatureInterface :: HackageFeature
, cachedTarIndex :: BlobId -> IO TarIndex
, cachedPackageTarIndex :: PkgTarball -> IO TarIndex
}
instance IsHackageFeature TarIndexCacheFeature where
getFeatureInterface = tarIndexCacheFeatureInterface
initTarIndexCacheFeature :: ServerEnv
-> IO (UserFeature
-> IO TarIndexCacheFeature)
initTarIndexCacheFeature env@ServerEnv{serverStateDir} = do
tarIndexCache <- tarIndexCacheStateComponent serverStateDir
return $ \users -> do
let feature = tarIndexCacheFeature env users tarIndexCache
return feature
tarIndexCacheStateComponent :: FilePath -> IO (StateComponent AcidState TarIndexCache)
tarIndexCacheStateComponent stateDir = do
st <- openLocalStateFrom (stateDir </> "db" </> "TarIndexCache") initialTarIndexCache
return StateComponent {
stateDesc = "Mapping from tarball blob IDs to tarindex blob IDs"
, stateHandle = st
, getState = query st GetTarIndexCache
, putState = update st . ReplaceTarIndexCache
, resetState = tarIndexCacheStateComponent
-- We don't backup the tar indices, but reconstruct them on demand
, backupState = \_ _ -> []
, restoreState = RestoreBackup {
restoreEntry = error "The impossible happened"
, restoreFinalize = return initialTarIndexCache
}
}
tarIndexCacheFeature :: ServerEnv
-> UserFeature
-> StateComponent AcidState TarIndexCache
-> TarIndexCacheFeature
tarIndexCacheFeature ServerEnv{serverBlobStore = store}
UserFeature{..}
tarIndexCache =
TarIndexCacheFeature{..}
where
tarIndexCacheFeatureInterface :: HackageFeature
tarIndexCacheFeatureInterface = (emptyHackageFeature "tarIndexCache") {
featureDesc = "Generic cache for tarball indices"
-- We don't want to compare blob IDs
-- (TODO: We could potentially check that if a package occurs in both
-- packages then both caches point to identical tar indices, but for
-- that we would need to be in IO)
, featureState = [abstractAcidStateComponent' (\_ _ -> []) tarIndexCache]
, featureResources = [
(resourceAt "/server-status/tarindices.:format") {
resourceDesc = [ (GET, "Which tar indices have been generated?")
, (DELETE, "Delete all tar indices (will be regenerated on the fly)")
]
, resourceGet = [ ("json", \_ -> serveTarIndicesStatus) ]
, resourceDelete = [ ("", \_ -> deleteTarIndices) ]
}
]
}
-- This is the heart of this feature
cachedTarIndex :: BlobId -> IO TarIndex
cachedTarIndex tarBallBlobId = do
mTarIndexBlobId <- queryState tarIndexCache (FindTarIndex tarBallBlobId)
case mTarIndexBlobId of
Just tarIndexBlobId -> do
serializedTarIndex <- fetch store tarIndexBlobId
case runGetLazy safeGet serializedTarIndex of
Left err -> throwIO (userError err)
Right tarIndex -> return tarIndex
Nothing -> do
tarBall <- fetch store tarBallBlobId
tarIndex <- case constructTarIndex tarBall of
Left err -> throwIO (userError err)
Right tarIndex -> return tarIndex
tarIndexBlobId <- add store (runPutLazy (safePut tarIndex))
updateState tarIndexCache (SetTarIndex tarBallBlobId tarIndexBlobId)
return tarIndex
cachedPackageTarIndex :: PkgTarball -> IO TarIndex
cachedPackageTarIndex = cachedTarIndex . pkgTarballNoGz
serveTarIndicesStatus :: ServerPartE Response
serveTarIndicesStatus = do
TarIndexCache state <- liftIO $ getState tarIndexCache
return . toResponse . toJSON . Map.toList $ state
-- | With curl:
--
-- > curl -X DELETE http://admin:admin@localhost:8080/server-status/tarindices
deleteTarIndices :: ServerPartE Response
deleteTarIndices = do
guardAuthorised_ [InGroup adminGroup]
-- TODO: This resets the tar indices _state_ only, we don't actually
-- remove any blobs
liftIO $ putState tarIndexCache initialTarIndexCache
ok $ toResponse "Ok!"
| haskell-infra/hackage-server | Distribution/Server/Features/TarIndexCache.hs | bsd-3-clause | 5,380 | 0 | 21 | 1,411 | 957 | 516 | 441 | 90 | 4 |
module HpcLexer where
import Data.Char
data Token
= ID String
| SYM Char
| INT Int
| STR String
| CAT String
deriving (Eq,Show)
initLexer :: String -> [Token]
initLexer str = [ t | (_,_,t) <- lexer str 1 1 ]
lexer :: String -> Int -> Int -> [(Int,Int,Token)]
lexer (c:cs) line column
| c == '\n' = lexer cs (succ line) 1
| c == '\"' = lexerSTR cs line (succ column)
| c == '[' = lexerCAT cs "" line (succ column)
| c `elem` "{};-:"
= (line,column,SYM c) : lexer cs line (succ column)
| isSpace c = lexer cs line (succ column)
| isAlpha c = lexerKW cs [c] line (succ column)
| isDigit c = lexerINT cs [c] line (succ column)
| otherwise = error "lexer failure"
lexer [] _ _ = []
lexerKW :: String -> String -> Int -> Int -> [(Int,Int,Token)]
lexerKW (c:cs) s line column
| isAlpha c = lexerKW cs (s ++ [c]) line (succ column)
lexerKW other s line column = (line,column,ID s) : lexer other line column
lexerINT :: String -> String -> Int -> Int -> [(Int,Int,Token)]
lexerINT (c:cs) s line column
| isDigit c = lexerINT cs (s ++ [c]) line (succ column)
lexerINT other s line column = (line,column,INT (read s)) : lexer other line column
-- not technically correct for the new column count, but a good approximation.
lexerSTR :: String -> Int -> Int -> [(Int,Int,Token)]
lexerSTR cs line column
= case lex ('"' : cs) of
[(str,rest)] -> (line,succ column,STR (read str))
: lexer rest line (length (show str) + column + 1)
_ -> error "bad string"
lexerCAT :: String -> String -> Int -> Int -> [(Int,Int,Token)]
lexerCAT (c:cs) s line column
| c == ']' = (line,column,CAT s) : lexer cs line (succ column)
| otherwise = lexerCAT cs (s ++ [c]) line (succ column)
lexerCAT [] _ _ _ = error "lexer failure in CAT"
test :: IO ()
test = do
t <- readFile "EXAMPLE.tc"
print (initLexer t)
| nomeata/ghc | utils/hpc/HpcLexer.hs | bsd-3-clause | 1,929 | 4 | 15 | 499 | 953 | 489 | 464 | 46 | 2 |
module Canonicalize.Port (check) where
import qualified Data.Foldable as Foldable
import qualified AST.Declaration as D
import qualified AST.Expression.General as E
import qualified AST.Expression.Canonical as Canonical
import qualified AST.Type as T
import qualified AST.Variable as Var
import qualified Reporting.Annotation as A
import qualified Reporting.Error.Canonicalize as Error
import qualified Reporting.Region as R
import qualified Canonicalize.Result as Result
-- CHECK FOR PORT
check
:: R.Region
-> String
-> Maybe Canonical.Expr
-> T.Canonical
-> Result.ResultErr D.CanonicalPort
check region name maybeExpr rootType =
D.CanonicalPort <$> checkHelp region name maybeExpr rootType rootType
checkHelp
:: R.Region
-> String
-> Maybe Canonical.Expr
-> T.Canonical
-> T.Canonical
-> Result.ResultErr (E.PortImpl Canonical.Expr T.Canonical)
checkHelp region name maybeExpr rootType tipe =
case (maybeExpr, tipe) of
(_, T.Aliased _ args t) ->
checkHelp region name maybeExpr rootType (T.dealias args t)
(Just expr, T.App (T.Type task) [ _x, _a ])
| Var.isTask task ->
Result.ok (E.Task name expr (T.Normal tipe))
(Just expr, T.App (T.Type signal) [ arg@(T.App (T.Type task) [ _x, _a ]) ])
| Var.isSignal signal && Var.isTask task ->
Result.ok (E.Task name expr (T.Signal tipe arg))
(_, T.App (T.Type signal) [arg])
| Var.isSignal signal ->
case maybeExpr of
Nothing ->
const (E.In name (T.Signal rootType arg))
<$> validForeignType region name True arg arg
Just expr ->
const (E.Out name expr (T.Signal rootType arg))
<$> validForeignType region name False arg arg
_ ->
case maybeExpr of
Nothing ->
const (E.In name (T.Normal rootType))
<$> validForeignType region name True rootType tipe
Just expr ->
const (E.Out name expr (T.Normal rootType))
<$> validForeignType region name False rootType tipe
-- CHECK INBOUND AND OUTBOUND TYPES
validForeignType
:: R.Region
-> String
-> Bool
-> T.Canonical
-> T.Canonical
-> Result.ResultErr ()
validForeignType region name isInbound rootType tipe =
let valid localType =
validForeignType region name isInbound rootType localType
err problem =
Result.err $ A.A region $
Error.port name isInbound rootType tipe problem
in
case tipe of
T.Aliased _ args t ->
valid (T.dealias args t)
T.Type v ->
case any ($ v) [ Var.isJson, Var.isPrimitive, Var.isTuple ] of
True -> Result.ok ()
False -> err Nothing
T.App t [] ->
valid t
T.App (T.Type v) [t]
| Var.isMaybe v -> valid t
| Var.isArray v -> valid t
| Var.isList v -> valid t
T.App (T.Type v) ts
| Var.isTuple v ->
Foldable.traverse_ valid ts
T.App _ _ ->
err Nothing
T.Var _ ->
err (Just "a free type variable")
T.Lambda _ _ ->
err (Just "a function")
T.Record _ (Just _) ->
err (Just "an extended record")
T.Record fields Nothing ->
Foldable.traverse_ (\(k,v) -> (,) k <$> valid v) fields
| laszlopandy/elm-compiler | src/Canonicalize/Port.hs | bsd-3-clause | 3,449 | 0 | 18 | 1,090 | 1,173 | 588 | 585 | 92 | 11 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
module Language.Haskell.Refact.Refactoring.MoveDef
( liftToTopLevel
, compLiftToTopLevel
, liftOneLevel
, compLiftOneLevel
, demote
, compDemote
-- ,liftingInClientMod
) where
import qualified Data.Generics as SYB
import qualified GHC.SYB.Utils as SYB
import qualified Data.Generics.Zipper as Z
import qualified Exception as GHC
import qualified GHC as GHC
import qualified Name as GHC
import qualified RdrName as GHC
import Control.Exception
import Control.Monad.State
import Data.Foldable
import Data.List
import Data.Maybe
import qualified GhcMod as GM
import Language.Haskell.Refact.API
import Language.Haskell.GHC.ExactPrint.Types
import Language.Haskell.GHC.ExactPrint
import Data.Generics.Strafunski.StrategyLib.StrategyLib
import System.Directory
-- import Debug.Trace
-- ---------------------------------------------------------------------
-- data Direction = UptoTopLevel | UpOneLevel | Down
{--------This function handles refactorings involving moving a definition--------
According to the Haskell's syntax, a declaration may occur in one of
the following six contexts:
1. A top level declaration in the module:
old: HsModule SrcLoc ModuleName (Maybe [HsExportSpecI i]) [HsImportDeclI i] ds
new: (HsGroup Name, [LImportDecl Name], Maybe [LIE Name], Maybe LHsDocString)
HsGroup hs_valds :: HsValBinds id ...
2. A local declaration in a Match: (of a FunBind)
old: HsMatch SrcLoc i [p] (HsRhs e) ds
new: Match [LPat id] (Maybe (LHsType id)) (GRHSs id)
3. A local declaration in a pattern binding:
old: HsPatBind SrcLoc p (HsRhs e) ds
new: PatBind (LPat idL) (GRHSs idR) PostTcType NameSet (Maybe tickish)
4. A local declaration in a Let expression:
old: HsLet ds e
new: HsLet (HsLocalBinds id) (LHsExpr id)
5. A local declaration in a Case alternative:
old: HsAlt SrcLoc p (HsRhs e) ds
new: HsCase (LHsExpr id) (MatchGroup id)
new is same as in a FunBind.
6. A local declaration in a Do statement:
old: HsLetStmt ds (HsStmt e p ds)
new: LetStmt (HsLocalBindsLR idL idR)
in context GRHS [LStmt id] (LHsExpr id)
-}
-- | Lift a definition to the top level
liftToTopLevel :: RefactSettings -> GM.Options -> FilePath -> SimpPos -> IO [FilePath]
liftToTopLevel settings opts fileName (row,col) = do
absFileName <- canonicalizePath fileName
runRefacSession settings opts (compLiftToTopLevel absFileName (row,col))
compLiftToTopLevel :: FilePath -> SimpPos
-> RefactGhc [ApplyRefacResult]
compLiftToTopLevel fileName (row,col) = do
parseSourceFileGhc fileName
logParsedSource "liftToMod orig:"
parsed <- getRefactParsed
nm <- getRefactNameMap
let (Just (modName,_)) = getModuleName parsed
let maybePn = locToRdrName (row, col) parsed
case maybePn of
Just ln@(GHC.L l _) -> liftToTopLevel' modName (GHC.L l (rdrName2NamePure nm ln))
_ -> error "\nInvalid cursor position!\n"
{- Refactoring Names: 'liftToTopLevel'
This refactoring lifts a local function/pattern binding to the top
level of the module, so as to make it accessible to other functions in
the current module, and those modules that import current module.
In the current implementation, a definition will be lifted only if
none of the identifiers defined in this definition will cause name
clash/capture problems in the current module after lifting.
In the case that the whole current module is exported implicitly,
the lifted identifier will be exported automatically after lifting. If
the identifier will cause name clash/ambiguous occurrence problem in a
client module, it will be hided in the import declaration of the
client module (Note: this might not be the best solution, we prefer
hiding it in the server module instead of in the client module in the
final version).
In the case of indirect importing, it might be time-consuming to
trace whether the lifted identifier will cause any problem in a client
module that indirectly imports the current module. The current
solution is: suppose a defintion is lifted to top level in module A,
and module A is imported and exported by module B, then the lifted
identifier will be hided in the import declaration of B no matter
whether it causes problems in module B or not.
Function name: liftToTopLevel
parameters: fileName--current file name.
mod -- the scoped abstract syntax tree of the module.
pn -- the function/pattern name to be lifted.
-}
liftToTopLevel' :: GHC.ModuleName
-> GHC.Located GHC.Name
-> RefactGhc [ApplyRefacResult]
liftToTopLevel' modName pn@(GHC.L _ n) = do
renamed <- getRefactRenamed
parsed <- getRefactParsed
nm <- getRefactNameMap
targetModule <- getRefactTargetModule
logm $ "liftToTopLevel':pn=" ++ (showGhc pn)
if isLocalFunOrPatName nm n parsed
then do
(refactoredMod,declPns) <- applyRefac liftToMod RSAlreadyLoaded
logm $ "liftToTopLevel' applyRefac done "
if modIsExported modName renamed
then do clients <- clientModsAndFiles targetModule
logm $ "liftToTopLevel':(clients,declPns)=" ++ (showGhc (clients,declPns))
refactoredClients <- mapM (liftingInClientMod modName declPns) clients
return (refactoredMod:(concat refactoredClients))
else do return [refactoredMod]
else error "\nThe identifier is not a local function/pattern name!"
where
{-step1: divide the module's top level declaration list into three parts: 'parent'
is the top level declaration containing the lifted declaration, 'before'
and `after` are those declarations before and after 'parent'.
step2: get the declarations to be lifted from parent, bind it to liftedDecls
step3: remove the lifted declarations from parent and extra arguments
may be introduced.
step4. test whether there are any names need to be renamed.
-}
liftToMod = do
parsed' <- getRefactParsed
parsed <- liftT $ balanceAllComments parsed'
nm <- getRefactNameMap
-- logDataWithAnns "parsed after balanceAllComments" parsed
declsp <- liftT $ hsDecls parsed
(before,parent,after) <- divideDecls declsp pn
{- ++AZ++TODO: reinstate this, hsDecls does : hsBinds does not return class or instance definitions
when (isClassDecl $ ghead "liftToMod" parent)
$ error "Sorry, the refactorer cannot lift a definition from a class declaration!"
when (isInstDecl $ ghead "liftToMod" parent)
$ error "Sorry, the refactorer cannot lift a definition from an instance declaration!"
-}
-- declsParent <- liftT $ hsDecls (ghead "liftToMod" parent)
-- logm $ "liftToMod:(declsParent)=" ++ (showGhc declsParent)
let liftedDecls = definingDeclsRdrNames nm [n] parent True True
declaredPns = nub $ concatMap (definedNamesRdr nm) liftedDecls
liftedSigs = definingSigsRdrNames nm declaredPns parent
mLiftedSigs = liftedSigs
-- logDataWithAnns "liftedDecls" liftedDecls
-- Check that the lifted declaration does not include a tuple pattern on the lhs
when (any isTupleDecl liftedDecls) $ do
error "Cannot lift a declaration assigning to a tuple pattern"
-- TODO: what about declarations between this
-- one and the top level that are used in this one?
pns <- pnsNeedRenaming parsed parent liftedDecls declaredPns
logm $ "liftToMod:(pns needing renaming)=" ++ (showGhc pns)
decls <- liftT $ hsDecls parsed'
let dd = getDeclaredVarsRdr nm decls
logm $ "liftToMod:(ddd)=" ++ (showGhc dd)
if null pns
then do
(parent',liftedDecls',mLiftedSigs') <- addParamsToParentAndLiftedDecl n dd parent liftedDecls mLiftedSigs
let defName = ghead "liftToMod" (definedNamesRdr nm (ghead "liftToMod2" parent'))
parsed1 <- liftT $ replaceDecls parsed (before++parent'++after)
parsed2 <- moveDecl1 parsed1 (Just defName) [GHC.unLoc pn] liftedDecls'
declaredPns mLiftedSigs'
putRefactParsed parsed2 emptyAnns
logParsedSource "liftToMod done:"
return declaredPns
else askRenamingMsg pns "lifting"
isTupleDecl :: GHC.LHsDecl GHC.RdrName -> Bool
isTupleDecl (GHC.L _ (GHC.ValD (GHC.PatBind (GHC.L _ GHC.TuplePat {}) _ _ _ _))) = True
isTupleDecl (GHC.L _ (GHC.ValD (GHC.PatBind (GHC.L _ (GHC.AsPat _ (GHC.L _ GHC.TuplePat {}))) _ _ _ _))) = True
isTupleDecl _ = False
-- ---------------------------------------------------------------------
-- | Move a definition one level up from where it is now
liftOneLevel :: RefactSettings -> GM.Options -> FilePath -> SimpPos -> IO [FilePath]
liftOneLevel settings opts fileName (row,col) = do
absFileName <- canonicalizePath fileName
runRefacSession settings opts (compLiftOneLevel absFileName (row,col))
compLiftOneLevel :: FilePath -> SimpPos
-> RefactGhc [ApplyRefacResult]
compLiftOneLevel fileName (row,col) = do
parseSourceFileGhc fileName
parsed <- getRefactParsed
nm <- getRefactNameMap
let (Just (modName,_)) = getModuleName parsed
let maybePn = locToRdrName (row, col) parsed
case maybePn of
Just ln@(GHC.L l _) -> do
rs <- liftOneLevel' modName (GHC.L l (rdrName2NamePure nm ln))
logm $ "compLiftOneLevel:rs=" ++ (show $ (refactDone rs,map (\((_,d),_) -> d) rs))
if (refactDone rs)
then return rs
else error ( "Lifting this definition failed. "++
" This might be because that the definition to be "++
"lifted is defined in a class/instance declaration.")
_ -> error "\nInvalid cursor position!\n"
{- Refactoring Names: 'liftOneLevel'
Description:
this refactoring lifts a local function/pattern binding only one level up.
By 'lifting one-level up' , I mean:
case1: In a module (HsModule SrcLoc ModuleName (Maybe [HsExportSpecI i]) [HsImportDeclI i] ds):
A local declaration D will be lifted to the same level as the 'ds', if D is in the
where clause of one of ds's element declaration.
new: (HsModule mmn mexp imps ds mdepr _haddock)
In pactice this means processing
a. Matches in a FunBind
(Match mln pats _typ (GRHSs grhs ds))
b. A PatBind
(PatBind lhs (GRHSs grhs ds) _typ _fvs _ticks)
and lifting a decl D from ds to the top.
VarBinds and AbsBinds are introduced by the type checker, so can be ignored here.
A PatSynBind does not have decls in it, so is ignored.
case2: In a match ( HsMatch SrcLoc i [p] (HsRhs e) ds) :
A local declaration D will be lifted to the same level as the 'ds', if D is in the
where clause of one of ds's element declaration.
A declaration D,say,in the rhs expression 'e' will be lifted to 'ds' if D is Not local to
other declaration list in 'e'
(in a FunBind)
new: (Match mln pats _typ (GRHSs grhs lb))
case3: In a pattern binding (HsPatBind SrcLoc p (HsRhs e) ds):
A local declaration D will be lifted to the same level as the 'ds', if D is in the
where clause of one of ds's element declaration.
A declaration D,say,in the rhs expression 'e' will be lifted to 'ds' if D is Not local to
other declaration list in 'e'
new: (PatBind lhs (GRHSs grhs ds) _typ _fvs _ticks)
case4: In the Let expression (Exp (HsLet ds e):
A local declaration D will be lifted to the same level as the 'ds', if D is in the
where clause of one of ds's element declaration.
A declaration D, say, in the expression 'e' will be lifted to 'ds' if D is not local to
other declaration list in 'e'
new: HsLet ds e
case5: In the case Alternative expression:(HsAlt loc p rhs ds)
A local declaration D will be lifted to the same level as the 'ds', if D is in the
where clause of one of ds's element declaration.
A declaration D in 'rhs' will be lifted to 'ds' if D is not local to other declaration
list in 'rhs'.
new: HsCase (LHsExpr id) (MatchGroup id)
new is same as in a FunBind.
case6: In the do statement expression:(HsLetStmt ds stmts)
A local declaration D will be lifted to the same level as the 'ds', if D is in the
where clause of one of ds's element declaration.
A declaration D in 'stmts' will be lifted to 'ds' if D is not local to other declaration
list in 'stmts'.
new: LetStmt (HsLocalBindsLR idL idR)
in context GRHS [LStmt id] (LHsExpr id)
Function name: liftOneLevel
parameters: fileName--current file name.
mod -- the scoped abstract syntax tree of the module.
pn -- the function/pattern name to be lifted.
-}
liftOneLevel' :: GHC.ModuleName
-> GHC.Located GHC.Name
-> RefactGhc [ApplyRefacResult]
liftOneLevel' modName pn@(GHC.L _ n) = do
renamed <- getRefactRenamed
parsed <- getRefactParsed
nm <- getRefactNameMap
targetModule <- getRefactTargetModule
if isLocalFunOrPatName nm n parsed
then do
(refactoredMod,(b,pns)) <- applyRefac doLiftOneLevel RSAlreadyLoaded
logm $ "liftOneLevel':main refactoring done:(p,pns)=" ++ showGhc (b,pns)
if b && modIsExported modName renamed
then do
logm $ "liftOneLevel':looking for clients"
clients <- clientModsAndFiles targetModule
logm $ "liftOneLevel':(clients,pns)=" ++ (showGhc (clients,pns))
refactoredClients <- mapM (liftingInClientMod modName pns) clients
return (refactoredMod:concat refactoredClients)
else do return [refactoredMod]
else error "\nThe identifer is not a function/pattern name!"
where
doLiftOneLevel = do
logm $ "in doLiftOneLevel"
parsed <- getRefactParsed
logDataWithAnns "doLiftOneLevel:parsed" parsed
nm <- getRefactNameMap
ans <- liftT getAnnsT
zp <- ztransformStagedM SYB.Parser
(Nothing
`SYB.mkQ` (liftToModQ nm ans)
`SYB.extQ` (liftToMatchQ nm ans)
`SYB.extQ` (liftToLetQ nm ans)
) (Z.toZipper parsed)
let parsed' = Z.fromZipper zp
putRefactParsed parsed' emptyAnns
liftedToTopLevel pn parsed'
where
isMatch :: GHC.LMatch GHC.RdrName (GHC.LHsExpr GHC.RdrName) -> Bool
isMatch _ = True
isHsLet :: GHC.LHsExpr GHC.RdrName -> Bool
isHsLet (GHC.L _ (GHC.HsLet _ _)) = True
isHsLet _ = False
-- ------------------------
liftToModQ ::
NameMap -> Anns
-> GHC.ParsedSource
-> Maybe (SYB.Stage
-> Z.Zipper GHC.ParsedSource
-> RefactGhc (Z.Zipper GHC.ParsedSource))
liftToModQ nm ans (p :: GHC.ParsedSource)
| nonEmptyList candidateBinds
= Just (doLiftZ p declsp)
| otherwise = Nothing
where
(declsp ,_,_) = runTransform ans (hsDecls p)
doOne bs = (definingDeclsRdrNames nm [n] declsbs False False,bs)
where
(declsbs,_,_) = runTransform ans (hsDeclsGeneric bs)
candidateBinds = map snd
$ filter (\(l,_bs) -> nonEmptyList l)
$ map doOne
$ declsp
getHsDecls ans t = decls
where (decls,_,_) = runTransform ans (hsDeclsGeneric t)
-- ------------------------
liftToMatchQ :: (SYB.Data a)
=> NameMap -> Anns
-> GHC.LMatch GHC.RdrName (GHC.LHsExpr GHC.RdrName)
-> Maybe (SYB.Stage -> Z.Zipper a -> RefactGhc (Z.Zipper a))
liftToMatchQ nm ans (m@(GHC.L _ (GHC.Match _ _pats _mtyp (GHC.GRHSs _rhs ds)))::GHC.LMatch GHC.RdrName (GHC.LHsExpr GHC.RdrName))
| (nonEmptyList (definingDeclsRdrNames nm [n] (getHsDecls ans ds) False False))
= Just (doLiftZ m (getHsDecls ans ds))
| otherwise = Nothing
-- ------------------------
liftToLetQ :: SYB.Data a
=> NameMap -> Anns
-> GHC.LHsExpr GHC.RdrName -> Maybe (SYB.Stage -> Z.Zipper a -> RefactGhc (Z.Zipper a))
liftToLetQ nm ans ll@(GHC.L _ (GHC.HsLet ds _e))
| nonEmptyList (definingDeclsRdrNames nm [n] (getHsDecls ans ds) False False)
= Just (doLiftZ ll (getHsDecls ans ll))
| otherwise = Nothing
liftToLetQ _ _ _ = Nothing
-- ------------------------
doLiftZ :: (SYB.Data t,SYB.Data a)
=> t -- ^Item containing the decls which contain the ones to be lifted
-> [GHC.LHsDecl GHC.RdrName] -- ^decls containing the ones to be lifted.
-- ++AZ++:TODO: these are redundant, can be pulled out of t
-> SYB.Stage -- ++AZ++:TODO: get rid of this
-> Z.Zipper a
-> RefactGhc (Z.Zipper a)
doLiftZ ds decls _stage z =
do
logm $ "doLiftZ entered"
logDataWithAnns "doLiftZ:ds" ds
logDataWithAnns "doLiftZ:decls" decls
let zu = case (Z.up z) of
Just zz -> fromMaybe (error $ "MoveDef.liftToLet.1" ++ SYB.showData SYB.Parser 0 decls)
$ upUntil (False `SYB.mkQ` isMatch
`SYB.extQ` isHsLet
)
zz
Nothing -> z
let
wtop (ren::GHC.ParsedSource) = do
logm $ "wtop entered"
nm <- getRefactNameMap
let (_,DN dd) = (hsFreeAndDeclaredRdr nm ren)
-- ++AZ++ : TODO: get rid of worker in favour of
-- workerTop
worker ren decls pn dd
-- workerTop ren decls dd
wmatch :: GHC.LMatch GHC.RdrName (GHC.LHsExpr GHC.RdrName)
-> RefactGhc (GHC.LMatch GHC.RdrName (GHC.LHsExpr GHC.RdrName))
wmatch (m@(GHC.L _ (GHC.Match _mln _pats _typ grhss))) = do
logm $ "wmatch entered:" ++ SYB.showData SYB.Parser 0 m
nm <- getRefactNameMap
let (_,DN dd) = hsFreeAndDeclaredRdr nm grhss
decls' <- liftT $ hsDecls m
workerTop m decls' dd
wlet :: GHC.LHsExpr GHC.RdrName -> RefactGhc (GHC.LHsExpr GHC.RdrName)
wlet l@(GHC.L _ (GHC.HsLet dsl _e)) = do
logm $ "wlet entered "
nm <- getRefactNameMap
let (_,DN dd) = hsFreeAndDeclaredRdr nm dsl
dsl' <- workerTop l decls dd
return dsl'
wlet x = return x
ds' <- Z.transM ( SYB.mkM wtop
`SYB.extM` wmatch
`SYB.extM` wlet
) zu
return ds'
-- ----------------------------------------
-- This is currently used for everything but the top level
workerTop :: (HasDecls t)
=> t -- ^The destination of the lift operation
-> [GHC.LHsDecl GHC.RdrName] -- ^ list containing the decl to be
-- lifted
-> [GHC.Name] -- ^Declared variables in the destination
-> RefactGhc t
workerTop dest ds dd
=do
logm $ "MoveDef.worker: dest" ++ SYB.showData SYB.Parser 0 dest
logm $ "MoveDef.workerTop: ds=" ++ (showGhc ds)
done <- getRefactDone
if done then return dest
else do
setRefactDone
let parent = dest
nm <- getRefactNameMap
let liftedDecls = definingDeclsRdrNames' nm [n] parent
declaredPns = nub $ concatMap (definedNamesRdr nm) liftedDecls
logm $ "MoveDef.workerTop: n=" ++ (showGhc n)
logm $ "MoveDef.workerTop: liftedDecls=" ++ (showGhc liftedDecls)
pns <- pnsNeedRenaming dest parent liftedDecls declaredPns
logm $ "MoveDef.workerTop: pns=" ++ (showGhc pns)
if pns==[]
then do
(parent',liftedDecls',mLiftedSigs')<-addParamsToParentAndLiftedDecl n dd
parent liftedDecls []
logm $ "MoveDef.workerTop: liftedDecls'=" ++ (showGhc liftedDecls')
--True means the new decl will be at the same level with its parant.
let toMove = parent'
pdecls <- liftT $ hsDecls toMove
-- logm $ "MoveDef.workerTop:toMove=" ++ SYB.showData SYB.Parser 0 toMove
-- logm $ "MoveDef.workerTop:pdecls=" ++ (showGhc pdecls)
let mAfter = case pdecls of
[] -> Nothing
_ -> (Just (ghead "worker" (definedNamesRdr nm (glast "workerTop" ds))))
dest' <- moveDecl1 toMove
mAfter
[n] liftedDecls' declaredPns mLiftedSigs'
return dest'
else askRenamingMsg pns "lifting"
-- ----------------------------------------
-- TODO: get rid of this in favour of workerTop
worker :: (HasDecls t)
=> t -- ^The destination of the lift operation
-> [GHC.LHsDecl GHC.RdrName] -- ^ list containing the decl to be
-- lifted
-> GHC.Located GHC.Name -- ^ The name of the decl to be lifted
-> [GHC.Name] -- ^Declared variables in the destination
-> RefactGhc t
worker dest ds pnn dd
=do
-- logm $ "MoveDef.worker: dest" ++ (showGhc dest)
logm $ "MoveDef.worker: ds=" ++ (showGhc ds)
done <- getRefactDone
if done then return dest
else do
setRefactDone
(before,parent,after) <- divideDecls ds pnn -- parent is misnomer, it is the decl to be moved
logm $ "MoveDef.worker:(before,parent,after)" ++ showGhc (before,parent,after)
nm <- getRefactNameMap
let liftedDecls = definingDeclsRdrNames nm [n] parent True True
declaredPns = nub $ concatMap (definedNamesRdr nm) liftedDecls
pns <- pnsNeedRenaming dest parent liftedDecls declaredPns
logm $ "MoveDef.worker: pns=" ++ (showGhc pns)
if pns==[]
then do
(parent',liftedDecls',mLiftedSigs')<-addParamsToParentAndLiftedDecl n dd
parent liftedDecls []
--True means the new decl will be at the same level with its parant.
toMove <- liftT $ replaceDecls dest (before++parent'++after)
dest' <- moveDecl1 toMove
(Just (ghead "worker" (definedNamesRdr nm (ghead "worker" parent'))))
[n] liftedDecls' declaredPns mLiftedSigs'
return dest'
else askRenamingMsg pns "lifting"
-- ---------------------------------------------------------------------
-- | Move a definition one level down
demote :: RefactSettings -> GM.Options -> FilePath -> SimpPos -> IO [FilePath]
demote settings opts fileName (row,col) = do
absFileName <- canonicalizePath fileName
runRefacSession settings opts (compDemote absFileName (row,col))
compDemote ::FilePath -> SimpPos
-> RefactGhc [ApplyRefacResult]
compDemote fileName (row,col) = do
parseSourceFileGhc fileName
parsed <- getRefactParsed
nm <- getRefactNameMap
-- TODO: make the next one an API call, that also gets the
-- parsed source
let (Just (modName,_)) = getModuleName parsed
let maybePn = locToRdrName (row, col) parsed
case maybePn of
Just pn@(GHC.L l _) -> demote' modName (GHC.L l (rdrName2NamePure nm pn))
_ -> error "\nInvalid cursor position!\n"
-- ---------------------------------------------------------------------
moveDecl1 :: (SYB.Data t)
=> t -- ^ The syntax element to update
-> Maybe GHC.Name -- ^ If specified, add defn after this one
-> [GHC.Name] -- ^ The first one is the decl to move
-> [GHC.LHsDecl GHC.RdrName]
-> [GHC.Name] -- ^ The signatures to remove. May be multiple if
-- decl being moved has a patbind.
-> [GHC.LSig GHC.RdrName] -- ^ lifted decls signature if present
-> RefactGhc t -- ^ The updated syntax element (and tokens in monad)
moveDecl1 t defName ns mliftedDecls sigNames mliftedSigs = do
logm $ "moveDecl1:(defName,ns,sigNames,mliftedDecls)=" ++ showGhc (defName,ns,sigNames,mliftedDecls)
-- logm $ "moveDecl1:(t)=" ++ SYB.showData SYB.Parser 0 (t)
-- TODO: rmDecl can now remove the sig at the same time.
(t'',_sigsRemoved) <- rmTypeSigs sigNames t
-- logm $ "moveDecl1:after rmTypeSigs:t''" ++ SYB.showData SYB.Parser 0 t''
logm $ "moveDecl1:mliftedSigs=" ++ showGhc mliftedSigs
(t',_declRemoved,_sigRemoved) <- rmDecl (ghead "moveDecl3.1" ns) False t''
-- logm $ "moveDecl1:after rmDecl:t'" ++ SYB.showData SYB.Parser 0 t'
let sigs = map wrapSig mliftedSigs
r <- addDecl t' defName (sigs++mliftedDecls,Nothing)
return r
-- ---------------------------------------------------------------------
askRenamingMsg :: [GHC.Name] -> String -> t
askRenamingMsg pns str
= error ("The identifier(s): " ++ (intercalate "," $ map showPN pns) ++
" will cause name clash/capture or ambiguity occurrence problem after "
++ str ++", please do renaming first!")
where
showPN pn = showGhc (pn,GHC.nameSrcLoc pn)
-- |Get the subset of 'pns' that need to be renamed before lifting.
pnsNeedRenaming :: (SYB.Data t1,SYB.Data t2) =>
t1 -> t2 -> t3 -> [GHC.Name]
-> RefactGhc [GHC.Name]
pnsNeedRenaming dest parent _liftedDecls pns
= do
logm $ "MoveDef.pnsNeedRenaming entered:pns=" ++ showGhc pns
r <- mapM pnsNeedRenaming' pns
return (concat r)
where
pnsNeedRenaming' pn
= do
logm $ "MoveDef.pnsNeedRenaming' entered"
nm <- getRefactNameMap
let (FN f,DN d) = hsFDsFromInsideRdr nm dest --f: free variable names that may be shadowed by pn
--d: declaread variables names that may clash with pn
logm $ "MoveDef.pnsNeedRenaming':(f,d)=" ++ showGhc (f,d)
DN vs <- hsVisibleDsRdr nm pn parent --vs: declarad variables that may shadow pn
logm $ "MoveDef.pnsNeedRenaming':vs=" ++ showGhc vs
let vars = map pNtoName (nub (f `union` d `union` vs) \\ [pn]) -- `union` inscpNames
isInScope <- isInScopeAndUnqualifiedGhc (pNtoName pn) Nothing
logm $ "MoveDef.pnsNeedRenaming:(f,d,vs,vars,isInScope)=" ++ (showGhc (f,d,vs,vars,isInScope))
-- if elem (pNtoName pn) vars || isInScope && findEntity pn dest
if elem (pNtoName pn) vars || isInScope && findNameInRdr nm pn dest
then return [pn]
else return []
pNtoName = showGhc
-- ---------------------------------------------------------------------
addParamsToParent :: (SYB.Data t) => GHC.Name -> [GHC.RdrName] -> t -> RefactGhc t
addParamsToParent _pn [] t = return t
addParamsToParent pn params t = do
logm $ "addParamsToParent:(pn,params)" ++ (showGhc (pn,params))
nm <- getRefactNameMap
applyTP (full_buTP (idTP `adhocTP` (inExp nm))) t
where
#if __GLASGOW_HASKELL__ <= 710
inExp nm (e@(GHC.L l (GHC.HsVar n)) :: GHC.LHsExpr GHC.RdrName) = do
#else
inExp nm (e@(GHC.L l (GHC.HsVar (GHC.L _ n))) :: GHC.LHsExpr GHC.RdrName) = do
#endif
let ne = rdrName2NamePure nm (GHC.L l n)
if GHC.nameUnique ne == GHC.nameUnique pn
then addActualParamsToRhs pn params e
else return e
inExp _ e = return e
-- addActualParamsToRhs pn params t
-- |Do refactoring in the client module. that is to hide the identifer
-- in the import declaration if it will cause any problem in the
-- client module.
liftingInClientMod :: GHC.ModuleName -> [GHC.Name] -> TargetModule
-> RefactGhc [ApplyRefacResult]
liftingInClientMod serverModName pns targetModule = do
logm $ "liftingInClientMod:targetModule=" ++ (show targetModule)
getTargetGhc targetModule
parsed <- getRefactParsed
clientModule <- getRefactModule
logm $ "liftingInClientMod:clientModule=" ++ (showGhc clientModule)
modNames <- willBeUnQualImportedBy serverModName
logm $ "liftingInClientMod:modNames=" ++ (showGhc modNames)
if isJust modNames
then do
pns' <- namesNeedToBeHided clientModule (gfromJust "liftingInClientMod" modNames) pns
let pnsRdr' = map GHC.nameRdrName pns'
logm $ "liftingInClientMod:pns'=" ++ (showGhc pns')
if (nonEmptyList pns')
then do (refactoredMod,_) <- applyRefac (addHiding serverModName parsed pnsRdr') RSAlreadyLoaded
return [refactoredMod]
else return []
else return []
-- ---------------------------------------------------------------------
-- |Test whether an identifier defined in the modules specified by
-- 'names' will be exported by current module.
willBeExportedByClientMod :: [GHC.ModuleName] -> GHC.RenamedSource -> Bool
willBeExportedByClientMod names renamed =
let (_,_,exps,_) = renamed
in if isNothing exps
then False
else any isJust $ map (\y-> (find (\x-> (simpModule x==Just y)) (gfromJust "willBeExportedByClientMod" exps))) names
where simpModule (GHC.L _ (GHC.IEModuleContents (GHC.L _ m))) = Just m
simpModule _ = Nothing
-- |get the module name or alias name by which the lifted identifier
-- will be imported automatically.
-- TODO: maybe move this into TypeUtils
-- willBeUnQualImportedBy::HsName.ModuleName->HsModuleP->Maybe [HsName.ModuleName]
willBeUnQualImportedBy :: GHC.ModuleName -> RefactGhc (Maybe [GHC.ModuleName])
willBeUnQualImportedBy modName = do
(_,imps,_,_) <- getRefactRenamed
let ms = filter (\(GHC.L _ (GHC.ImportDecl _ (GHC.L _ modName1) _qualify _source _safe isQualified _isImplicit _as h))
-> modName == modName1 && (not isQualified) && (isNothing h || (isJust h && ((fst (fromJust h)) == True))))
imps
res = if (emptyList ms) then Nothing
else Just $ nub $ map getModName ms
getModName (GHC.L _ (GHC.ImportDecl _ (GHC.L _ modName2) _qualify _source _safe _isQualified _isImplicit as _h))
= if isJust as then simpModName (fromJust as)
else modName2
simpModName m = m
logm $ "willBeUnQualImportedBy:(ms,res)=" ++ (showGhc (ms,res))
return res
-- ---------------------------------------------------------------------
-- |get the subset of 'pns', which need to be hided in the import
-- declaration in module 'mod'
-- Note: these are newly exported from the module, so we cannot use
-- the GHC name resolution in this case.
namesNeedToBeHided :: GHC.Module -> [GHC.ModuleName] -> [GHC.Name]
-> RefactGhc [GHC.Name]
namesNeedToBeHided clientModule modNames pns = do
renamed <- getRefactRenamed
parsed <- getRefactParsed
logm $ "namesNeedToBeHided:willBeExportedByClientMod=" ++ (show $ willBeExportedByClientMod modNames renamed)
gnames <- GHC.getNamesInScope
let clientInscopes = filter (\n -> clientModule == GHC.nameModule n) gnames
logm $ "namesNeedToBeHided:(clientInscopes)=" ++ (showGhc (clientInscopes))
pnsMapped <- mapM getLocalEquiv pns
logm $ "namesNeedToBeHided:pnsMapped=" ++ (showGhc pnsMapped)
let pnsMapped' = filter (\(_,_,ns) -> not $ emptyList ns) pnsMapped
if willBeExportedByClientMod modNames renamed
then return pns
else do
ff <- mapM (needToBeHided parsed) pnsMapped'
return $ concat ff
where
-- | Strip the package prefix from the name and return the
-- stripped name together with any names in the local module that
-- may match the stripped one
getLocalEquiv :: GHC.Name -> RefactGhc (GHC.Name,String,[GHC.Name])
getLocalEquiv pn = do
let pnStr = stripPackage $ showGhc pn
logm $ "MoveDef getLocalEquiv: about to parseName:" ++ (show pnStr)
ecns <- GHC.gtry $ GHC.parseName pnStr
let cns = case ecns of
Left (_e::SomeException) -> []
Right v -> v
logm $ "MoveDef getLocalEquiv: cns:" ++ (showGhc cns)
return (pn,pnStr,cns)
stripPackage :: String -> String
stripPackage str = reverse s
where
(s,_) = break (== '.') $ reverse str
needToBeHided :: GHC.ParsedSource -> (GHC.Name,String,[GHC.Name]) -> RefactGhc [GHC.Name]
needToBeHided parsed (pn,_pnStr,pnsLocal) = do
let uwoq = map (\n -> usedWithoutQualR n parsed) pnsLocal
-- logm $ "needToBeHided:(hsBinds renamed)=" ++ (showGhc (hsBinds renamed))
logm $ "needToBeHided:(pn,uwoq)=" ++ (showGhc (pn,uwoq))
if (any (== True) uwoq --the same name is used in the module unqualifiedly or
--is exported unqualifiedly by an Ent decl
-- TODO: ++AZ++ check if next line needs to be reinstated
-- was || any (\m -> causeNameClashInExports oldPN pn m renamed) modNames)
|| False)
then return [pn]
else return []
-- **************************************************************************************************************--
-- ---------------------------------------------------------------------
-- |When liftOneLevel is complete, identify whether any new declarations have
-- been put at the top level
liftedToTopLevel :: GHC.Located GHC.Name -> GHC.ParsedSource -> RefactGhc (Bool,[GHC.Name])
liftedToTopLevel (GHC.L _ pn) parsed = do
logm $ "liftedToTopLevel entered:pn=" ++ showGhc pn
nm <- getRefactNameMap
decls <- liftT $ hsDecls parsed
let topDecs = definingDeclsRdrNames nm [pn] decls False False
-- ++AZ++ :TODO: we are not updating the nameMap to reflect moved decls
if nonEmptyList topDecs
then do
let liftedDecls = definingDeclsRdrNames nm [pn] topDecs False False
declaredPns = nub $ concatMap (definedNamesRdr nm) liftedDecls
return (True, declaredPns)
else return (False, [])
-- ---------------------------------------------------------------------
addParamsToParentAndLiftedDecl :: (SYB.Data t) =>
GHC.Name -- ^name of decl being lifted
-> [GHC.Name] -- ^Declared names in parent
-> t -- ^parent
-> [GHC.LHsDecl GHC.RdrName] -- ^ decls being lifted
-> [GHC.LSig GHC.RdrName] -- ^ lifted decls signature if present
-> RefactGhc (t, [GHC.LHsDecl GHC.RdrName], [GHC.LSig GHC.RdrName])
addParamsToParentAndLiftedDecl pn dd parent liftedDecls mLiftedSigs
=do
logm $ "addParamsToParentAndLiftedDecl:liftedDecls=" ++ (showGhc liftedDecls)
nm <- getRefactNameMap
let (FN ef,_) = hsFreeAndDeclaredRdr nm parent
let (FN lf,_) = hsFreeAndDeclaredRdr nm liftedDecls
logm $ "addParamsToParentAndLiftedDecl:(ef,lf)=" ++ showGhc (ef,lf)
-- parameters to be added to pn because of lifting
let newParamsNames = ((nub lf) \\ (nub ef)) \\ dd
newParams = map GHC.nameRdrName newParamsNames
logm $ "addParamsToParentAndLiftedDecl:(newParams,ef,lf,dd)=" ++ (showGhc (newParams,ef,lf,dd))
if newParams /= []
then if (any isComplexPatDecl liftedDecls)
then error "This pattern binding cannot be lifted, as it uses some other local bindings!"
else do -- first remove the decls to be lifted, so they are not disturbed
(parent'',liftedDecls'',_msig) <- rmDecl pn False parent
parent' <- addParamsToParent pn newParams parent''
liftedDecls' <- addParamsToDecls [liftedDecls''] pn newParams
mLiftedSigs' <- mapM (addParamsToSigs newParamsNames) mLiftedSigs
logm $ "addParamsToParentAndLiftedDecl:mLiftedSigs'=" ++ showGhc mLiftedSigs'
return (parent',liftedDecls', mLiftedSigs')
else return (parent,liftedDecls,mLiftedSigs)
-- ---------------------------------------------------------------------
{-
-- TODO: perhaps move this to TypeUtils
addParamsToSigs :: [GHC.Name] -> GHC.LSig GHC.RdrName -> RefactGhc (GHC.LSig GHC.RdrName)
addParamsToSigs [] ms = return ms
addParamsToSigs newParams (GHC.L l (GHC.TypeSig lns ltyp pns)) = do
mts <- mapM getTypeForName newParams
let ts = catMaybes mts
logm $ "addParamsToSigs:ts=" ++ showGhc ts
logDataWithAnns "addParamsToSigs:ts=" ts
let newStr = ":: " ++ (intercalate " -> " $ map printSigComponent ts) ++ " -> "
logm $ "addParamsToSigs:newStr=[" ++ newStr ++ "]"
typ' <- liftT $ foldlM addOneType ltyp (reverse ts)
sigOk <- isNewSignatureOk ts
logm $ "addParamsToSigs:(sigOk,newStr)=" ++ show (sigOk,newStr)
if sigOk
then return (GHC.L l (GHC.TypeSig lns typ' pns))
else error $ "\nNew type signature may fail type checking: " ++ newStr ++ "\n"
where
addOneType :: GHC.LHsType GHC.RdrName -> GHC.Type -> Transform (GHC.LHsType GHC.RdrName)
addOneType et t = do
hst <- typeToLHsType t
ss1 <- uniqueSrcSpanT
hst1 <- case t of
(GHC.FunTy _ _) -> do
ss <- uniqueSrcSpanT
let t1 = GHC.L ss (GHC.HsParTy hst)
setEntryDPT hst (DP (0,0))
addSimpleAnnT t1 (DP (0,0)) [((G GHC.AnnOpenP),DP (0,1)),((G GHC.AnnCloseP),DP (0,0))]
return t1
_ -> return hst
let typ = GHC.L ss1 (GHC.HsFunTy hst1 et)
addSimpleAnnT typ (DP (0,0)) [((G GHC.AnnRarrow),DP (0,1))]
return typ
addParamsToSigs np ls = error $ "addParamsToSigs: no match for:" ++ showGhc (np,ls)
-- ---------------------------------------------------------------------
printSigComponent :: GHC.Type -> String
printSigComponent x = ppType x
-- ---------------------------------------------------------------------
-- |Fail any signature having a forall in it.
-- TODO: this is unnecesarily restrictive, but needs
-- a) proper reversing of GHC.Type to GHC.LhsType
-- b) some serious reverse type inference to ensure that the
-- constraints are modified properly to merge the old signature
-- part and the new.
isNewSignatureOk :: [GHC.Type] -> RefactGhc Bool
isNewSignatureOk types = do
-- NOTE: under some circumstances enabling Rank2Types or RankNTypes
-- can resolve the type conflict, this can potentially be checked
-- for.
-- NOTE2: perhaps proceed and reload the tentative refactoring into
-- the GHC session and accept it only if it type checks
let
r = SYB.everythingStaged SYB.TypeChecker (++) []
([] `SYB.mkQ` usesForAll) types
usesForAll (GHC.ForAllTy _ _) = [1::Int]
usesForAll _ = []
return $ emptyList r
-- ---------------------------------------------------------------------
-- TODO: perhaps move this to TypeUtils
-- TODO: complete this
typeToLHsType :: GHC.Type -> Transform (GHC.LHsType GHC.RdrName)
typeToLHsType (GHC.TyVarTy v) = do
ss <- uniqueSrcSpanT
let typ = GHC.L ss (GHC.HsTyVar (GHC.nameRdrName $ Var.varName v))
addSimpleAnnT typ (DP (0,0)) [((G GHC.AnnVal),DP (0,0))]
return typ
typeToLHsType (GHC.AppTy t1 t2) = do
t1' <- typeToLHsType t1
t2' <- typeToLHsType t2
ss <- uniqueSrcSpanT
return $ GHC.L ss (GHC.HsAppTy t1' t2')
typeToLHsType t@(GHC.TyConApp _tc _ts) = tyConAppToHsType t
typeToLHsType (GHC.FunTy t1 t2) = do
t1' <- typeToLHsType t1
t2' <- typeToLHsType t2
ss <- uniqueSrcSpanT
let typ = GHC.L ss (GHC.HsFunTy t1' t2')
addSimpleAnnT typ (DP (0,0)) [((G GHC.AnnRarrow),DP (0,1))]
return typ
typeToLHsType (GHC.ForAllTy _v t) = do
t' <- typeToLHsType t
ss1 <- uniqueSrcSpanT
ss2 <- uniqueSrcSpanT
return $ GHC.L ss1 (GHC.HsForAllTy GHC.Explicit Nothing (GHC.HsQTvs [] []) (GHC.L ss2 []) t')
typeToLHsType (GHC.LitTy (GHC.NumTyLit i)) = do
ss <- uniqueSrcSpanT
let typ = GHC.L ss (GHC.HsTyLit (GHC.HsNumTy (show i) i)) :: GHC.LHsType GHC.RdrName
addSimpleAnnT typ (DP (0,0)) [((G GHC.AnnVal),DP (0,0))]
return typ
typeToLHsType (GHC.LitTy (GHC.StrTyLit s)) = do
ss <- uniqueSrcSpanT
let typ = GHC.L ss (GHC.HsTyLit (GHC.HsStrTy "" s)) :: GHC.LHsType GHC.RdrName
addSimpleAnnT typ (DP (0,0)) [((G GHC.AnnVal),DP (0,0))]
return typ
{-
data Type
= TyVarTy Var -- ^ Vanilla type or kind variable (*never* a coercion variable)
| AppTy -- See Note [AppTy invariant]
Type
Type -- ^ Type application to something other than a 'TyCon'. Parameters:
--
-- 1) Function: must /not/ be a 'TyConApp',
-- must be another 'AppTy', or 'TyVarTy'
--
-- 2) Argument type
| TyConApp -- See Note [AppTy invariant]
TyCon
[KindOrType] -- ^ Application of a 'TyCon', including newtypes /and/ synonyms.
-- Invariant: saturated appliations of 'FunTyCon' must
-- use 'FunTy' and saturated synonyms must use their own
-- constructors. However, /unsaturated/ 'FunTyCon's
-- do appear as 'TyConApp's.
-- Parameters:
--
-- 1) Type constructor being applied to.
--
-- 2) Type arguments. Might not have enough type arguments
-- here to saturate the constructor.
-- Even type synonyms are not necessarily saturated;
-- for example unsaturated type synonyms
-- can appear as the right hand side of a type synonym.
| FunTy
Type
Type -- ^ Special case of 'TyConApp': @TyConApp FunTyCon [t1, t2]@
-- See Note [Equality-constrained types]
| ForAllTy
Var -- Type or kind variable
Type -- ^ A polymorphic type
| LitTy TyLit -- ^ Type literals are simillar to type constructors.
-}
tyConAppToHsType :: GHC.Type -> Transform (GHC.LHsType GHC.RdrName)
tyConAppToHsType (GHC.TyConApp tc _ts) = r (show $ GHC.tyConName tc)
where
r str = do
ss <- uniqueSrcSpanT
let typ = GHC.L ss (GHC.HsTyLit (GHC.HsStrTy str $ GHC.mkFastString str)) :: GHC.LHsType GHC.RdrName
addSimpleAnnT typ (DP (0,0)) [((G GHC.AnnVal),DP (0,1))]
return typ
-- tyConAppToHsType t@(GHC.TyConApp _tc _ts)
-- = error $ "tyConAppToHsType: unexpected:" ++ (SYB.showData SYB.TypeChecker 0 t)
{-
HsType
HsForAllTy HsExplicitFlag (LHsTyVarBndrs name) (LHsContext name) (LHsType name)
HsTyVar name
HsAppTy (LHsType name) (LHsType name)
HsFunTy (LHsType name) (LHsType name)
HsListTy (LHsType name)
HsPArrTy (LHsType name)
HsTupleTy HsTupleSort [LHsType name]
HsOpTy (LHsType name) (LHsTyOp name) (LHsType name)
HsParTy (LHsType name)
HsIParamTy HsIPName (LHsType name)
HsEqTy (LHsType name) (LHsType name)
HsKindSig (LHsType name) (LHsKind name)
HsQuasiQuoteTy (HsQuasiQuote name)
HsSpliceTy (HsSplice name) FreeVars PostTcKind
HsDocTy (LHsType name) LHsDocString
HsBangTy HsBang (LHsType name)
HsRecTy [ConDeclField name]
HsCoreTy Type
HsExplicitListTy PostTcKind [LHsType name]
HsExplicitTupleTy [PostTcKind] [LHsType name]
HsTyLit HsTyLit
HsWrapTy HsTyWrapper (HsType name)
-}
-}
--------------------------------End of Lifting-----------------------------------------
{-Refactoring : demote a function/pattern binding(simpe or complex) to the declaration where it is used.
Descritption: if a declaration D, say, is only used by another declaration F,say, then D can be
demoted into the local declaration list (where clause) in F.
So currently, D can not be demoted if more than one declaration use it.
In a multi-module context, a top-level definition can not be demoted if it is used
by other modules. In the case that the demoted identifer is in the hiding list of
import declaration in a client module, it should be removed from the hiding list.
Function name:demote
parameters: fileName--current file name.
mod -- the scoped abstract syntax tree of the module.
pn -- the function/pattern name to be demoted.
-}
demote' ::
GHC.ModuleName
-- -> FilePath
-- -> (ParseResult,[PosToken])
-> GHC.Located GHC.Name
-> RefactGhc [ApplyRefacResult]
demote' modName (GHC.L _ pn) = do
renamed <- getRefactRenamed
parsed <- getRefactParsed
nm <- getRefactNameMap
targetModule <- getRefactTargetModule
if isFunOrPatName nm pn parsed
then do
isTl <- isTopLevelPN pn
if isTl && isExplicitlyExported nm pn parsed
then error "This definition can not be demoted, as it is explicitly exported by the current module!"
else do
(refactoredMod,declaredPns) <- applyRefac (doDemoting pn) RSAlreadyLoaded
if isTl && modIsExported modName renamed
then do
logm $ "demote':isTl && isExported"
clients <- clientModsAndFiles targetModule
logm $ "demote':clients=" ++ (showGhc clients)
refactoredClients <-mapM (demotingInClientMod declaredPns) clients
return (refactoredMod:refactoredClients)
else do return [refactoredMod]
else error "\nInvalid cursor position!"
-- |Do refactoring in the client module, that is:
-- a) Check whether the identifier is used in the module body
-- b) If the identifier is not used but is hided by the import
-- declaration, then remove it from the hiding.
demotingInClientMod ::
[GHC.Name] -> TargetModule
-> RefactGhc ApplyRefacResult
demotingInClientMod pns targetModule = do
logm $ "demotingInClientMod:(pns,targetModule)=" ++ showGhc (pns,targetModule)
getTargetGhc targetModule
modu <- getRefactModule
(refactoredMod,_) <- applyRefac (doDemotingInClientMod pns modu) RSAlreadyLoaded
return refactoredMod
doDemotingInClientMod :: [GHC.Name] -> GHC.Module -> RefactGhc ()
doDemotingInClientMod pns modName = do
logm $ "doDemotingInClientMod:(pns,modName)=" ++ showGhc (pns,modName)
(GHC.L _ p) <- getRefactParsed
nm <- getRefactNameMap
if any (\pn -> findNameInRdr nm pn (GHC.hsmodDecls p) || findNameInRdr nm pn (GHC.hsmodExports p)) pns
then error $ "This definition can not be demoted, as it is used in the client module '"++(showGhc modName)++"'!"
else if any (\pn->findNameInRdr nm pn (GHC.hsmodImports p)) pns
-- TODO: reinstate this
then do -- (mod',((ts',m),_))<-runStateT (rmItemsFromImport mod pns) ((ts,unmodified),(-1000,0))
return ()
else return ()
-- ---------------------------------------------------------------------
doDemoting :: GHC.Name -> RefactGhc [GHC.Name]
doDemoting pn = do
clearRefactDone -- Only do this action once
parsed <- getRefactParsed
parsed' <- everywhereMStaged' SYB.Parser (SYB.mkM demoteInMod
`SYB.extM` demoteInMatch
`SYB.extM` demoteInPat
`SYB.extM` demoteInLet
`SYB.extM` demoteInStmt
) parsed
putRefactParsed parsed' emptyAnns
nm <- getRefactNameMap
decls <- liftT $ hsDecls parsed
let demotedDecls'= definingDeclsRdrNames nm [pn] decls True False
declaredPnsRdr = nub $ concatMap definedPNsRdr demotedDecls'
declaredPns = map (rdrName2NamePure nm) declaredPnsRdr
return declaredPns
where
--1. demote from top level
demoteInMod x@(parsed :: GHC.ParsedSource) = do
decls <- liftT $ hsDecls parsed
nm <- getRefactNameMap
if not $ emptyList (definingDeclsRdrNames nm [pn] decls False False)
then do
logm "MoveDef:demoteInMod" -- ++AZ++
demoted <- doDemoting' parsed pn
return demoted
else return x
--2. The demoted definition is a local decl in a match
demoteInMatch match@(GHC.L _ (GHC.Match _ _pats _mt (GHC.GRHSs _ _ds))::GHC.LMatch GHC.RdrName (GHC.LHsExpr GHC.RdrName)) = do
-- decls <- liftT $ hsDecls ds
decls <- liftT $ hsDecls match
nm <- getRefactNameMap
if not $ emptyList (definingDeclsRdrNames nm [pn] decls False False)
then do
logm "MoveDef:demoteInMatch" -- ++AZ++
done <- getRefactDone
match' <- if (not done)
then doDemoting' match pn
else return match
return match'
else return match
--3. The demoted definition is a local decl in a pattern binding
demoteInPat x@(pat@(GHC.L _ (GHC.ValD (GHC.PatBind _p (GHC.GRHSs _grhs _lb) _ _ _)))::GHC.LHsDecl GHC.RdrName) = do
decls <- liftT $ hsDeclsPatBindD x
nm <- getRefactNameMap
if not $ emptyList (definingDeclsRdrNames nm [pn] decls False False)
then do
logm "MoveDef:demoteInPat" -- ++AZ++
done <- getRefactDone
pat' <- if (not done)
then doDemoting' pat pn
else return pat
return pat'
else return x
demoteInPat x = return x
--4: The demoted definition is a local decl in a Let expression
demoteInLet x@(letExp@(GHC.L _ (GHC.HsLet _ds _e))::GHC.LHsExpr GHC.RdrName) = do
decls <- liftT $ hsDecls x
nm <- getRefactNameMap
if not $ emptyList (definingDeclsRdrNames nm [pn] decls False False)
then do
logm "MoveDef:demoteInLet" -- ++AZ++
done <- getRefactDone
letExp' <- if (not done)
then doDemoting' letExp pn
else return letExp
return letExp'
else return x
demoteInLet x = return x
--6.The demoted definition is a local decl in a Let statement.
-- demoteInStmt (letStmt@(HsLetStmt ds stmts):: (HsStmt (HsExpP) (HsPatP) [HsDeclP]))
demoteInStmt (letStmt@(GHC.L _ (GHC.LetStmt _binds))::GHC.LStmt GHC.RdrName (GHC.LHsExpr GHC.RdrName)) = do
decls <- liftT $ hsDecls letStmt
nm <- getRefactNameMap
if not $ emptyList (definingDeclsRdrNames nm [pn] decls False False)
then do
logm "MoveDef:demoteInStmt" -- ++AZ++
done <- getRefactDone
letStmt' <- if (not done)
then doDemoting' letStmt pn
else return letStmt
return letStmt'
else return letStmt
demoteInStmt x = return x
-- |Demote the declaration of 'pn' in the context of 't'.
doDemoting' :: (UsedByRhs t) => t -> GHC.Name -> RefactGhc t
doDemoting' t pn = do
nm <- getRefactNameMap
-- origDecls <- liftT $ hsDecls t
origDecls <- liftT $ hsDeclsGeneric t
let
demotedDecls'= definingDeclsRdrNames nm [pn] origDecls True False
declaredPns = nub $ concatMap (definedNamesRdr nm) demotedDecls'
pnsUsed = usedByRhsRdr nm t declaredPns
logm $ "doDemoting':(pn,declaredPns)=" ++ showGhc (pn,declaredPns)
-- logm $ "doDemoting':t=" ++ (SYB.showData SYB.Renamer 0 t)
logm $ "doDemoting':(declaredPns,pnsUsed)=" ++ showGhc (declaredPns,pnsUsed)
r <- if not pnsUsed -- (usedByRhs t declaredPns)
then do
logm $ "doDemoting' no pnsUsed"
-- dt <- liftT $ hsDecls t
let dt = origDecls
let demotedDecls = definingDeclsRdrNames nm [pn] dt True True
otherBinds = (deleteFirstsBy (sameBindRdr nm) dt demotedDecls)
{- From 'hsDecls t' to 'hsDecls t \\ demotedDecls'.
Bug fixed 06/09/2004 to handle direct recursive function.
-}
xx = map (\b -> (b,uses nm declaredPns [b])) otherBinds
useCount = sum $ concatMap snd xx
logm $ "doDemoting': declaredPns=" ++ (showGhc declaredPns)
logm $ "doDemoting': uses xx=" ++ (showGhc xx)
logm $ "doDemoting': uses useCount=" ++ (show useCount)
case useCount of
0 ->do error "\n Nowhere to demote this function!\n"
1 -> --This function is only used by one friend function
do
logm "MoveDef.doDemoting':target location found" -- ++AZ++
let (FN f,_d) = hsFreeAndDeclaredRdr nm demotedDecls
(ds,removedDecl,_sigRemoved) <- rmDecl pn False t
(t',demotedSigs) <- rmTypeSigs declaredPns ds
logDataWithAnns "MoveDef.doDemoting':after rmTypeSigs:demotedSigs=" demotedSigs
logm $ "MoveDef:declaredPns=" ++ (showGhc declaredPns) -- ++AZ++
dl <- mapM (flip (declaredNamesInTargetPlace nm) ds) declaredPns
logm $ "mapM declaredNamesInTargetPlace done"
--make sure free variable in 'f' do not clash with variables in 'dl',
--otherwise do renaming.
let clashedNames=filter (\x-> elem (id x) (map id f)) $ (nub.concat) dl
--rename clashed names to new names created automatically,update TOKEN STREAM as well.
if clashedNames/=[]
then error ("The identifier(s):" ++ showGhc clashedNames ++
", declared in where the definition will be demoted to, will cause name clash/capture"
++" after demoting, please do renaming first!")
else --duplicate demoted declarations to the right place.
do
duplicateDecls declaredPns removedDecl demotedSigs t'
_ ->error "\nThis function/pattern binding is used by more than one friend bindings\n"
else error "This function can not be demoted as it is used in current level!\n"
return r
where
---find how many matches/pattern bindings use 'pn'-------
uses :: NameMap -> [GHC.Name] -> [GHC.LHsDecl GHC.RdrName] -> [Int]
uses nm pns t2
= concatMap used t2
where
used :: GHC.LHsDecl GHC.RdrName -> [Int]
#if __GLASGOW_HASKELL__ <= 710
used (GHC.L _ (GHC.ValD (GHC.FunBind _n _ (GHC.MG matches _ _ _) _ _ _)))
#else
used (GHC.L _ (GHC.ValD (GHC.FunBind _n (GHC.MG (GHC.L _ matches) _ _ _) _ _ _)))
#endif
= concatMap (usedInMatch pns) matches
used (GHC.L _ (GHC.ValD (GHC.PatBind pat rhs _ _ _)))
| (not $ findNamesRdr nm pns pat) && findNamesRdr nm pns rhs
= [1::Int]
used _ = []
usedInMatch pns' (GHC.L _ (GHC.Match _ pats _ rhs))
| (not $ findNamesRdr nm pns' pats) && findNamesRdr nm pns' rhs
= [1::Int]
usedInMatch _ _ = []
duplicateDecls :: (SYB.Data t,SYB.Typeable t)
=> [GHC.Name] -- ^ function names to be demoted
-> GHC.LHsDecl GHC.RdrName -- ^Bind being demoted
-> [GHC.LSig GHC.RdrName] -- ^Signatures being demoted, if any
-> t
-> RefactGhc t
duplicateDecls pns demoted dsig o = do
logm $ "duplicateDecls:t=" ++ SYB.showData SYB.Parser 0 o
hasDeclsSybTransform workerHsDecls workerBind o
where
workerHsDecls :: forall t. HasDecls t => t -> RefactGhc t
workerHsDecls t' = do
dds <- liftT $ hsDecls t'
ds'' <- duplicateDecls' pns demoted dsig dds
liftT $ replaceDecls t' ds''
workerBind :: (GHC.LHsBind GHC.RdrName -> RefactGhc (GHC.LHsBind GHC.RdrName))
workerBind t'@(GHC.L _ (GHC.PatBind{})) = do
dds <- liftT $ hsDeclsPatBind t'
ds'' <- duplicateDecls' pns demoted dsig dds
liftT $ replaceDeclsPatBind t' ds''
workerBind x = error $ "MoveDef.duplicateDecls.workerBind:unmatched LHsBind:" ++ showGhc x
-- duplicate demotedDecls to the right place (the outer most level where it is used).
duplicateDecls' :: [GHC.Name] -- ^ function names to be demoted
-> GHC.LHsDecl GHC.RdrName -- ^Bind being demoted
-> [GHC.LSig GHC.RdrName] -- ^Signatures being demoted, if any
-> [GHC.LHsDecl GHC.RdrName] -- ^Binds of original top
-- level entiity,
-- including src and dst
-> RefactGhc [GHC.LHsDecl GHC.RdrName]
duplicateDecls' pns demoted dsig decls
= do
nm <- getRefactNameMap
everywhereMStaged' SYB.Parser (SYB.mkM (dupInMatch nm) -- top-down approach
`SYB.extM` (dupInPat nm)) decls
where
dupInMatch nm (match@(GHC.L _ (GHC.Match _ pats _mt rhs)) :: GHC.LMatch GHC.RdrName (GHC.LHsExpr GHC.RdrName))
| (not $ findNamesRdr nm pns pats) && findNamesRdr nm pns rhs
= do
done <- getRefactDone
logm $ "duplicateDecls.dupInMatch:value of done=" ++ (show done) -- ++AZ++
if done
then return match
else do
logm "duplicateDecls:setting done" -- ++AZ++
setRefactDone
match' <- foldParams pns match decls demoted dsig
return match'
dupInMatch _ x = return x
dupInPat nm ((GHC.PatBind pat rhs@(GHC.GRHSs grhs lb) ty fvs ticks) :: GHC.HsBind GHC.RdrName)
| (not $ findNamesRdr nm pns pat) && findNamesRdr nm pns rhs
= do
logm $ "duplicateDecls.dupInPat"
let declsToLift = definingDeclsRdrNames' nm pns t
lb' <- moveDecl1 lb Nothing pns declsToLift pns []
return (GHC.PatBind pat (GHC.GRHSs grhs lb') ty fvs ticks)
dupInPat _ x = return x
-- demotedDecls = definingDecls pns decls True False
---------------------------------------------------------------------
declaredNamesInTargetPlace :: (SYB.Data t)
=> NameMap -> GHC.Name -> t
-> RefactGhc [GHC.Name]
declaredNamesInTargetPlace nm pn' t' = do
logm $ "declaredNamesInTargetPlace:pn=" ++ (showGhc pn')
res <- applyTU (stop_tdTU (failTU
`adhocTU` inMatch
`adhocTU` inPat)) t'
logm $ "declaredNamesInTargetPlace:res=" ++ (showGhc res)
return res
where
inMatch ((GHC.Match _ _pats _ rhs) :: GHC.Match GHC.RdrName (GHC.LHsExpr GHC.RdrName))
| findNameInRdr nm pn' rhs = do
logm $ "declaredNamesInTargetPlace:inMatch"
-- fds <- hsFDsFromInside rhs
let (_,DN ds) = hsFDsFromInsideRdr nm rhs
return ds
inMatch _ = return mzero
inPat ((GHC.PatBind pat rhs _ _ _) :: GHC.HsBind GHC.RdrName)
|findNameInRdr nm pn' rhs = do
logm $ "declaredNamesInTargetPlace:inPat"
let (_,DN ds) = hsFDsFromInsideRdr nm pat
return ds
inPat _= return mzero
-- ---------------------------------------------------------------------
{- foldParams:remove parameters in the demotedDecls if possible
parameters: pn -- the function/pattern name to be demoted in PName format
match--where the demotedDecls will be demoted to
demotedDecls -- the declarations to be demoted.
example:
module Test where demote 'sq' module Test where
sumSquares x y ===> sumSquares x y =(sq 0) + (sq y)
= sq x 0+ sq x y where sq y=x ^ y
sq x y=x^y
-}
--PROBLEM: TYPE SIGNATURE SHOULD BE CHANGED.
--- TEST THIS FUNCTION!!!
foldParams :: [GHC.Name] -- ^The (list?) function name being demoted
-> GHC.LMatch GHC.RdrName (GHC.LHsExpr GHC.RdrName) -- ^The RHS of the place to receive the demoted decls
-> [GHC.LHsDecl GHC.RdrName] -- ^Binds of original top level entiity, including src and dst
-> GHC.LHsDecl GHC.RdrName -- ^The decls being demoted
-> [GHC.LSig GHC.RdrName] -- ^Signatures being demoted, if any
-> RefactGhc (GHC.LMatch GHC.RdrName (GHC.LHsExpr GHC.RdrName))
foldParams pns match@(GHC.L l (GHC.Match _mfn _pats _mt rhs)) _decls demotedDecls dsig
=do
logm $ "MoveDef.foldParams entered"
nm <- getRefactNameMap
let matches = concatMap matchesInDecls [demotedDecls]
pn = ghead "foldParams" pns --pns /=[]
logm $ "MoveDef.foldParams before allParams"
params <- allParams pn rhs []
logm $ "foldParams:params=" ++ showGhc params
if (length.nub.map length) params==1 -- have same number of param
&& ((length matches)==1) -- only one 'match' in the demoted declaration
then do
let patsInDemotedDecls=(patsInMatch.(ghead "foldParams")) matches
subst = mkSubst nm patsInDemotedDecls params
fstSubst = map fst subst
sndSubst = map snd subst
rhs' <- rmParamsInParent pn sndSubst rhs
let ls = map (hsFreeAndDeclaredRdr nm) sndSubst
let newNames = ((concatMap (fn . fst) ls)) \\ (fstSubst)
--There may be name clashing because of introducing new names.
clashedNames <- getClashedNames nm fstSubst newNames (ghead "foldParams" matches)
logm $ "MoveDef.foldParams about to foldInDemotedDecls"
demotedDecls''' <- foldInDemotedDecls pns clashedNames subst [demotedDecls]
logm $ "MoveDef.foldParams foldInDemotedDecls done"
let match' = GHC.L l ((GHC.unLoc match) {GHC.m_grhss = rhs' })
match'' <- addDecl match' Nothing (demotedDecls''',Nothing)
logm $ "MoveDef.foldParams addDecl done 1"
return match''
else do
logm $ "foldParams:no params"
let sigs = map wrapSig dsig
match' <- addDecl match Nothing (sigs++[demotedDecls],Nothing)
logm "MoveDef.foldParams addDecl done 2"
return match'
where
matchesInDecls :: GHC.LHsDecl GHC.RdrName -> [GHC.LMatch GHC.RdrName (GHC.LHsExpr GHC.RdrName)]
#if __GLASGOW_HASKELL__ <= 710
matchesInDecls (GHC.L _ (GHC.ValD (GHC.FunBind _ _ (GHC.MG matches _ _ _) _ _ _))) = matches
#else
matchesInDecls (GHC.L _ (GHC.ValD (GHC.FunBind _ (GHC.MG (GHC.L _ matches) _ _ _) _ _ _))) = matches
#endif
matchesInDecls _x = []
patsInMatch (GHC.L _ (GHC.Match _ pats' _ _)) = pats'
foldInDemotedDecls :: [GHC.Name] -- ^The (list?) of names to be demoted
-> [GHC.Name] -- ^Any names that clash
-> [(GHC.Name, GHC.HsExpr GHC.RdrName)] -- ^Parameter substitutions required
-> [GHC.LHsDecl GHC.RdrName] -- ^Binds of original top level entity, including src and dst
-> RefactGhc [GHC.LHsDecl GHC.RdrName]
foldInDemotedDecls pns' clashedNames subst decls = do
logm $ "foldInDemotedDecls:(pns',clashedNames,subst)=" ++ showGhc (pns',clashedNames,subst)
logm $ "foldInDemotedDecls:decls=" ++ SYB.showData SYB.Parser 0 decls
nm <- getRefactNameMap
SYB.everywhereMStaged SYB.Parser (SYB.mkM (worker nm) `SYB.extM` (workerBind nm)) decls
where
#if __GLASGOW_HASKELL__ <= 710
worker nm (match'@(GHC.L _ (GHC.FunBind ln _ (GHC.MG _matches _ _ _) _ _ _)) :: GHC.LHsBind GHC.RdrName)
#else
worker nm (match'@(GHC.L _ (GHC.FunBind ln (GHC.MG _matches _ _ _) _ _ _)) :: GHC.LHsBind GHC.RdrName)
#endif
= do
logm $ "foldInDemotedDecls:rdrName2NamePure nm ln=" ++ show (rdrName2NamePure nm ln)
if isJust (find (== rdrName2NamePure nm ln) pns')
then do
logm $ "foldInDemotedDecls:found match'"
match'' <- foldM (flip autoRenameLocalVar) match' clashedNames
match''' <- foldM replaceExpWithUpdToks match'' subst
rmParamsInDemotedDecls (map fst subst) match'''
else return match'
worker _ x = return x
workerBind nm ((GHC.L ll (GHC.ValD d)) :: GHC.LHsDecl GHC.RdrName)
= do
(GHC.L _ d') <- worker nm (GHC.L ll d)
return (GHC.L ll (GHC.ValD d'))
workerBind _ x = return x
------Get all of the paramaters supplied to pn ---------------------------
{- eg. sumSquares x1 y1 x2 y2 = rt x1 y1 + rt x2 y2
rt x y = x+y
demote 'rt' to 'sumSquares',
'allParams pn rhs []' returns [[x1,x2],[y1,y2]]
where pn is 'rt' and rhs is 'rt x1 y1 + rt x2 y2'
-}
allParams :: GHC.Name -> GHC.GRHSs GHC.RdrName (GHC.LHsExpr GHC.RdrName)
-> [[GHC.HsExpr GHC.RdrName]]
-> RefactGhc [[GHC.HsExpr GHC.RdrName]]
allParams pn rhs1 initial -- pn: demoted function/pattern name.
=do
nm <- getRefactNameMap
let p = getOneParam nm pn rhs1
-- putStrLn (show p)
logm $ "allParams:p=" ++ showGhc p
if (nonEmptyList p)
then do rhs' <- rmOneParam pn rhs1
logDataWithAnns "allParams:rhs'=" rhs'
allParams pn rhs' (initial++[p])
else return initial
where
getOneParam :: (SYB.Data t) => NameMap -> GHC.Name -> t -> [GHC.HsExpr GHC.RdrName]
getOneParam nm pn1
= SYB.everythingStaged SYB.Renamer (++) []
([] `SYB.mkQ` worker)
-- =applyTU (stop_tdTU (failTU `adhocTU` worker))
where
worker :: GHC.HsExpr GHC.RdrName -> [GHC.HsExpr GHC.RdrName]
worker (GHC.HsApp e1 e2)
|(expToNameRdr nm e1 == Just pn1) = [GHC.unLoc e2]
worker _ = []
rmOneParam :: (SYB.Data t) => GHC.Name -> t -> RefactGhc t
rmOneParam pn1 t
-- This genuinely needs to be done once only. Damn.
-- =applyTP (stop_tdTP (failTP `adhocTP` worker))
= do
-- _ <- clearRefactDone
nm <- getRefactNameMap
everywhereMStaged' SYB.Parser (SYB.mkM (worker nm)) t
where
worker nm (GHC.L _ (GHC.HsApp e1 _e2 )) -- The param being removed is e2
|expToNameRdr nm e1 == Just pn1 = return e1
worker _ x = return x
{-
AST output
addthree x y z
becomes
(HsApp
(L {test/testdata/Demote/WhereIn6.hs:10:17-28}
(HsApp
(L {test/testdata/Demote/WhereIn6.hs:10:17-26}
(HsApp
(L {test/testdata/Demote/WhereIn6.hs:10:17-24}
(HsVar {Name: WhereIn6.addthree}))
(L {test/testdata/Demote/WhereIn6.hs:10:26}
(HsVar {Name: x}))))
(L {test/testdata/Demote/WhereIn6.hs:10:28}
(HsVar {Name: y}))))
(L {test/testdata/Demote/WhereIn6.hs:10:30}
(HsVar {Name: z})))
-----
(HsApp
(HsApp
(HsApp
(HsVar {Name: WhereIn6.addthree}))
(HsVar {Name: x}))))
(HsVar {Name: y}))))
(HsVar {Name: z})))
-----
sq p x
becomes
(HsApp
(HsApp
(HsVar {Name: Demote.WhereIn4.sq}))
(HsVar {Name: p}))))
(HsVar {Name: x})))
----
sq x
becomes
(HsApp
(HsVar {Name: sq}))
(HsVar {Name: x})))
-}
-----------remove parameters in demotedDecls-------------------------------
rmParamsInDemotedDecls :: [GHC.Name] -> GHC.LHsBind GHC.RdrName
-> RefactGhc (GHC.LHsBind GHC.RdrName)
rmParamsInDemotedDecls ps bind
-- =applyTP (once_tdTP (failTP `adhocTP` worker))
= SYB.everywhereMStaged SYB.Parser (SYB.mkM worker) bind
where worker :: GHC.Match GHC.RdrName (GHC.LHsExpr GHC.RdrName) -> RefactGhc (GHC.Match GHC.RdrName (GHC.LHsExpr GHC.RdrName))
worker (GHC.Match mfn' pats2 typ rhs1)
= do
nm <- getRefactNameMap
let pats'=filter (\x->not ((patToNameRdr nm x /= Nothing) &&
elem (gfromJust "rmParamsInDemotedDecls" $ patToNameRdr nm x) ps)) pats2
return (GHC.Match mfn' pats' typ rhs1)
----------remove parameters in the parent functions' rhs-------------------
rmParamsInParent :: GHC.Name -> [GHC.HsExpr GHC.RdrName]
-> GHC.GRHSs GHC.RdrName (GHC.LHsExpr GHC.RdrName)
-> RefactGhc (GHC.GRHSs GHC.RdrName (GHC.LHsExpr GHC.RdrName))
rmParamsInParent pn es grhss = do
nm <- getRefactNameMap
-- =applyTP (full_buTP (idTP `adhocTP` worker))
SYB.everywhereMStaged SYB.Renamer (SYB.mkM (worker nm)) grhss
where worker nm expr@(GHC.L _ (GHC.HsApp e1 e2))
| findNamesRdr nm [pn] e1 && (elem (showGhc (GHC.unLoc e2)) (map (showGhc) es))
= do
liftT $ transferEntryDPT expr e1
return e1
worker nm (expr@(GHC.L _ (GHC.HsPar e1)))
|Just pn==expToNameRdr nm e1
= do
liftT $ transferEntryDPT expr e1
return e1
worker _ x =return x
getClashedNames :: NameMap -> [GHC.Name] -> [GHC.Name]
-> GHC.LMatch GHC.RdrName (GHC.LHsExpr GHC.RdrName)
-> RefactGhc [GHC.Name]
getClashedNames nm oldNames newNames match'
= do let (_f,DN d) = hsFDsFromInsideRdr nm match'
ds'' <- mapM (flip (hsVisibleDsRdr nm) match') oldNames
let ds' = map (\(DN ds) -> ds) ds''
-- return clashed names
return (filter (\x->elem ({- pNtoName -} x) newNames) --Attention: nub
( nub (d `union` (nub.concat) ds')))
----- make Substitions between formal and actual parameters.-----------------
mkSubst :: NameMap
-> [GHC.LPat GHC.RdrName] -> [[GHC.HsExpr GHC.RdrName]]
-> [(GHC.Name,GHC.HsExpr GHC.RdrName)]
mkSubst nm pats1 params
= catMaybes (zipWith (\x y -> if (patToNameRdr nm x/=Nothing) && (length (nub $ map showGhc y)==1)
then Just (gfromJust "mkSubst" $ patToNameRdr nm x,(ghead "mkSubst") y)
else Nothing) pats1 params)
-- |substitute an old expression by new expression
replaceExpWithUpdToks :: GHC.LHsBind GHC.RdrName -> (GHC.Name, GHC.HsExpr GHC.RdrName)
-> RefactGhc (GHC.LHsBind GHC.RdrName)
replaceExpWithUpdToks decls subst = do
nm <- getRefactNameMap
let
worker (e@(GHC.L l _)::GHC.LHsExpr GHC.RdrName)
|(expToNameRdr nm e) == Just (fst subst)
= return (GHC.L l (snd subst))
worker x=return x
-- = applyTP (full_buTP (idTP `adhocTP` worker)) decls
everywhereMStaged' SYB.Parser (SYB.mkM worker) decls
-- | return True if pn is a local function/pattern name
isLocalFunOrPatName :: SYB.Data t => NameMap -> GHC.Name -> t -> Bool
isLocalFunOrPatName nm pn scope
= isLocalPN pn && isFunOrPatName nm pn scope
-- EOF
| RefactoringTools/HaRe | src/Language/Haskell/Refact/Refactoring/MoveDef.hs | bsd-3-clause | 76,745 | 1 | 30 | 25,582 | 13,857 | 6,895 | 6,962 | 905 | 14 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE PackageImports #-}
{-# LANGUAGE TemplateHaskell #-}
module Snap.Snaplet.Internal.Tests
( tests, initTest ) where
------------------------------------------------------------------------------
import Control.Lens (makeLenses)
import Control.Monad.Trans (MonadIO, liftIO)
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as B
import Data.Text (Text)
import Prelude hiding (catch, (.))
import System.Directory (getCurrentDirectory)
import Test.Framework (Test, testGroup)
import Test.Framework.Providers.HUnit (testCase)
import Test.Framework.Providers.SmallCheck (testProperty)
import Test.HUnit hiding (Test, path)
import Test.SmallCheck ((==>))
------------------------------------------------------------------------------
import Snap.Snaplet.Internal.Initializer
import Snap.Snaplet.Internal.Types
---------------------------------
-- TODO: this module is a mess --
---------------------------------
------------------------------------------------------------------------------
data Foo = Foo Int
data Bar = Bar Int
data App = App
{ _foo :: Snaplet Foo
, _bar :: Snaplet Bar
}
makeLenses ''App
--showConfig :: SnapletConfig -> IO ()
--showConfig c = do
-- putStrLn "SnapletConfig:"
-- print $ _scAncestry c
-- print $ _scFilePath c
-- print $ _scId c
-- print $ _scDescription c
-- print $ _scRouteContext c
-- putStrLn ""
------------------------------------------------------------------------------
assertGet :: (MonadIO m, Show a, Eq a) => String -> m a -> a -> m ()
assertGet name getter val = do
v <- getter
liftIO $ assertEqual name val v
------------------------------------------------------------------------------
configAssertions :: (MonadSnaplet m, MonadIO (m b v))
=> [Char]
-> ([Text], FilePath, Maybe Text, Text, ByteString)
-> m b v ()
configAssertions prefix (a,f,n,d,r) = do
assertGet (prefix ++ "ancestry" ) getSnapletAncestry a
assertGet (prefix ++ "file path" ) getSnapletFilePath f
assertGet (prefix ++ "name" ) getSnapletName n
assertGet (prefix ++ "description" ) getSnapletDescription d
assertGet (prefix ++ "route context" ) getSnapletRootURL r
------------------------------------------------------------------------------
appInit :: SnapletInit App App
appInit = makeSnaplet "app" "Test application" Nothing $ do
cwd <- liftIO getCurrentDirectory
configAssertions "root "
([], cwd, Just "app", "Test application", "")
assertGet "environment" getEnvironment "devel"
f <- nestSnaplet "foo" foo $ fooInit
b <- nestSnaplet "bar" bar $ barInit
return $ App f b
------------------------------------------------------------------------------
fooInit :: SnapletInit b Foo
fooInit = makeSnaplet "foo" "Foo Snaplet" Nothing $ do
cwd <- liftIO getCurrentDirectory
let dir = cwd ++ "/snaplets/foo"
configAssertions "foo "
(["app"], dir, Just "foo", "Foo Snaplet", "foo")
return $ Foo 42
------------------------------------------------------------------------------
barInit :: SnapletInit b Bar
barInit = makeSnaplet "bar" "Bar Snaplet" Nothing $ do
cwd <- liftIO getCurrentDirectory
let dir = cwd ++ "/snaplets/bar"
configAssertions "bar "
(["app"], dir, Just "bar", "Bar Snaplet", "bar")
return $ Bar 2
------------------------------------------------------------------------------
initTest :: IO ()
initTest = do
(out,_,_) <- runSnaplet Nothing appInit
-- note from gdc: wtf?
if out == "aoeu"
then putStrLn "Something really strange"
else return ()
------------------------------------------------------------------------------
tests :: Test
tests = testGroup "Snap.Snaplet.Internal"
[ testCase "initializer tests" initTest
, testProperty "buildPath generates no double slashes" doubleSlashes
]
--doubleSlashes :: Monad m => [String] -> Property m
doubleSlashes arrStr = noSlashes ==> not (B.isInfixOf "//" $ buildPath arr)
where
arr = map B.pack arrStr
noSlashes = not $ or $ map (B.elem '/') arr
| sopvop/snap | test/suite/Snap/Snaplet/Internal/Tests.hs | bsd-3-clause | 4,669 | 0 | 11 | 1,206 | 963 | 520 | 443 | 76 | 2 |
--
-- Copyright (c) 2012 Citrix Systems, Inc.
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
--
{-# LANGUAGE PatternGuards, ScopedTypeVariables #-}
module Vm.ProductProperty
(
ProductProperty (..)
, ProductPropertyType (..)
, ProductPropertyValue
, PPUniqueID (..)
, ppUniqueID
, ppEnvKey
, vmPPList
, vmPPUpdate
, vmPPRm
, vmPPGetValue
, vmPPSetValue
, vmHasAnyPP
, strPPT
, pptStr
) where
import Control.Applicative
import Control.Monad
import Data.Maybe
import qualified Data.Map as Map
import Data.Map (Map)
import Data.Word
import Data.Int
import Text.Printf
import Rpc.Core
import Tools.Db
import Vm.Uuid
newtype PPUniqueID = PPUniqueID { strPPUniqueID :: String } deriving Eq
instance Show PPUniqueID where show = strPPUniqueID
data ProductProperty
= ProductProperty
{ ppKey :: String
, ppClass :: String
, ppInstance :: String
, ppType :: ProductPropertyType
, ppDescription :: String
, ppUserConfigurable :: Bool
, ppPassword :: Bool
, ppValue :: ProductPropertyValue
}
deriving (Eq,Show)
data ProductPropertyType
= PPT_Uint8 | PPT_Sint8 | PPT_Uint16 | PPT_Sint16 | PPT_Uint32 | PPT_Sint32 | PPT_Uint64 | PPT_Sint64
| PPT_String | PPT_Bool | PPT_Real32 | PPT_Real64
deriving (Eq,Ord,Show)
type ProductPropertyValue = String
pptStrMapping = Map.fromList [
(PPT_Uint8, "uint8")
, (PPT_Sint8, "sint8")
, (PPT_Uint16, "uint16")
, (PPT_Sint16, "sint16")
, (PPT_Uint32, "uint32")
, (PPT_Sint32, "sint32")
, (PPT_Uint64, "uint64")
, (PPT_Sint64, "sint64")
, (PPT_Real32, "real32")
, (PPT_Real64, "real64")
, (PPT_Bool, "Boolean")
, (PPT_String, "String")
]
strPPTMapping
= Map.fromList . map swap . Map.toList $ pptStrMapping where
swap (k,v) = (v,k)
strPPT :: ProductPropertyType -> String
strPPT t = str where Just str = Map.lookup t pptStrMapping
pptStr :: String -> Maybe ProductPropertyType
pptStr s = Map.lookup s strPPTMapping
instance Marshall ProductPropertyType where
dbWrite p v = dbWrite p (strPPT v)
dbRead p = do
str <- dbRead p
return $ fromMaybe (error $ "invalid ProductPropertyType: " ++ show str) (pptStr str)
instance Marshall ProductProperty where
dbWrite p pp = do
w "key" (noempty . ppKey)
w "class" (noempty . ppClass)
w "instance" (noempty . ppInstance)
w "type" (Just . strPPT . ppType)
w "description" (noempty . ppDescription)
w "userconfigurable" (Just . ppUserConfigurable)
w "password" (Just . ppPassword)
w "value" (noempty . ppValue)
where
w field f = dbMaybeWrite (p ++ "/" ++ field) (f pp)
noempty str
| null str = Nothing
| otherwise = Just str
dbRead p =
ProductProperty
<$> r "key" ""
<*> r "class" ""
<*> r "instance" ""
<*> r "type" PPT_String
<*> r "description" ""
<*> r "userconfigurable" False
<*> r "password" False
<*> r "value" ""
where
r k def = dbReadWithDefault def (p ++ "/" ++ k)
ppUniqueID :: ProductProperty -> PPUniqueID
ppUniqueID pp = PPUniqueID $
mapNoEmpty (++ ".") (ppClass pp)
++ ppKey pp
++ mapNoEmpty ("." ++) (ppInstance pp)
where
mapNoEmpty f "" = ""
mapNoEmpty f s = f s
ppEnvKey = strPPUniqueID
ppGroupDBPath vm = vmPath vm ++ "/productproperty"
ppDBPath vm_id pp_id = ppGroupDBPath vm_id ++ "/" ++ (strPPUniqueID pp_id)
vmPath uuid = "/vm/" ++ show uuid
vmHasAnyPP :: MonadRpc e m => Uuid -> m Bool
vmHasAnyPP vm = ((> 0) . length) <$> dbList (ppGroupDBPath vm)
vmPPList :: MonadRpc e m => Uuid -> m [ProductProperty]
vmPPList vm_id = filter valid <$> dbRead (ppGroupDBPath vm_id) where
valid = not . null . ppKey
vmPPUpdate :: MonadRpc e m => Uuid -> ProductProperty -> m ()
vmPPUpdate vm_id pp = dbWrite (ppDBPath vm_id (ppUniqueID pp)) pp
vmPPRm :: MonadRpc e m => Uuid -> PPUniqueID -> m ()
vmPPRm vm_id pp_id = dbRm (ppDBPath vm_id pp_id)
vmPPGetValue :: MonadRpc e m => Uuid -> PPUniqueID -> m String
vmPPGetValue vm_id pp_id = dbRead (ppDBPath vm_id pp_id ++ "/value")
vmPPSetValue :: MonadRpc e m => Uuid -> PPUniqueID -> String -> m ()
vmPPSetValue vm_id pp_id str = do
pp <- dbRead (ppDBPath vm_id pp_id)
case sanitiseValue str (ppType pp) of
Nothing -> error $ printf "value '%s' is invalid for product property '%s' of type %s" str (show $ ppUniqueID pp) (show $ ppType pp)
Just str -> dbWrite (ppDBPath vm_id pp_id ++ "/value") str
sanitiseValue :: String -> ProductPropertyType -> Maybe String
sanitiseValue v = f where
f PPT_String = Just v
f PPT_Uint8 = bounded (minBound :: Word8) (maxBound :: Word8) =<< integer
f PPT_Sint8 = bounded (minBound :: Int8) (maxBound :: Int8) =<< integer
f PPT_Uint16 = bounded (minBound :: Word16) (maxBound :: Word16) =<< integer
f PPT_Sint16 = bounded (minBound :: Int16) (maxBound :: Int16) =<< integer
f PPT_Uint32 = bounded (minBound :: Word32) (maxBound :: Word32) =<< integer
f PPT_Sint32 = bounded (minBound :: Int32) (maxBound :: Int32) =<< integer
f PPT_Uint64 = bounded (minBound :: Word64) (maxBound :: Word64) =<< integer
f PPT_Sint64 = bounded (minBound :: Int64) (maxBound :: Int64) =<< integer
f PPT_Bool
| v `elem` ["true", "false"] = Just v
| otherwise = Nothing
f PPT_Real32
| parses (undefined :: Float) v = Just v
| otherwise = Nothing
f PPT_Real64
| parses (undefined :: Double) v = Just v
| otherwise = Nothing
bounded min max x
| x >= fromIntegral min, x <= fromIntegral max = Just v
| otherwise = Nothing
integer :: Maybe Integer
integer = parse v
parses :: forall a. Read a => a -> String -> Bool
parses _ str = isJust (parse str :: Maybe a)
parse :: Read a => String -> Maybe a
parse v = case reads v of
((i,_):_) -> Just i
_ -> Nothing
| jean-edouard/manager | xenmgr-core/Vm/ProductProperty.hs | gpl-2.0 | 6,554 | 0 | 14 | 1,511 | 2,039 | 1,071 | 968 | 155 | 13 |
module MapFusion where
import Prelude hiding (map)
{-# RULES "map-fusion" forall f g. map f . map g = map (f . g) #-}
map :: (a -> b) -> [a] -> [b]
map f [] = []
map f (a:as) = f a : map f as
| conal/hermit | examples/map-fusion/MapFusion.hs | bsd-2-clause | 201 | 0 | 7 | 57 | 83 | 46 | 37 | 6 | 1 |
{-# LANGUAGE DeriveGeneric #-}
module GHC.ForeignSrcLang.Type
( ForeignSrcLang(..)
) where
import Prelude -- See note [Why do we import Prelude here?]
import GHC.Generics (Generic)
-- | Foreign formats supported by GHC via TH
data ForeignSrcLang
= LangC -- ^ C
| LangCxx -- ^ C++
| LangObjc -- ^ Objective C
| LangObjcxx -- ^ Objective C++
| LangAsm -- ^ Assembly language (.s)
| RawObject -- ^ Object (.o)
deriving (Eq, Show, Generic)
| sdiehl/ghc | libraries/ghc-boot-th/GHC/ForeignSrcLang/Type.hs | bsd-3-clause | 470 | 0 | 6 | 108 | 75 | 50 | 25 | 13 | 0 |
module B1 where
import A1
f :: C1 -> [Int]
f (C1 x@[]) = x
f (C1 x@(b_1 : b_2)) = x
f (C1 x) = x | kmate/HaRe | old/testing/subIntroPattern/B1_TokOut.hs | bsd-3-clause | 98 | 0 | 10 | 28 | 76 | 42 | 34 | 6 | 1 |
module ScopeNamesBase where
import ScopeNames
import ScopeNamesBaseStruct
import DefinedNamesBase()
import FreeNamesBase()
import Syntax
instance Eq i => ScopeNames i e (HsExpI i) (HsExpI (i,e)) where
scopeNames = scopeNamesRec
instance Eq i => ScopeNames i e (HsDeclI i) (HsDeclI (i,e)) where
scopeNames = scopeNamesRec
instance ScopeNames i e (HsPatI i) (HsPatI (i,e)) where
scopeNames = scopeNamesRec
instance ScopeNames i e (HsTypeI i) (HsTypeI (i,e)) where
scopeNames = scopeNamesRec
| forste/haReFork | tools/base/defs/ScopeNamesBase.hs | bsd-3-clause | 507 | 0 | 8 | 85 | 187 | 103 | 84 | -1 | -1 |
module Pfe2Cmds where
--import Prelude hiding (putStr,putStrLn)
--import WorkModule(analyzeSCM,expRel,inscpRel,mkWM)
import Relations(applyRel)
import SourceNames(SN(..))
import SrcLoc1(loc0)
import Pfe1Cmds(pfe1Cmds)
import PfeParse(moduleArg,idArgs,runCmds)
import PFE2(runPFE2,getModuleExports,getAllExports)
import PFE0(pput,allModules)
--import AbstractIO
import PrettyPrint
import MUtils(done)
pfe2 ext = runPFE2Cmds ext pfe2Cmds
runPFE2Cmds ext = runCmds (runPFE2 ext)
pfe2Cmds =
pfe1Cmds ++
[-- Module system queries (import/export, top level environment)
-- ("topenv" , (Null topenv, "check all import and export specifications")), -- just update, no output
("exports" , (moduleArg exports,"list entities exported by the modules")),
("find" , (idArgs find,"find exported entities with the given names"))
]
--- Module system queries (import/export, top level environment) ---------------
exports = showModuleInfo snd
showModuleInfo sel m = pput . ppModuleInfo sel m =<< getModuleExports m
ppExports = ppModuleInfo snd
ppModuleInfo sel m info = sep [m<>":",nest 2 . ppi $ sel info]
find ids = do exports <- getAllExports
mapM_ (mapM_ pp1 . find1 exports) ids
where
pp1 (m,ents) = pput (m<>":"<+>vcat ents)
find1 mes id =
[(m,ents)|(m,(t,es))<-mes,
let ents=applyRel es (sn id),
not (null ents)]
--topenv = analyzeModules >> done
sn n = SN n loc0 -- !!
| forste/haReFork | tools/pfe/Pfe2Cmds.hs | bsd-3-clause | 1,444 | 4 | 14 | 263 | 412 | 226 | 186 | 29 | 1 |
{-# LANGUAGE Unsafe #-}
{-# LANGUAGE ExistentialQuantification, NoImplicitPrelude #-}
module GHC.Event.Internal
(
-- * Event back end
Backend
, backend
, delete
, poll
, modifyFd
, modifyFdOnce
-- * Event type
, Event
, evtRead
, evtWrite
, evtClose
, eventIs
-- * Lifetimes
, Lifetime(..)
, EventLifetime
, eventLifetime
, elLifetime
, elEvent
-- * Timeout type
, Timeout(..)
-- * Helpers
, throwErrnoIfMinus1NoRetry
) where
import Data.Bits ((.|.), (.&.))
import Data.OldList (foldl', filter, intercalate, null)
import Foreign.C.Error (eINTR, getErrno, throwErrno)
import System.Posix.Types (Fd)
import GHC.Base
import GHC.Num (Num(..))
import GHC.Show (Show(..))
-- | An I\/O event.
newtype Event = Event Int
deriving (Eq)
evtNothing :: Event
evtNothing = Event 0
{-# INLINE evtNothing #-}
-- | Data is available to be read.
evtRead :: Event
evtRead = Event 1
{-# INLINE evtRead #-}
-- | The file descriptor is ready to accept a write.
evtWrite :: Event
evtWrite = Event 2
{-# INLINE evtWrite #-}
-- | Another thread closed the file descriptor.
evtClose :: Event
evtClose = Event 4
{-# INLINE evtClose #-}
eventIs :: Event -> Event -> Bool
eventIs (Event a) (Event b) = a .&. b /= 0
-- | @since 4.3.1.0
instance Show Event where
show e = '[' : (intercalate "," . filter (not . null) $
[evtRead `so` "evtRead",
evtWrite `so` "evtWrite",
evtClose `so` "evtClose"]) ++ "]"
where ev `so` disp | e `eventIs` ev = disp
| otherwise = ""
-- | @since 4.3.1.0
instance Monoid Event where
mempty = evtNothing
mappend = evtCombine
mconcat = evtConcat
evtCombine :: Event -> Event -> Event
evtCombine (Event a) (Event b) = Event (a .|. b)
{-# INLINE evtCombine #-}
evtConcat :: [Event] -> Event
evtConcat = foldl' evtCombine evtNothing
{-# INLINE evtConcat #-}
-- | The lifetime of an event registration.
--
-- @since 4.8.1.0
data Lifetime = OneShot -- ^ the registration will be active for only one
-- event
| MultiShot -- ^ the registration will trigger multiple times
deriving (Show, Eq)
-- | The longer of two lifetimes.
elSupremum :: Lifetime -> Lifetime -> Lifetime
elSupremum OneShot OneShot = OneShot
elSupremum _ _ = MultiShot
{-# INLINE elSupremum #-}
-- | @mappend@ == @elSupremum@
--
-- @since 4.8.0.0
instance Monoid Lifetime where
mempty = OneShot
mappend = elSupremum
-- | A pair of an event and lifetime
--
-- Here we encode the event in the bottom three bits and the lifetime
-- in the fourth bit.
newtype EventLifetime = EL Int
deriving (Show, Eq)
-- | @since 4.8.0.0
instance Monoid EventLifetime where
mempty = EL 0
EL a `mappend` EL b = EL (a .|. b)
eventLifetime :: Event -> Lifetime -> EventLifetime
eventLifetime (Event e) l = EL (e .|. lifetimeBit l)
where
lifetimeBit OneShot = 0
lifetimeBit MultiShot = 8
{-# INLINE eventLifetime #-}
elLifetime :: EventLifetime -> Lifetime
elLifetime (EL x) = if x .&. 8 == 0 then OneShot else MultiShot
{-# INLINE elLifetime #-}
elEvent :: EventLifetime -> Event
elEvent (EL x) = Event (x .&. 0x7)
{-# INLINE elEvent #-}
-- | A type alias for timeouts, specified in seconds.
data Timeout = Timeout {-# UNPACK #-} !Double
| Forever
deriving (Show)
-- | Event notification backend.
data Backend = forall a. Backend {
_beState :: !a
-- | Poll backend for new events. The provided callback is called
-- once per file descriptor with new events.
, _bePoll :: a -- backend state
-> Maybe Timeout -- timeout in milliseconds ('Nothing' for non-blocking poll)
-> (Fd -> Event -> IO ()) -- I/O callback
-> IO Int
-- | Register, modify, or unregister interest in the given events
-- on the given file descriptor.
, _beModifyFd :: a
-> Fd -- file descriptor
-> Event -- old events to watch for ('mempty' for new)
-> Event -- new events to watch for ('mempty' to delete)
-> IO Bool
-- | Register interest in new events on a given file descriptor, set
-- to be deactivated after the first event.
, _beModifyFdOnce :: a
-> Fd -- file descriptor
-> Event -- new events to watch
-> IO Bool
, _beDelete :: a -> IO ()
}
backend :: (a -> Maybe Timeout -> (Fd -> Event -> IO ()) -> IO Int)
-> (a -> Fd -> Event -> Event -> IO Bool)
-> (a -> Fd -> Event -> IO Bool)
-> (a -> IO ())
-> a
-> Backend
backend bPoll bModifyFd bModifyFdOnce bDelete state =
Backend state bPoll bModifyFd bModifyFdOnce bDelete
{-# INLINE backend #-}
poll :: Backend -> Maybe Timeout -> (Fd -> Event -> IO ()) -> IO Int
poll (Backend bState bPoll _ _ _) = bPoll bState
{-# INLINE poll #-}
-- | Returns 'True' if the modification succeeded.
-- Returns 'False' if this backend does not support
-- event notifications on this type of file.
modifyFd :: Backend -> Fd -> Event -> Event -> IO Bool
modifyFd (Backend bState _ bModifyFd _ _) = bModifyFd bState
{-# INLINE modifyFd #-}
-- | Returns 'True' if the modification succeeded.
-- Returns 'False' if this backend does not support
-- event notifications on this type of file.
modifyFdOnce :: Backend -> Fd -> Event -> IO Bool
modifyFdOnce (Backend bState _ _ bModifyFdOnce _) = bModifyFdOnce bState
{-# INLINE modifyFdOnce #-}
delete :: Backend -> IO ()
delete (Backend bState _ _ _ bDelete) = bDelete bState
{-# INLINE delete #-}
-- | Throw an 'IOError' corresponding to the current value of
-- 'getErrno' if the result value of the 'IO' action is -1 and
-- 'getErrno' is not 'eINTR'. If the result value is -1 and
-- 'getErrno' returns 'eINTR' 0 is returned. Otherwise the result
-- value is returned.
throwErrnoIfMinus1NoRetry :: (Eq a, Num a) => String -> IO a -> IO a
throwErrnoIfMinus1NoRetry loc f = do
res <- f
if res == -1
then do
err <- getErrno
if err == eINTR then return 0 else throwErrno loc
else return res
| snoyberg/ghc | libraries/base/GHC/Event/Internal.hs | bsd-3-clause | 6,369 | 0 | 16 | 1,795 | 1,397 | 778 | 619 | 138 | 3 |
module Main where
import X
main :: IO ()
main = print $ case f x of A -> True; B -> False
| ghc-android/ghc | testsuite/tests/driver/recomp010/Main.hs | bsd-3-clause | 93 | 0 | 8 | 26 | 46 | 25 | 21 | 4 | 2 |
module Main where
import Game
main = putStrLn "This game is not yet implemented, so you win by default!"
| PolyglotSymposium/textual-game-hs | Main.hs | mit | 107 | 0 | 5 | 21 | 15 | 9 | 6 | 3 | 1 |
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
import qualified Data.ByteString as BS
import Control.Applicative ((<$>))
import Data.Proxy
import Manifest.Manifest
import Manifest.PureManifest
import Manifest.PostgreSQL
data User = User BS.ByteString
deriving (Show)
type Email = BS.ByteString
data WithEmail a = WithEmail a Email
deriving (Show)
email :: WithEmail a -> Email
email (WithEmail _ x) = x
instance ManifestKey User where
manifestibleKeyDump (User b) = b
manifestibleKeyPull = Just . User
instance Manifestible (WithEmail a) where
type ManifestibleKey (WithEmail a) = a
type ManifestibleValue (WithEmail a) = Email
manifestibleKey (WithEmail x _) = x
manifestibleValue (WithEmail _ x) = x
manifestibleFactorization = WithEmail
ada = User "ada"
richard = User "richard"
adaEmail = WithEmail ada "[email protected]"
richardEmail = WithEmail richard "[email protected]"
-- If we wish to use a PureManifest, all we have to do is uncomment this,
-- and remove the conflicting definitions below!
--type MyEmailManifest = PureManifest
--myEmailManifest :: MyEmailManifest a
--myEmailManifest = emptyPM
type MyEmailManifest = PostgreSQL
myEmailManifest = postgresql info "emails"
where
info = ConnectInfo "localhost" (fromIntegral 5432) "" "" "alex"
main = do
let emailManifest = myEmailManifest
let writeem = do {
mput adaEmail (Proxy :: Proxy MyEmailManifest);
mput richardEmail (Proxy :: Proxy MyEmailManifest);
}
let readem = do {
adasEmail <- mget ada (Proxy :: Proxy (MyEmailManifest (WithEmail User)));
richardsEmail <- mget richard (Proxy :: Proxy (MyEmailManifest (WithEmail User)));
return (email <$> adasEmail, email <$> richardsEmail)
}
(writeOutcome, emailManifest) <- manifest emailManifest writeem
(readOutcome1, emailManifest) <- manifest emailManifest readem
let deleteem = do {
richardsEmail <- mdel richard (Proxy :: Proxy (MyEmailManifest (WithEmail User)));
return richardsEmail
}
(deleteOutcome, emailManifest) <- manifest emailManifest deleteem
(readOutcome2, emailManifest) <- manifest emailManifest readem
printOutcome writeOutcome
printOutcome readOutcome1
printOutcome deleteOutcome
printOutcome readOutcome2
where
printOutcome x = case x of
Right y -> putStr "OK! " >> print y
Left y -> case y of
GeneralFailure f -> putStr "Not OK! " >> print f
PeculiarFailure f -> putStr "Not OK! " >> print f
| avieth/Manifest-PostgreSQL | examples/User.hs | mit | 2,579 | 30 | 17 | 521 | 675 | 353 | 322 | 57 | 3 |
{-# LANGUAGE ExistentialQuantification, MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings, FlexibleInstances #-}
{-# OPTIONS_HADDOCK prune, not-home #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
-- | Provides framework to interact with REST api gateways. Implementations specific to the
-- Discord API are provided in Network.Discord.Rest.Channel, Network.Discord.Rest.Guild,
-- and Network.Discord.Rest.User.
module Network.Discord.Rest
( module Network.Discord.Rest
, module Network.Discord.Rest.Prelude
, module Network.Discord.Rest.Channel
, module Network.Discord.Rest.Guild
, module Network.Discord.Rest.User
) where
import Control.Monad (void)
import Data.Maybe (fromJust)
import Control.Exception (throwIO)
import qualified Network.HTTP.Req as R
import Control.Monad.Morph (lift)
import Data.Aeson.Types
import Data.Hashable
import Network.URL
import Pipes.Core
import Network.Discord.Types as Dc
import Network.Discord.Rest.Channel
import Network.Discord.Rest.Guild
import Network.Discord.Rest.Prelude
import Network.Discord.Rest.User
import Network.Discord.Rest.HTTP (baseUrl)
-- | Perform an API request.
fetch :: (DoFetch a, Hashable a)
=> a -> Pipes.Core.Proxy X () c' c DiscordM Fetched
fetch req = restServer +>> (request $ Fetch req)
-- | Perform an API request, ignoring the response
fetch' :: (DoFetch a, Hashable a)
=> a -> Pipes.Core.Proxy X () c' c DiscordM ()
fetch' = void . fetch
-- | Alternative method of interacting with the REST api
withApi :: Pipes.Core.Client Fetchable Fetched DiscordM Fetched
-> Effect DiscordM ()
withApi inner = void $ restServer +>> inner
-- | Provides a pipe to perform REST actions
restServer :: Fetchable -> Server Fetchable Fetched DiscordM Fetched
restServer req =
lift (doFetch req) >>= respond >>= restServer
instance R.MonadHttp IO where
handleHttpException = throwIO
-- | Obtains a new gateway to connect to.
getGateway :: IO URL
getGateway = do
r <- R.req R.GET (baseUrl R./: "gateway") R.NoReqBody R.jsonResponse mempty
return . fromJust $ importURL =<< parseMaybe getURL (R.responseBody r)
where
getURL :: Value -> Parser String
getURL = withObject "url" (.: "url")
| jano017/Discord.hs | src/Network/Discord/Rest.hs | mit | 2,346 | 0 | 11 | 490 | 502 | 290 | 212 | 45 | 1 |
{-|
Parse a list of flags supported in any of the front ends.
Returns the flags in a data structure, along with any invalid flags.
Deal with any files/include files in this stage.
-}
module CmdLine.Flag(
CmdFlag(..), flagsHelp,
flagsWebArgs, flagsWebQuery, flagsCmdLine
) where
import General.Code
import General.Glob
---------------------------------------------------------------------
-- The flags
data CmdFlag = Version -- ^ Version information
| Web -- ^ Operate as a CGI process
| Help -- ^ Help text
| Test -- ^ Run the regression tests
| Color Bool -- ^ Colors on the console
| Start Int -- ^ First result to show
| Count Int -- ^ Number of results to show
| Convert FilePath -- ^ Convert a database
| Output FilePath -- ^ Output file
| Dump String -- ^ Dump a database to a file (optional section)
| DataFile FilePath -- ^ Database location
| Verbose -- ^ Display verbose information
| Info -- ^ Display as much information as you can
| Debug -- ^ Do debugging activities
| Include FilePath -- ^ Include directory
| TestFile FilePath -- ^ Run tests in a file
| Rank FilePath -- ^ Generate rankings
| Combine FilePath -- ^ Merge a set of databases
| Mode String -- ^ Web modes
deriving (Show,Eq {-! Enum !-} )
-- | In which circumstances are you allowed to pass this command
data Permission = PWebArgs | PWebQuery | PCmdLine | PMultiple
deriving (Show,Eq)
data Argument = ArgNone CmdFlag
| ArgBool (Bool -> CmdFlag)
| ArgInt (Int -> CmdFlag)
| ArgNat (Int -> CmdFlag)
| ArgPos (Int -> CmdFlag)
| ArgFileIn (FilePath -> CmdFlag) [String]
| ArgFileOut (FilePath -> CmdFlag)
| ArgDir (FilePath -> CmdFlag)
| ArgStr (String -> CmdFlag)
instance Show Argument where
show (ArgNone _) = ""
show (ArgInt _) = "INT"
show (ArgNat _) = "NAT"
show (ArgPos _) = "POS"
show (ArgBool _) = "BOOL"
show (ArgFileIn _ _) = "FILE"
show (ArgFileOut _) = "FILE"
show (ArgDir _) = "DIR"
show (ArgStr _) = "STR"
data FlagInfo = FlagInfo {
argument :: Argument,
names :: [String],
permissions :: [Permission],
description :: String
}
flagInfo =
[f (ArgNone Version) ["version","ver"] [PCmdLine] "Print out version information"
,f (ArgNone Help) ["?","help","h"] [PCmdLine] "Show help message"
,f (ArgNone Web) ["w","web"] [PCmdLine] "Run as though it was a CGI script"
,f (ArgBool Color) ["c","color","col","colour"] [PCmdLine] "Show color output (default=false)"
,f (ArgPos Start) ["s","start"] [PCmdLine,PWebArgs] "First result to show (default=1)"
,f (ArgPos Count) ["n","count","length","len"] [PCmdLine,PWebArgs] "Number of results to show (default=all)"
,f (ArgNone Test) ["test"] [PCmdLine] "Run the regression tests"
,f (ArgFileIn Convert ["txt"]) ["convert"] [PCmdLine,PMultiple] "Convert a database"
,f (ArgFileOut Output) ["output"] [PCmdLine] "Output file for convert"
,f (ArgStr Dump) ["dump"] [PCmdLine] "Dump a database for debugging"
,f (ArgFileIn DataFile ["hoo"]) ["d","data"] [PCmdLine,PMultiple] "Database file"
,f (ArgNone Verbose) ["v","verbose"] [PCmdLine] "Display verbose information"
,f (ArgNone Info) ["info"] [PCmdLine] "Display full information on an entry"
,f (ArgNone Debug) ["debug"] [PCmdLine] "Debugging only"
,f (ArgDir Include) ["i","include"] [PCmdLine,PMultiple] "Include directories"
,f (ArgFileIn TestFile ["txt"]) ["testfile"] [PCmdLine,PMultiple] "Run tests from a file"
,f (ArgFileIn Rank ["txt"]) ["rank"] [PCmdLine,PMultiple] "Generate ranking scores"
,f (ArgFileIn Combine ["hoo"]) ["combine"] [PCmdLine,PMultiple] "Combine multiple databases"
,f (ArgStr Mode) ["mode"] [PCmdLine,PWebArgs] "Web mode"
]
where f = FlagInfo
cmdFlagBadArg flag typ "" = "Missing argument to flag " ++ flag ++ ", expected argument of type " ++ typ
cmdFlagBadArg flag "" x = "Unexpected argument to flag " ++ flag ++ ", got \"" ++ x ++ "\""
cmdFlagBadArg flag typ x = "Bad argument to flag " ++ flag ++ ", expected argument of type " ++ typ ++ ", got \"" ++ x ++ "\""
cmdFlagPermission flag = "Flag not allowed when running in this mode, flag " ++ flag
cmdFlagUnknown flag = "Unknown flag " ++ flag
cmdFlagDuplicate flag = "The flag " ++ flag ++ " may only occur once, but occured multiple times"
---------------------------------------------------------------------
-- Operations on Flags
-- | flags that are passed in through web arguments,
-- i.e. ?foo=bar&...
flagsWebArgs :: [(String,String)] -> IO ([CmdFlag],[String])
flagsWebArgs = parseFlags PWebArgs
-- | flags that are given in the web query string
flagsWebQuery :: [(String,String)] -> IO ([CmdFlag],[String])
flagsWebQuery = parseFlags PWebQuery
-- | flags that are given in a query on the command line
flagsCmdLine :: [(String,String)] -> IO ([CmdFlag],[String])
flagsCmdLine = parseFlags PCmdLine
flagsHelp :: String
flagsHelp = unlines $ map f res
where
f (a,b,c) = " " ++ (if null a then " " else "--" ++ a ++ ",") ++
" --" ++ b ++ replicate (maxLong - length b) ' ' ++
" " ++ c
maxLong = maximum $ map (length . snd3) res
res = [ (shortOpt (names i), longOpt (names i) ++ typ (argument i), description i)
| i <- flagInfo, PCmdLine `elem` permissions i]
shortOpt ([x]:_) = [x]
shortOpt _ = ""
longOpt ([_]:x:_) = x
longOpt (x:_) = x
typ x = ['='|s/=""] ++ s
where s = show x
---------------------------------------------------------------------
-- Parsing Flags
-- TODO: check no flag is specified twice
-- TODO: Fix a bug, try /merge=t1;t2 and you get [t1,t1,t2,t2]
parseFlags :: Permission -> [(String,String)] -> IO ([CmdFlag],[String])
parseFlags perm xs = do
let args = concatMap (parseFlag perm) xs
inc = [x | Right (_,_,_,Include x) <- args]
incs <- mapM globDir $ ["."|null inc] ++ inc
(a,b) <- mapAndUnzipM (f incs) args
return ([Include "."|null inc] ++ concat a, concat b)
where
f inc (Right (_,val,FlagInfo{argument=ArgFileIn gen exts},_)) = do
let vals = parseFile val
files <- concatMapM (globFile inc exts) vals
return (map gen files, [])
f inc (Left v) = return ([],[v])
f inc (Right (_,_,_,v)) = return ([v],[])
-- does all validity checks apart from checking for duplicate flags
parseFlag :: Permission -> (String, String) -> [Either String (String,String,FlagInfo,CmdFlag)]
parseFlag perm (key,val)
| isNothing m = [Left $ cmdFlagUnknown key]
| perm `notElem` permissions flg = [Left $ cmdFlagPermission key]
| null arg = [Left $ cmdFlagBadArg key (show $ argument flg) val]
| otherwise = [Right (key,val,flg,a) | a <- arg]
where
key2 = lower key
m@ ~(Just flg) = listToMaybe [i | i <- flagInfo, key2 `elem` names i]
arg = parseArg (argument flg) val
parseArg :: Argument -> String -> [CmdFlag]
parseArg (ArgNone v) xs = [v | null xs]
parseArg (ArgStr v) xs = [v xs]
parseArg (ArgBool v) xs = map v $ parseBool xs
parseArg (ArgNat v) xs = map v $ parseNat xs
parseArg (ArgInt v) xs = map v $ parseInt xs
parseArg (ArgPos v) xs = map v $ parsePos xs
parseArg (ArgFileIn v _) xs = map v $ parseFile xs
parseArg (ArgFileOut v) xs = map v $ parseFile xs
parseArg (ArgDir v) xs = map v $ parseFile xs
parseNat, parsePos, parseInt :: String -> [Int]
parseNat = filter (>= 0) . parseInt
parsePos = filter (> 0) . parseInt
parseInt x = [a | (a,"") <- reads x]
parseFile :: String -> [String]
parseFile = splitSearchPath
parseBool :: String -> [Bool]
parseBool v | v2 `elem` ["","on","yes","1","true","meep"] = [True]
| v2 `elem` ["off","no","0","false","moop"] = [False]
| otherwise = []
where v2 = lower v
--------------------------------------------------------
-- DERIVES GENERATED CODE
-- DO NOT MODIFY BELOW THIS LINE
-- CHECKSUM: 1401092643
instance Enum CmdFlag
where toEnum 0 = Version{}
toEnum 1 = Web{}
toEnum 2 = Help{}
toEnum 3 = Test{}
toEnum 4 = Color{}
toEnum 5 = Start{}
toEnum 6 = Count{}
toEnum 7 = Convert{}
toEnum 8 = Output{}
toEnum 9 = Dump{}
toEnum 10 = DataFile{}
toEnum 11 = Verbose{}
toEnum 12 = Info{}
toEnum 13 = Debug{}
toEnum 14 = Include{}
toEnum 15 = TestFile{}
toEnum 16 = Rank{}
toEnum 17 = Combine{}
toEnum n = error ((++) "toEnum " ((++) (show n) ", not defined for CmdFlag"))
fromEnum (Version {}) = 0
fromEnum (Web {}) = 1
fromEnum (Help {}) = 2
fromEnum (Test {}) = 3
fromEnum (Color {}) = 4
fromEnum (Start {}) = 5
fromEnum (Count {}) = 6
fromEnum (Convert {}) = 7
fromEnum (Output {}) = 8
fromEnum (Dump {}) = 9
fromEnum (DataFile {}) = 10
fromEnum (Verbose {}) = 11
fromEnum (Info {}) = 12
fromEnum (Debug {}) = 13
fromEnum (Include {}) = 14
fromEnum (TestFile {}) = 15
fromEnum (Rank {}) = 16
fromEnum (Combine {}) = 17
| Pnom/haskell-ast-pretty | Test/examples/RealHoogle.hs | mit | 9,798 | 0 | 16 | 2,836 | 3,182 | 1,733 | 1,449 | 179 | 4 |
import Graphics.UI.SDL
import Graphics.Rendering.OpenGL
import Data.List
import Data.Maybe
import Data.Word
import Control.Monad
import Control.Monad.State
import Formulae
type ARTFVect = (GLfloat, GLfloat, GLfloat)
data Camera = Camera {
pos :: ARTFVect
}
data ARTFFlags = Alive | Dead
deriving (Eq)
data ARTF = ARTF {
flags :: ARTFFlags,
cam :: Camera,
formula :: Int -> GLfloat -> GLfloat -> Formula,
gen :: Int, -- change this to (Data.)Word
lineLen :: GLfloat,
angle :: GLfloat,
userinput :: String
}
initialARTF :: ARTF
initialARTF = ARTF Alive (Camera (0.0, 0.0, 0.0)) plant 6 0.1 6 ""
handleUserInput :: ARTF -> ARTF
handleUserInput artf = artf
incGenerations :: Int -> ARTF -> ARTF
incGenerations nN artf@(ARTF flags cam f n l a ui)
| newN > 0 = ARTF flags cam f newN l a ui
| otherwise = artf
where newN = nN + n
incAngle :: GLfloat -> ARTF -> ARTF
incAngle nA artf@(ARTF flags cam f n l a ui) = ARTF flags cam f n l (a+nA) ui
artfAlive :: ARTF -> Bool
artfAlive artf = (flags artf) == Alive
main :: IO ()
main = do
Graphics.UI.SDL.init [InitVideo]
setVideoMode 640 480 32 [OpenGL, HWSurface]
viewport $= (Position 0 0, Size 640 480)
clearColor $= (Color4 0 1.0 0 0)
--initialDisplayMode $= [DoubleBuffered, RGBMode, WithDepthBuffer]
lighting $= Enabled
depthFunc $= Just Less
scr <- getVideoSurface
gameLoop initialARTF scr
quit
gameLoop :: ARTF -> s -> IO ()
gameLoop artf@(ARTF flags (Camera (cx, cy, cz)) f n l a ui) w = do
clear [ColorBuffer, DepthBuffer]
loadIdentity
translate $ Vector3 cx cy cz
--rotate (90 :: GLfloat) $ Vector3 0 0 1
mapM_ (renderPrimitive (vertType vert) . mapM_ vertex) (vertices vert)
--mapM_ (renderPrimitive LineStrip . mapM_ vertex) (sierpinski 8 lineLen)
translate $ Vector3 (-cx) (-cy) (-cz)
glSwapBuffers
events <- getEvents
let newartf = handleEvents artf events
if artfAlive newartf
then gameLoop newartf w
else return ()
where
vert = f n l a
-- Get all Events so they can be worked with in a pure context
getEvents :: IO [Event]
getEvents = do
ev <- pollEvent
nextEvents ev
where
nextEvents :: Event -> IO [Event]
nextEvents NoEvent = return []
nextEvents x = do
ev <- pollEvent
xs <- nextEvents ev
return (x:xs)
-- a b are ignored
handleKeyDown :: ARTF -> SDLKey -> a -> b -> ARTF
handleKeyDown artf@(ARTF flags oldcam@(Camera (cx, cy, cz)) f n l a ui) key sym mod
| key == SDLK_q = (ARTF Dead oldcam f n l a ui)
| key == SDLK_d = (ARTF flags (Camera ((cx-0.1), cy, cz)) f n l a ui)
| key == SDLK_a = (ARTF flags (Camera ((cx+0.1), cy, cz)) f n l a ui)
| key == SDLK_w = (ARTF flags (Camera (cx, (cy-0.1), cz)) f n l a ui)
| key == SDLK_s = (ARTF flags (Camera (cx, (cy+0.1), cz)) f n l a ui)
| key == SDLK_v = (ARTF flags oldcam f n (l/2) a ui)
| key == SDLK_b = (ARTF flags oldcam f n (l*2) a ui)
| key == SDLK_y = (ARTF flags oldcam sierpinski n l a ui)
| key == SDLK_t = (ARTF flags oldcam cantor n l a ui)
| key == SDLK_f = (ARTF flags oldcam koch n l a ui)
| key == SDLK_e = (ARTF flags oldcam dragon n l a ui)
| key == SDLK_g = (ARTF flags oldcam plant 6 l 25 ui)
| key == SDLK_p = incGenerations 1 artf
| key == SDLK_o = incGenerations (-1) artf
| key == SDLK_r = initialARTF
| key == SDLK_l = incAngle 5.0 artf
| key == SDLK_k = incAngle (-5.0) artf
| otherwise = (ARTF flags oldcam f n l a ui)
handleEvents :: ARTF -> [Event] -> ARTF
handleEvents artf [] = artf
handleEvents oldartf@(ARTF flags cam f n l a ui) (x:xs) = do
case x of
(KeyDown (Keysym key a b)) -> handleKeyDown oldartf key a b
Quit -> (ARTF Dead cam f n l a ui)
_ -> (ARTF flags cam f n l a ui)
| esjee/hlsystem-artf | Main.hs | mit | 3,626 | 26 | 13 | 784 | 1,713 | 871 | 842 | 96 | 3 |
module Core.LambdaLift.DeBruijn
( deBruijn
) where
import Common
import Core.AST
import Core.AnnotAST
import Core.FreeVars
import Core.Prelude
import qualified Data.Map as M
import qualified Data.Set as S
deBruijn :: Program Name -> AnnotProgram Int (Annot Int Name)
deBruijn = ProgramF . map deBruijnSC . getProgramF . freeVars
where deBruijnSC (SupercombF name [] body) = SupercombF name [] body'
where body' = deBruijnExpr 0 M.empty body
deBruijnExpr :: Int -> M.Map Name Int -> AnnotExpr (S.Set Name) Name -> AnnotExpr Int (Annot Int Name)
deBruijnExpr k env (Annot (fv, e)) = Annot $ case e of
EVarF v -> (M.findWithDefault 0 v env, EVarF v)
ENumF n -> (0, ENumF n)
EConstrF tag arity -> (0, EConstrF tag arity)
EApF e1 e2 -> (,) k' $ if isArith (EAp (removeAnnot e1) (removeAnnot e2))
then EApF (Annot (k', unAnnot e1')) e2'
else EApF e1' e2'
where e1' = deBruijnExpr k env e1
e2' = deBruijnExpr k env e2
k' = max (getAnnot e1') (getAnnot e2')
ELetF rec defs body -> (getAnnot body', ELetF rec defs' body')
where xs' = map (Annot . (,) k') xs
exps' = map (deBruijnExpr k (if rec then env' else env)) exps
defs' = zip xs' exps'
body' = deBruijnExpr k env' body
env' = extend env (zip xs (repeat k'))
env'' = if rec then extend env (zip xs (repeat 0)) else env
k' = deBruijnFreeVars env'' (S.unions (map getAnnot exps))
(xs, exps) = unzip defs
ECaseF e alts -> (k'', ECaseF e' alts')
where e' = deBruijnExpr k env e
alts' = map (deBruijnAlter k k' env) alts
k' = getAnnot e'
k'' = foldr max k' [getAnnot body | AlterF _ _ body <- alts']
EAbsF args body -> (deBruijnFreeVars env fv, EAbsF args' body')
where args' = map (Annot . (,) k') args
body' = deBruijnExpr k' env' body
env' = extend env (zip args (repeat k'))
k' = k + 1
deBruijnAlter :: Int -> Int -> M.Map Name Int -> AnnotAlter (S.Set Name) Name -> AnnotAlter Int (Annot Int Name)
deBruijnAlter k k' env (AlterF tag xs body) = AlterF tag xs' body'
where xs' = map (Annot . (,) k') xs
body' = deBruijnExpr k env' body
env' = extend env (zip xs (repeat k'))
deBruijnFreeVars :: M.Map Name Int -> S.Set Name -> Int
deBruijnFreeVars env fv = foldr max 0 xs
where xs = [M.findWithDefault 0 v env | v <- S.toList fv]
| meimisaki/Rin | src/Core/LambdaLift/DeBruijn.hs | mit | 2,400 | 0 | 16 | 630 | 1,033 | 524 | 509 | 51 | 10 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE CPP #-}
module CorePrelude
( -- * Standard
-- ** Operators
(Prelude.$)
, (Prelude.$!)
, (Prelude.&&)
, (Prelude.||)
, (Control.Category..)
-- ** Functions
, Prelude.not
, Prelude.otherwise
, Prelude.fst
, Prelude.snd
, Control.Category.id
, Prelude.maybe
, Prelude.either
, Prelude.flip
, Prelude.const
, Prelude.error
, putStr
, putStrLn
, print
, getArgs
, terror
, Prelude.odd
, Prelude.even
, Prelude.uncurry
, Prelude.curry
, Data.Tuple.swap
, Prelude.until
, Prelude.asTypeOf
, Prelude.undefined
, Prelude.seq
-- ** Type classes
, Prelude.Ord (..)
, Prelude.Eq (..)
, Prelude.Bounded (..)
, Prelude.Enum (..)
, Prelude.Show
, Prelude.Read
, Prelude.Functor (..)
, Prelude.Monad (..)
, (Control.Monad.=<<)
, Data.String.IsString (..)
-- ** Numeric type classes
, Prelude.Num (..)
, Prelude.Real (..)
, Prelude.Integral (..)
, Prelude.Fractional (..)
, Prelude.Floating (..)
, Prelude.RealFrac (..)
, Prelude.RealFloat(..)
-- ** Data types
, Prelude.Maybe (..)
, Prelude.Ordering (..)
, Prelude.Bool (..)
, Prelude.Char
, Prelude.IO
, Prelude.Either (..)
-- * Re-exports
-- ** Packed reps
, ByteString
, LByteString
, Text
, LText
-- ** Containers
, Map
, HashMap
, IntMap
, Set
, HashSet
, IntSet
, Seq
, Vector
, UVector
, Unbox
, SVector
, Data.Vector.Storable.Storable
, Hashable
-- ** Numbers
, Word
, Word8
, Word32
, Word64
, Prelude.Int
, Int32
, Int64
, Prelude.Integer
, Prelude.Rational
, Prelude.Float
, Prelude.Double
-- ** Numeric functions
, (Prelude.^)
, (Prelude.^^)
, Prelude.subtract
, Prelude.fromIntegral
, Prelude.realToFrac
-- ** Monoids
, Monoid (..)
, (<>)
-- ** Folds and traversals
, Data.Foldable.Foldable
, Data.Foldable.asum
, Data.Traversable.Traversable
-- ** arrow
, Control.Arrow.first
, Control.Arrow.second
, (Control.Arrow.***)
, (Control.Arrow.&&&)
-- ** Bool
, bool
-- ** Maybe
, Data.Maybe.mapMaybe
, Data.Maybe.catMaybes
, Data.Maybe.fromMaybe
, Data.Maybe.isJust
, Data.Maybe.isNothing
, Data.Maybe.listToMaybe
, Data.Maybe.maybeToList
-- ** Either
, Data.Either.partitionEithers
, Data.Either.lefts
, Data.Either.rights
-- ** Ord
, Data.Function.on
, Data.Ord.comparing
, equating
, GHC.Exts.Down (..)
-- ** Applicative
, Control.Applicative.Applicative (..)
, (Control.Applicative.<$>)
, (Control.Applicative.<|>)
-- ** Monad
, (Control.Monad.>=>)
-- ** Transformers
, Control.Monad.Trans.Class.lift
, Control.Monad.IO.Class.MonadIO
, Control.Monad.IO.Class.liftIO
-- ** Exceptions
, Control.Exception.Exception (..)
, Data.Typeable.Typeable (..)
, Control.Exception.SomeException
, Control.Exception.IOException
, module System.IO.Error
-- ** Files
, Prelude.FilePath
, (F.</>)
, (F.<.>)
-- ** Strings
, Prelude.String
-- ** Hashing
, hash
, hashWithSalt
) where
import qualified Prelude
import Prelude (Char, (.), Eq, Bool)
import Data.Hashable (Hashable, hash, hashWithSalt)
import Data.Vector.Unboxed (Unbox)
import Data.Monoid (Monoid (..))
import qualified Control.Arrow
import Control.Applicative
import qualified Control.Category
import qualified Control.Monad
import qualified Control.Exception
import qualified Data.Typeable
import qualified Data.Foldable
import qualified Data.Traversable
import Data.Word (Word8, Word32, Word64, Word)
import Data.Int (Int32, Int64)
import qualified Data.Text.IO
import qualified Data.Maybe
import qualified Data.Either
import qualified Data.Ord
import qualified Data.Function
import qualified Data.Tuple
import qualified Data.String
import qualified Control.Monad.Trans.Class
import qualified Control.Monad.IO.Class
import Control.Monad.IO.Class (MonadIO (liftIO))
import Data.ByteString (ByteString)
import qualified Data.ByteString.Lazy
import Data.Text (Text)
import qualified Data.Text.Lazy
import Data.Vector (Vector)
import qualified Data.Vector.Unboxed
import qualified Data.Vector.Storable
import Data.Map (Map)
import Data.Set (Set)
import Data.IntMap (IntMap)
import Data.IntSet (IntSet)
import Data.Sequence (Seq)
import Data.HashMap.Strict (HashMap)
import Data.HashSet (HashSet)
import qualified System.FilePath as F
import qualified System.Environment
import qualified Data.Text
import qualified Data.List
import System.IO.Error hiding (catch, try)
import qualified GHC.Exts
#if MIN_VERSION_base(4,7,0)
import Data.Bool (bool)
#endif
#if MIN_VERSION_base(4,5,0)
import Data.Monoid ((<>))
#endif
#if MIN_VERSION_base(4,9,0)
import GHC.Stack (HasCallStack)
#endif
type LText = Data.Text.Lazy.Text
type LByteString = Data.ByteString.Lazy.ByteString
type UVector = Data.Vector.Unboxed.Vector
type SVector = Data.Vector.Storable.Vector
#if !MIN_VERSION_base(4,7,0)
bool :: a -> a -> Bool -> a
bool f t b = if b then t else f
#endif
#if !MIN_VERSION_base(4,5,0)
infixr 6 <>
(<>) :: Monoid w => w -> w -> w
(<>) = mappend
{-# INLINE (<>) #-}
#endif
equating :: Eq a => (b -> a) -> b -> b -> Bool
equating = Data.Function.on (Prelude.==)
getArgs :: MonadIO m => m [Text]
getArgs = liftIO (Data.List.map Data.Text.pack <$> System.Environment.getArgs)
putStr :: MonadIO m => Text -> m ()
putStr = liftIO . Data.Text.IO.putStr
putStrLn :: MonadIO m => Text -> m ()
putStrLn = liftIO . Data.Text.IO.putStrLn
print :: (MonadIO m, Prelude.Show a) => a -> m ()
print = liftIO . Prelude.print
-- | @error@ applied to @Text@
--
-- Since 0.4.1
#if MIN_VERSION_base(4,9,0)
terror :: HasCallStack => Text -> a
#else
terror :: Text -> a
#endif
terror = Prelude.error . Data.Text.unpack
| snoyberg/basic-prelude | src/CorePrelude.hs | mit | 6,110 | 0 | 9 | 1,397 | 1,555 | 1,011 | 544 | 198 | 2 |
flip f = \a b -> f b a
| scravy/nodash | doc/Function/flip.hs | mit | 23 | 1 | 6 | 9 | 24 | 10 | 14 | 1 | 1 |
module Tools.Mill.Table where
import Data.ByteString
import Text.Parsec.Prim
import Text.Parsec.Char
import Text.Parsec.Combinator
import Text.Parsec.ByteString (GenParser)
import qualified Data.ByteString.Char8 as C
import Control.Applicative ((<$>), (<*>), (*>), (<*))
type Colname = ByteString
type DataLine = ByteString
type Header = [Colname]
parseHeader :: GenParser Char st Header
parseHeader = (char '#' *> many1 colname)
where colname = C.pack <$> (spaces *> many1 (noneOf " "))
| lucasdicioccio/mill | Tools/Mill/Table.hs | mit | 518 | 0 | 12 | 91 | 157 | 98 | 59 | 14 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Data.CmdItemSpec (main, spec) where
#if !MIN_VERSION_base(4,8,0)
import Control.Applicative ((<$>), (<*>))
#endif
import Test.Hspec
import Test.Hspec.Laws
import Test.QuickCheck
import Test.QuickCheck.Instances ()
import Data.CmdItem
spec :: Spec
spec = describe "CmdItem" $ shouldSatisfyMonoidLaws (undefined :: CmdItem)
main :: IO ()
main = hspec spec
instance Arbitrary CmdItem where
arbitrary = CmdItem <$> arbitrary <*> arbitrary
| geraud/cmd-item | test/Data/CmdItemSpec.hs | mit | 551 | 0 | 7 | 81 | 131 | 79 | 52 | 16 | 1 |
module Barycenter where
barTriang :: (Double, Double) -> (Double, Double) -> (Double, Double) -> (Double, Double)
barTriang (a, b) (c, d) (e, f) = (x, y)
where
x = (a + c + e) / 3
y = (b + d + f) / 3 | cojoj/Codewars | Haskell/Codewars.hsproj/Barycenter.hs | mit | 225 | 0 | 10 | 70 | 123 | 73 | 50 | 5 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-integration.html
module Stratosphere.Resources.ApiGatewayV2Integration where
import Stratosphere.ResourceImports
-- | Full data type definition for ApiGatewayV2Integration. See
-- 'apiGatewayV2Integration' for a more convenient constructor.
data ApiGatewayV2Integration =
ApiGatewayV2Integration
{ _apiGatewayV2IntegrationApiId :: Val Text
, _apiGatewayV2IntegrationConnectionType :: Maybe (Val Text)
, _apiGatewayV2IntegrationContentHandlingStrategy :: Maybe (Val Text)
, _apiGatewayV2IntegrationCredentialsArn :: Maybe (Val Text)
, _apiGatewayV2IntegrationDescription :: Maybe (Val Text)
, _apiGatewayV2IntegrationIntegrationMethod :: Maybe (Val Text)
, _apiGatewayV2IntegrationIntegrationType :: Val Text
, _apiGatewayV2IntegrationIntegrationUri :: Maybe (Val Text)
, _apiGatewayV2IntegrationPassthroughBehavior :: Maybe (Val Text)
, _apiGatewayV2IntegrationRequestParameters :: Maybe Object
, _apiGatewayV2IntegrationRequestTemplates :: Maybe Object
, _apiGatewayV2IntegrationTemplateSelectionExpression :: Maybe (Val Text)
, _apiGatewayV2IntegrationTimeoutInMillis :: Maybe (Val Integer)
} deriving (Show, Eq)
instance ToResourceProperties ApiGatewayV2Integration where
toResourceProperties ApiGatewayV2Integration{..} =
ResourceProperties
{ resourcePropertiesType = "AWS::ApiGatewayV2::Integration"
, resourcePropertiesProperties =
hashMapFromList $ catMaybes
[ (Just . ("ApiId",) . toJSON) _apiGatewayV2IntegrationApiId
, fmap (("ConnectionType",) . toJSON) _apiGatewayV2IntegrationConnectionType
, fmap (("ContentHandlingStrategy",) . toJSON) _apiGatewayV2IntegrationContentHandlingStrategy
, fmap (("CredentialsArn",) . toJSON) _apiGatewayV2IntegrationCredentialsArn
, fmap (("Description",) . toJSON) _apiGatewayV2IntegrationDescription
, fmap (("IntegrationMethod",) . toJSON) _apiGatewayV2IntegrationIntegrationMethod
, (Just . ("IntegrationType",) . toJSON) _apiGatewayV2IntegrationIntegrationType
, fmap (("IntegrationUri",) . toJSON) _apiGatewayV2IntegrationIntegrationUri
, fmap (("PassthroughBehavior",) . toJSON) _apiGatewayV2IntegrationPassthroughBehavior
, fmap (("RequestParameters",) . toJSON) _apiGatewayV2IntegrationRequestParameters
, fmap (("RequestTemplates",) . toJSON) _apiGatewayV2IntegrationRequestTemplates
, fmap (("TemplateSelectionExpression",) . toJSON) _apiGatewayV2IntegrationTemplateSelectionExpression
, fmap (("TimeoutInMillis",) . toJSON) _apiGatewayV2IntegrationTimeoutInMillis
]
}
-- | Constructor for 'ApiGatewayV2Integration' containing required fields as
-- arguments.
apiGatewayV2Integration
:: Val Text -- ^ 'agviApiId'
-> Val Text -- ^ 'agviIntegrationType'
-> ApiGatewayV2Integration
apiGatewayV2Integration apiIdarg integrationTypearg =
ApiGatewayV2Integration
{ _apiGatewayV2IntegrationApiId = apiIdarg
, _apiGatewayV2IntegrationConnectionType = Nothing
, _apiGatewayV2IntegrationContentHandlingStrategy = Nothing
, _apiGatewayV2IntegrationCredentialsArn = Nothing
, _apiGatewayV2IntegrationDescription = Nothing
, _apiGatewayV2IntegrationIntegrationMethod = Nothing
, _apiGatewayV2IntegrationIntegrationType = integrationTypearg
, _apiGatewayV2IntegrationIntegrationUri = Nothing
, _apiGatewayV2IntegrationPassthroughBehavior = Nothing
, _apiGatewayV2IntegrationRequestParameters = Nothing
, _apiGatewayV2IntegrationRequestTemplates = Nothing
, _apiGatewayV2IntegrationTemplateSelectionExpression = Nothing
, _apiGatewayV2IntegrationTimeoutInMillis = Nothing
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-integration.html#cfn-apigatewayv2-integration-apiid
agviApiId :: Lens' ApiGatewayV2Integration (Val Text)
agviApiId = lens _apiGatewayV2IntegrationApiId (\s a -> s { _apiGatewayV2IntegrationApiId = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-integration.html#cfn-apigatewayv2-integration-connectiontype
agviConnectionType :: Lens' ApiGatewayV2Integration (Maybe (Val Text))
agviConnectionType = lens _apiGatewayV2IntegrationConnectionType (\s a -> s { _apiGatewayV2IntegrationConnectionType = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-integration.html#cfn-apigatewayv2-integration-contenthandlingstrategy
agviContentHandlingStrategy :: Lens' ApiGatewayV2Integration (Maybe (Val Text))
agviContentHandlingStrategy = lens _apiGatewayV2IntegrationContentHandlingStrategy (\s a -> s { _apiGatewayV2IntegrationContentHandlingStrategy = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-integration.html#cfn-apigatewayv2-integration-credentialsarn
agviCredentialsArn :: Lens' ApiGatewayV2Integration (Maybe (Val Text))
agviCredentialsArn = lens _apiGatewayV2IntegrationCredentialsArn (\s a -> s { _apiGatewayV2IntegrationCredentialsArn = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-integration.html#cfn-apigatewayv2-integration-description
agviDescription :: Lens' ApiGatewayV2Integration (Maybe (Val Text))
agviDescription = lens _apiGatewayV2IntegrationDescription (\s a -> s { _apiGatewayV2IntegrationDescription = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-integration.html#cfn-apigatewayv2-integration-integrationmethod
agviIntegrationMethod :: Lens' ApiGatewayV2Integration (Maybe (Val Text))
agviIntegrationMethod = lens _apiGatewayV2IntegrationIntegrationMethod (\s a -> s { _apiGatewayV2IntegrationIntegrationMethod = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-integration.html#cfn-apigatewayv2-integration-integrationtype
agviIntegrationType :: Lens' ApiGatewayV2Integration (Val Text)
agviIntegrationType = lens _apiGatewayV2IntegrationIntegrationType (\s a -> s { _apiGatewayV2IntegrationIntegrationType = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-integration.html#cfn-apigatewayv2-integration-integrationuri
agviIntegrationUri :: Lens' ApiGatewayV2Integration (Maybe (Val Text))
agviIntegrationUri = lens _apiGatewayV2IntegrationIntegrationUri (\s a -> s { _apiGatewayV2IntegrationIntegrationUri = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-integration.html#cfn-apigatewayv2-integration-passthroughbehavior
agviPassthroughBehavior :: Lens' ApiGatewayV2Integration (Maybe (Val Text))
agviPassthroughBehavior = lens _apiGatewayV2IntegrationPassthroughBehavior (\s a -> s { _apiGatewayV2IntegrationPassthroughBehavior = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-integration.html#cfn-apigatewayv2-integration-requestparameters
agviRequestParameters :: Lens' ApiGatewayV2Integration (Maybe Object)
agviRequestParameters = lens _apiGatewayV2IntegrationRequestParameters (\s a -> s { _apiGatewayV2IntegrationRequestParameters = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-integration.html#cfn-apigatewayv2-integration-requesttemplates
agviRequestTemplates :: Lens' ApiGatewayV2Integration (Maybe Object)
agviRequestTemplates = lens _apiGatewayV2IntegrationRequestTemplates (\s a -> s { _apiGatewayV2IntegrationRequestTemplates = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-integration.html#cfn-apigatewayv2-integration-templateselectionexpression
agviTemplateSelectionExpression :: Lens' ApiGatewayV2Integration (Maybe (Val Text))
agviTemplateSelectionExpression = lens _apiGatewayV2IntegrationTemplateSelectionExpression (\s a -> s { _apiGatewayV2IntegrationTemplateSelectionExpression = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-integration.html#cfn-apigatewayv2-integration-timeoutinmillis
agviTimeoutInMillis :: Lens' ApiGatewayV2Integration (Maybe (Val Integer))
agviTimeoutInMillis = lens _apiGatewayV2IntegrationTimeoutInMillis (\s a -> s { _apiGatewayV2IntegrationTimeoutInMillis = a })
| frontrowed/stratosphere | library-gen/Stratosphere/Resources/ApiGatewayV2Integration.hs | mit | 8,500 | 0 | 15 | 825 | 1,256 | 709 | 547 | 86 | 1 |
{-# OPTIONS_GHC -fno-warn-incomplete-patterns #-}
module HyLoRes.Formula.Internal(
module HyLoRes.Formula.TypeLevel,
--
Form(..),
top, bot, nom, negNom, prop, negProp,
conj, disj,
diam, box, at, down,
opaque,
nnfAtFormula, unNNF, eqUnNNF, showDebug,
--
Attrib(..), attrib,
--
Atom(..), Negation(..), negSymbol,
--
HasSubformula(..), HasSubformulas(..), OnSubf(..), Flatten(..),
--
ModalOp(..), label, boundVar,
--
mapSig, replaceNom, instanceFreeVar,
--
nonOpaque, nonOpaque2,
--
metap_read_Opaque, metap_read_AtNomOpaque,
unit_tests )
where
import Test.QuickCheck hiding ( label )
import HyLo.Test ( UnitTest, runTest )
import Control.Monad ( liftM, liftM2 )
import Text.Show.Functions ()
import Text.Read ( Read(..) )
import HyLo.Signature.Simple ( PropSymbol, NomSymbol, RelSymbol )
import qualified HyLo.Formula as F
import HyLo.Model ( ModelsRel(..), Model, valN )
import HyLoRes.Formula.TypeLevel
data Form n p r a f where
Top :: a -> Form n p r a Top
NegTop :: a -> Form n p r a (Neg Top)
--
Nom :: a -> n -> Form n p r a Nom
Prop :: a -> p -> Form n p r a Prop
--
NegNom :: a -> n -> Form n p r a (Neg Nom)
NegProp :: a -> p -> Form n p r a (Neg Prop)
--
Disj :: a -> [Form n p r a f] -> Form n p r a Disj
Conj :: a -> [Form n p r a f] -> Form n p r a Conj
--
Diam :: a -> r -> Form n p r a f -> Form n p r a (Diam f)
Box :: a -> r -> Form n p r a f -> Form n p r a (Box f)
--
At :: a -> n -> Form n p r a f -> Form n p r a (At f)
--
Down :: a -> n -> Form n p r a f -> Form n p r a (Down f)
--
Opaque :: Form n p r a f -> Form n p r a Opaque
-- --------------
-- IMPORTANT: As an invariant, Opaque (Opaque _) is an invalid term
-- --------------
eqUnNNF :: (Eq n, Eq p, Eq r) => Form n p r a f -> Form n p r a g -> Bool
eqUnNNF f g = unNNF f == unNNF g
instance (Show n, Show p, Show r) => Show (Form n p r a f) where
show = show . unNNF
instance Specializable (Form n p r a) where
specialize f@(At _ _ Top{}) = AtTop f
specialize f@(At _ _ Prop{}) = AtProp f
specialize f@(At _ _ Nom{}) = AtNom f
--
specialize f@(At _ _ NegTop{}) = AtNegTop f
specialize f@(At _ _ NegProp{}) = AtNegProp f
specialize f@(At _ _ NegNom{}) = AtNegNom f
--
specialize f@(At _ _ Disj{}) = AtDisj f
specialize f@(At _ _ Conj{}) = AtConj f
--
specialize f@(At _ _ (Diam _ _ Nom{})) = AtDiamNom f
specialize (At a i (Diam b r (Opaque f))) = specialize (At a i (Diam b r f))
specialize (At a i (Diam b r f)) = AtDiamF (At a i$Diam b r$Opaque f)
specialize (At a i (Box b r f)) = AtBoxF (At a i$Box b r$opaque f)
--
specialize (At a i (Down b x f)) = AtDownF (At a i$Down b x$opaque f)
--
specialize (At a i (Opaque f)) = specialize (At a i f)
specialize (At _ _ f@At{}) = specialize f
specialize f = error $ "NNF.specialize: " ++
showDebug f
data P = P deriving (Show, Read)
data N = N deriving (Show, Read)
data R = R deriving (Show, Read)
showDebug :: Form n p r a f -> String
showDebug = showDebugF . unNNF
showDebugF :: F.Formula n p r -> String
showDebugF = show . F.mapSig (const N) (const P) (const R)
instance (Read n, Read p, Read r, Attrib a n p r)
=> Read (Form n p r a Opaque) where
readPrec = unsafeFromF =<< readPrec
instance (Read n, Read p, Read r, Attrib a n p r)
=> Read (Form n p r a (At Opaque)) where
readPrec = asAtOpaque =<< readPrec
where asAtOpaque :: (Monad m, Attrib a n p r)
=> Form n p r a Opaque
-> m (Form n p r a (At Opaque))
asAtOpaque (Opaque f@At{}) = return $ onSubf opaque f
asAtOpaque _ = fail "Not an at-formula"
instance (Read n,Read p,Read r,Attrib a n p r) => Read (Form n p r a (At Nom))
where
readPrec = asAtNom =<< readPrec
where asAtNom :: (Monad m, Attrib a n p r)
=> Form n p r a Opaque
-> m (Form n p r a (At Nom))
asAtNom (Opaque f@(At _ _ Nom{})) = return f
asAtNom _ = fail "Not an equality"
instance (Read n,Read p,Read r,Attrib a n p r) => Read (Form n p r a (At Prop))
where
readPrec = asAtNom =<< readPrec
where asAtNom :: (Monad m, Attrib a n p r)
=> Form n p r a Opaque
-> m (Form n p r a (At Prop))
asAtNom (Opaque f@(At _ _ Prop{})) = return f
asAtNom _ = fail "Not an at-prop"
instance (Read n, Read p, Read r, Attrib a n p r)
=> Read (Form n p r a (At (Diam Nom)))
where
readPrec = asAtNom =<< readPrec
where asAtNom :: (Monad m, Attrib a n p r)
=> Form n p r a Opaque
-> m (Form n p r a (At (Diam Nom)))
asAtNom (Opaque f@(At _ _ (Diam _ _ Nom{}))) = return f
asAtNom _ = fail "Not a relation"
class Attrib a n p r where
-- | @computeAttrib f@ must not read @attrib f@.
computeAttrib :: Form n p r a f -> a
instance Attrib () n p r where
computeAttrib = const ()
top :: Attrib a n p r => Form n p r a Top
top = let f = Top a; a = computeAttrib f in f
bot :: Attrib a n p r => Form n p r a (Neg Top)
bot = let f = NegTop a; a = computeAttrib f in f
nom :: Attrib a n p r => n -> Form n p r a Nom
nom i = let f = Nom a i; a = computeAttrib f in f
negNom :: Attrib a n p r => n -> Form n p r a (Neg Nom)
negNom i = let f = NegNom a i; a = computeAttrib f in f
prop :: Attrib a n p r => p -> Form n p r a Prop
prop p = let f = Prop a p; a = computeAttrib f in f
negProp :: Attrib a n p r => p -> Form n p r a (Neg Prop)
negProp p = let f = NegProp a p; a = computeAttrib f in f
disj :: Attrib a n p r => [Form n p r a f] -> Form n p r a Disj
disj fs = let f = Disj a fs; a = computeAttrib f in f
conj :: Attrib a n p r => [Form n p r a f] -> Form n p r a Conj
conj fs = let f = Conj a fs; a = computeAttrib f in f
diam :: Attrib a n p r => r -> Form n p r a f -> Form n p r a (Diam f)
diam r g = let f = Diam a r g; a = computeAttrib f in f
box :: Attrib a n p r => r -> Form n p r a f -> Form n p r a (Box f)
box r g = let f = Box a r g; a = computeAttrib f in f
at :: Attrib a n p r => n -> Form n p r a f -> Form n p r a (At f)
at i g = let f = At a i g; a = computeAttrib f in f
down :: Attrib a n p r => n -> Form n p r a f -> Form n p r a (Down f)
down x g = let f = Down a x g; a = computeAttrib f in f
opaque :: Form n p r a f -> Form n p r a Opaque
opaque o_f@(Opaque _) = o_f
opaque f = Opaque f
{-# INLINE nonOpaque #-}
nonOpaque :: (forall t . Form n p r a t -> b) -> Form n p r a t' -> b
nonOpaque fun (Opaque f') = fun f'
nonOpaque fun f = fun f
{-# INLINE nonOpaque2 #-}
nonOpaque2 :: (forall t s . Form n p r a t -> Form n p r a s -> c)
-> (Form n p r a t' -> Form n p r a s' -> c)
nonOpaque2 fun f = nonOpaque (nonOpaque fun f)
maybeAddPrefix :: Attrib a n p r
=> n
-> Form n p r a Opaque
-> Form n p r a (At Opaque)
maybeAddPrefix _ (Opaque (At _ n f)) = at n (opaque f)
maybeAddPrefix i opaque_f = at i opaque_f
unNNF :: Form n p r a f -> F.Formula n p r
unNNF (Top _) = F.Top
unNNF (NegTop _) = F.Neg F.Top
unNNF (Prop _ p) = F.Prop p
unNNF (NegProp _ p) = F.Neg $ F.Prop p
unNNF (Nom _ n) = F.Nom n
unNNF (NegNom _ n) = F.Neg $ F.Nom n
unNNF (Disj _ [f]) = unNNF f
unNNF (Disj _ fs) = foldr1 (F.:|:) $ map unNNF fs
unNNF (Conj _ [f]) = unNNF f
unNNF (Conj _ fs) = foldr1 (F.:&:) $ map unNNF fs
unNNF (Diam _ r f) = F.Diam r (unNNF f)
unNNF (Box _ r f) = F.Box r (unNNF f)
unNNF (At _ n f) = F.At n (unNNF f)
unNNF (Down _ x f) = F.Down x (unNNF f)
unNNF (Opaque f) = unNNF f
nnfAtFormula :: Attrib a n p r=>n -> F.Formula n p r -> Form n p r a (At Opaque)
nnfAtFormula n = maybeAddPrefix n . get . unsafeFromF . F.nnf
where get = maybe (error $ "nnfAtFormula: Unexpected formula") id
unsafeFromF :: forall n p r a m . (Monad m, Attrib a n p r)
=> F.Formula n p r
-> m (Form n p r a Opaque)
unsafeFromF F.Top = return $ Opaque top
unsafeFromF (F.Neg F.Top) = return $ Opaque bot
unsafeFromF F.Bot = return $ Opaque bot
unsafeFromF (F.Neg F.Bot) = return $ Opaque top
unsafeFromF (F.Prop p) = return $ Opaque (prop p)
unsafeFromF (F.Neg (F.Prop p)) = return $ Opaque (negProp p)
unsafeFromF (F.Nom n) = return $ Opaque (nom n)
unsafeFromF (F.Neg (F.Nom n)) = return $ Opaque (negNom n)
unsafeFromF f@(_ F.:&: _) = (Opaque . conj) `liftM`
(mapM unsafeFromF $ listifyC f)
unsafeFromF f@(_ F.:|: _) = (Opaque . disj) `liftM`
(mapM unsafeFromF $ listifyD f)
unsafeFromF (F.Diam r f) = do op <- unsafeFromF f
case op :: Form n p r a Opaque of
Opaque g -> return $ Opaque (diam r g)
unsafeFromF (F.Box r f) = do op <- unsafeFromF f
case op :: Form n p r a Opaque of
Opaque g -> return $ Opaque (box r g)
unsafeFromF (F.At n f) = do op <- unsafeFromF f
case op :: Form n p r a Opaque of
Opaque g -> return $ Opaque (at n g)
unsafeFromF (F.Down x f) = do op <- unsafeFromF f
case op :: Form n p r a Opaque of
Opaque g -> return $ Opaque (down x g)
unsafeFromF f = fail $ "unsafeFromF: Unexpected formula: " ++
showDebugF f
listifyD :: F.Formula n p r -> [F.Formula n p r]
listifyD (f1 F.:|: f2) = listifyD f1 ++ listifyD f2
listifyD f = [f]
listifyC :: F.Formula n p r -> [F.Formula n p r]
listifyC (f1 F.:&: f2) = listifyC f1 ++ listifyC f2
listifyC f = [f]
instance (Ord w, Ord n, Ord p, Ord r)
=> ModelsRel (Model w n p r, w) (Form n p r a f) n p r where
(m,w) |= f = (m,w) |= unNNF f
instance (Ord w, Ord n, Ord p, Ord r)
=> ModelsRel (Model w n p r) (Form n p r a (At f)) n p r where
m |= f = (m, valN m $ label f) |= f
label :: Form n p r a (At f) -> n
label (At _ n _) = n
boundVar :: Form n p r a (Down f) -> n
boundVar (Down _ x _) = x
attrib :: Form n p r a f -> a
attrib (Top a) = a
attrib (Nom a _) = a
attrib (Prop a _) = a
--
attrib (NegTop a) = a
attrib (NegNom a _) = a
attrib (NegProp a _) = a
--
attrib (Disj a _) = a
attrib (Conj a _) = a
--
attrib (Diam a _ _) = a
attrib (Box a _ _) = a
attrib (At a _ _) = a
attrib (Down a _ _) = a
--
attrib (Opaque f) = attrib f
class (Replace t s f_t f_s) => OnSubf t s f_t f_s where
onSubf :: Attrib a n p r
=> (Form n p r a t -> Form n p r a s)
-> Form n p r a f_t
-> Form n p r a f_s
instance Negation g (Neg g) => OnSubf f g (Neg f) (Neg g) where
onSubf fun NegTop{} = neg (fun top)
onSubf fun f@NegNom{} = neg (fun $ subf f)
onSubf fun f@NegProp{} = neg (fun $ subf f)
instance OnSubf f g (Diam f) (Diam g) where
onSubf fun f@Diam{} = diam (relSym f) (fun $ subf f)
instance OnSubf f g (Box f) (Box g) where
onSubf fun f@Box{} = box (relSym f) (fun $ subf f)
instance OnSubf f g (At f) (At g) where
onSubf fun f@At{} = at (label f) (fun $ subf f)
instance OnSubf f g (Down f) (Down g) where
onSubf fun f@Down{} = down (boundVar f) (fun $ subf f)
class HasSubformula t s | t -> s where
subf :: Attrib a n p r => Form n p r a t -> Form n p r a s
instance HasSubformula (Neg f) f where
subf NegTop{} = top
subf (NegProp _ p) = prop p
subf (NegNom _ i) = nom i
instance HasSubformula (Diam f) f where
subf (Diam _ _ f) = f
instance HasSubformula (Box f) f where
subf (Box _ _ f) = f
instance HasSubformula (At f) f where
subf (At _ _ f) = f
instance HasSubformula (Down f) f where
subf (Down _ _ f) = f
class HasSubformulas t where
subfs :: Form n p r a t -> [Form n p r a Opaque]
instance HasSubformulas Conj where
subfs (Conj _ fs) = map opaque fs
instance HasSubformulas Disj where
subfs (Disj _ fs) = map opaque fs
class Flatten f flattened | f -> flattened where
flatten :: f -> flattened
instance Flatten (Form n p r a (At Nom)) (n, n) where
flatten (At _ i (Nom _ j)) = (i,j)
instance Flatten (Form n p r a (At (Neg Nom))) (n, n) where
flatten (At _ i (NegNom _ j)) = (i,j)
instance Flatten (Form n p r a (At Prop)) (n, p) where
flatten (At _ i (Prop _ p)) = (i, p)
instance Flatten (Form n p r a (At (Neg Prop))) (n, p) where
flatten (At _ i (NegProp _ p)) = (i, p)
instance Flatten (Form n p r a (At (Diam Nom))) (n, r, n) where
flatten (At _ i (Diam _ r (Nom _ j))) = (i, r, j)
class ModalOp t where
relSym :: Form n p r a t -> r
instance ModalOp (Diam f) where
relSym (Diam _ r _) = r
instance ModalOp (Box f) where
relSym (Box _ r _) = r
class Atom f b | f -> b where
symbol :: f -> b
fromSymbol :: b -> f
instance Attrib a n p r => Atom (Form n p r a Top) () where
symbol (Top _) = ()
fromSymbol _ = top
instance Attrib a n p r => Atom (Form n p r a Prop) p where
symbol (Prop _ p) = p
fromSymbol p = prop p
instance Attrib a n p r => Atom (Form n p r a Nom) n where
symbol (Nom _ n) = n
fromSymbol i = nom i
negSymbol :: (Atom (Form n p r a t) s,Attrib a n p r)=>Form n p r a (Neg t) -> s
negSymbol = symbol . subf
class Negation t n_t | t -> n_t, n_t -> t where
neg :: Attrib a n p r => Form n p r a t -> Form n p r a n_t
instance Negation Top (Neg Top) where
neg Top{} = let f = NegTop a; a = computeAttrib f in f
instance Negation (Neg Top) Top where
neg g@NegTop{} = subf g
instance Negation Nom (Neg Nom) where
neg g@Nom{} = let f = NegNom a (symbol g); a = computeAttrib f in f
instance Negation (Neg Nom) Nom where
neg g@NegNom{} = subf g
instance Negation Prop (Neg Prop) where
neg g@Prop{} = let f = NegProp a (symbol g); a = computeAttrib f in f
instance Negation (Neg Prop) Prop where
neg g@NegProp{} = subf g
instance Negation t n_t => Negation (Diam t) (Box n_t) where
neg f@Diam{} = box (relSym f) (neg $ subf f)
instance Negation t n_t => Negation (Box t) (Diam n_t) where
neg f@Box{} = diam (relSym f) (neg $ subf f)
instance Negation t n_t => Negation (At t) (At n_t) where
neg f@At{} = at (label f) (neg $ subf f)
instance Negation t n_t => Negation (Down t) (Down n_t) where
neg f@Down{} = down (boundVar f) (neg $ subf f)
instance Negation Opaque Opaque where
neg (Opaque f@Top{}) = Opaque $ neg f
neg (Opaque f@Nom{}) = Opaque $ neg f
neg (Opaque f@Prop{}) = Opaque $ neg f
neg (Opaque f@NegTop{}) = Opaque $ neg f
neg (Opaque f@NegNom{}) = Opaque $ neg f
neg (Opaque f@NegProp{}) = Opaque $ neg f
neg (Opaque f@Disj{}) = Opaque $ conj (map (neg . opaque) $ subfs f)
neg (Opaque f@Conj{}) = Opaque $ disj (map (neg . opaque) $ subfs f)
neg (Opaque f@Diam{}) = Opaque $ box (relSym f) (neg . opaque $ subf f)
neg (Opaque f@Box{}) = Opaque $ diam (relSym f) (neg . opaque $ subf f)
neg (Opaque f@At{}) = Opaque $ at (label f) (neg . opaque $ subf f)
neg (Opaque f@Down{}) = Opaque $ down (boundVar f) (neg . opaque $ subf f)
neg (Opaque Opaque{}) = error "neg: opaque-opaque!"
mapSig :: (Attrib a n p r, Attrib b m q s)
=> (n -> m)
-> (p -> q)
-> (r -> s)
-> Form n p r a f
-> Form m q s b f
mapSig _ _ _ Top{} = top
mapSig _ _ _ NegTop{} = bot
--
mapSig fn _ _ f@Nom{} = nom (fn $ symbol f)
mapSig _ fp _ f@Prop{} = prop (fp $ symbol f)
--
mapSig fn _ _ f@NegNom{} = negNom (fn $ negSymbol f)
mapSig _ fp _ f@NegProp{} = negProp (fp $ negSymbol f)
--
mapSig fn fp fr f@Disj{} = disj (map (mapSig fn fp fr) $ subfs f)
mapSig fn fp fr f@Conj{} = conj (map (mapSig fn fp fr) $ subfs f)
--
mapSig fn fp fr f@Diam{} = diam (fr $ relSym f) (mapSig fn fp fr $ subf f)
mapSig fn fp fr f@Box{} = box (fr $ relSym f) (mapSig fn fp fr $ subf f)
--
mapSig fn fp fr f@At{} = at (fn $ label f) (mapSig fn fp fr $ subf f)
--
mapSig fn fp fr f@Down{} = down (fn $ boundVar f) (mapSig fn fp fr $ subf f)
--
mapSig fn fp fr (Opaque f) = Opaque (mapSig fn fp fr f)
replaceNom :: (Eq n,Attrib a n p r)=>n -> n -> Form n p r a f -> Form n p r a f
replaceNom i i' f@Nom{} = if i == symbol f then nom i' else f
replaceNom i i' f@NegNom{} = if i == (symbol $ subf f) then negNom i' else f
replaceNom i i' f@At{} = if i == label f
then at i' (replaceNom i i' $ subf f)
else onSubf (replaceNom i i') f
replaceNom i i' f@Disj{} = disj [replaceNom i i' f' | f' <- subfs f]
replaceNom i i' f@Conj{} = conj [replaceNom i i' f' | f' <- subfs f]
replaceNom i i' f@Diam{} = onSubf (replaceNom i i') f
replaceNom i i' f@Box{} = onSubf (replaceNom i i') f
replaceNom i i' f@Down{} = if i == boundVar f
then down i' (replaceNom i i' $ subf f)
else onSubf (replaceNom i i') f
replaceNom i i' (Opaque f) = Opaque (replaceNom i i' f)
replaceNom _ _ f = f
instanceFreeVar :: (Eq n, Attrib a n p r)
=> n
-> n
-> Form n p r a f
-> Form n p r a f
instanceFreeVar i i' f@Nom{} = if i == symbol f then nom i' else f
instanceFreeVar i i' f@NegNom{} = if i == negSymbol f
then negNom i'
else f
instanceFreeVar i i' f@At{} = if i == label f
then at i' (instanceFreeVar i i' $ subf f)
else onSubf (instanceFreeVar i i') f
instanceFreeVar i i' f@Disj{} = disj [instanceFreeVar i i' f' | f' <- subfs f]
instanceFreeVar i i' f@Conj{} = conj [instanceFreeVar i i' f' | f' <- subfs f]
instanceFreeVar i i' f@Diam{} = onSubf (instanceFreeVar i i') f
instanceFreeVar i i' f@Box{} = onSubf (instanceFreeVar i i') f
instanceFreeVar i i' f@Down{} = if i == boundVar f
then f
else onSubf (instanceFreeVar i i') f
instanceFreeVar i i' (Opaque f) = Opaque (instanceFreeVar i i' f)
instanceFreeVar _ _ f = f
---------------------------------------
-- QuickCheck stuff --
---------------------------------------
instance (Arbitrary n, Arbitrary p, Arbitrary r, Eq n, Attrib a n p r)
=> Arbitrary (Form n p r a Opaque) where
arbitrary = do f <- arbitrary
return (subf $ nnfAtFormula undefined (removeUniversals f))
--
coarbitrary = coarbitrary . unNNF
removeUniversals :: F.Formula n p r -> F.Formula n p r
removeUniversals (F.A f) = removeUniversals f
removeUniversals (F.E f) = removeUniversals f
removeUniversals (F.D f) = removeUniversals f
removeUniversals (F.B f) = removeUniversals f
removeUniversals f = F.composeMap id removeUniversals f
instance (Arbitrary n, Arbitrary p, Arbitrary r, Attrib a n p r)
=> Arbitrary (Form n p r a Top)
where
arbitrary = return top
coarbitrary = const $ coarbitrary ()
instance (Arbitrary n, Arbitrary p, Arbitrary r, Attrib a n p r)
=> Arbitrary (Form n p r a Prop)
where
arbitrary = liftM fromSymbol arbitrary
--
coarbitrary = coarbitrary . unNNF
instance (Arbitrary n, Arbitrary p, Arbitrary r, Attrib a n p r)
=> Arbitrary (Form n p r a Nom)
where
arbitrary = liftM fromSymbol arbitrary
--
coarbitrary = coarbitrary . unNNF
instance (Arbitrary n, Arbitrary p, Arbitrary r, Attrib a n p r)
=> Arbitrary (Form n p r a (Neg Prop)) where
arbitrary = liftM negProp arbitrary
--
coarbitrary = coarbitrary . unNNF
instance (Arbitrary n, Arbitrary p, Arbitrary r, Attrib a n p r)
=> Arbitrary (Form n p r a (Neg Nom)) where
arbitrary = liftM negNom arbitrary
--
coarbitrary = coarbitrary . unNNF
instance (Arbitrary n, Arbitrary p, Arbitrary r,
Arbitrary (Form n p r a f), Attrib a n p r)
=> Arbitrary (Form n p r a (At f)) where
arbitrary = liftM2 at arbitrary arbitrary
--
coarbitrary = coarbitrary . unNNF
instance (Arbitrary n, Arbitrary p, Arbitrary r,
Arbitrary (Form n p r a f), Attrib a n p r)
=> Arbitrary (Form n p r a (Down f)) where
arbitrary = liftM2 down arbitrary arbitrary
--
coarbitrary = coarbitrary . unNNF
instance (Arbitrary n, Arbitrary p, Arbitrary r,
Arbitrary (Form n p r a f), Attrib a n p r)
=> Arbitrary (Form n p r a (Diam f)) where
arbitrary = liftM2 diam arbitrary arbitrary
--
coarbitrary = coarbitrary . unNNF
instance (Arbitrary n, Arbitrary p, Arbitrary r,
Arbitrary (Form n p r a f), Attrib a n p r)
=> Arbitrary (Form n p r a (Box f)) where
arbitrary = liftM2 box arbitrary arbitrary
--
coarbitrary = coarbitrary . unNNF
instance (Arbitrary n, Arbitrary p, Arbitrary r, Eq n, Attrib a n p r)
=> Arbitrary (Form n p r a Disj) where
arbitrary = do (f,fs) <- arbitrary
return $ disj (f:fs :: [Form n p r a Opaque])
--
coarbitrary = coarbitrary . unNNF
instance (Arbitrary n, Arbitrary p, Arbitrary r, Eq n, Attrib a n p r)
=> Arbitrary (Form n p r a Conj) where
arbitrary = do (f,fs) <- arbitrary
return $ conj (f:fs :: [Form n p r a Opaque])
--
coarbitrary = coarbitrary . unNNF
metap_read_NNF :: (Show (Form n p r a f), Read (Form n p r a f),
Arbitrary (Form n p r a f), Attrib a n p r,
Eq n, Eq p, Eq r)
=> Form n p r a f -> Bool
metap_read_NNF f = eqUnNNF f f'
where f' = (read $ show f) `asTypeOf` f
metap_read_Opaque :: (Show (Form n p r a Opaque),
Read (Form n p r a Opaque),
Arbitrary (Form n p r a Opaque),
Eq n, Eq p, Eq r,
Attrib a n p r)
=> Form n p r a Opaque -> Bool
metap_read_Opaque = metap_read_NNF
metap_read_AtNomOpaque :: (Show (Form n p r a (At Opaque)),
Read (Form n p r a (At Opaque)),
Arbitrary (Form n p r a (At Opaque)),
Eq n, Eq p, Eq r,
Attrib a n p r)
=> Form n p r a (At Opaque) -> Bool
metap_read_AtNomOpaque = metap_read_NNF
type TestFormula f = Form NomSymbol PropSymbol RelSymbol () f
prop_read_Opaque :: TestFormula Opaque -> Bool
prop_read_Opaque = metap_read_Opaque
prop_read_AtNomOpaque :: TestFormula (At Opaque) -> Bool
prop_read_AtNomOpaque = metap_read_AtNomOpaque
prop_mapSig :: (NomSymbol -> NomSymbol)
-> (PropSymbol -> PropSymbol)
-> (RelSymbol -> RelSymbol)
-> TestFormula (At Opaque)
-> Bool
prop_mapSig fn fp fr f = (unNNF mapSig_f) == (F.mapSig fn fp fr . unNNF $ f)
where mapSig_f = (mapSig fn fp fr $ f) :: TestFormula (At Opaque)
prop_replaceNom :: NomSymbol -> NomSymbol -> TestFormula Opaque -> Bool
prop_replaceNom i j f = eqUnNNF (replaceNom i j f) (mapSig (repl i j) id id f)
where repl a b c = if c == a then b else c
prop_instFreeVarSameBnds :: NomSymbol -> NomSymbol -> TestFormula Opaque -> Bool
prop_instFreeVarSameBnds x i f = boundVars f == boundVars f'
where f' = instanceFreeVar x i f
boundVars = F.boundVars . unNNF
prop_instFreeVarRepl :: NomSymbol -> NomSymbol -> TestFormula Opaque -> Property
prop_instFreeVarRepl x i f = (null . F.boundVars $ unNNF f) ==>
eqUnNNF (instanceFreeVar x i f) (replaceNom x i f)
prop_spec_rel_opaque :: TestFormula (At (Diam Nom)) -> Bool
prop_spec_rel_opaque f = case specialize (onSubf (onSubf opaque) f) of
AtDiamNom f' -> eqUnNNF f f'
_ -> False
unit_tests :: UnitTest
unit_tests = [
("read/show - F Opaque", runTest prop_read_Opaque),
("read/show - F (At Opaque)", runTest prop_read_AtNomOpaque),
("mapSig works", runTest prop_mapSig),
("replaceNom/mapSig", runTest prop_replaceNom),
("instanceFreeVar/bound vars", runTest prop_instFreeVarSameBnds),
("instanceFreeVar/replaceNom", runTest prop_instFreeVarRepl),
("specialize - Rel Opaque", runTest prop_spec_rel_opaque)
]
| nevrenato/HyLoRes_Source | src/HyLoRes/Formula/Internal.hs | gpl-2.0 | 25,259 | 0 | 16 | 8,390 | 12,142 | 6,140 | 6,002 | -1 | -1 |
main :: IO ()
main = putStrLn "compiled & run"
| adamwespiser/wespiser.com | my-site/drafts/simple.hs | gpl-3.0 | 47 | 1 | 6 | 10 | 22 | 9 | 13 | 2 | 1 |
{- |
Module : $Header$
Description : Spec for Crypto.Phec.Primes.
Copyright : 2015 Stian Ellingsen <[email protected]>
License : LGPL-3
Maintainer : Stian Ellingsen <[email protected]>
-}
module Crypto.Phec.PrimesSpec (spec) where
import Control.Arrow ((>>>))
import Control.Monad (forM_)
import Crypto.Phec.Primes (isGermainPrime, isGermainPrime', isSafePrime)
import Data.Functor ((<$>))
import Data.Monoid ((<>))
import Math.NumberTheory.Primes.Counting (nthPrime)
import Math.NumberTheory.Primes.Testing (isPrime)
import Test.Hspec (Spec, describe, it, parallel, shouldSatisfy)
import Test.Hspec.QuickCheck (prop)
import Test.QuickCheck
( Gen, (===), (==>), arbitrary, choose, forAll, getNonNegative, getPositive
, infiniteListOf, oneof, sized )
genPositiveLargeInteger :: Gen Integer
genPositiveLargeInteger = sized $ \n -> do
b <- choose (1, 24 + n)
choose (1, 2^b)
genLargePrime :: Gen Integer
genLargePrime = do
n <- infiniteListOf $ (1 +) <$> (2 *) <$> genPositiveLargeInteger
return . head $ filter isPrime n
genPrime :: Gen Integer
genPrime = nthPrime <$> getPositive <$> arbitrary
genGermainCandidate :: Gen Integer
genGermainCandidate = subtract 1 <$> (6 *) <$> genPositiveLargeInteger
genCompound :: Gen Integer
genCompound = do
a <- (1 +) <$> oneof [getPositive <$> arbitrary, genPositiveLargeInteger]
b <- (a +) <$> oneof [getNonNegative <$> arbitrary, genPositiveLargeInteger]
return $ a * b
largeSafePrimes :: [Integer]
largeSafePrimes = [2^(2^i :: Int) - x | (i, x) <- zip [5 :: Int ..] xs]
where xs = [209, 1469, 15449, 36113, 38117, 1093337, 1942289, 10895177]
safePrimes :: [Integer]
safePrimes = [5, 7, 11, 23, 2579, 2819, 2879, 2903] <> largeSafePrimes
germainPrimes :: [Integer]
germainPrimes = (`div` 2) <$> safePrimes
spec :: Spec
spec = parallel $ do
describe "isGermainPrime'" $ do
prop "returns False for compound numbers" .
forAll genGermainCandidate $ \n ->
not (isPrime n) ==> not (isGermainPrime' n)
prop "returns False for compound 2 * n + 1" .
forAll genGermainCandidate $ \n ->
not (isPrime (2 * n + 1)) ==> not (isGermainPrime' n)
describe "isGermainPrime" $ do
prop "returns False for non-positive numbers" .
forAll (negate <$> getNonNegative <$> arbitrary) $ not . isGermainPrime
prop "returns False for numbers > 5 not congruent to 5 modulo 6" .
forAll ((6 *) <$> genPositiveLargeInteger) $ \x ->
not $ or [isGermainPrime $ x + i | i <- [0..4]]
prop "for any prime p, returns True iff 2 * p + 1 is prime" .
forAll (oneof [genLargePrime, genPrime]) $ \p ->
isPrime (2 * p + 1) === isGermainPrime p
prop "returns False for compound numbers" .
forAll genCompound $ not . isGermainPrime
it "returns True for certain known Germain primes" $
forM_ germainPrimes (`shouldSatisfy` isGermainPrime)
describe "isSafePrime" $ do
prop "returns True iff (n - 1) / 2 is a Germain prime" $
getPositive >>> \a ->
isSafePrime a === (a `mod` 2 == 1 && isGermainPrime (a `div` 2))
prop "for any prime p, returns True iff (p - 1) / 2 is prime" .
forAll (oneof [genLargePrime, genPrime]) $ \p ->
isSafePrime p === isPrime (p `div` 2)
it "returns True for certain known safe primes" $
forM_ safePrimes (`shouldSatisfy` isSafePrime)
| stiell/phec | test-suite/Crypto/Phec/PrimesSpec.hs | gpl-3.0 | 3,349 | 0 | 19 | 685 | 1,040 | 568 | 472 | 68 | 1 |
-- | Command-Line driver for compiling Verse documents.
import Control.Applicative
import Control.Monad
import qualified Data.Map as M
import System.IO
import System.Environment (getArgs)
import System.Exit
import Language.Verse.Parser
import Language.Verse.Renderer
import Language.Verse.Renderer.Html
import Language.Verse.Transform.Bold
import Language.Verse.Transform.Italics
import Language.Verse.Transform.Chess
import Language.Verse.Transform.Code
import Language.Verse.Transform.Music
main :: IO ()
main = do
args <- getArgs
when (length args /= 1) (putStrLn "Provide an input file." >> exitWith (ExitFailure 1))
let inFile = head args
fileContents <- readFile inFile
let Right x = runParser document inFile fileContents
let transforms = M.fromList [
("bold", TransformContext BoldTC)
, ("italics", TransformContext ItalicsTC)
, ("code", TransformContext $ CodeTC "pygmentize")
, ("music", TransformContext $ MusicTC False "vexflow.js" "jquery.js")
, ("chess", TransformContext $ ChessTC 0 "chessboard.js")
]
y <- runRenderer transforms HtmlRenderContext . renderD $ x
putStrLn $ serialize y
| sykora/verse | src/Verse.hs | gpl-3.0 | 1,221 | 1 | 14 | 249 | 320 | 171 | 149 | 29 | 1 |
{-# LANGUAGE ScopedTypeVariables, CPP #-}
{-|
Utilities for top-level modules and ghci. See also Hledger.Read and
Hledger.Utils.
-}
module Hledger.Cli.Utils
(
withJournalDo,
writeOutput,
journalReload,
journalReloadIfChanged,
journalFileIsNewer,
journalSpecifiedFileIsNewer,
fileModificationTime,
openBrowserOn,
writeFileWithBackup,
writeFileWithBackupIfChanged,
readFileStrictly,
Test(TestList),
)
where
import Control.Exception as C
import Data.List
import Data.Maybe
import Safe (readMay)
import System.Console.CmdArgs
import System.Directory (getModificationTime, getDirectoryContents, copyFile)
import System.Exit
import System.FilePath ((</>), splitFileName, takeDirectory)
import System.Info (os)
import System.Process (readProcessWithExitCode)
import System.Time (ClockTime, getClockTime, diffClockTimes, TimeDiff(TimeDiff))
import Test.HUnit
import Text.Printf
import Text.Regex.TDFA ((=~))
-- kludge - adapt to whichever directory version is installed, or when
-- cabal macros aren't available, assume the new directory
#ifdef MIN_VERSION_directory
#if MIN_VERSION_directory(1,2,0)
#define directory_1_2
#endif
#else
#define directory_1_2
#endif
#ifdef directory_1_2
import System.Time (ClockTime(TOD))
import Data.Time.Clock.POSIX (utcTimeToPOSIXSeconds)
#endif
import Hledger.Cli.Options
import Hledger.Data
import Hledger.Read
import Hledger.Utils
-- | Parse the user's specified journal file and run a hledger command on
-- it, or throw an error.
withJournalDo :: CliOpts -> (CliOpts -> Journal -> IO ()) -> IO ()
withJournalDo opts cmd = do
-- We kludgily read the file before parsing to grab the full text, unless
-- it's stdin, or it doesn't exist and we are adding. We read it strictly
-- to let the add command work.
rulespath <- rulesFilePathFromOpts opts
journalpath <- journalFilePathFromOpts opts
ej <- readJournalFile Nothing rulespath (not $ ignore_assertions_ opts) journalpath
either error' (cmd opts . journalApplyAliases (aliasesFromOpts opts)) ej
-- | Write some output to stdout or to a file selected by --output-file.
writeOutput :: CliOpts -> String -> IO ()
writeOutput opts s = do
f <- outputFileFromOpts opts
(if f == "-" then putStr else writeFile f) s
-- -- | Get a journal from the given string and options, or throw an error.
-- readJournalWithOpts :: CliOpts -> String -> IO Journal
-- readJournalWithOpts opts s = readJournal Nothing Nothing Nothing s >>= either error' return
-- | Re-read a journal from its data file, or return an error string.
journalReload :: Journal -> IO (Either String Journal)
journalReload j = readJournalFile Nothing Nothing True $ journalFilePath j
-- | Re-read a journal from its data file mostly, only if the file has
-- changed since last read (or if there is no file, ie data read from
-- stdin). The provided options are mostly ignored. Return a journal or
-- the error message while reading it, and a flag indicating whether it
-- was re-read or not.
journalReloadIfChanged :: CliOpts -> Journal -> IO (Either String Journal, Bool)
journalReloadIfChanged _ j = do
let maybeChangedFilename f = do newer <- journalSpecifiedFileIsNewer j f
return $ if newer then Just f else Nothing
changedfiles <- catMaybes `fmap` mapM maybeChangedFilename (journalFilePaths j)
if not $ null changedfiles
then do
whenLoud $ printf "%s has changed, reloading\n" (head changedfiles)
jE <- journalReload j
return (jE, True)
else
return (Right j, False)
-- | Has the journal's main data file changed since the journal was last
-- read ?
journalFileIsNewer :: Journal -> IO Bool
journalFileIsNewer j@Journal{filereadtime=tread} = do
tmod <- fileModificationTime $ journalFilePath j
return $ diffClockTimes tmod tread > (TimeDiff 0 0 0 0 0 0 0)
-- | Has the specified file (presumably one of journal's data files)
-- changed since journal was last read ?
journalSpecifiedFileIsNewer :: Journal -> FilePath -> IO Bool
journalSpecifiedFileIsNewer Journal{filereadtime=tread} f = do
tmod <- fileModificationTime f
return $ diffClockTimes tmod tread > (TimeDiff 0 0 0 0 0 0 0)
-- | Get the last modified time of the specified file, or if it does not
-- exist or there is some other error, the current time.
fileModificationTime :: FilePath -> IO ClockTime
fileModificationTime f
| null f = getClockTime
| otherwise = (do
#ifdef directory_1_2
utc <- getModificationTime f
let nom = utcTimeToPOSIXSeconds utc
let clo = TOD (read $ takeWhile (`elem` "0123456789") $ show nom) 0 -- XXX read
#else
clo <- getModificationTime f
#endif
return clo
)
`C.catch` \(_::C.IOException) -> getClockTime
-- | Attempt to open a web browser on the given url, all platforms.
openBrowserOn :: String -> IO ExitCode
openBrowserOn u = trybrowsers browsers u
where
trybrowsers (b:bs) u = do
(e,_,_) <- readProcessWithExitCode b [u] ""
case e of
ExitSuccess -> return ExitSuccess
ExitFailure _ -> trybrowsers bs u
trybrowsers [] u = do
putStrLn $ printf "Could not start a web browser (tried: %s)" $ intercalate ", " browsers
putStrLn $ printf "Please open your browser and visit %s" u
return $ ExitFailure 127
browsers | os=="darwin" = ["open"]
| os=="mingw32" = ["c:/Program Files/Mozilla Firefox/firefox.exe"]
| otherwise = ["sensible-browser","gnome-www-browser","firefox"]
-- jeffz: write a ffi binding for it using the Win32 package as a basis
-- start by adding System/Win32/Shell.hsc and follow the style of any
-- other module in that directory for types, headers, error handling and
-- what not.
-- ::ShellExecute(NULL, "open", "www.somepage.com", NULL, NULL, SW_SHOWNORMAL);
-- | Back up this file with a (incrementing) numbered suffix then
-- overwrite it with this new text, or give an error, but only if the text
-- is different from the current file contents, and return a flag
-- indicating whether we did anything.
writeFileWithBackupIfChanged :: FilePath -> String -> IO Bool
writeFileWithBackupIfChanged f t = do
s <- readFile' f
if t == s then return False
else backUpFile f >> writeFile f t >> return True
-- | Back up this file with a (incrementing) numbered suffix, then
-- overwrite it with this new text, or give an error.
writeFileWithBackup :: FilePath -> String -> IO ()
writeFileWithBackup f t = backUpFile f >> writeFile f t
readFileStrictly :: FilePath -> IO String
readFileStrictly f = readFile' f >>= \s -> C.evaluate (length s) >> return s
-- | Back up this file with a (incrementing) numbered suffix, or give an error.
backUpFile :: FilePath -> IO ()
backUpFile fp = do
fs <- safeGetDirectoryContents $ takeDirectory $ fp
let (d,f) = splitFileName fp
versions = catMaybes $ map (f `backupNumber`) fs
next = maximum (0:versions) + 1
f' = printf "%s.%d" f next
copyFile fp (d </> f')
safeGetDirectoryContents :: FilePath -> IO [FilePath]
safeGetDirectoryContents "" = getDirectoryContents "."
safeGetDirectoryContents fp = getDirectoryContents fp
-- | Does the second file represent a backup of the first, and if so which version is it ?
-- XXX nasty regex types intruding, add a simpler api to Hledger.Utils.Regex
backupNumber :: FilePath -> FilePath -> Maybe Int
backupNumber f g = case g =~ ("^" ++ f ++ "\\.([0-9]+)$") of
(_::FilePath, _::FilePath, _::FilePath, [ext::FilePath]) -> readMay ext
_ -> Nothing
| kmels/hledger | hledger/Hledger/Cli/Utils.hs | gpl-3.0 | 7,641 | 0 | 18 | 1,559 | 1,586 | 834 | 752 | 116 | 3 |
module Interpreter (interpreteProgram
,interpreteModule
,repl) where
-- map
import qualified Data.Map as Map
import Data.Map (Map)
-- other
import Data.IORef
import Control.Monad.Except
import Control.Monad.IO.Class (liftIO)
import Control.Monad (unless)
import System.Console.Readline
import System.IO
-- local modules
import qualified Reader as R
import qualified Evaluator as E
import Lib.Everything
import Base
import Point
preludePath :: String
preludePath = "stdlib/prelude.unlisp"
-- | Interprete a module and returns its scope
interpreteModule :: Bool -> String -> EvalM (IORef Scope)
interpreteModule prelude filename = do
scope <- liftIO $ loadEnv prelude
text <- liftIO $ readFile filename
childScope <- liftIO $ newLocal scope
exps <- forwardExcept $ R.read (startPoint filename) text
exps' <- preprocess childScope exps
E.expandEvalSeq childScope exps'
return childScope
-- | A lisp interpretator is just a reader and evaluator joined together
interpreteProgram :: Bool -> String -> [String] -> IO ()
interpreteProgram prelude filename args = do
scopeRef <- loadEnv prelude
modifyIORef scopeRef (modifyCmdArgs $ const args)
text <- readFile filename
handleEvalM $ do
exps <- forwardExcept $ R.read (startPoint filename) text
exps' <- preprocess scopeRef exps
E.expandEvalBody scopeRef exps'
-- | REPL (read-eval-print-loop) environment
repl :: Bool -> IO ()
repl prelude = do
scope <- loadEnv prelude
childScope <- newLocal scope
handleLines (startPoint "<REPL>") childScope
where handleLines :: Point -> IORef Scope -> IO ()
handleLines p scopeRef = do
line <- readline $ "[" ++ show (pRow p) ++ "]> "
case line of
Just line -> do
unless (null line) $ addHistory line
result <- runEvalM $ do
exps <- forwardExcept $ R.read p line
exps' <- preprocess scopeRef exps
result <- E.expandEvalSeq scopeRef exps'
return $ if null result then nil else last result
exp <- case result of
Right val -> return val
Left f -> do
hPrint stderr f
return nil
unless (isNil exp) (putStrLn $ "=> " ++ show exp)
modifyIORef scopeRef (scInsert "it" exp)
handleLines (forwardRow p) scopeRef
Nothing -> putStrLn "Bye!"
-- | Load start environment.
-- No prelude if the first argument is false
loadEnv :: Bool -> IO (IORef Scope)
loadEnv True = loadPrelude
loadEnv False = newIORef $ newGlobal' startEnv []
-- | loads prelude and start environment
loadPrelude :: IO (IORef Scope)
loadPrelude = do
text <- readFile preludePath
global <- newIORef $ newGlobal' startEnv []
let result = runExcept $ R.read (startPoint preludePath) text
case result of
Right exps -> handleEvalM $ E.expandEvalSeq global exps
Left fail -> hPrint stderr fail
return global
-- | start environment
-- | contains built-in functions and special operators
startEnv :: Map String SExpr
startEnv = Map.fromList $ fmap (\(name, args, f) -> (name, procedure $ BuiltIn name args f [])) specialOperators
-- | Do all preprocessing.
-- For now it's just importing modules.
preprocess :: IORef Scope -> [SExpr] -> EvalM [SExpr]
preprocess = collectImports
-- | Collect imports in the scope
collectImports :: IORef Scope -> [SExpr] -> EvalM [SExpr]
collectImports scopeRef = foldM (\acc exp -> do
import' <- parseImport exp
case import' of
Just filename -> do moduleScope <- interpreteModule True filename
liftIO $ modifyIORef scopeRef $ modifyImports (moduleScope:)
return acc
Nothing -> return $ acc ++ [exp])
[]
-- | Parse an import expression
parseImport :: SExpr -> EvalM (Maybe String)
parseImport (SList p [SAtom _ (ASymbol "import"), filename])
| not $ isList filename = reportE p "string expected"
| null $ fromList filename = reportE p "module name cannot be empty"
| otherwise = Just <$> (mapM Base.getChar . tail $ fromList filename)
parseImport (SList p (SAtom _ (ASymbol "import"):_)) = reportE p "just one argument required"
parseImport _ = return Nothing
| Kotolegokot/Underlisp | src/Interpreter.hs | gpl-3.0 | 4,625 | 0 | 21 | 1,401 | 1,283 | 625 | 658 | 93 | 4 |
{-# LANGUAGE NoImplicitPrelude #-}
module ZetaTypeOfRings(
module ZetaTypeOfRings
) where
import TannakianSymbols
import Parsing
import Data.List
import qualified Prelude
import Prelude hiding ((+),(-),(*),(^),(/), negate)
data Zmod = Zmod [Integer]
cleanupZM :: Zmod -> Zmod
cleanupZM (Zmod x) = Zmod . combine . reverse . sort $ x where
combine [] = []
combine (x:[]) = if x==1 then [] else [x]
combine (x:y:m) = let (a, b) = (gcd x y, lcm x y) in
if a == 1 then combine (b : m) else b : combine (a : m)
instance CMult Zmod where
e = Zmod []
Zmod a * Zmod b = cleanupZM . Zmod $ a ++ b
instance Show Zmod where
show (Zmod []) = "0"
show (Zmod n) = intercalate " + " $ fmap (("Z/" ++) . show) n
instance Eq Zmod where
a == b = let (Zmod x, Zmod y) = (cleanupZM a, cleanupZM b) in x == y
type Ringmonoid = TS Zmod
instance Read Zmod where
readPrec = fmap (cleanupZM . Zmod) $ split '+' (expectS "Z/" >> readPrec)
| torstein-vik/zeta-types | src/case studies/ZetaTypeOfRings.hs | gpl-3.0 | 1,073 | 2 | 13 | 340 | 466 | 250 | 216 | 26 | 5 |
{-# 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.Storage.Objects.List
-- 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)
--
-- Retrieves a list of objects matching the criteria.
--
-- /See:/ <https://developers.google.com/storage/docs/json_api/ Cloud Storage JSON API Reference> for @storage.objects.list@.
module Network.Google.Resource.Storage.Objects.List
(
-- * REST Resource
ObjectsListResource
-- * Creating a Request
, objectsList
, ObjectsList
-- * Request Lenses
, olPrefix
, olBucket
, olVersions
, olProjection
, olPageToken
, olDelimiter
, olMaxResults
) where
import Network.Google.Prelude
import Network.Google.Storage.Types
-- | A resource alias for @storage.objects.list@ method which the
-- 'ObjectsList' request conforms to.
type ObjectsListResource =
"storage" :>
"v1" :>
"b" :>
Capture "bucket" Text :>
"o" :>
QueryParam "prefix" Text :>
QueryParam "versions" Bool :>
QueryParam "projection" ObjectsListProjection :>
QueryParam "pageToken" Text :>
QueryParam "delimiter" Text :>
QueryParam "maxResults" (Textual Word32) :>
QueryParam "alt" AltJSON :> Get '[JSON] Objects
-- | Retrieves a list of objects matching the criteria.
--
-- /See:/ 'objectsList' smart constructor.
data ObjectsList = ObjectsList'
{ _olPrefix :: !(Maybe Text)
, _olBucket :: !Text
, _olVersions :: !(Maybe Bool)
, _olProjection :: !(Maybe ObjectsListProjection)
, _olPageToken :: !(Maybe Text)
, _olDelimiter :: !(Maybe Text)
, _olMaxResults :: !(Maybe (Textual Word32))
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'ObjectsList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'olPrefix'
--
-- * 'olBucket'
--
-- * 'olVersions'
--
-- * 'olProjection'
--
-- * 'olPageToken'
--
-- * 'olDelimiter'
--
-- * 'olMaxResults'
objectsList
:: Text -- ^ 'olBucket'
-> ObjectsList
objectsList pOlBucket_ =
ObjectsList'
{ _olPrefix = Nothing
, _olBucket = pOlBucket_
, _olVersions = Nothing
, _olProjection = Nothing
, _olPageToken = Nothing
, _olDelimiter = Nothing
, _olMaxResults = Nothing
}
-- | Filter results to objects whose names begin with this prefix.
olPrefix :: Lens' ObjectsList (Maybe Text)
olPrefix = lens _olPrefix (\ s a -> s{_olPrefix = a})
-- | Name of the bucket in which to look for objects.
olBucket :: Lens' ObjectsList Text
olBucket = lens _olBucket (\ s a -> s{_olBucket = a})
-- | If true, lists all versions of an object as distinct results. The
-- default is false. For more information, see Object Versioning.
olVersions :: Lens' ObjectsList (Maybe Bool)
olVersions
= lens _olVersions (\ s a -> s{_olVersions = a})
-- | Set of properties to return. Defaults to noAcl.
olProjection :: Lens' ObjectsList (Maybe ObjectsListProjection)
olProjection
= lens _olProjection (\ s a -> s{_olProjection = a})
-- | A previously-returned page token representing part of the larger set of
-- results to view.
olPageToken :: Lens' ObjectsList (Maybe Text)
olPageToken
= lens _olPageToken (\ s a -> s{_olPageToken = a})
-- | Returns results in a directory-like mode. items will contain only
-- objects whose names, aside from the prefix, do not contain delimiter.
-- Objects whose names, aside from the prefix, contain delimiter will have
-- their name, truncated after the delimiter, returned in prefixes.
-- Duplicate prefixes are omitted.
olDelimiter :: Lens' ObjectsList (Maybe Text)
olDelimiter
= lens _olDelimiter (\ s a -> s{_olDelimiter = a})
-- | Maximum number of items plus prefixes to return. As duplicate prefixes
-- are omitted, fewer total results may be returned than requested. The
-- default value of this parameter is 1,000 items.
olMaxResults :: Lens' ObjectsList (Maybe Word32)
olMaxResults
= lens _olMaxResults (\ s a -> s{_olMaxResults = a})
. mapping _Coerce
instance GoogleRequest ObjectsList where
type Rs ObjectsList = Objects
type Scopes ObjectsList =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/cloud-platform.read-only",
"https://www.googleapis.com/auth/devstorage.full_control",
"https://www.googleapis.com/auth/devstorage.read_only",
"https://www.googleapis.com/auth/devstorage.read_write"]
requestClient ObjectsList'{..}
= go _olBucket _olPrefix _olVersions _olProjection
_olPageToken
_olDelimiter
_olMaxResults
(Just AltJSON)
storageService
where go
= buildClient (Proxy :: Proxy ObjectsListResource)
mempty
| rueshyna/gogol | gogol-storage/gen/Network/Google/Resource/Storage/Objects/List.hs | mpl-2.0 | 5,646 | 0 | 19 | 1,362 | 825 | 481 | 344 | 112 | 1 |
module Main where
import Test.Tasty
import qualified Tests.Data.Predicate as Predicate
import qualified Tests.Wai.Predicate as WaiPredicate
main :: IO ()
main = defaultMain $ testGroup "Tests"
[ Predicate.tests
, WaiPredicate.tests
]
| twittner/wai-predicates | test/TestSuite.hs | mpl-2.0 | 249 | 0 | 8 | 45 | 61 | 38 | 23 | 8 | 1 |
module Problem047 where
import Data.List
main =
print $ head $ dropWhile (not . c) [1..]
where c x = all (== 4) $ map (nods !!) $ map (+ x) [0..3]
nods = map (length . nub . divisors) [0..]
divisors 0 = []
divisors 1 = []
divisors x = divisors' primes [] x
where divisors' _ ds 1 = ds
divisors' (p:ps) ds x
| r == 0 = divisors' (p:ps) (p:ds) q
| otherwise = divisors' ps ds x
where (q, r) = x `quotRem` p
isPrime = primeF primes
primes = 2 : 3 : filter (primeF primes) [5, 7 ..]
primeF (p:ps) x = p * p > x || x `rem` p /= 0 && primeF ps x
| vasily-kartashov/playground | euler/problem-047.hs | apache-2.0 | 593 | 0 | 10 | 178 | 331 | 174 | 157 | 17 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module Model.Service where
import Control.Applicative
import Control.Monad
import Data.Aeson
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as C
import Data.Map (Map)
import Data.Maybe (fromJust)
import Data.Text (Text)
import Data.Word (Word16)
import Database.CouchDB.Conduit (Revision)
import Network.HTTP.Types.Method (Method)
import Model.URI
import Model.UUID
type Params = Map ByteString [ByteString]
data Service = Service {
uuid :: UUID,
revision :: Revision,
description :: Text,
host :: ByteString,
port :: Word16,
path :: ByteString,
methods :: [Method],
params :: Params
} deriving (Eq, Show)
url :: Service -> URI
url s = fromJust . parseURI . C.unpack $ C.concat
["http://", host s, ":", C.pack . show $ port s, if C.null $ path s
then ""
else '/' `C.cons` path s]
instance FromJSON Service where
parseJSON (Object v) =
Service <$> v .: "_id"
<*> v .: "_rev"
<*> v .: "description"
<*> v .: "host"
<*> v .: "port"
<*> v .: "path"
<*> v .: "methods"
<*> v .: "params"
parseJSON _ = mzero
instance ToJSON Service where
toJSON (Service _ _ d h p pa m par) =
object [ "type" .= ("service" :: ByteString)
, "description" .= d
, "host" .= h
, "port" .= p
, "path" .= pa
, "methods" .= m
, "params" .= par
]
| alexandrelucchesi/pfec | server-common/src/Model/Service.hs | apache-2.0 | 2,064 | 0 | 21 | 996 | 482 | 273 | 209 | 51 | 2 |
{-# LANGUAGE TemplateHaskell #-}
import HMSTimeSpec
import FFMpegCommandSpec
main :: IO ()
main =
do runHMSTimeSpecTests
runFFMpegCommandTests
return () | connrs/ffsplitgen | out/production/ffsplitgen/test/Spec.hs | apache-2.0 | 167 | 0 | 8 | 33 | 37 | 18 | 19 | 8 | 1 |
import Data.Char
ans :: String -> String
ans [] = []
ans (c:cs)
| isUpper c = (toLower c):(ans cs)
| isLower c = (toUpper c):(ans cs)
| otherwise = c:(ans cs)
main = do
c <- getContents
let i = lines c
o = map ans i
mapM_ putStrLn o
| a143753/AOJ | ITP1_8_A.hs | apache-2.0 | 259 | 0 | 10 | 77 | 156 | 74 | 82 | 12 | 1 |
{-# LANGUAGE TupleSections, OverloadedStrings, ScopedTypeVariables #-}
{-# OPTIONS_GHC -fno-warn-missing-signatures #-}
module Handler.Asset where
import Import
import qualified Data.Text
import Database.Persist.GenericSql
import Handler.Utils
import Handler.Rent (assetRentFormWidgetM)
import Handler.Review (reviewForm)
import Handler.File (deleteFile)
-- assets
assetAForm :: (Maybe Asset) -> [(Text,AssetId)] -> AForm App App Asset
assetAForm proto otherAssets = Asset
<$> areq textField "Name" (fmap assetName proto)
<*> areq textareaField "Description" (fmap assetDescription proto)
<*> areq (selectFieldList kinds) "Kind" (fmap assetKind proto)
<*> aopt (selectFieldList otherAssets) "Next asset" (fmap assetNext proto)
where
kinds :: [(Text,AssetKind)]
kinds = [("music",AssetMusic),("book",AssetBook),("movie",AssetMovie)]
assetForm :: Maybe Asset -> [(Text,AssetId)] -> Html -> MForm App App (FormResult Asset, Widget)
assetForm proto other = renderTable $ assetAForm proto other
-----
assetRentedWidget :: AssetId -> Handler Widget
assetRentedWidget aid = do
-- rentals <- runDB $ selectList [RentWhat ==. aid] [Asc RentId]
role <- getThisUserRole
let getThisUserId = do
mu <- maybeAuth
case mu of
Nothing -> return (const False)
Just user -> return (\uid -> uid == entityKey user)
checkSelf <- getThisUserId
let isAdmin = role [AdminRole]
canAuthorize = role [AdminRole, ResidentRole]
canUserSee uid = checkSelf uid || role [AdminRole, ResidentRole]
-- isAdmin
let query = Data.Text.concat [
"SELECT DISTINCT ??, ??, ",
" CASE ",
" WHEN rent.authorized_by IS NULL THEN NULL ",
" ELSE u2.ident END ",
" FROM rent, ",
" public.user, ",
" public.user as u2 ",
" WHERE rent.what = ? ",
" AND rent.taken_by = public.user.id ",
" AND (rent.authorized_by = u2.id OR rent.authorized_by IS NULL) ",
" ORDER BY rent.id "]
query' = "SELECT DISTINCT ??,??,NULL FROM rent, public.user WHERE what = ?"
results' <- runDB (do
ret <- rawSql query [unKey aid]
return (ret :: [(Entity Rent, Entity User, Single (Maybe Text))]))
let results = map (\ (a,b,Single c) -> (a,b,c)) results'
return $(widgetFile "asset/rented-widget")
----
getAssetViewR :: AssetId -> Handler RepHtml
getAssetViewR aid = do
asset :: Asset <- runDB $ get404 aid
displayUserWidget <- mkDisplayUserWidget
grpElems :: [Entity AssetGroupElement] <- runDB $ selectList [AssetGroupElementAsset ==. aid] [Desc AssetGroupElementAsset]
let agrpIds = map (assetGroupElementGroup . entityVal) grpElems
assetGroupsAll :: [Entity AssetGroup] <- runDB $ selectList [] [Desc AssetGroupId]
reviews :: [Entity Review] <- runDB $ selectList [ReviewWhat ==. aid] [Desc ReviewId]
files :: [Entity File] <- runDB $ selectList [FileAsset ==. aid] [Desc FileId]
let assetGroupsNot = filter (\ ent -> not ((entityKey ent) `elem` agrpIds)) assetGroupsAll
assetGroupsIn = filter (\ ent -> ((entityKey ent) `elem` agrpIds)) assetGroupsAll
rentedWidget <- assetRentedWidget aid
rentWidget <- assetRentFormWidgetM aid
let mkRevForm (Just user) = fmap Just (generateFormPost (renderTable (reviewForm (entityKey user) aid)))
mkRevForm Nothing = return Nothing
m'form'review <- mkRevForm =<< maybeAuth
thisUserRole <- getThisUserRole
let canModifyGroups = thisUserRole [AdminRole, ResidentRole, FriendRole]
canPostReviews = thisUserRole [AdminRole, ResidentRole, FriendRole, GuestRole]
canDelReviews = thisUserRole [AdminRole]
canUploadFiles = thisUserRole [AdminRole, ResidentRole, FriendRole]
canDeleteFiles = thisUserRole [AdminRole]
canDeleteAsset = thisUserRole [AdminRole]
defaultLayout $ do
setTitle $ toHtml $ "Asset " ++ show (assetName asset)
$(widgetFile "asset/view")
prepareAssetsToList assets = map (\a -> (formatAsset a, entityKey a)) assets
formatAsset a = Data.Text.concat [assetName (entityVal a), "(id=", (Data.Text.pack . showPeristentKey . unKey . entityKey $ a) , ")"]
getAssetAllGeneric title filter'lst = do
assets :: [Entity Asset] <- runDB $ selectList filter'lst [Asc AssetId]
(fwidget, enctype) <- generateFormPost (assetForm Nothing $ prepareAssetsToList assets)
thisUserRole <- getThisUserRole
let auth = thisUserRole [AdminRole, ResidentRole]
defaultLayout $ do
setTitle title
$(widgetFile "asset/all-view")
getAssetAllMusicR :: Handler RepHtml
getAssetAllMusicR = getAssetAllGeneric "A list of all music assets." [AssetKind ==. AssetMusic]
getAssetAllMoviesR :: Handler RepHtml
getAssetAllMoviesR = getAssetAllGeneric "A list of all movie assets." [AssetKind ==. AssetMovie]
getAssetAllBooksR :: Handler RepHtml
getAssetAllBooksR = getAssetAllGeneric "A list of all book assets." [AssetKind ==. AssetBook]
getAssetAllR :: Handler RepHtml
getAssetAllR = getAssetAllGeneric "A list of all assets." []
getAssetNewR :: Handler RepHtml
getAssetNewR = do
assets :: [Entity Asset] <- runDB $ selectList [] [Asc AssetId]
(fwidget, enctype) <- generateFormPost (assetForm Nothing $ prepareAssetsToList assets)
defaultLayout $ do
setTitle "A new asset."
$(widgetFile "asset/new")
postAssetNewR :: Handler RepHtml
postAssetNewR = do
assets :: [Entity Asset] <- runDB $ selectList [] [Asc AssetId]
((result, fwidget), enctype) <- runFormPost (assetForm Nothing $ prepareAssetsToList assets)
case result of
FormSuccess asset -> do
aid <- runDB $ insert asset
redirect (AssetViewR aid)
_ -> defaultLayout $ do
setTitle "A new asset."
$(widgetFile "asset/new")
getAssetEditR :: AssetId -> Handler RepHtml
getAssetEditR aid = do
asset <- runDB $ get404 aid
assets :: [Entity Asset] <- runDB $ selectList [] [Asc AssetId]
(fwidget, enctype) <- generateFormPost (assetForm (Just asset) $ prepareAssetsToList assets)
defaultLayout $ do
setTitle "Edit existing asset."
$(widgetFile "asset/edit")
postAssetEditR ::AssetId -> Handler RepHtml
postAssetEditR aid = do
asset :: Asset <- runDB $ get404 aid
assets :: [Entity Asset] <- runDB $ selectList [] [Asc AssetId]
((result, fwidget), enctype) <- runFormPost (assetForm (Just asset) $ prepareAssetsToList assets)
case result of
FormSuccess asset'new -> do
runDB $ replace aid asset'new
redirect (AssetViewR aid)
_ -> defaultLayout $ do
setTitle "Edit existing asset."
$(widgetFile "asset/edit")
assetDeleteForm = renderTable (const <$> areq areYouSureField "Are you sure?" (Just False))
where areYouSureField = check isSure boolField
isSure False = Left ("You must be sure to delete an asset" :: Text)
isSure True = Right True
getAssetDeleteR ::AssetId -> Handler RepHtml
getAssetDeleteR aid = do
asset :: Asset <- runDB $ get404 aid
(fwidget, enctype) <- generateFormPost assetDeleteForm
defaultLayout $ do
setTitle "Deleting an asset."
$(widgetFile "asset/delete")
postAssetDeleteR ::AssetId -> Handler RepHtml
postAssetDeleteR aid = do
asset :: Asset <- runDB $ get404 aid
((result,fwidget), enctype) <- runFormPost assetDeleteForm
case result of
FormSuccess _ -> do
files <- runDB $ selectList [FileAsset ==. aid] []
mapM_ deleteFile files
runDB $ do
deleteWhere [AssetGroupElementAsset ==. aid]
deleteWhere [RentWhat ==. aid]
deleteWhere [ReviewWhat ==. aid]
delete aid
defaultLayout [whamlet|
<p> <strong>Asset deleted.</strong> |]
_ -> defaultLayout $ do
setTitle "Deleting an asset."
$(widgetFile "asset/delete")
| Tener/personal-library-yesod | Handler/Asset.hs | bsd-2-clause | 8,574 | 0 | 19 | 2,412 | 2,359 | 1,167 | 1,192 | -1 | -1 |
{-# LANGUAGE CPP, DeriveDataTypeable, MagicHash, UnboxedTuples #-}
#if __GLASGOW_HASKELL__ >= 701
{-# LANGUAGE Trustworthy #-}
#endif
-----------------------------------------------------------------------------
-- |
-- Module : Control.Concurrent.STM.TMVar
-- Copyright : (c) The University of Glasgow 2004
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : non-portable (requires STM)
--
-- TMVar: Transactional MVars, for use in the STM monad
-- (GHC only)
--
-----------------------------------------------------------------------------
module Control.Concurrent.STM.TMVar (
#ifdef __GLASGOW_HASKELL__
-- * TMVars
TMVar,
newTMVar,
newEmptyTMVar,
newTMVarIO,
newEmptyTMVarIO,
takeTMVar,
putTMVar,
readTMVar,
tryReadTMVar,
swapTMVar,
tryTakeTMVar,
tryPutTMVar,
isEmptyTMVar,
mkWeakTMVar
#endif
) where
#ifdef __GLASGOW_HASKELL__
import GHC.Base
import GHC.Conc
import GHC.Weak
import Data.Typeable (Typeable)
newtype TMVar a = TMVar (TVar (Maybe a)) deriving (Eq, Typeable)
{- ^
A 'TMVar' is a synchronising variable, used
for communication between concurrent threads. It can be thought of
as a box, which may be empty or full.
-}
-- |Create a 'TMVar' which contains the supplied value.
newTMVar :: a -> STM (TMVar a)
newTMVar a = do
t <- newTVar (Just a)
return (TMVar t)
-- |@IO@ version of 'newTMVar'. This is useful for creating top-level
-- 'TMVar's using 'System.IO.Unsafe.unsafePerformIO', because using
-- 'atomically' inside 'System.IO.Unsafe.unsafePerformIO' isn't
-- possible.
newTMVarIO :: a -> IO (TMVar a)
newTMVarIO a = do
t <- newTVarIO (Just a)
return (TMVar t)
-- |Create a 'TMVar' which is initially empty.
newEmptyTMVar :: STM (TMVar a)
newEmptyTMVar = do
t <- newTVar Nothing
return (TMVar t)
-- |@IO@ version of 'newEmptyTMVar'. This is useful for creating top-level
-- 'TMVar's using 'System.IO.Unsafe.unsafePerformIO', because using
-- 'atomically' inside 'System.IO.Unsafe.unsafePerformIO' isn't
-- possible.
newEmptyTMVarIO :: IO (TMVar a)
newEmptyTMVarIO = do
t <- newTVarIO Nothing
return (TMVar t)
-- |Return the contents of the 'TMVar'. If the 'TMVar' is currently
-- empty, the transaction will 'retry'. After a 'takeTMVar',
-- the 'TMVar' is left empty.
takeTMVar :: TMVar a -> STM a
takeTMVar (TMVar t) = do
m <- readTVar t
case m of
Nothing -> retry
Just a -> do writeTVar t Nothing; return a
-- | A version of 'takeTMVar' that does not 'retry'. The 'tryTakeTMVar'
-- function returns 'Nothing' if the 'TMVar' was empty, or @'Just' a@ if
-- the 'TMVar' was full with contents @a@. After 'tryTakeTMVar', the
-- 'TMVar' is left empty.
tryTakeTMVar :: TMVar a -> STM (Maybe a)
tryTakeTMVar (TMVar t) = do
m <- readTVar t
case m of
Nothing -> return Nothing
Just a -> do writeTVar t Nothing; return (Just a)
-- |Put a value into a 'TMVar'. If the 'TMVar' is currently full,
-- 'putTMVar' will 'retry'.
putTMVar :: TMVar a -> a -> STM ()
putTMVar (TMVar t) a = do
m <- readTVar t
case m of
Nothing -> do writeTVar t (Just a); return ()
Just _ -> retry
-- | A version of 'putTMVar' that does not 'retry'. The 'tryPutTMVar'
-- function attempts to put the value @a@ into the 'TMVar', returning
-- 'True' if it was successful, or 'False' otherwise.
tryPutTMVar :: TMVar a -> a -> STM Bool
tryPutTMVar (TMVar t) a = do
m <- readTVar t
case m of
Nothing -> do writeTVar t (Just a); return True
Just _ -> return False
-- | This is a combination of 'takeTMVar' and 'putTMVar'; ie. it
-- takes the value from the 'TMVar', puts it back, and also returns
-- it.
readTMVar :: TMVar a -> STM a
readTMVar (TMVar t) = do
m <- readTVar t
case m of
Nothing -> retry
Just a -> return a
-- | A version of 'readTMVar' which does not retry. Instead it
-- returns @Nothing@ if no value is available.
tryReadTMVar :: TMVar a -> STM (Maybe a)
tryReadTMVar (TMVar t) = readTVar t
-- |Swap the contents of a 'TMVar' for a new value.
swapTMVar :: TMVar a -> a -> STM a
swapTMVar (TMVar t) new = do
m <- readTVar t
case m of
Nothing -> retry
Just old -> do writeTVar t (Just new); return old
-- |Check whether a given 'TMVar' is empty.
isEmptyTMVar :: TMVar a -> STM Bool
isEmptyTMVar (TMVar t) = do
m <- readTVar t
case m of
Nothing -> return True
Just _ -> return False
-- | Make a 'Weak' pointer to a 'TMVar', using the second argument as
-- a finalizer to run when the 'TMVar' is garbage-collected.
--
-- @since 2.4.4
mkWeakTMVar :: TMVar a -> IO () -> IO (Weak (TMVar a))
mkWeakTMVar tmv@(TMVar (TVar t#)) (IO finalizer) = IO $ \s ->
case mkWeak# t# tmv finalizer s of (# s1, w #) -> (# s1, Weak w #)
#endif
| gridaphobe/packages-stm | Control/Concurrent/STM/TMVar.hs | bsd-3-clause | 4,893 | 0 | 14 | 1,053 | 1,071 | 542 | 529 | 2 | 0 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
module Snap.Chat.Internal.Types where
------------------------------------------------------------------------------
import Control.Applicative
import Control.Concurrent.MVar
import Control.Concurrent.STM
import Data.Aeson
import qualified Data.Aeson.Types as A
import Data.ByteString (ByteString)
import Data.Data
import qualified Data.HashTable.IO as HT
import qualified Data.HashMap.Strict as Map
import Data.Monoid
import Data.Text (Text)
import System.Posix.Types
------------------------------------------------------------------------------
import System.TimeoutManager (TimeoutManager, TimeoutHandle)
------------------------------------------------------------------------------
type UserName = Text
------------------------------------------------------------------------------
data MessageContents = Talk { _messageText :: !Text }
| Action { _messageText :: !Text }
| Join
| Leave { _messageText :: !Text }
deriving (Show, Eq)
instance FromJSON MessageContents where
parseJSON (Object obj) = do
ty <- (obj .: "type") :: A.Parser Text
case ty of
"talk" -> Talk <$>
obj .: "text"
"action" -> Action <$>
obj .: "text"
"join" -> pure Join
"leave" -> Leave <$>
obj .: "text"
_ -> fail "bad type"
parseJSON _ = fail "MessageContents: JSON object of wrong type"
------------------------------------------------------------------------------
instance ToJSON MessageContents where
toJSON (Talk t) =
Object $ Map.fromList [ ("type", toJSON ("talk"::Text))
, ("text", toJSON t )
]
toJSON (Action t) =
Object $ Map.fromList [ ("type", toJSON ("action"::Text))
, ("text", toJSON t )
]
toJSON (Join) =
Object $ Map.fromList [ ("type", toJSON ("join"::Text))
]
toJSON (Leave t) =
Object $ Map.fromList [ ("type", toJSON ("leave"::Text))
, ("text", toJSON t )
]
------------------------------------------------------------------------------
data Message = Message {
_messageUser :: !UserName
, _messageTime :: !EpochTime
, _messageContents :: !MessageContents
}
deriving (Show, Eq)
------------------------------------------------------------------------------
getMessageUserName :: Message -> UserName
getMessageUserName = _messageUser
getMessageTime :: Message -> EpochTime
getMessageTime = _messageTime
getMessageContents :: Message -> MessageContents
getMessageContents = _messageContents
------------------------------------------------------------------------------
instance FromJSON Message where
parseJSON (Object obj) =
Message <$>
obj .: "user" <*>
(toEnum <$> obj .: "time") <*>
obj .: "contents"
parseJSON _ = fail "Message: JSON object of wrong type"
instance ToJSON Message where
toJSON (Message u t c) =
Object $ Map.fromList [ ("user" , toJSON u )
, ("time" , toJSON $ fromEnum t)
, ("contents", toJSON c ) ]
------------------------------------------------------------------------------
newtype UserToken = UserToken ByteString
deriving (Show, Eq, Data, Ord, Typeable, Monoid, FromJSON, ToJSON)
------------------------------------------------------------------------------
data User = User {
_userName :: !UserName
, _userMsgChan :: !(TChan Message)
, _userToken :: !UserToken
, _timeoutHandle :: !TimeoutHandle
}
------------------------------------------------------------------------------
getUserName :: User -> UserName
getUserName = _userName
------------------------------------------------------------------------------
getUserToken :: User -> UserToken
getUserToken = _userToken
------------------------------------------------------------------------------
type HashTable k v = HT.CuckooHashTable k v
------------------------------------------------------------------------------
data ChatRoom = ChatRoom {
_timeoutManager :: !TimeoutManager
, _userMap :: !(MVar (HashTable UserName User))
, _chatChannel :: !(TChan Message)
, _userTimeout :: !Int -- ^ how long users can remain
-- inactive
}
| snapframework/cufp2011 | sample-implementation/Snap/Chat/Internal/Types.hs | bsd-3-clause | 4,997 | 0 | 13 | 1,469 | 921 | 519 | 402 | 117 | 1 |
{-# LANGUAGE ExtendedDefaultRules #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE RecordWildCards #-}
{-# OPTIONS_GHC -Wall -fno-warn-orphans -fno-warn-type-defaults #-}
-- | Orphan 'FromJSON' and 'ToJSON' instances for certain Cryptol
-- types. Since these are meant to be consumed over a wire, they are
-- mostly focused on base values and interfaces rather than a full
-- serialization of internal ASTs and such.
module Cryptol.Aeson where
import Control.Applicative
import Control.Exception
import Data.Aeson
import Data.Aeson.TH
import qualified Data.HashMap.Strict as HM
import Data.List
import qualified Data.Map as Map
import Data.Map (Map)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Cryptol.Eval.Error as E
import qualified Cryptol.Eval.Value as E
import qualified Cryptol.ModuleSystem as M
import qualified Cryptol.ModuleSystem.Monad as M
import qualified Cryptol.ModuleSystem.Renamer as M
import Cryptol.ModuleSystem.Interface
import Cryptol.ModuleSystem.Name
import qualified Cryptol.Parser as P
import qualified Cryptol.Parser.AST as P
import qualified Cryptol.Parser.Lexer as P
import qualified Cryptol.Parser.NoInclude as P
import qualified Cryptol.Parser.NoPat as NoPat
import qualified Cryptol.Parser.Position as P
import Cryptol.REPL.Monad
import qualified Cryptol.TypeCheck.AST as T
import qualified Cryptol.TypeCheck.InferTypes as T
import Cryptol.Utils.PP hiding (empty)
instance FromJSON a => FromJSON (Map QName a) where
parseJSON = withObject "QName map" $ \o -> do
let (ks, vs) = unzip (HM.toList o)
ks' = map keyToQName ks
vs' <- mapM parseJSON vs
return (Map.fromList (zip ks' vs'))
instance ToJSON a => ToJSON (Map QName a) where
toJSON m = Object (HM.fromList (zip ks' vs'))
where (ks, vs) = unzip (Map.toList m)
ks' = map keyFromQName ks
vs' = map toJSON vs
-- | Assume that a 'QName' contains only an optional 'ModName' and a
-- 'Name', rather than a 'NewName'. This should be safe for the
-- purposes of this API where we're dealing with top-level names.
keyToQName :: Text -> QName
keyToQName str =
case map T.unpack (T.split (== '.') str) of
[] -> error "empty QName"
[""] -> error "empty QName"
[x] -> mkUnqual (Name x)
xs -> mkQual (ModName (init xs)) (Name (last xs))
keyFromQName :: QName -> Text
keyFromQName = \case
QName Nothing (Name x) -> T.pack x
QName (Just (ModName mn)) (Name x) ->
T.pack (intercalate "." (mn ++ [x]))
_ -> error "NewName unsupported in JSON"
instance ToJSON Doc where
toJSON = String . T.pack . render
instance ToJSON E.Value where
toJSON = \case
E.VRecord fs -> object
[ "record" .= fs ]
E.VTuple vs -> object
[ "tuple" .= vs ]
E.VBit b -> object
[ "bit" .= b ]
E.VSeq isWord xs -> object
[ "sequence" .= object [ "isWord" .= isWord, "elements" .= xs ] ]
E.VWord w -> object
[ "word" .= w ]
E.VStream _ -> object
[ "stream" .= object [ "@note" .= "streams not supported" ] ]
E.VFun _ -> object
[ "function" .= object [ "@note" .= "functions not supported" ] ]
E.VPoly _ -> object
[ "poly" .= object [ "@note" .= "polymorphic values not supported" ] ]
instance FromJSON E.Value where
parseJSON = withObject "Value" $ \o ->
E.VRecord <$> o .: "record"
<|> E.VTuple <$> o .: "tuple"
<|> E.VBit <$> o .: "bit"
<|> do s <- o .: "sequence"
E.VSeq <$> s .: "isWord" <*> s .: "elements"
<|> E.VWord <$> o .: "word"
<|> error ("unexpected JSON value: " ++ show o)
instance ToJSON P.Token where
toJSON = toJSON . pp
instance ToJSON IOException where
toJSON exn = object
[ "IOException" .= show exn ]
instance ToJSON M.RenamerError where
toJSON err = object
[ "renamerError" .= pp err ]
instance ToJSON T.Error where
toJSON err = object
[ "inferError" .= pp err ]
instance ToJSON E.BV where
toJSON = \case
E.BV w v -> object
[ "bitvector" .= object [ "width" .= w, "value" .= v ] ]
instance FromJSON E.BV where
parseJSON = withObject "BV" $ \o -> do
bv <- o .: "bitvector"
E.BV <$> bv .: "width" <*> bv .: "value"
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''REPLException)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''NameEnv)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''NameInfo)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''E.EvalError)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''P.ParseError)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''P.Position)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''P.Range)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''P.Located)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''P.IncludeError)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''P.Schema)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''P.Type)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''P.TParam)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''P.Prop)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''P.Named)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''P.Kind)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''NoPat.Error)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''M.ModuleError)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''M.ImportSource)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''T.Import)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''T.ImportSpec)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''T.Type)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''T.TParam)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''T.Kind)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''T.TVar)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''T.TCon)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''T.PC)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''T.TC)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''T.UserTC)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''T.Schema)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''T.TFun)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''T.Selector)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } { fieldLabelModifier = drop 1 } ''T.Fixity)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''T.Pragma)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''Assoc)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''QName)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''ModName)
$(deriveJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''Name)
$(deriveJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''Pass)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''IfaceDecl)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''T.Newtype)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''T.TySyn)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''IfaceDecls)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''Iface)
| ntc2/cryptol | cryptol-server/Cryptol/Aeson.hs | bsd-3-clause | 7,781 | 0 | 21 | 1,259 | 2,294 | 1,195 | 1,099 | 149 | 4 |
{-# LANGUAGE PackageImports ,FlexibleInstances ,MultiParamTypeClasses#-}
module PkgCereal(PkgCereal(..),Data.Serialize.Serialize,sd) where
import Control.Exception
import Types hiding (Serialize)
import qualified Types as T
import Test.Data
import Test.Data.Values
import qualified Data.ByteString.Lazy as L
import "cereal" Data.Serialize
import Data.ByteString as B
data PkgCereal a = PkgCereal a deriving (Eq,Show)
instance Arbitrary a => Arbitrary (PkgCereal a) where arbitrary = fmap PkgCereal arbitrary
sd = ("cereal","cereal",serializeF,deserializeF)
serializeF = L.fromStrict . encode
deserializeF = either (Left . error . show) Right . decode . L.toStrict
{-
instance Serialize a => T.Serialize (PkgCereal a) where
serialize (PkgCereal a) = encodeLazy a
-- deserialize = either (Left . error . show) (\(_,_,v) -> Right $ PkgCereal v) . Binary.decodeOrFail
deserialize = either (Left . error) (Right . PkgCereal) . decodeLazy
-}
instance Serialize a => T.Serialize PkgCereal a where
serialize (PkgCereal a) = encodeLazy a
deserialize = either (Left . error) (Right . PkgCereal) . decodeLazy
pkg = PkgCereal
unpkg (PkgCereal a) = a
-- Tests
t = ser $ PkgCereal tree1
-- x = Prelude.putStrLn $ derive (undefined :: Engine)
{-
benchmarking serialize/deserialise/tree1
mean: 5.103695 us, lb 4.868698 us, ub 5.414622 us, ci 0.950
std dev: 1.373780 us, lb 1.141381 us, ub 1.700686 us, ci 0.950
found 18 outliers among 100 samples (18.0%)
5 (5.0%) high mild
13 (13.0%) high severe
variance introduced by outliers: 96.797%
variance is severely inflated by outliers
benchmarking serialize/deserialise/tree2
mean: 1.136065 us, lb 1.120947 us, ub 1.159394 us, ci 0.950
std dev: 95.01065 ns, lb 68.06466 ns, ub 137.1691 ns, ci 0.950
found 7 outliers among 100 samples (7.0%)
3 (3.0%) high mild
4 (4.0%) high severe
variance introduced by outliers: 72.777%
variance is severely inflated by outliers
benchmarking serialize/deserialise/car1
mean: 15.31410 us, lb 15.21677 us, ub 15.52387 us, ci 0.950
std dev: 699.8115 ns, lb 403.9063 ns, ub 1.387295 us, ci 0.950
found 4 outliers among 100 samples (4.0%)
3 (3.0%) high mild
1 (1.0%) high severe
variance introduced by outliers: 43.485%
variance is moderately inflated by outliers
-}
instance Serialize Car
instance Serialize Acceleration
instance Serialize Consumption
instance Serialize CarModel
instance Serialize OptionalExtra
instance Serialize Engine
instance Serialize Various
instance Serialize N
instance {-# OVERLAPPABLE #-} Serialize a => Serialize (List a)
instance {-# OVERLAPPABLE #-} Serialize a => Serialize (Tree a)
instance {-# OVERLAPPING #-} Serialize (Tree N)
instance {-# OVERLAPPING #-} Serialize (Tree (N,N,N))
instance {-# OVERLAPPING #-} Serialize [N]
instance {-# OVERLAPPING #-} Serialize (N,N,N)
-- !! Apparently Generics based derivation is as fast as hand written one.
{-
benchmarking serialize/deserialise/tree1
mean: 4.551243 us, lb 4.484404 us, ub 4.680212 us, ci 0.950
std dev: 459.9530 ns, lb 260.7037 ns, ub 704.4624 ns, ci 0.950
found 9 outliers among 100 samples (9.0%)
5 (5.0%) high mild
4 (4.0%) high severe
variance introduced by outliers: 79.996%
variance is severely inflated by outliers
benchmarking serialize/deserialise/tree2
mean: 1.148759 us, lb 1.138991 us, ub 1.183448 us, ci 0.950
std dev: 83.66155 ns, lb 25.57640 ns, ub 190.4369 ns, ci 0.950
found 7 outliers among 100 samples (7.0%)
4 (4.0%) high mild
2 (2.0%) high severe
variance introduced by outliers: 66.638%
variance is severely inflated by outliers
benchmarking serialize/deserialise/car1
mean: 15.67617 us, lb 15.57603 us, ub 15.82105 us, ci 0.950
std dev: 611.6098 ns, lb 450.8581 ns, ub 853.6561 ns, ci 0.950
found 6 outliers among 100 samples (6.0%)
3 (3.0%) high mild
3 (3.0%) high severe
variance introduced by outliers: 35.595%
variance is moderately inflated by outliers
instance (Binary a) => Binary (Tree a) where
put (Node a b) = putWord8 0 >> put a >> put b
put (Leaf a) = putWord8 1 >> put a
get = do
tag_ <- getWord8
case tag_ of
0 -> get >>= \a -> get >>= \b -> return (Node a b)
1 -> get >>= \a -> return (Leaf a)
_ -> fail "no decoding"
instance Binary Car where
put (Car a b c d e f g h i j k l) = put a >> put b >> put c >> put d >> put e >> put f >> put g >> put h >> put i >> put j >> put k >> put l
get = get >>= \a -> get >>= \b -> get >>= \c -> get >>= \d -> get >>= \e -> get >>= \f -> get >>= \g -> get >>= \h -> get >>= \i -> get >>= \j -> get >>= \k -> get >>= \l -> return (Car a b c d e f g h i j k l)
instance Binary Acceleration where
put (Acceleration a b) = put a >> put b
get = get >>= \a -> get >>= \b -> return (Acceleration a b)
instance Binary Consumption where
put (Consumption a b) = put a >> put b
get = get >>= \a -> get >>= \b -> return (Consumption a b)
instance Binary Model where
put A = putWord8 0
put B = putWord8 1
put C = putWord8 2
get = do
tag_ <- getWord8
case tag_ of
0 -> return A
1 -> return B
2 -> return C
_ -> fail "no decoding"
instance Binary OptionalExtra where
put SunRoof = putWord8 0
put SportsPack = putWord8 1
put CruiseControl = putWord8 2
get = do
tag_ <- getWord8
case tag_ of
0 -> return SunRoof
1 -> return SportsPack
2 -> return CruiseControl
_ -> fail "no decoding"
instance Binary Engine where
put (Engine a b c d e) = put a >> put b >> put c >> put d >> put e
get = get >>= \a -> get >>= \b -> get >>= \c -> get >>= \d -> get >>= \e -> return (Engine a b c d e)
-}
| tittoassini/flat | benchmarks/PkgCereal.hs | bsd-3-clause | 5,593 | 0 | 10 | 1,147 | 451 | 247 | 204 | 35 | 1 |
{-# LANGUAGE ExistentialQuantification #-}
module Main where
import Scheme()
import Text.ParserCombinators.Parsec hiding (spaces)
import System.Environment
import Numeric
import GHC.Real
import Data.Char
import Data.Complex
import Data.IORef
import Data.Maybe
import Control.Monad.Except
import System.IO
symbol :: Parser Char
symbol = oneOf "!$%&|*+-/:<=>?@^_~,"
readExpr :: String -> ThrowsError LispVal
readExpr = readOrThrow parseExpr
readExprList = readOrThrow (endBy parseExpr spaces)
readOrThrow :: Parser a -> String -> ThrowsError a
readOrThrow parser input = case parse parser "lisp" input of
Left err -> throwError $ Parser err
Right val -> return val
spaces :: Parser ()
spaces = skipMany1 space
ioPrimitives :: [(String, [LispVal] -> IOThrowsError LispVal)]
ioPrimitives = [("apply", applyProc),
("open-input-file", makePort ReadMode),
("open-output-file", makePort WriteMode),
("close-input-port", closePort),
("close-output-port", closePort),
("read", readProc),
("write", writeProc),
("read-contents", readContents),
("read-all", readAll)
]
applyProc :: [LispVal] -> IOThrowsError LispVal
applyProc [func, List args] = apply func args
applyProc (func : args) = apply func args
makePort :: IOMode -> [LispVal] -> IOThrowsError LispVal
makePort mode [String filename] = fmap Port $ liftIO $ openFile filename mode
closePort :: [LispVal] -> IOThrowsError LispVal
closePort [Port port] = liftIO $ hClose port >> return (Bool True)
closePort _ = return $ Bool False
readProc :: [LispVal] -> IOThrowsError LispVal
readProc [] = readProc [Port stdin]
readProc [Port port] = liftIO (hGetLine port) >>= liftThrows . readExpr
writeProc :: [LispVal] -> IOThrowsError LispVal
writeProc [obj] = writeProc [obj, Port stdout]
writeProc [obj, Port port] = liftIO $ hPrint port obj >> return (Bool True)
readContents :: [LispVal] -> IOThrowsError LispVal
readContents [String filename] = fmap String $ liftIO $ readFile filename
load :: String -> IOThrowsError [LispVal]
load filename = liftIO (readFile filename) >>= liftThrows . readExprList
readAll :: [LispVal] -> IOThrowsError LispVal
readAll [String filename] = List <$> load filename
-- Type
data LispVal = Atom String
| List [LispVal]
| DottedList [LispVal] LispVal
| Number Integer
| Float Double
| String String
| Bool Bool
| Character Char
| Ratio Rational
| Complex (Complex Double)
| PrimitiveFunc ([LispVal] -> ThrowsError LispVal)
| Func {params :: [String], vararg :: Maybe String,
body :: [LispVal], closure :: Env}
| Macro {params :: [String], vararg :: Maybe String,
body :: [LispVal], closure :: Env}
| IOFunc ([LispVal] -> IOThrowsError LispVal)
| Port Handle
instance Eq LispVal where
Atom x == Atom x' = x == x'
Atom _ == _ = False
List xs == List xs' = xs == xs'
List _ == _ = False
DottedList xs x == DottedList xs' x' = xs == xs' && x == x'
DottedList _ _ == _ = False
Number n == Number n' = n == n'
Number _ == _ = False
Float x == Float x' = x == x'
Float _ == _ = False
Bool b == Bool b' = b == b'
String s == String s' = s == s'
String _ == _ = False
Bool _ == _ = False
Character c == Character c' = c == c'
Character _ == _ = False
Ratio r == Ratio r' = r == r'
Ratio _ == _ = False
Complex c == Complex c' = c == c'
Complex _ == _ = False
PrimitiveFunc _ == _ = False
Func params vararg body closure == Func params' vararg' body' closure' =
params == params' && vararg == vararg' && body == body' && closure == closure'
Func {} == _ = False
-- Parser
parseString :: Parser LispVal
parseString = do char '"'
x <- many (escapedChars <|> noneOf "\"")
char '"'
return $ String x
parseCharacter :: Parser LispVal
parseCharacter = do
try $ string "#\\"
value <- try (string "newline" <|> string "space")
<|> do { x <- anyChar; notFollowedBy alphaNum ; return [x] }
return $ Character $ case value of
"space" -> ' '
"newline" -> '\n'
_ -> head value
escapedChars :: Parser Char
escapedChars = do x <- char '\\' >> oneOf "\\\"nrt"
return $ case x of
'n' -> '\n'
'r' -> '\r'
't' -> '\t'
_ -> x
parseAtom :: Parser LispVal
parseAtom = do first <- letter <|> symbol
rest <- many (letter <|> digit <|> symbol)
let atom = first:rest
return $ Atom atom
parseBool :: Parser LispVal
parseBool = do string "#"
x <- oneOf "tf"
return $ case x of
't' -> Bool True
'f' -> Bool False
parseNumber :: Parser LispVal
parseNumber = parseDigital1 <|> parseDigital2 <|> parseHex <|> parseOct <|> parseBin
parseDigital1 :: Parser LispVal
parseDigital1 = do x <- many1 digit
(return . Number . read) x
parseDigital2 :: Parser LispVal
parseDigital2 = do try $ string "#d"
x <- many1 digit
(return . Number . read) x
parseHex :: Parser LispVal
parseHex = do try $ string "#x"
x <- many1 hexDigit
return $ Number (hex2dig x)
parseOct :: Parser LispVal
parseOct = do try $ string "#o"
x <- many1 octDigit
return $ Number (oct2dig x)
parseBin :: Parser LispVal
parseBin = do try $ string "#b"
x <- many1 $ oneOf "10"
return $ Number (bin2dig x)
oct2dig x = fst $ head $ readOct x
hex2dig x = fst $ head $ readHex x
bin2dig = bin2dig' 0
bin2dig' digint "" = digint
bin2dig' digint (x:xs) = let old = 2 * digint + (if x == '0' then 0 else 1) in
bin2dig' old xs
parseFloat :: Parser LispVal
parseFloat = do x <- many1 digit
char '.'
y <- many1 digit
return $ Float (fst . head $ readFloat (x++ "." ++y))
parseRatio :: Parser LispVal
parseRatio = do x <- many1 digit
char '/'
y <- many1 digit
return $ Ratio (read x % read y)
toDouble :: LispVal -> Double
toDouble (Float f) = f
toDouble (Number n) = fromIntegral n
parseComplex :: Parser LispVal
parseComplex = do x <- try parseFloat <|> parseNumber
char '+'
y <- try parseFloat <|> parseNumber
char 'i'
return $ Complex (toDouble x :+ toDouble y)
parseList :: Parser LispVal
parseList = List <$> sepBy parseExpr spaces
parseDottedList :: Parser LispVal
parseDottedList = do
head <- endBy parseExpr spaces
tail <- char '.' >> spaces >> parseExpr
return $ DottedList head tail
parseQuoted :: Parser LispVal
parseQuoted = do char '\''
x <- parseExpr
return $ List [Atom "quote", x]
parseQuasiQuoted :: Parser LispVal
parseQuasiQuoted = do char '`'
x <- parseInQuasiQuoted
return $ List [Atom "backQuote", x]
parseInQuasiQuoted :: Parser LispVal
parseInQuasiQuoted = try parseUnquoteSpliced
<|> try parseUnquoted
<|> try parseInQuasiQuotedList
<|> parseExpr
parseInQuasiQuotedList :: Parser LispVal
parseInQuasiQuotedList = do char '('
x <- List <$> sepBy parseInQuasiQuoted spaces
char ')'
return x
parseUnquoted :: Parser LispVal
parseUnquoted = do char ','
x <- parseExpr
return $ List [Atom "unquote", x]
parseUnquoteSpliced :: Parser LispVal
parseUnquoteSpliced = do string ",@"
x <- parseExpr
return $ List [Atom "unquote-spliced", x]
parseExpr :: Parser LispVal
parseExpr = parseAtom
<|> try parseQuasiQuoted
<|> try parseQuoted
<|> parseString
<|> try parseFloat
<|> try parseRatio
<|> try parseComplex
<|> try parseNumber
<|> try parseBool
<|> try parseCharacter
<|> do char '('
x <- try parseList <|> parseDottedList
char ')'
return x
-- Show
instance Show LispVal where show = showVal
showVal :: LispVal -> String
showVal (String contents) = "\"" ++ contents ++ "\""
showVal (Character contents) = "#\\" ++ show contents
showVal (Atom name) = name
showVal (Number contents) = show contents
showVal (Float contents) = show contents
showVal (Ratio (x :% y)) = show x ++ "/" ++ show y
showVal (Complex (r :+ i)) = show r ++ "+" ++ show i ++ "i"
showVal (Bool True) = "#t"
showVal (Bool False) = "#f"
showVal (List contents) = "(" ++ unwordsList contents ++ ")"
showVal (DottedList head tail) = "(" ++ unwordsList head ++ " . " ++ showVal tail ++ ")"
showVal (PrimitiveFunc _) = "<primitive>"
showVal Func {params = args, vararg = varargs, body = body, closure = env} =
"(lambda (" ++ unwords (map show args) ++
(case varargs of
Nothing -> ""
Just arg -> " . " ++ arg) ++ ") ...)"
showVal Macro {params = args, vararg = varargs, body = body, closure = env} =
"(lambda (" ++ unwords (map show args) ++
(case varargs of
Nothing -> ""
Just arg -> " . " ++ arg) ++ ") ...)"
showVal (Port _) = "<IO port>"
showVal (IOFunc _) = "<IO primitive>"
unwordsList :: [LispVal] -> String
unwordsList = unwords . map showVal
eval :: Env -> LispVal -> IOThrowsError LispVal
eval _ val@(String _) = return val
eval _ val@(Character _) = return val
eval _ val@(Number _) = return val
eval _ val@(Float _) = return val
eval _ val@(Ratio _) = return val
eval _ val@(Complex _) = return val
eval _ val@(Bool _) = return val
eval env (Atom id) = getVar env id
eval _ (List [Atom "quote", val]) = return val
eval env (List [Atom "backQuote", val]) =
case val of
List [Atom "unquote", _] -> evalUnquote val
List vals -> List <$> mapM evalUnquote vals
_ -> evalUnquote val
where
evalUnquote (List [Atom "unquote", val]) = eval env val
evalUnquote val = return val
eval env (List [Atom "if", pred, conseq, alt]) =
do result <- eval env pred
case result of
Bool False -> eval env alt
_ -> eval env conseq
eval env (List (Atom "cond" : expr : rest)) = eval' expr rest
where eval' (List [cond, value]) (x : xs) = do
result <- eval env cond
case result of
Bool False -> eval' x xs
_ -> eval env value
eval' (List [Atom "else", value]) [] = eval env value
eval' (List [cond, value]) [] = do
result <- eval env cond
case result of
Bool False -> return $ Atom "#<undef>"
_ -> eval env value
eval env form@(List (Atom "case":key:clauses)) =
if null clauses
then throwError $ BadSpecialForm "no true clause in case expression: " form
else case head clauses of
List (Atom "else" : exprs) -> fmap last (mapM (eval env) exprs)
List (List datums : exprs) -> do
result <- eval env key
equality <- liftThrows $ mapM (\x -> eqv [result, x]) datums
if Bool True `elem` equality
then fmap last (mapM (eval env) exprs)
else eval env $ List (Atom "case" : key : tail clauses)
_ -> throwError $ BadSpecialForm "ill-formed case expression: " form
eval env (List [Atom "set!", Atom var, form]) =
eval env form >>= setVar env var
eval env (List [Atom "define", Atom var, form]) =
eval env form >>= defineVar env var
eval env (List (Atom "define" : List (Atom var:params) : body)) =
makeNormalFunc env params body >>= defineVar env var
eval env (List (Atom "define" : DottedList (Atom var : params) varargs : body)) =
makeVarargs varargs env params body >>= defineVar env var
eval env (List (Atom "define-macro" : List (Atom var:params) : body)) =
makeNormalMacro env params body >>= defineVar env var
eval env (List (Atom "define-macro" : DottedList (Atom var : params) varargs : body)) =
makeVarArgsMacro varargs env params body >>= defineVar env var
eval env (List (Atom "lambda" : List params : body)) =
makeNormalFunc env params body
eval env (List (Atom "lambda" : DottedList params varargs : body)) =
makeVarargs varargs env params body
eval env (List (Atom "lambda" : varargs@(Atom _) : body)) =
makeVarargs varargs env [] body
eval env (List [Atom "load", String filename]) =
load filename >>= fmap last . mapM (eval env)
-- bindings = [List LispVal]
eval env (List (Atom "let" : List bindings : body)) =
eval env (List (List (Atom "lambda" : List (fmap fst' bindings) : body) : fmap snd' bindings))
where fst' :: LispVal -> LispVal
fst' (List (x:xs)) = x
snd' :: LispVal -> LispVal
snd' (List (x:y:xs)) = y
eval env (List (function : args)) = do
func <- eval env function
argVals <- mapM (eval env) args
apply func argVals
eval _ badForm = throwError $ BadSpecialForm "Unrecognized special form" badForm
apply :: LispVal -> [LispVal] -> IOThrowsError LispVal
apply (PrimitiveFunc func) args = liftThrows $ func args
apply (Macro params varargs body closure) args =
if num params /= num args && isNothing varargs
then throwError $ NumArgs (num params) args
else liftIO (bindVars closure $ zip params args) >>= bindVarArgs varargs >>= evalMacro
where remainingArgs = drop (length params) args
num = toInteger . length
evalMacro env = do
evaled <- mapM (eval env) body
last <$> mapM (eval env) evaled
bindVarArgs arg env = case arg of
Just argName -> liftIO $ bindVars env [(argName, List remainingArgs)]
Nothing -> return env
apply (Func params varargs body closure) args =
if num params /= num args && isNothing varargs
then throwError $ NumArgs (num params) args
else liftIO (bindVars closure $ zip params args) >>= bindVarArgs varargs >>= evalBody
where remainingArgs = drop (length params) args
num = toInteger . length
evalBody env = last <$> mapM (eval env) body
bindVarArgs arg env = case arg of
Just argName -> liftIO $ bindVars env [(argName, List remainingArgs)]
Nothing -> return env
apply (IOFunc func) args = func args
primitives :: [(String, [LispVal] -> ThrowsError LispVal)]
primitives = [("+", numericBinop (+)),
("-", numericBinop (-)),
("*", numericBinop (*)),
("/", numericBinop div),
("mod", numericBinop mod),
("quotient", numericBinop quot),
("remainder", numericBinop rem),
("symbol?", isSym),
("symbol->string", symbolToString),
("=", numBoolBinop (==)),
("<", numBoolBinop (<)),
(">", numBoolBinop (>)),
("/=", numBoolBinop (/=)),
(">=", numBoolBinop (>=)),
("&&", boolBoolBinop (&&)),
("||", boolBoolBinop (||)),
("string?", isString),
("make-string", makeString),
("string-length", stringLength),
("string-ref", stringLef),
("string->symbol", stringToSymbol),
("string=?", strBoolBinop (==)),
("string<?", strBoolBinop (<)),
("string>?", strBoolBinop (>)),
("string<=?", strBoolBinop (<=)),
("string>=?", strBoolBinop (>=)),
("string-ci=?", strCiBinop (==)),
("string-ci<?", strCiBinop (<)),
("string-ci>?", strCiBinop (>)),
("string-ci<=?", strCiBinop (<=)),
("string-ci>=?", strCiBinop (>=)),
("substring", subString),
("string-append", stringAppend),
("string->list", stringList),
("list->string", listString),
("string-copy", stringCopy),
("string-fill!", stringFill),
("car", car),
("cdr", cdr),
("cons", cons),
("eq?", eqv),
("eqv?", eqv),
("equal?", equal)
]
numericBinop :: (Integer -> Integer -> Integer) -> [LispVal] -> ThrowsError LispVal
numericBinop _ singleVal@[args] = throwError $ NumArgs 2 singleVal
numericBinop op params = fmap (Number . foldl1 op) (mapM unpackNum params)
boolBinop :: (LispVal -> ThrowsError a) -> (a -> a -> Bool) -> [LispVal] -> ThrowsError LispVal
boolBinop unpacker op args = if length args /= 2
then throwError $ NumArgs 2 args
else do left <- unpacker $ head args
right <- unpacker $ args !! 1
return $ Bool $ left `op` right
strCiBinop :: (String -> String -> Bool) -> [LispVal] -> ThrowsError LispVal
strCiBinop op [String x, String y] = return $ Bool $ map toLower x `op` map toLower y
strCiBinop _ [notStr, String y] = throwError $ TypeMismatch "string" notStr
strCiBinop _ [String x, notStr] = throwError $ TypeMismatch "string" notStr
strCiBinop _ argList = throwError $ NumArgs 2 argList
subString :: [LispVal] -> ThrowsError LispVal
subString [String str, Number start, Number end]
| start <= end = return $ String $ take (fromIntegral (end - start)) $ drop (fromIntegral start) str
| start > end = throwError $ Otherwise $ "end argument (" ++ show end ++ ") must be greater than or equal to the start argument (" ++ show start ++ ")"
subString [notStr, Number _, Number _] = throwError $ TypeMismatch "string" notStr
subString [String _, notNum, _] = throwError $ TypeMismatch "number" notNum
subString [_, _, notNum] = throwError $ TypeMismatch "number" notNum
subString argList = throwError $ NumArgs 3 argList
stringAppend :: [LispVal] -> ThrowsError LispVal
stringAppend [] = return $ String ""
stringAppend args = foldM stringAppend' (String "") args
stringAppend' :: LispVal -> LispVal -> ThrowsError LispVal
stringAppend' (String x) (String y) = return $ String $ x ++ y
stringAppend' (String _) notStr = throwError $ TypeMismatch "string" notStr
stringAppend' notStr _ = throwError $ TypeMismatch "string" notStr
stringList :: [LispVal] -> ThrowsError LispVal
stringList [String s] = return $ List $ fmap Character s
stringList [notStr] = throwError $ TypeMismatch "string" notStr
stringList argList = throwError $ NumArgs 1 argList
listString :: [LispVal] -> ThrowsError LispVal
listString [list@(List xs)] = if all isCharacter xs
then return $ String $ fmap (\(Character c) -> c) xs
else throwError $ TypeMismatch "character list" list
where isCharacter (Character _) = True
isCharacter _ = False
listString argList = throwError $ NumArgs 1 argList
stringCopy :: [LispVal] -> ThrowsError LispVal
stringCopy [String str] = return $ String $ foldr (:) [] str
stringCopy [notStr] = throwError $ TypeMismatch "string" notStr
stringCopy argList = throwError $ NumArgs 1 argList
stringFill :: [LispVal] -> ThrowsError LispVal
stringFill [String str, Character c] = return $ String $ stringFill' str c
where stringFill' [] c = []
stringFill' str c = c:stringFill' (tail str) c
stringFill [String _, notChar] = throwError $ TypeMismatch "character" notChar
stringFill [notStr, _] = throwError $ TypeMismatch "string" notStr
stringFill argList = throwError $ NumArgs 2 argList
numBoolBinop = boolBinop unpackNum
strBoolBinop = boolBinop unpackStr
boolBoolBinop = boolBinop unpackBool
unpackNum :: LispVal -> ThrowsError Integer
unpackNum (Number n) = return n
unpackNum (String n) = let parsed = reads n
in if null parsed
then throwError $ TypeMismatch "number" $ String n
else return $ fst $ head parsed
unpackNum (List [n]) = unpackNum n
unpackNum notNum = throwError $ TypeMismatch "number" notNum
unpackStr :: LispVal -> ThrowsError String
unpackStr (String s) = return s
unpackStr (Number s) = return $ show s
unpackStr (Bool s) = return $ show s
unpackStr notString = throwError $ TypeMismatch "string" notString
unpackBool :: LispVal -> ThrowsError Bool
unpackBool (Bool b) = return b
unpackBool notBool = throwError $ TypeMismatch "boolean" notBool
isSym :: [LispVal] -> ThrowsError LispVal
isSym [Atom _] = return $ Bool True
isSym xs = case length xs of
1 -> return $ Bool False
_ -> throwError $ NumArgs 1 xs
symbolToString :: [LispVal] -> ThrowsError LispVal
symbolToString [Atom x] = return $ String x
symbolToString [notSym] = throwError $ TypeMismatch "symbol" notSym
symbolToString xs = throwError $ NumArgs 1 xs
stringToSymbol :: [LispVal] -> ThrowsError LispVal
stringToSymbol [String x] = return $ Atom x
stringToSymbol [notString] = throwError $ TypeMismatch "string" notString
stringToSymbol xs = throwError $ NumArgs 1 xs
isString :: [LispVal] -> ThrowsError LispVal
isString [String _] = return $ Bool True
isString [_] = return $ Bool False
isString badArgList = throwError $ NumArgs 1 badArgList
makeString :: [LispVal] -> ThrowsError LispVal
makeString [Number n] = makeString [Number n, Character ' ']
makeString [notNumber] = throwError $ TypeMismatch "number" notNumber
makeString [Number n, Character c] = return $ String $ replicate (fromIntegral n) c
makeString [notNumber, Character _] = throwError $ TypeMismatch "number" notNumber
makeString [Number _, notChar] = throwError $ TypeMismatch "char" notChar
makeString [notNumber, _] = throwError $ TypeMismatch "number" notNumber
makeString badArgList = throwError $ NumArgs 2 badArgList
stringLength :: [LispVal] -> ThrowsError LispVal
stringLength [String s] = return $ Number $ fromIntegral . length $ s
stringLength [notString] = throwError $ TypeMismatch "string" notString
stringLength badArgList = throwError $ NumArgs 1 badArgList
stringLef :: [LispVal] -> ThrowsError LispVal
stringLef [String s, Number n] = return $ Character $ s !! fromIntegral n
stringLef [notString, Number _] = throwError $ TypeMismatch "string" notString
stringLef [String _, notNumber] = throwError $ TypeMismatch "number" notNumber
stringLef [notString, _] = throwError $ TypeMismatch "string" notString
stringLef badArgList = throwError $ NumArgs 2 badArgList
car :: [LispVal] -> ThrowsError LispVal
car [List (x:_)] = return x
car [DottedList (x:_) _] =return x
car [badArg] = throwError $ TypeMismatch "pair" badArg
car badArgList = throwError $ NumArgs 1 badArgList
cdr :: [LispVal] -> ThrowsError LispVal
cdr [List (_:xs)] = return $ List xs
cdr [DottedList [_] x] = return x
cdr [DottedList (_:xs) x] = return $ DottedList xs x
cdr [badArg] = throwError $ TypeMismatch "pair" badArg
cdr badArgList = throwError $ NumArgs 1 badArgList
cons :: [LispVal] -> ThrowsError LispVal
cons [x1, List []] = return $ List [x1]
cons [x, List xs] = return $ List $ x:xs
cons [x, DottedList xs xlast] = return $ DottedList (x:xs) xlast
cons [x1, x2] = return $ DottedList [x1] x2
cons badArgList = throwError $ NumArgs 2 badArgList
eqv :: [LispVal] -> ThrowsError LispVal
eqv [Bool arg1, Bool arg2] = return $ Bool $ arg1 == arg2
eqv [Number arg1, Number arg2] = return $ Bool $ arg1 == arg2
eqv [String arg1, String arg2] = return $ Bool $ arg1 == arg2
eqv [Atom arg1, Atom arg2] = return $ Bool $ arg1 == arg2
eqv [DottedList xs x, DottedList ys y] = eqv [List $ xs ++ [x], List $ ys ++ [y]]
eqv [List arg1, List arg2] = return $ Bool $ length arg1 == length arg2 && all eqvPair (zip arg1 arg2)
where eqvPair (x1, x2) = case eqv [x1, x2] of
Left _ -> False
Right (Bool val) -> val
eqv [_, _] = return $ Bool False
eqv badArgList = throwError $ NumArgs 2 badArgList
data Unpacker = forall a. Eq a => AnyUnpacker (LispVal -> ThrowsError a)
unpackEquals :: LispVal -> LispVal -> Unpacker -> ThrowsError Bool
unpackEquals arg1 arg2 (AnyUnpacker unpacker) =
do unpacked1 <- unpacker arg1
unpacked2 <- unpacker arg2
return $ unpacked1 == unpacked2
`catchError` const (return False)
equal :: [LispVal] -> ThrowsError LispVal
equal [l1@(List _), l2@(List _)] = eqvList equal [l1, l2]
equal [DottedList xs x, DottedList ys y] = equal [List $ xs ++ [x], List $ ys ++ [y]]
equal [arg1, arg2] = do
primitiveEquals <- or <$> mapM (unpackEquals arg1 arg2)
[AnyUnpacker unpackNum, AnyUnpacker unpackStr, AnyUnpacker unpackBool]
eqvEquals <- eqv [arg1, arg2]
return $ Bool (primitiveEquals || let (Bool x) = eqvEquals in x)
equal badArgList = throwError $ NumArgs 2 badArgList
eqvList :: ([LispVal] -> ThrowsError LispVal) -> [LispVal] -> ThrowsError LispVal
eqvList eqvFunc [List arg1, List arg2] = return $ Bool $ length arg1 == length arg2 && all eqvPair (zip arg1 arg2)
where eqvPair (x1, x2) = case eqvFunc [x1, x2] of
Left _ -> False
Right (Bool val) -> val
-- Error
data LispError = NumArgs Integer [LispVal]
| TypeMismatch String LispVal
| Parser ParseError
| BadSpecialForm String LispVal
| NotFunction String String
| UnboundVar String String
| Otherwise String
showError :: LispError -> String
showError (UnboundVar message varname) = message ++ ": " ++ varname
showError (BadSpecialForm message form) = message ++ ": " ++ show form
showError (NotFunction message func) = message ++ ": " ++ show func
showError (NumArgs expected found) = "Expected " ++ show expected
++ " args: found valued " ++ unwordsList found
showError (TypeMismatch expected found) = "Invalid type: expected " ++ expected ++ ", found " ++ show found
showError (Parser parseErr) = "Parse error at " ++ show parseErr
showError (Otherwise message) = message
instance Show LispError where show = showError
type ThrowsError = Either LispError
trapError action = catchError action (return . show)
-- Env
type Env = IORef [(String, IORef LispVal)]
nullEnv :: IO Env
nullEnv = newIORef []
type IOThrowsError = ExceptT LispError IO
liftThrows :: ThrowsError a -> IOThrowsError a
liftThrows (Left err) = throwError err
liftThrows (Right val) = return val
runIOThrows :: IOThrowsError String -> IO String
runIOThrows action = fmap extractValue (runExceptT (trapError action))
isBound :: Env -> String -> IO Bool
isBound envRef var = fmap (isJust . lookup var) (readIORef envRef)
getVar :: Env -> String -> IOThrowsError LispVal
getVar envRef var = do env <- liftIO $ readIORef envRef
maybe (throwError $ UnboundVar "Getting an unbound variable: " var)
(liftIO . readIORef)
(lookup var env)
setVar :: Env -> String -> LispVal -> IOThrowsError LispVal
setVar envRef var value = do env <- liftIO $ readIORef envRef
maybe (throwError $ UnboundVar "Setting an unbound variable: " var)
(liftIO . flip writeIORef value)
(lookup var env)
return value
defineVar :: Env -> String -> LispVal -> IOThrowsError LispVal
defineVar envRef var value = do
alreadyDefined <- liftIO $ isBound envRef var
if alreadyDefined
then setVar envRef var value >> return value
else liftIO $ do
valueRef <- newIORef value
env <- readIORef envRef
writeIORef envRef ((var, valueRef) : env)
return value
bindVars :: Env -> [(String, LispVal)] -> IO Env
bindVars envRef bindings = readIORef envRef >>= extendEnv bindings >>= newIORef
where extendEnv bindings env = fmap (++ env) (mapM addBinding bindings)
addBinding (var, value) = do ref <- newIORef value
return (var, ref)
makeFunc varargs env params body = return $ Func (map showVal params) varargs body env
makeNormalFunc = makeFunc Nothing
makeVarargs = makeFunc . Just . showVal
makeMacro varargs env params body = return $ Macro (map showVal params) varargs body env
makeNormalMacro = makeMacro Nothing
makeVarArgsMacro = makeMacro . Just . showVal
primitiveBindings :: IO Env
primitiveBindings = nullEnv >>= flip bindVars (map (makeFunc IOFunc) ioPrimitives
++ map (makeFunc PrimitiveFunc) primitives)
where makeFunc constructor (var, func) = (var, constructor func)
extractValue :: ThrowsError a -> a
extractValue (Right val) = val
flushStr :: String -> IO ()
flushStr str = putStr str >> hFlush stdout
readPrompt :: String -> IO String
readPrompt prompt = flushStr prompt >> getLine
evalString :: Env -> String -> IO String
evalString env expr = runIOThrows $ fmap show $ liftThrows (readExpr expr) >>= eval env
evalAndPrint :: Env -> String -> IO ()
evalAndPrint env expr = evalString env expr >>= putStrLn
until_ :: Monad m => (a -> Bool) -> m a -> (a -> m ()) -> m ()
until_ pred prompt action = do
result <- prompt
unless (pred result) $ action result >> until_ pred prompt action
runRepl :: IO ()
runRepl = primitiveBindings >>= until_ (== "quit") (readPrompt "Lisp>>> ") . evalAndPrint
runOne :: [String] -> IO ()
runOne args = do
env <- primitiveBindings >>= flip bindVars [("args", List $ map String $ drop 1 args)]
runIOThrows (show <$> eval env (List [Atom "load", String (head args)]))
>>= hPutStrLn stderr
main :: IO ()
main = do args <- getArgs
if null args
then runRepl
else runOne args
| wat-aro/scheme | app/Main.hs | bsd-3-clause | 29,792 | 0 | 17 | 8,030 | 10,922 | 5,447 | 5,475 | 643 | 13 |
{-# LANGUAGE FlexibleContexts, RankNTypes #-}
module EC2Tests.AvailabilityZoneTests
( runAvailabilityZoneTests
)
where
import Data.Text (Text)
import Test.Hspec
import Cloud.AWS.EC2
import Util
import EC2Tests.Util
region :: Text
region = "ap-northeast-1"
runAvailabilityZoneTests :: IO ()
runAvailabilityZoneTests = do
hspec describeAvailabilityZonesTest
describeAvailabilityZonesTest :: Spec
describeAvailabilityZonesTest = do
describe "describeAvailabilityZones doesn't fail" $ do
it "describeAvailabilityZones doesn't throw any exception" $ do
testEC2 region (describeAvailabilityZones [] []) `miss` anyConnectionException
| worksap-ate/aws-sdk | test/EC2Tests/AvailabilityZoneTests.hs | bsd-3-clause | 673 | 0 | 17 | 110 | 128 | 69 | 59 | 18 | 1 |
import Distribution.Simple
import Distribution.Simple.Setup
import Distribution.Simple.LocalBuildInfo
import Distribution.Simple.Program
import qualified Distribution.LV2 as LV2
main = defaultMainWithHooks simpleUserHooks { confHook = LV2.confHook simpleUserHooks }
| mmartin/haskell-lv2 | examples/amp-lv2/Setup.hs | bsd-3-clause | 268 | 0 | 9 | 25 | 53 | 32 | 21 | 6 | 1 |
-- | Description: Applicative order evaluation Krivine machine.
module Rossum.Krivine.Eager where
import Data.Maybe
import Rossum.Krivine.Term
data Sided a = L | V a | R
deriving (Show)
type Configuration = (Env, Maybe Term, Stack (Sided Closure))
-- | Step an applicative order Krivine machine.
--
-- Implements rules from Hankin (2004), pp 125-127.
step :: Configuration -> Maybe Configuration
step c = case c of
(p, Just (App m n), s) -> Just (p, Just m, L : (V (Closure n p)) : s)
(p, Just (Abs m), s) -> Just ([], Nothing, (V (Closure (Abs m) p)) : s)
(u:p, Just (Var n), s) | n > 1 -> Just (p, Just (Var (n - 1)), s)
(u:p, Just (Var 1), s) -> Just ([], Nothing, (V u) : s)
([], Nothing, (V u):L:(V (Closure n p)):s) -> Just (p, Just n, R : V u : s)
([], Nothing, (V u):R:(V (Closure (Abs m) p)):s) -> Just (u:p, Just m, s)
_ -> Nothing
run :: Configuration -> [Configuration]
run c = map fromJust . takeWhile isJust $ iterate (>>= step) (Just c)
-- | Execute a compiled 'Term' in applicative order.
execute :: Term -> Either [String] [String]
execute kt =
let cfg = ([], Just kt, [])
cfg' = last (run cfg)
in Right [ "K Term: " ++ format kt
, "Result: " ++ show cfg'
]
| thsutton/rossum | src/Rossum/Krivine/Eager.hs | bsd-3-clause | 1,276 | 0 | 17 | 333 | 636 | 339 | 297 | 23 | 7 |
{-# LANGUAGE QuasiQuotes #-}
import LiquidHaskell
import Language.Haskell.Liquid.Prelude
[lq| assume foo :: {v:Bool | (Prop v)} |]
foo = False
bar = liquidAssertB foo
| spinda/liquidhaskell | tests/gsoc15/unknown/pos/Assume.hs | bsd-3-clause | 174 | 0 | 5 | 31 | 32 | 20 | 12 | 6 | 1 |
module MultiLinear.Class where
import Rotation.SO2
import Rotation.SO3
import Exponential.SO3
import qualified Linear.Matrix as M
import Data.Distributive
import Linear.V3
class MultiLinear f where
(!*!) :: Num a => f a -> f a -> f a
transpose :: Num a => f a -> f a
r0 = rotation (V3 0.1 0.1 0.1)
r1 = rotation (V3 0.1 0.1 0.1)
instance MultiLinear SH2 where
SH2 x !*! SH2 y = SH2 ( x M.!*! y )
transpose = SH2 . distribute . unSH2
instance MultiLinear SO2 where
SO2 x !*! SO2 y = SO2 ( x M.!*! y )
transpose = SO2 . distribute . unSO2
instance MultiLinear SO3 where
SO3 x !*! SO3 y = SO3 ( x M.!*! y )
transpose = SO3 . distribute . unSO3
| massudaw/mtk | MultiLinear/Class.hs | bsd-3-clause | 682 | 0 | 10 | 169 | 287 | 144 | 143 | 21 | 1 |
module Genotype.Types where
import Data.Text (Text)
data BasePair = C | T | A | G deriving (Eq, Show)
data Name = Name Text Text (Maybe Char) deriving (Eq, Show)
data Datum
= Missing
| Estimated BasePair
| Certain BasePair
deriving (Eq, Show)
data Genotype = Genotype
{ geno_name :: Name
, geno_subpopLabel :: Int
, geno_datums :: [(Datum, Datum)]
} deriving (Eq, Show)
| Jonplussed/genotype-parser | src/Genotype/Types.hs | bsd-3-clause | 391 | 0 | 10 | 85 | 148 | 87 | 61 | 14 | 0 |
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{- | Provides a representation for (top-level) integer term rewrite systems.
See <http://aprove.informatik.rwth-aachen.de/help_new/inttrs.html> for details.
Example:
@
outer(x, r) -> inner(1, 1, x, r) [ x >= 0 && r <= 100000 ]
inner(f, i, x, r) -> inner(f + i, i+1, x, r) [ i <= x ]
inner(f, i, x, r) -> outer(x - 1, r + f) [ i > x ]
g(cons(x, xs), y) -> g(xs, y + 1)
h(xs, y) -> h(cons(0, xs), y - 1) [ y > 0]
@
Remarks:
* no arithmetic expressions on the lhs of a rule
* no variable section in contrast to TRS (WST) format; non-arithmetic constants require parenthesis, ie, @c()@
Assumption:
* system is well-typed wrt. to @Univ@ and @Int@ type
* arithmetic are expressions not on root positions
* for the translation to ITS there is a unique start location, ie., exists ONE rule with unique function symbol on lhs
Changelog:
0.2.1.0
* add wellformed-ness predicate and processor
0.2.0.0 - successfully parses all examples of the TPDB
* identifier can contain `.`, `$` and `-
* ppKoat: FUNCTIONSYMBOLS instead of FUNCTIONSYMBOL
* for the ITS translation introduce an extra rule if the original one consists of a single rule; koat and tct-its do not allow start rules to have incoming edges
* parse and ignore TRUE in constraints
* parse && as well as /\ in constraints
* parse integer numbers
-}
module Tct.IntTrs
(
-- * Transformation
toTrs' , toIts' , infer
, parseRules, parse, parseIO
, prettyPrintRules
, putTrs, putIts
-- * Tct Integration
, IntTrs, IntTrsConfig
, isWellFormed
, rules
, runIntTrs, intTrsConfig
, toTrs, toIts, withTrs, withIts, withBoth, wellformed, intTrsDeclarations
) where
import Control.Applicative ((<|>))
import Control.Monad.Except
import Control.Monad.RWS.Strict
import qualified Data.Map.Strict as M
import Data.Maybe (fromJust, fromMaybe, catMaybes)
import qualified Data.Set as S
import System.IO (hPutStrLn, stderr)
import qualified Tct.Common.Polynomial as P
import qualified Tct.Common.Ring as R
import Tct.Core
import Tct.Core.Common.Pretty (Doc, Pretty, pretty)
import qualified Tct.Core.Common.Pretty as PP
import Tct.Core.Common.Xml (Xml, XmlContent, toXml)
import qualified Tct.Core.Common.Xml as Xml
import qualified Tct.Core.Data as T
import Tct.Core.Processor.Transform (transform)
import qualified Text.Parsec as PS
import qualified Text.Parsec.Expr as PE
import qualified Text.Parsec.Language as PL
import qualified Text.Parsec.Token as PT
import qualified Data.Rewriting.Problem as R
import qualified Data.Rewriting.Rule as R
import qualified Data.Rewriting.Rules as RS
import qualified Data.Rewriting.Term as T
-- TODO: MS: better export list for Its
import Tct.Its (Its)
import qualified Tct.Its.Data.Problem as Its (Its (..), initialise, domain)
import qualified Tct.Its.Data.Types as Its (AAtom (..), ARule (..), ATerm (..), rules)
import qualified Tct.Its.Strategies as Its (runtime)
import Tct.Trs (Trs)
import qualified Tct.Trs as Trs (runtime)
import qualified Tct.Trs.Data.Problem as Trs (fromRewriting)
-- TODO: MS: rename Nat
data IFun = Add | Mul | Sub | Nat Int deriving (Eq, Ord, Show)
type ITerm f v = T.Term IFun v
data CFun = Lte | Lt | Eq | Gt | Gte deriving (Eq, Ord, Show, Enum, Bounded)
data Constraint f v = Constraint (ITerm f v) CFun (ITerm f v) deriving (Eq, Ord, Show)
data Fun f = UFun f | IFun IFun deriving (Eq, Ord, Show)
type Term f v = T.Term (Fun f) v
data Rule f v = Rule
{ rule :: R.Rule (Fun f) v
, constraints :: [Constraint f v ] }
deriving (Eq, Ord, Show)
rename :: (v -> v') -> Rule f v -> Rule f v'
rename var (Rule rl cs) = Rule (R.rename var rl) (k `fmap` cs)
where k (Constraint t1 op t2) = Constraint (T.rename var t1) op (T.rename var t2)
-- vars :: Ord v => Rule f v -> [v]
-- vars (Rule (R.Rule lhs rhs) cs) = S.toList $ S.fromList $ (T.varsDL lhs <> T.varsDL rhs <> cvarsDL cs) []
-- where cvarsDL = foldr (mappend . k) id where k (Constraint t1 _ t2) = T.varsDL t1 <> T.varsDL t2
varsL :: Ord v => Rule f v -> [v]
varsL (Rule (R.Rule lhs rhs) cs) = (T.varsDL lhs <> T.varsDL rhs <> cvarsDL cs) []
where cvarsDL = foldr (mappend . k) id where k (Constraint t1 _ t2) = T.varsDL t1 <> T.varsDL t2
termToITerm :: ErrorM m => Term f v -> m (ITerm f v)
termToITerm (T.Fun (UFun _) _) = throwError "termToIterm: not an iterm"
termToITerm (T.Fun (IFun f) ts) = T.Fun f <$> traverse termToITerm ts
termToITerm (T.Var v) = pure (T.Var v)
type Rules f v = [Rule f v]
-- | Checks wether the system is wellformed.
-- A system is well-formed if for all rules following properties is fullfilled.
--
-- * no variables at root position
-- * no arithmetic expression at root position
-- * no univ function symbols below arithmetic expressions
--
-- This properties are sometimes used during translation; but actually never checked.
isWellFormed' :: (ErrorM m, Show f, Show v) => Rules f v -> m (Rules f v)
isWellFormed' rs = all' isWellFormedRule rs *> pure rs
where
isWellFormedRule (Rule (R.Rule lhs rhs) _) = isWellFormedRoot lhs *> isWellFormedRoot rhs
isWellFormedRoot (T.Fun (UFun _) ts) = all' isWellFormedTerm ts
isWellFormedRoot t@(T.Fun (IFun _) _) = throwError $ "iterm at root position: " ++ show t
isWellFormedRoot t@(T.Var _) = throwError $ "var at root position: " ++ show t
isWellFormedTerm (T.Fun (UFun _) ts) = all' isWellFormedTerm ts
isWellFormedTerm t@(T.Fun (IFun _) _) = isWellFormedITerm t
isWellFormedTerm (T.Var _ ) = pure True
isWellFormedITerm t@(T.Fun (UFun _) _) = throwError $ "uterm at iterm position" ++ show t
isWellFormedITerm (T.Fun (IFun Add) ts@[_,_]) = all' isWellFormedITerm ts
isWellFormedITerm (T.Fun (IFun Mul) ts@[_,_]) = all' isWellFormedITerm ts
isWellFormedITerm (T.Fun (IFun Sub) ts@[_,_]) = all' isWellFormedITerm ts
isWellFormedITerm (T.Fun (IFun (Nat _)) []) = pure True
isWellFormedITerm t@(T.Fun (IFun _) _) = throwError $ "iterm with wrong arity" ++ show t
isWellFormedITerm (T.Var _) = pure True
all' f as = and <$> traverse f as
iop :: f -> T.Term f v -> T.Term f v -> T.Term f v
iop f x y = T.Fun f [x,y]
add, mul, sub :: T.Term IFun v -> T.Term IFun v -> T.Term IFun v
add = iop Add
mul = iop Mul
sub = iop Sub
int :: Int -> ITerm f v
int i = T.Fun (Nat i) []
iRep :: IFun -> String
iRep Mul = "*"
iRep Add = "+"
iRep Sub = "-"
iRep (Nat i) = show i
cRep :: CFun -> String
cRep Lte = "<="
cRep Lt = "<"
cRep Eq = "="
cRep Gt = ">"
cRep Gte = ">="
type ErrorM = MonadError String
--- * parser ---------------------------------------------------------------------------------------------------------
tok :: PT.TokenParser st
tok = PT.makeTokenParser
PL.emptyDef
{ PT.commentStart = "(*)"
, PT.commentEnd = "*)"
, PT.nestedComments = False
, PT.identStart = PS.letter
, PT.identLetter = PS.alphaNum <|> PS.oneOf "_'.$-"
, PT.reservedOpNames = cRep `fmap` [(minBound :: CFun)..]
, PT.reservedNames = []
, PT.caseSensitive = True }
pIdentifier, pComma :: Parser String
pIdentifier = PT.identifier tok
pComma = PT.comma tok
pSymbol :: String -> Parser String
pSymbol = PT.symbol tok
pParens :: Parser a -> Parser a
pParens = PT.parens tok
pReservedOp :: String -> Parser ()
pReservedOp = PT.reservedOp tok
pInt :: Parser Int
pInt = fromIntegral <$> PT.integer tok
type Parser = PS.Parsec String ()
-- type Parser = PS.ParsecT Text () Identity
pVar :: Parser (T.Term f String)
pVar = T.Var `fmap` pIdentifier
pTerm :: Parser (T.Term (Fun String) String)
pTerm =
PS.try (T.Fun <$> (UFun <$> pIdentifier) <*> pParens (pTerm `PS.sepBy` pComma))
<|> T.map IFun id <$> pITerm
pITerm :: Parser (ITerm String String)
pITerm = PE.buildExpressionParser table (pParens pITerm <|> (int <$> pInt) <|> pVar)
where
table =
-- [ [ unary "-" neg ]
[ [ binaryL (iRep Mul) mul PE.AssocLeft]
, [ binaryL (iRep Add) add PE.AssocLeft, binaryL (iRep Sub) sub PE.AssocLeft] ]
-- unary f op = PE.Prefix (PS.reserved f *> return op)
binaryL f op = PE.Infix (pSymbol f *> return op)
pCFun :: Parser CFun
pCFun = PS.choice $ k `fmap` [(minBound :: CFun)..]
where k c = PS.try (pReservedOp $ cRep c) *> return c
pConstraint :: Parser (Maybe (Constraint String String))
pConstraint =
(PS.try (pSymbol "TRUE") *> return Nothing)
<|> (Just <$> (Constraint <$> pITerm <*> pCFun <*> pITerm))
pConstraints :: Parser [Constraint String String]
pConstraints = catMaybes <$> PS.option [] (brackets $ pConstraint `PS.sepBy1` pAnd)
where
brackets p = pSymbol "[" *> p <* pSymbol "]"
pAnd = pSymbol "&&" <|> pSymbol "/\\"
pRule :: Parser (Rule String String)
pRule = Rule <$> k <*> pConstraints
where k = R.Rule <$> (pTerm <* pSymbol "->") <*> pTerm
pRules :: Parser (Rules String String)
pRules = PS.many1 pRule
-- | Parser for intTrs rules
parseRules :: Parser (Rules String String)
parseRules = pRules
--- * type inference -------------------------------------------------------------------------------------------------
type Signature f = M.Map (Fun f) Int
signature :: Ord f => Rules f v -> Signature f
signature = M.fromList . RS.funs . fmap (rmap T.withArity . rule)
where rmap k (R.Rule lhs rhs) = R.Rule (k lhs) (k rhs)
fsignature :: Ord f => Rules f v -> Signature f
fsignature = M.filterWithKey (\k _ -> isUTerm k) . signature
where isUTerm f = case f of {(UFun _) -> True; _ -> False}
-- | @vars r = (univvars, numvars)@. Variables in constraints and arithmetic expressions are @numvars@, all other wars
-- are @univvars@.
tvars :: Ord v => Rule f v -> ([v],[v])
tvars (Rule (R.Rule lhs rhs) cs) = (S.toList $ tvarS `S.difference` nvarS, S.toList nvarS)
where
tvarS = S.fromList $ (T.varsDL lhs <> T.varsDL rhs) []
nvarS = S.fromList $ (nvars1 lhs <> nvars1 rhs <> nvars2 cs) []
nvars1 (T.Fun (UFun _) ts) = foldr (mappend . nvars1) id ts
nvars1 (T.Fun (IFun _) ts) = foldr (mappend . T.varsDL) id ts
nvars1 _ = id
nvars2 = foldr (mappend . k) id where k (Constraint t1 _ t2) = T.varsDL t1 <> T.varsDL t2
data Type = Univ | Num | Alpha Int
deriving (Eq, Ord, Show)
data TypeDecl = TypeDecl
{ inputTypes :: [Type]
, outputType :: Type }
deriving Show
type Typing f = M.Map (Fun f) TypeDecl
type Unify = [(Type, Type)]
data Environment f v = Environment
{ variables_ :: M.Map v Type
, declarations_ :: M.Map (Fun f) TypeDecl }
newtype InferM f v a = InferM { runInferM :: RWST (Environment f v) Unify Int (Except String) a }
deriving
(Functor, Applicative, Monad
, MonadWriter Unify
, MonadReader (Environment f v)
, MonadState Int
, MonadError String)
(=~) :: Type -> Type -> InferM f v ()
a =~ b = tell [(a,b)]
-- MS: (almost) standard type inference
-- we already know the type output type of function symbols, and the type of variables in arithmetic expressions
-- still we have to type the rest of the variables
infer :: (ErrorM m, Show v, Show f, Ord f, Ord v) => Rules f v -> m (Typing f)
infer rs = either throwError pure $ do
(decs,_,up) <- runExcept $ runRWST (runInferM inferM) (Environment M.empty M.empty) 0
subst <- unify up
return $ instDecl subst `fmap` decs
where
lookupEnv v = asks variables_ >>= maybe (throwError $ "undefined var: " ++ show v) return . M.lookup v
lookupDecl f = asks declarations_ >>= maybe (throwError $ "undefined fun: " ++ show f) return . M.lookup f
fresh = do { i <- get; put $! i + 1; return $ Alpha i}
inferM = do
tdecls <- M.traverseWithKey initDecl (signature rs)
local (\e -> e {declarations_ = tdecls}) $ do
forM_ rs typeRule
return tdecls
instDecl subst (TypeDecl its ot) = TypeDecl [apply subst t | t <- its] (apply subst ot)
initDecl (UFun _) i = TypeDecl <$> mapM (const fresh) [1..i] <*> pure Univ
initDecl (IFun _) i = TypeDecl <$> mapM (const fresh) [1..i] <*> pure Num
typeRule rl = do
let
(uvars,nvars) = tvars rl
env1 = foldr (`M.insert` Num) M.empty nvars
env2 <- foldM (\ e v -> flip (M.insert v) e `liftM` fresh) env1 uvars
local (\e -> e {variables_ = env2}) $ do
l <- typeTerm (R.lhs $ rule rl)
r <- typeTerm (R.rhs $ rule rl)
l =~ r
typeTerm (T.Var v) = lookupEnv v
typeTerm (T.Fun f ts) = do
TypeDecl its ot <- lookupDecl f
its' <- forM ts typeTerm
sequence_ [ t1 =~ t2 | (t1,t2) <- zip its' its ]
return ot
apply subst t = t `fromMaybe` M.lookup t subst
s1 `compose` s2 = (apply s2 `M.map` s1) `M.union` s2 -- left-biased
unify [] = pure M.empty
unify ((t1,t2):ts) = case (t1,t2) of
(Univ, Num) -> throwError "type inference error"
(Num, Univ) -> throwError "type inference error"
_ | t1 == t2 -> unify ts
_ -> compose s `fmap` unify [(s `apply` t3,s `apply` t4) | (t3,t4) <- ts]
-- TODO: make this more explicit
where s = if t1 > t2 then M.insert t1 t2 M.empty else M.insert t2 t1 M.empty -- MS: we want to replace alphas if possible
--- * transformations ------------------------------------------------------------------------------------------------
toTrs' :: Typing String -> Rules String String -> Either String Trs
toTrs' tys rs = Trs.fromRewriting =<< toRewriting' tys rs
-- | Transforms the inttrs rules to a Trs. If successfull the problem is rendered to the standard output, otherwise
-- the error is rendered to standard error.
putTrs :: Rules String String -> IO ()
putTrs rs = case infer rs >>= flip toRewriting' rs of
Left err -> hPutStrLn stderr err
Right trs -> putStrLn $ PP.display $ R.prettyWST pretty pretty trs
toRewriting' :: Ord f => Typing f -> Rules f v -> Either String (R.Problem f v)
toRewriting' tys rs = case filterUniv tys rs of
Left s -> Left s
Right trs -> Right R.Problem
{ R.startTerms = R.BasicTerms
, R.strategy = R.Innermost
, R.theory = Nothing
, R.rules = R.RulesPair
{ R.weakRules = []
, R.strictRules = trs }
, R.variables = RS.vars trs
, R.symbols = RS.funs trs
, R.comment = Just "intTrs2Trs"}
filterUniv :: Ord f => Typing f -> Rules f v -> Either String [R.Rule f v]
filterUniv tys = traverse (filterRule . rule)
where
filterRule (R.Rule lhs rhs) = R.Rule <$> filterTerm lhs <*> filterTerm rhs
filterTerm (T.Fun f@(UFun g) ts) = T.Fun g <$> (filterEach f ts >>= traverse filterTerm)
filterTerm (T.Fun _ _) = throwError "filterUniv: type inference error"
filterTerm (T.Var v) = pure (T.Var v)
filterEach f ts = maybe
(throwError "filterUniv: undefined function symbol")
(pure . fst . unzip . filter ((/= Num). snd) . zip ts . inputTypes)
(M.lookup f tys)
-- MS: assumes top-level rewriting; lhs and rhs is following form
-- f(aexp1,...,aexp2) -> g(aexp1,...,aexp2)
toIts' :: ErrorM m => Typing String -> Rules String String -> m Its
toIts' tys rs = do
let (tys1, rs1) = addStartRule (tys,rs)
l0 <- findStart rs1
rs2 <- filterNum tys1 rs1
asItsRules l0 . padRules . renameRules $ filter (not . rhsIsVar) rs2
where
rhsIsVar = T.isVar . R.rhs . rule
asItsRules l0 rls = toItsRules rls >>= \rls' -> return $ Its.initialise ([l0],[],rls')
-- | Transforms the inttrs rules to a Its. If successfull the problem is rendered to the standard output, otherwise
-- the error is rendered to standard error.
putIts :: Rules String String -> IO ()
putIts rs = case infer rs >>= flip toIts' rs of
Left err -> hPutStrLn stderr err
Right its -> putStrLn $ PP.display $ ppKoat its
-- TODO: MS: move to tct-its
ppKoat :: Its -> Doc
ppKoat its = PP.vcat
[ PP.text "(GOAL COMPLEXITY)"
, PP.text "(STARTTERM (FUNCTIONSYMBOLS "<> PP.text (Its.fun $ Its.startterm_ its) <> PP.text "))"
, PP.text "(VAR " <> PP.hsep (PP.text `fmap` Its.domain its) <> PP.text ")"
, PP.text "(RULES "
, PP.indent 2 $ PP.vcat (pp `fmap` Its.rules (Its.irules_ its))
, PP.text ")" ]
where
pp (Its.Rule lhs rhss cs) =
PP.pretty lhs
<> PP.text " -> "
<> PP.text "Com_" <> PP.int (length rhss) <> PP.tupled' rhss
<> if null cs then PP.empty else PP.encloseSep PP.lbracket PP.rbracket (PP.text " /\\ ") (PP.pretty `fmap` cs)
renameRules :: Rules f String -> Rules f String
renameRules = fmap renameRule
renameRule :: Rule f String -> Rule f String
renameRule r = rename mapping r
where
mapping v = fromJust . M.lookup v . fst $ foldl k (M.empty, freshvars) (varsL r)
k (m,i) v = if M.member v m then (m,i) else (M.insert v (head i) m, tail i)
freshvars :: [String]
freshvars = (mappend "x" . show) `fmap` [(0::Int)..]
padRules :: Ord f => Rules f String -> Rules f String
padRules rls = padRule (mx rls) `fmap` rls
where mx = maximum . M.elems . fsignature
padRule :: Int -> Rule f String -> Rule f String
padRule mx (Rule (R.Rule lhs rhs) cs) = Rule (R.Rule (padTerm mx lhs) (padTerm mx rhs)) cs
padTerm :: Int -> Term f String -> Term f String
padTerm mx (T.Fun (UFun f) ts) = T.Fun (UFun f) $ zip' ts (take mx freshvars)
where
zip' (s:ss) (_:rr) = s: zip' ss rr
zip' [] rr = T.Var `fmap` rr
zip' _ [] = error "a"
padTerm _ _ = error "a"
toItsRules :: (Ord v, ErrorM m) => Rules f v -> m [Its.ARule f v]
toItsRules = traverse toItsRule
toItsRule :: (Ord v, ErrorM m) => Rule f v -> m (Its.ARule f v)
toItsRule (Rule (R.Rule lhs rhs) cs) = Its.Rule <$> toItsTerm lhs <*> ((:[]) <$> toItsTerm rhs) <*> traverse toItsConstraint cs
toItsTerm :: (Ord v, ErrorM m) => Term f v -> m (Its.ATerm f v)
toItsTerm (T.Fun (UFun f) ts) = Its.Term f <$> traverse (termToITerm >=> itermToPoly) ts
toItsTerm _ = throwError "toItsTerm: not a valid term"
itermToPoly :: (Ord v, ErrorM m) => ITerm f v -> m (P.Polynomial Int v)
itermToPoly (T.Fun (Nat n) []) = pure $ P.constant n
itermToPoly (T.Fun f ts@(t1:t2:tss)) = case f of
Add -> R.bigAdd <$> traverse itermToPoly ts
Mul -> R.bigMul <$> traverse itermToPoly ts
Sub -> R.sub <$> itermToPoly t1 <*> (R.bigAdd `fmap` traverse itermToPoly (t2:tss))
_ -> throwError "itermToPoly: not a valid term"
itermToPoly (T.Var v) = pure $ P.variable v
itermToPoly _ = throwError "itermToPoly: not a valid term"
toItsConstraint :: (Ord v, ErrorM m) => Constraint f v -> m (Its.AAtom v)
toItsConstraint (Constraint t1 cop t2) = case cop of
Lte -> Its.Gte <$> itermToPoly t2 <*> itermToPoly t1
Lt -> Its.Gte <$> itermToPoly t2 <*> (R.add R.one <$> itermToPoly t1)
Eq -> Its.Eq <$> itermToPoly t1 <*> itermToPoly t2
Gt -> Its.Gte <$> itermToPoly t1 <*> (R.add R.one <$> itermToPoly t2)
Gte -> Its.Gte <$> itermToPoly t1 <*> itermToPoly t2
-- MS: just another hack to deduce the starting location
-- | If the system constists only of a single rule; introduce an extra rule with a unique start location.
addStartRule :: (Ord f, Monoid f) => (Typing f, Rules f v) -> (Typing f, Rules f v)
addStartRule (ty,rs@[Rule (R.Rule (T.Fun (UFun f) ts) (T.Fun (UFun g) _)) _]) = (M.insert lfun ldec ty, Rule r []:rs)
where
ldec = TypeDecl [] Univ
lfun = UFun (f <> g)
r = R.Rule (T.Fun lfun []) (T.Fun (UFun f) ts)
addStartRule rs = rs
-- | Look for a single unique function symbol on the rhs.
findStart :: (ErrorM m, Ord f) => Rules f v -> m f
findStart rs = case S.toList $ roots R.lhs `S.difference` roots R.rhs of
[fun] -> pure fun
_ -> throwError "Could not deduce a start symbol."
where
roots f = foldr (k f) S.empty rs
k f (Rule r _) acc = case f r of {T.Fun (UFun g) _ -> g `S.insert` acc; _ -> acc}
-- | Restricts to 'Num' type
-- If successfull, 'UFun' appears only at root positions, and 'IFun' appear only below root.
filterNum :: (ErrorM m, Ord f) => Typing f -> Rules f v -> m (Rules f v)
filterNum tys = traverse filterRule
where
filterRule (Rule (R.Rule lhs rhs) cs) = Rule <$> (R.Rule <$> filterRoot lhs <*> filterRoot rhs) <*> pure cs
filterRoot (T.Fun f@(UFun _) ts) = T.Fun f <$> (filterEach f ts >>= validate)
filterRoot (T.Fun _ _) = throwError "filterNum: arithmetic expression at root position"
filterRoot (T.Var v) = pure (T.Var v)
filterEach f ts = maybe
(throwError "filterUniv: undefined function symbol")
(pure . fst . unzip . filter ((== Num). snd) . zip ts . inputTypes)
(M.lookup f tys)
validate ts = if all p ts then pure ts else throwError "filterNum: type inference error"
where p t = case t of {(T.Fun (UFun _) _) -> False; _ -> True}
--- * TcT integration ------------------------------------------------------------------------------------------------
--- ** Problem -------------------------------------------------------------------------------------------------------
-- MS: integration with TcT
data Problem f v = Problem { rules :: Rules f v } deriving Show
ppRules :: (f -> Doc) -> (v -> Doc) -> Rules f v -> Doc
ppRules fun var rs = PP.vcat (ppRule fun var `fmap` rs)
-- | Pretty printer for a list of rules.
prettyPrintRules :: (f -> Doc) -> (v -> Doc) -> Rules f v -> Doc
prettyPrintRules = ppRules
ppRule :: (f -> Doc) -> (v -> Doc) -> Rule f v -> Doc
ppRule fun var (Rule (R.Rule lhs rhs) cs) =
PP.hang 2 $ ppTerm fun var lhs PP.<+> PP.string "->" PP.</> ppTerm fun var rhs PP.<+> ppConstraints var cs
ppTerm :: (f -> Doc) -> (v -> Doc) -> Term f v -> Doc
ppTerm fun var (T.Fun (UFun f) ts) = fun f <> PP.tupled (ppTerm fun var `fmap` ts)
ppTerm fun var (T.Fun (IFun f) ts) = case f of
Nat i -> PP.int i
op -> k op
where k op = PP.encloseSep PP.lparen PP.rparen (PP.space <> PP.text (iRep op) <> PP.space) (ppTerm fun var `fmap` ts)
ppTerm _ var (T.Var v) = var v
ppConstraints :: (v -> Doc) -> [Constraint f v] -> Doc
ppConstraints var cs = PP.encloseSep PP.lbracket PP.rbracket (PP.text " && ") (ppConstraint var `fmap` cs)
ppConstraint :: (v -> Doc) -> Constraint f v -> Doc
ppConstraint var (Constraint lhs eq rhs) = ppITerm lhs PP.<+> PP.text (cRep eq) PP.<+> ppITerm rhs
where
k op ts = PP.encloseSep PP.lparen PP.rparen (PP.space <> PP.text (iRep op) <> PP.space) (ppITerm `fmap` ts)
ppITerm (T.Fun f ts) = case f of
Nat i -> PP.int i
op -> k op ts
ppITerm (T.Var v) = var v
xmlRules :: (f -> XmlContent) -> (v -> XmlContent) -> Rules f v -> XmlContent
xmlRules _ _ _ = Xml.empty
instance (Pretty f, Pretty v) => Pretty (Problem f v) where
pretty (Problem rs) = PP.text "Rules" PP.<$$> PP.indent 2 (ppRules PP.pretty PP.pretty rs)
instance (Xml f, Xml v) => Xml (Problem f v) where
toXml (Problem rs) = Xml.elt "inttrs" [ Xml.elt "rules" [xmlRules toXml toXml rs] ]
instance {-# OVERLAPPING #-} Xml (Problem String String) where
toXml (Problem rs) = Xml.elt "inttrs" [ Xml.elt "rules" [xmlRules Xml.text Xml.text rs] ]
--- ** Config --------------------------------------------------------------------------------------------------------
type IntTrs = Problem String String
type IntTrsConfig = TctConfig IntTrs
parse :: String -> Either String IntTrs
parse s = case PS.parse pRules "" s of
Left e -> Left (show e)
Right p -> Right (Problem p)
parseIO :: FilePath -> IO (Either String IntTrs)
parseIO fn = parse <$> readFile fn
isWellFormed :: (ErrorM m, Ord f, Ord v, Show f, Show v) => Rules f v -> m (Rules f v)
isWellFormed rs = isWellFormed' rs *> infer rs *> pure rs
intTrsConfig :: IntTrsConfig
intTrsConfig = (defaultTctConfig parseIO)
{ defaultStrategy = withBoth Trs.runtime Its.runtime }
runIntTrs :: Declared IntTrs IntTrs => IntTrsConfig -> IO ()
runIntTrs = runTct
-- | Checks wether the problem 'isWellFormed'.
wellformed :: Strategy IntTrs IntTrs
wellformed = withProblem $ \p -> case isWellFormed (rules p) of
Left err -> failing err
Right _ -> identity
toTrs :: Strategy IntTrs Trs
toTrs = transform "We extract a TRS fragment from the current int-TRS problem:"
(\p -> infer (rules p) >>= \tp -> toTrs' tp (rules p))
withTrs :: Strategy Trs Trs -> Strategy IntTrs Trs
withTrs st = toTrs .>>> st
toIts :: Strategy IntTrs Its
toIts = transform "We extract a Its fragment from the current int-TRS problem:"
(\p -> infer (rules p) >>= \tp -> toIts' tp (rules p))
-- (\p -> infer (rules p) >>= \tp -> toIts' tp (rules p) >>= \its' -> trace (PP.display $ PP.pretty p) (trace (PP.display $ PP.pretty its') (return its')))
withIts :: Strategy Its Its -> Strategy IntTrs Its
withIts st = toIts .>>> st
withBoth :: Strategy Trs Trs -> Strategy Its Its -> Strategy IntTrs IntTrs
withBoth st1 st2 = withProblem $ \p -> let tpM = infer (rules p) in fastest
[ transform "a" (const $ tpM >>= \tp -> toTrs' tp (rules p)) .>>> st1 .>>> close
, transform "a" (const $ tpM >>= \tp -> toIts' tp (rules p)) .>>> st2 .>>> close]
-- TODO: MS: move to tct-trs
trsArg :: Declared Trs Trs => T.Argument 'T.Required (Strategy Trs Trs)
trsArg = T.strat "trs" ["This argument specifies the trs strategy to apply."]
-- TODO: MS: move to tct-its
itsArg :: Declared Its Its => T.Argument 'T.Required (Strategy Its Its)
itsArg = T.strat "its" ["This argument specifies the trs strategy to apply."]
intTrsDeclarations :: (Declared Trs Trs, Declared Its Its) => [StrategyDeclaration IntTrs IntTrs]
intTrsDeclarations =
[ T.SD $ T.declare "withTrs" ["Solve with TRS."]
(OneTuple $ trsArg `optional` Trs.runtime)
(\st -> withTrs st .>>> close)
, T.SD $ T.declare "withIts" ["Solve with ITS."]
(OneTuple $ itsArg `optional` Its.runtime)
(\st -> withIts st .>>> close)
, T.SD $ T.declare "withBoth" ["Solve with TRS and ITS."]
(trsArg `optional` Trs.runtime, itsArg `optional` Its.runtime)
(\st1 st2 -> withBoth st1 st2 .>>> close)
, T.SD $ T.declare "wellformed" ["checks wether the system is wellformed"]
()
wellformed ]
| ComputationWithBoundedResources/tct-inttrs | src/Tct/IntTrs.hs | bsd-3-clause | 26,631 | 0 | 19 | 6,383 | 9,635 | 4,981 | 4,654 | -1 | -1 |
{-# LANGUAGE FlexibleContexts #-}
import Plots
import Plots.Axis
import Plots.Types hiding (B)
import Data.List
import Diagrams.Prelude
import Diagrams.Backend.Rasterific
mydata1 = [(1,3), (2,5.5), (3.2, 6), (3.5, 6.1)]
mydata2 = mydata1 & each . _1 *~ 0.5
mydata3 = [V2 1.2 2.7, V2 2 5.1, V2 3.2 2.6, V2 3.5 5]
-- Could add helper functions in plots to make this easier
fillOpacity = barStyle . mapped . _opacity
myaxis :: Axis B V2 Double
myaxis = r2Axis &~ do
ribbonPlot' ((fst foo1) ++ reverse (zeroy (fst foo1))) $ do
addLegendEntry (snd foo1)
plotColor .= white
fillOpacity .= 0.7
strokeEdge .= False
ribbonPlot' ((fst foo2) ++ reverse (zeroy (fst foo2))) $ do
addLegendEntry (snd foo1)
fillOpacity .= 0.5
ribbonPlot' ((fst foo3) ++ reverse (zeroy (fst foo3))) $ do
addLegendEntry (snd foo1)
fillOpacity .= 0.5
strokeEdge .= False
make :: Diagram B -> IO ()
make = renderRasterific "test.png" (mkWidth 600) . frame 20
main :: IO ()
main = make $ renderAxis myaxis
foo1 = ([(111.0,0.1),(140.0,1.2),(150.0,2.3)],"typeA")
foo2 = ([(155.0,3.5),(167.0,5.1),(200.0,6.4),(211.0,7.5)],"typeB")
foo3 = ([(191.0,5.8),(233.0,8.5),(250.0,9.1),(270.0,9.6)],"typeC")
| bergey/plots | examples/ribbonopacity.hs | bsd-3-clause | 1,247 | 0 | 16 | 258 | 553 | 301 | 252 | -1 | -1 |
{-# LANGUAGE FlexibleContexts #-}
module Database.Redis.Internal where
import Control.Monad.Trans ( MonadIO, liftIO )
import Control.Failure ( MonadFailure, failure )
import Data.Convertible.Base ( convertUnsafe )
import Data.Convertible.Instances ( )
import Database.Redis.Core
import System.IO ( hGetChar )
import qualified Data.Text as T
import qualified Data.Text.IO as TIO
-- ---------------------------------------------------------------------------
-- Command
--
command :: (MonadIO m, MonadFailure RedisError m) => Server -> m a -> m RedisValue
command r f = f >> getReply r
multiBulk :: (MonadIO m, MonadFailure RedisError m)
=> Server -> T.Text -> [T.Text] -> m ()
multiBulk (Server h) command' vs = do
let vs' = concatMap (\a -> ["$" ~~ (toParam $ T.length a), a]) $ [command'] ++ vs
liftIO $ TIO.hPutStrLn h $ "*" ~~ (toParam $ 1 + length vs)
mapM_ (liftIO . TIO.hPutStrLn h) vs'
multiBulkT2 :: (MonadIO m, MonadFailure RedisError m)
=> Server -> T.Text -> [(T.Text, T.Text)] -> m ()
multiBulkT2 r command' kvs = do
multiBulk r command' $ concatMap (\kv -> [fst kv] ++ [snd kv]) kvs
-- ---------------------------------------------------------------------------
-- Reply
--
getReply :: (MonadIO m, MonadFailure RedisError m) => Server -> m RedisValue
getReply r@(Server h) = do
prefix <- liftIO $ hGetChar h
getReplyType r prefix
getReplyType :: (MonadIO m, MonadFailure RedisError m)
=> Server -> Char -> m RedisValue
getReplyType r prefix =
case prefix of
'$' -> bulkReply r
':' -> integerReply r
'+' -> singleLineReply r
'-' -> singleLineReply r >>= \(RedisString m) -> failure $ ServerError m
'*' -> multiBulkReply r
_ -> singleLineReply r
bulkReply :: (MonadIO m, MonadFailure RedisError m) => Server -> m RedisValue
bulkReply r@(Server h) = do
l <- liftIO $ TIO.hGetLine h
let bytes = convertUnsafe l::Int
if bytes == -1
then return $ RedisNil
else do
v <- takeChar bytes r
_ <- liftIO $ TIO.hGetLine h -- cleans up
return $ RedisString v
integerReply :: (MonadIO m, MonadFailure RedisError m) => Server -> m RedisValue
integerReply (Server h) = do
l <- liftIO $ TIO.hGetLine h
return $ RedisInteger (convertUnsafe l::Int)
singleLineReply :: (MonadIO m, MonadFailure RedisError m) => Server -> m RedisValue
singleLineReply (Server h) = do
l <- liftIO $ TIO.hGetLine h
return $ RedisString l
multiBulkReply :: (MonadIO m, MonadFailure RedisError m) => Server -> m RedisValue
multiBulkReply r@(Server h) = do
l <- liftIO $ TIO.hGetLine h
let items = convertUnsafe l::Int
multiBulkReply' r items []
multiBulkReply' :: (MonadIO m, MonadFailure RedisError m)
=> Server -> Int -> [RedisValue] -> m RedisValue
multiBulkReply' _ 0 values = return $ RedisMulti values
multiBulkReply' r@(Server h) n values = do
_ <- liftIO $ hGetChar h -- discard the type data since we know it's a bulk string
v <- bulkReply r
multiBulkReply' r (n - 1) (values ++ [v])
takeChar :: (MonadIO m, MonadFailure RedisError m)
=> Int -> Server -> m (T.Text)
takeChar n r = takeChar' n r ""
takeChar' :: (MonadIO m, MonadFailure RedisError m)
=> Int -> Server -> T.Text -> m (T.Text)
takeChar' 0 _ s = return s
takeChar' n r@(Server h) s = do
c <- liftIO $ hGetChar h
(takeChar' (n - 1) r (s ~~ (T.singleton c)))
-- ---------------------------------------------------------------------------
-- Helpers
--
(~~) :: T.Text -> T.Text -> T.Text
(~~) = T.append
boolify :: (Monad m) => m RedisValue -> m (Bool)
boolify v' = do
v <- v'
return $ case v of RedisString "OK" -> True
RedisInteger 1 -> True
_ -> False
discard :: (Monad a) => a b -> a ()
discard f = f >> return ()
| brandur/redis-haskell | src/Database/Redis/Internal.hs | bsd-3-clause | 3,957 | 0 | 20 | 989 | 1,458 | 742 | 716 | 85 | 6 |
{-# OPTIONS -fglasgow-exts #-}
module LogicExample where
import Language.GroteTrap
import Data.Generics hiding (Prefix)
import Data.Set hiding (map)
-- Logic data structure.
data Logic
= Var String
| Or [Logic]
| And [Logic]
| Impl Logic Logic
| Not Logic
deriving (Show, Eq, Typeable, Data)
type LogicAlg a =
( String -> a
, [a] -> a
, [a] -> a
, a -> a -> a
, a -> a
)
foldLogic :: LogicAlg a -> Logic -> a
foldLogic (f1, f2, f3, f4, f5) = f where
f (Var a1 ) = f1 a1
f (Or a1) = f2 (map f a1)
f (And a1) = f3 (map f a1)
f (Impl a1 a2) = f4 (f a1) (f a2)
f (Not a1 ) = f5 (f a1)
-- Language definition.
logicLanguage :: Language Logic
logicLanguage = language
{ variable = Just Var
, operators =
[ Unary Not Prefix 0 "!"
, Assoc And 1 "&&"
, Assoc Or 2 "||"
, Binary Impl InfixR 3 "->"
]
}
-- Evaluation.
type Environment = Set String
evalLogic :: Environment -> Logic -> Bool
evalLogic env = foldLogic ((`member` env), or, and, (||) . not, not)
readLogic :: Environment -> String -> Bool
readLogic env = evalLogic env . readExpression logicLanguage
-- Examples
appie :: ParseTree
appie = readParseTree logicLanguage "piet && klaas && maartje -> supermarkt"
demo1 = appie
demo2 = unparse $ appie
demo9 = evaluate logicLanguage appie
demo3 = printTree $ appie
demo4 = fromError $ follow appie root
demo5 = fromError $ follow appie [0]
demo6 = range $ fromError $ follow appie [0]
demo7 = lshow logicLanguage (And [Var "p", Var "q"])
| MedeaMelana/GroteTrap | LogicExample.hs | bsd-3-clause | 1,566 | 0 | 9 | 410 | 601 | 327 | 274 | 48 | 5 |
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE PatternSynonyms #-}
module Syntax.Internal where
import Control.Lens.Prism
import Data.Map (Map)
import Data.Text (Text)
import Data.Vector (Vector)
import Syntax.Common
-- Would like to merge this with NType, but difficult to give a unifying type for Mon
-- Adding an extra type argument breaks a lot of stuff, and we then need to rethink Subst
data Kind
= KFun PType Kind
| KForall NTBinder Kind
| KVar NTVariable
| KObject KObject
| KUniverse
deriving (Show, Eq)
type Object = Map Projection
type KObject = Object Kind
type NObject = Object NType
_Fun :: Prism' NType (PType, NType)
_Fun = prism' (uncurry Fun) $ \case
Fun p n -> Just (p, n)
_ -> Nothing
_Forall :: Prism' NType (NTBinder, NType)
_Forall = prism' (uncurry Forall) $ \case
Forall p n -> Just (p, n)
_ -> Nothing
_NObject :: Prism' NType NObject
_NObject = prism' NObject $ \case
NObject n -> Just n
_ -> Nothing
_NCon :: Prism' NType (TConstructor, Args)
_NCon = prism' (uncurry NCon) $ \case
NCon d a -> Just (d, a)
_ -> Nothing
_Mon :: Prism' NType PType
_Mon = prism' Mon $ \case
Mon d -> Just d
_ -> Nothing
data NType
= Fun PType NType
-- ^ Functions, so far not dependent
| Forall NTBinder NType
| NVar NTVariable
| NCon TConstructor Args
| NObject NObject
| Mon PType
deriving (Show, Eq, Ord)
data TLit = TInt | TString
deriving (Show, Eq, Ord)
type PCoProduct = Map Constructor PType
type PStruct = Vector PType
_PCon :: Prism' PType (TConstructor, Args)
_PCon = prism' (uncurry PCon) $ \case
PCon d a -> Just (d,a)
_ -> Nothing
_PCoProduct :: Prism' PType PCoProduct
_PCoProduct = prism' PCoProduct $ \case
PCoProduct d -> Just d
_ -> Nothing
_PStruct :: Prism' PType PStruct
_PStruct = prism' PStruct $ \case
PStruct d -> Just d
_ -> Nothing
_Ptr :: Prism' PType NType
_Ptr = prism' Ptr $ \case
Ptr d -> Just d
_ -> Nothing
data PType
= PCon TConstructor Args
| PCoProduct PCoProduct
| PStruct PStruct
| PVar PTVariable
| Ptr NType
| PLit TLit
deriving (Show, Eq, Ord)
data CallFun = CDef Definition | CVar Variable deriving (Show, Eq, Ord)
data Call = Apply CallFun Args deriving (Show, Eq, Ord)
type TailCall = Call -- further checks should be done
-- can infer
data Act
= PutStrLn Val
| ReadLn
| Malloc PType Val
deriving (Show, Eq, Ord)
-- must check
data CMonad
= Act Act
| TCall TailCall
| Return Val
| CLeftTerm (LeftTerm CMonad)
| Bind Act Binder CMonad
| With Call Binder CMonad -- This allocates on the stack
deriving (Show)
-- must check
data Term mon
= Do mon
| RightTerm (RightTerm (Term mon))
| LeftTerm (LeftTerm (Term mon))
-- Explicit substitution, not sure yet I want this
-- | Let (ValSimple (ActSimple (CallSimple defs (Args nty defs free) free) free) free, PType defs pf nb nf bound free) bound
-- (Term mon defs pf nb nf bound free) -- This allocates on the stack
deriving (Show)
-- introduction for negatives,
-- (maybe it should have the CDef cut here)
data RightTerm cont
= Lam Binder cont
| TLam NTBinder cont
| New (Vector (CoBranch cont))
deriving (Show)
pattern Lam' :: Binder -> Term mon -> Term mon
pattern Lam' b t = RightTerm (Lam b t)
pattern TLam' :: NTBinder -> Term mon -> Term mon
pattern TLam' b t = RightTerm (TLam b t)
pattern New' :: Vector (CoBranch (Term mon)) -> Term mon
pattern New' bs = RightTerm (New bs)
-- elimination for positives + Cuts
--(maybe it should just have CVar -calls)
data LeftTerm cont
= Case Variable (Vector (Branch cont))
| Split Variable (Vector Binder) cont
| Derefence Variable cont
deriving (Show)
pattern Case' :: Variable -> (Vector (Branch (Term mon))) -> Term mon
pattern Case' v bs = LeftTerm (Case v bs)
pattern Split' :: Variable -> Vector Binder -> Term mon -> Term mon
pattern Split' v bs t = LeftTerm (Split v bs t)
pattern Derefence' :: Variable -> Term mon -> Term mon
pattern Derefence' v t = LeftTerm (Derefence v t)
data Branch cont = Branch Constructor cont
deriving (Show)
data CoBranch cont = CoBranch Projection cont
deriving (Show)
-- can infer
data Arg
= Push Val -- maybe we want (CMonad) and auto-lift computations to closest Do-block
-- Could have a run CMonad if it is guaranteed to be side-effect free (including free from non-termination aka it terminates)
| Proj Projection
| Type NType
deriving (Show, Eq, Ord)
-- type Arg defs pf nb nf bound free = ArgSimple
type Args = Vector Arg
data Literal = LInt Int | LStr Text
deriving (Show, Eq, Ord)
-- must check
data Val
= Var Variable
| Lit Literal
| Con Constructor Val
| Struct (Vector Val)
| Thunk Call -- or be monadic code?
| ThunkVal Val
deriving (Show, Eq, Ord)
| Danten/lejf | src/Syntax/Internal.hs | bsd-3-clause | 4,829 | 0 | 13 | 1,120 | 1,512 | 804 | 708 | 137 | 2 |
import Distribution.PackageDescription
import Distribution.Simple
import Distribution.Simple.LocalBuildInfo
import Distribution.Simple.UserHooks
import System.Directory
import System.Exit
import System.FilePath
import System.Process
testSuiteExe = "b1-tests"
main :: IO ()
main = defaultMainWithHooks hooks
hooks :: UserHooks
hooks = simpleUserHooks { runTests = runTestSuite }
runTestSuite :: Args -> Bool -> PackageDescription -> LocalBuildInfo -> IO ()
runTestSuite _ _ _ localBuildInfo = do
let testDir = buildDir localBuildInfo </> testSuiteExe
setCurrentDirectory testDir
exitCode <- system testSuiteExe
exitWith exitCode
| btmura/b1 | Setup.hs | bsd-3-clause | 642 | 0 | 11 | 86 | 162 | 84 | 78 | 19 | 1 |
module Data.MediaBus.Media.SyncStreamSpec
( spec,
)
where
import Control.Lens
import Control.Monad.State
import Data.Function
import Data.MediaBus
import Debug.Trace
import Test.Hspec
import Test.QuickCheck
import FakePayload
spec :: Spec
spec =
describe "setSequenceNumberAndTimestamp" $ do
it "increases the sequence number by one (only) for each frame" $
let prop :: (NonEmptyList (SyncStream () () FakePayload)) -> Bool
prop (NonEmpty inStr) =
let expectedLastSeqNum =
let isNext (MkStream (Next _)) = True
isNext _ = False
in max 0 (fromIntegral (length (filter isNext inStr)) - 1)
actualLastSeqNum =
let outStr =
let z :: (SeqNum16, Ticks64At8000)
z = (0, 0)
in evalState
( mapM
(state . setSequenceNumberAndTimestamp)
inStr
)
z
in case last outStr of
MkStream (Next f) -> f ^. seqNum
MkStream (Start f) -> max 0 (f ^. seqNum - 1)
in expectedLastSeqNum == actualLastSeqNum
in property prop
it "increases the sequence number monotonic" $
let prop :: (NonEmptyList (SyncStream () () FakePayload)) -> Bool
prop (NonEmpty inStr) =
let seqNumDiffs =
let outFrames =
let isNext (MkStream (Next _)) = True
isNext _ = False
outStr =
let z :: (SeqNum16, Ticks64At8000)
z = (0, 0)
in evalState
( mapM
(state . setSequenceNumberAndTimestamp)
inStr
)
z
in filter isNext outStr
in zipWith ((-) `on` (view seqNum)) (drop 1 outFrames) outFrames
in all (== 1) seqNumDiffs
in property prop
it "increases the timestamps by the duration of each frame" $
let prop :: (NonEmptyList (SyncStream () () FakePayload)) -> Bool
prop (NonEmpty inStr) =
let isNext (MkStream (Next _)) = True
isNext _ = False
outFrames :: [Stream () SeqNum16 Ticks64At8000 () FakePayload]
outFrames =
let outStr =
let z :: (SeqNum16, Ticks64At8000)
z = (0, MkTicks 0)
in evalState
( mapM
(state . setSequenceNumberAndTimestamp)
inStr
)
z
in filter isNext outStr
timestamps = map (view timestamp) outFrames
expectedTimestamps :: [Ticks64At8000]
expectedTimestamps =
let inFramesWithoutLast =
(filter isNext inStr)
inDurations =
map
(view (from nominalDiffTime) . getDuration)
inFramesWithoutLast
in scanl (+) 0 inDurations
in if and (zipWith (==) timestamps expectedTimestamps)
then True
else
traceShow
( timestamps,
expectedTimestamps,
outFrames
)
False
in property prop
| lindenbaum/mediabus | specs/Data/MediaBus/Media/SyncStreamSpec.hs | bsd-3-clause | 3,912 | 0 | 34 | 2,021 | 855 | 437 | 418 | 87 | 6 |
{-|
Module : Graphics.Mosaico.Ventana
Description : Ventanas interactivas con distribuciones de rectángulos
Copyright : ⓒ Manuel Gómez, 2015
License : BSD3
Maintainer : [email protected]
Stability : experimental
Portability : portable
Representación orientada a objetos de una ventana interactiva donde se puede
mostrar un 'Diagrama' con una parte enfocada, y obtener eventos de teclas
pulsadas en la ventana.
-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE UnicodeSyntax #-}
module Graphics.Mosaico.Ventana
( Ventana
, cerrar
, crearVentana
, leerTecla
, mostrar
)
where
import Control.Applicative (pure)
import Control.Concurrent (forkIO)
import Control.Concurrent.STM.TMChan (newTMChanIO, closeTMChan, readTMChan, writeTMChan)
import Control.Concurrent.STM.TVar (newTVarIO, readTVarIO, writeTVar)
import Control.Monad (void)
import Control.Monad.STM (atomically)
import Control.Monad.Unicode ((=≪))
import Control.Monad.IO.Class (liftIO)
import Data.Bool (Bool(True))
import Data.Colour.Names (blue, green, red, yellow)
import Data.Colour.SRGB (Colour, sRGB24)
import Data.Function (($), flip)
import Data.Function.Unicode ((∘))
import Data.Functor ((<$>))
import Data.List (reverse)
import Data.Maybe (Maybe(Nothing, Just))
import Data.Monoid (mappend, mempty)
import Data.String (String)
import Diagrams.Attributes (opacity)
import Diagrams.Backend.Cairo (Cairo)
import Diagrams.Backend.Gtk (renderToGtk, toGtkCoords)
import Diagrams.BoundingBox (boundingBox, boxExtents)
import Diagrams.Core.Types (Diagram)
import Diagrams.TwoD.Align (centerXY)
import Diagrams.TwoD.Attributes (fillColor, lineColor, lineWidth, ultraThick)
import Diagrams.TwoD.Combinators ((===), (|||))
import Diagrams.TwoD.Shapes (rect, unitSquare)
import Diagrams.TwoD.Size (SizeSpec2D(Dims), sized)
import Diagrams.TwoD.Transform (scaleX, scaleY)
import Diagrams.TwoD.Types (R2(R2))
import Diagrams.Util (( # ))
import Graphics.Mosaico.Imagen (Imagen(Imagen, altura, anchura), Color(Color, rojo, verde, azul))
import Graphics.Mosaico.Diagrama (Diagrama((:-:), (:|:), Hoja), Paso(Primero, Segundo), Rectángulo(Rectángulo, color, imagen))
import Graphics.UI.Gtk.Abstract.Container (containerChild)
import Graphics.UI.Gtk.Abstract.Widget (EventMask(KeyPressMask), Requisition(Requisition), exposeEvent, keyPressEvent, onDestroy, sizeRequest, widgetAddEvents, widgetDestroy, widgetQueueDraw, widgetShowAll)
import Graphics.UI.Gtk.Gdk.EventM (eventKeyName, eventWindow)
import Graphics.UI.Gtk.General.General (initGUI, mainGUI, mainQuit, postGUIAsync, postGUISync)
import Graphics.UI.Gtk.Misc.DrawingArea (drawingAreaNew)
import Graphics.UI.Gtk.Windows.Window (windowNew)
import Prelude (Double, Integer, fromInteger, fromIntegral)
import System.Glib.Attributes (AttrOp((:=)), set)
import System.Glib.Signals (on)
import System.Glib.UTFString (glibToString)
import System.IO (IO)
-- | Un valor del tipo 'Ventana' es un objeto que representa a una ventana
-- interactiva donde puede dibujarse un 'Diagrama'. Es posible, además,
-- obtener información de qué teclas son pulsadas sobre la ventana.
data Ventana
= Ventana
{ mostrar ∷ [Paso] → Diagrama → IO ()
-- ^ Dada una 'Ventana', un 'Diagrama', y una lista de 'Paso's,
-- representar gráficamente el 'Diagrama' dado sobre el lienzo de la
-- 'Ventana', haciendo resaltar visualmente el nodo del árbol alcanzado
-- si se realizan los movimientos correspondientes a la lista de
-- 'Paso's desde la raíz del árbol.
--
-- Los nodos se resaltan con un cuadro verde, y se colorean según el
-- tipo de nodo. En el caso de nodos intermedios, se colorea en azul
-- la región correspondiente al primer subárbol del nodo binario, y en
-- rojo la región correspondiente al segundo subárbol. En el caso de
-- nodos terminales (hojas), el rectángulo se colorea en amarillo.
, leerTecla ∷ IO (Maybe String)
-- ^ Dada una 'Ventana', esperar por un evento de teclado.
--
-- Cuando sobre la ventana se haya pulsado alguna tecla que no haya sido
-- reportada a través de este cómputo, se producirá como resultado
-- @'Just' tecla@, donde @tecla@ será el nombre de la tecla.
--
-- Si la ventana ya ha sido cerrada, se producirá como resultado
-- 'Nothing'.
--
-- El texto correspondiente a cada tecla es aproximadamente igual al
-- nombre del símbolo en la biblioteca GDK sin el prefijo @GDK_KEY_@.
-- La lista completa está disponible en
-- <https://git.gnome.org/browse/gtk+/plain/gdk/gdkkeysyms.h el código fuente de la biblioteca GDK>.
-- Sin embargo, la mejor manera de descubrir cuál simbolo corresponde
-- a cada tecla es crear una 'Ventana' y hacer que se imprima el texto
-- correspondiente a cada tecla pulsada sobre ella.
, cerrar ∷ IO ()
-- ^ Dada una 'Ventana', hacer que se cierre y que no pueda producir
-- más eventos de teclado.
}
-- | Construye un objeto del tipo 'Ventana' dadas sus dimensiones en número
-- de píxeles.
crearVentana
∷ Integer -- ^ Número de píxeles de anchura de la 'Ventana' a crear.
→ Integer -- ^ Número de píxeles de altura de la 'Ventana' a crear.
→ IO Ventana -- ^ La 'Ventana' nueva, ya visible, con el lienzo en blanco.
crearVentana anchura' altura'
= do
chan ← newTMChanIO
diagramaV ← newTVarIO mempty
void initGUI
window ← windowNew
drawingArea ← drawingAreaNew
set window [containerChild := drawingArea]
void
$ drawingArea `on` sizeRequest
$ pure (Requisition (fromInteger anchura') (fromInteger altura'))
void
$ window `on` keyPressEvent
$ do
key ← glibToString <$> eventKeyName
liftIO
∘ void
∘ atomically
$ writeTMChan chan key
pure True
void
$ drawingArea `on` exposeEvent
$ do
w ← eventWindow
liftIO
$ do
renderToGtk w
∘ toGtkCoords
∘ sized (Dims (fromIntegral anchura') (fromIntegral altura'))
=≪ readTVarIO diagramaV
pure True
void
$ onDestroy window
$ do
mainQuit
atomically $ closeTMChan chan
widgetAddEvents window [KeyPressMask]
widgetShowAll window
void $ forkIO mainGUI
let
ventana
= Ventana {..}
cerrar
= postGUISync
$ widgetDestroy window
leerTecla
= atomically
$ readTMChan chan
mostrar pasos diagrama
= postGUIAsync
$ do
atomically
∘ writeTVar diagramaV
$ renderDiagrama pasos diagrama
widgetQueueDraw drawingArea
pure ventana
renderDiagrama ∷ [Paso] → Diagrama → Diagram Cairo R2
renderDiagrama
= go ∘ pure
where
go pasos
= centerXY
∘ \ case
d1 :-: d2 → foco blue (go pasosPrimero d1) === foco red (go pasosSegundo d2)
d1 :|: d2 → foco blue (go pasosPrimero d1) ||| foco red (go pasosSegundo d2)
Hoja
Rectángulo { color = Color {..}, imagen = Imagen {..} }
→ foco yellow
$ unitSquare
# fillColor (sRGB24 rojo verde azul ∷ Colour Double)
# scaleX (fromInteger anchura)
# scaleY (fromInteger altura )
where
pasosPrimero
= case pasos of
Just (Primero:xs) → Just xs
_ → Nothing
pasosSegundo
= case pasos of
Just (Segundo:xs) → Just xs
_ → Nothing
foco color diagrama
= case pasos of
Just []
→ flip mappend (diagrama # centerXY)
∘ toRect
∘ boxExtents
$ boundingBox diagrama
_ → diagrama
where
toRect (R2 w h)
= rect w h
# fillColor (color ∷ Colour Double)
# lineColor (green ∷ Colour Double)
# lineWidth ultraThick
# opacity 0.25
| mgomezch/mosaico-lib | src/Graphics/Mosaico/Ventana.hs | bsd-3-clause | 8,806 | 2 | 19 | 2,608 | 1,630 | 940 | 690 | 156 | 6 |
module Exponent where
main = (5 ^ 4, 100 ^ 0, (-3) ^ 3 {- , 10 ^ 25 -} )
| roberth/uu-helium | test/correct/Exponent.hs | gpl-3.0 | 75 | 0 | 8 | 23 | 36 | 22 | 14 | 2 | 1 |
{-| Implementation of the Ganeti confd utilities.
This holds a few utility functions that could be useful in both
clients and servers.
-}
{-
Copyright (C) 2011, 2012 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Ganeti.Confd.Utils
( getClusterHmac
, parseSignedMessage
, parseRequest
, parseReply
, signMessage
, getCurrentTime
, extractJSONPath
) where
import qualified Data.Attoparsec.Text as P
import qualified Data.ByteString as B
import Data.Text (pack)
import qualified Text.JSON as J
import Ganeti.BasicTypes
import Ganeti.Confd.Types
import Ganeti.Hash
import qualified Ganeti.Constants as C
import qualified Ganeti.Path as Path
import Ganeti.JSON (fromJResult)
import Ganeti.Utils
-- | Type-adjusted max clock skew constant.
maxClockSkew :: Integer
maxClockSkew = fromIntegral C.confdMaxClockSkew
-- | Returns the HMAC key.
getClusterHmac :: IO HashKey
getClusterHmac = Path.confdHmacKey >>= fmap B.unpack . B.readFile
-- | Parses a signed message.
parseSignedMessage :: (J.JSON a) => HashKey -> String
-> Result (String, String, a)
parseSignedMessage key str = do
(SignedMessage hmac msg salt) <- fromJResult "parsing signed message"
$ J.decode str
parsedMsg <- if verifyMac key (Just salt) msg hmac
then fromJResult "parsing message" $ J.decode msg
else Bad "HMAC verification failed"
return (salt, msg, parsedMsg)
-- | Message parsing. This can either result in a good, valid request
-- message, or fail in the Result monad.
parseRequest :: HashKey -> String -> Integer
-> Result (String, ConfdRequest)
parseRequest hmac msg curtime = do
(salt, origmsg, request) <- parseSignedMessage hmac msg
ts <- tryRead "Parsing timestamp" salt::Result Integer
if abs (ts - curtime) > maxClockSkew
then fail "Too old/too new timestamp or clock skew"
else return (origmsg, request)
-- | Message parsing. This can either result in a good, valid reply
-- message, or fail in the Result monad.
-- It also checks that the salt in the message corresponds to the one
-- that is expected
parseReply :: HashKey -> String -> String -> Result (String, ConfdReply)
parseReply hmac msg expSalt = do
(salt, origmsg, reply) <- parseSignedMessage hmac msg
if salt /= expSalt
then fail "The received salt differs from the expected salt"
else return (origmsg, reply)
-- | Signs a message with a given key and salt.
signMessage :: HashKey -> String -> String -> SignedMessage
signMessage key salt msg =
SignedMessage { signedMsgMsg = msg
, signedMsgSalt = salt
, signedMsgHmac = hmac
}
where hmac = computeMac key (Just salt) msg
data Pointer = Pointer [String]
deriving (Show, Eq)
-- | Parse a fixed size Int.
readInteger :: String -> J.Result Int
readInteger = either J.Error J.Ok . P.parseOnly P.decimal . pack
-- | Parse a path for a JSON structure.
pointerFromString :: String -> J.Result Pointer
pointerFromString s =
either J.Error J.Ok . P.parseOnly parser $ pack s
where
parser = do
_ <- P.char '/'
tokens <- token `P.sepBy1` P.char '/'
return $ Pointer tokens
token =
P.choice [P.many1 (P.choice [ escaped
, P.satisfy $ P.notInClass "~/"])
, P.endOfInput *> return ""]
escaped = P.choice [escapedSlash, escapedTilde]
escapedSlash = P.string (pack "~1") *> return '/'
escapedTilde = P.string (pack "~0") *> return '~'
-- | Use a Pointer to access any value nested in a JSON object.
extractValue :: J.JSON a => Pointer -> a -> J.Result J.JSValue
extractValue (Pointer l) json =
getJSValue l $ J.showJSON json
where
indexWithString x (J.JSObject object) = J.valFromObj x object
indexWithString x (J.JSArray list) = do
i <- readInteger x
if 0 <= i && i < length list
then return $ list !! i
else J.Error ("list index " ++ show i ++ " out of bounds")
indexWithString _ _ = J.Error "Atomic value was indexed"
getJSValue :: [String] -> J.JSValue -> J.Result J.JSValue
getJSValue [] js = J.Ok js
getJSValue (x:xs) js = do
value <- indexWithString x js
getJSValue xs value
-- | Extract a 'JSValue' from an object at the position defined by the path.
--
-- The path syntax follows RCF6901. Error is returned if the path doesn't
-- exist, Ok if the path leads to an valid value.
--
-- JSON pointer syntax according to RFC6901:
--
-- > "/path/0/x" => Pointer ["path", "0", "x"]
--
-- This accesses 1 in the following JSON:
--
-- > { "path": { "0": { "x": 1 } } }
--
-- or the following:
--
-- > { "path": [{"x": 1}] }
extractJSONPath :: J.JSON a => String -> a -> J.Result J.JSValue
extractJSONPath path obj = do
pointer <- pointerFromString path
extractValue pointer obj
| mbakke/ganeti | src/Ganeti/Confd/Utils.hs | bsd-2-clause | 6,028 | 0 | 15 | 1,263 | 1,187 | 626 | 561 | 89 | 5 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ViewPatterns #-}
-- | Main stack tool entry point.
module Main where
import Control.Exception
import qualified Control.Exception.Lifted as EL
import Control.Monad hiding (mapM, forM)
import Control.Monad.IO.Class
import Control.Monad.Logger
import Control.Monad.Reader (ask, asks, runReaderT)
import Control.Monad.Trans.Control (MonadBaseControl)
import Data.Attoparsec.Args (withInterpreterArgs, parseArgs, EscapingMode (Escaping))
import qualified Data.ByteString.Lazy as L
import Data.IORef
import Data.List
import qualified Data.Map as Map
import qualified Data.Map.Strict as M
import Data.Maybe
import Data.Monoid
import qualified Data.Set as Set
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Data.Traversable
import Data.Typeable (Typeable)
import Data.Version (showVersion)
import Distribution.System (buildArch)
import Distribution.Text (display)
import Development.GitRev (gitCommitCount)
import GHC.IO.Encoding (mkTextEncoding, textEncodingName)
import Network.HTTP.Client
import Options.Applicative.Args
import Options.Applicative.Builder.Extra
import Options.Applicative.Simple
import Options.Applicative.Types (readerAsk)
import Path
import Path.Extra (toFilePathNoTrailingSep)
import Path.IO
import qualified Paths_stack as Meta
import Prelude hiding (pi, mapM)
import Stack.Build
import Stack.Types.Build
import Stack.Config
import Stack.Constants
import qualified Stack.Docker as Docker
import Stack.Dot
import Stack.Exec
import Stack.Fetch
import Stack.FileWatch
import Stack.Ide
import qualified Stack.Image as Image
import Stack.Init
import Stack.New
import Stack.Options
import Stack.Package (getCabalFileName)
import qualified Stack.PackageIndex
import Stack.Ghci
import Stack.GhcPkg (getGlobalDB, mkGhcPackagePath)
import Stack.SDist (getSDistTarball)
import Stack.Setup
import Stack.Solver (solveExtraDeps)
import Stack.Types
import Stack.Types.Internal
import Stack.Types.StackT
import Stack.Upgrade
import qualified Stack.Upload as Upload
import System.Directory (canonicalizePath, doesFileExist, doesDirectoryExist, createDirectoryIfMissing)
import System.Environment (getEnvironment, getProgName)
import System.Exit
import System.FileLock (lockFile, tryLockFile, unlockFile, SharedExclusive(Exclusive), FileLock)
import System.FilePath (searchPathSeparator)
import System.IO (hIsTerminalDevice, stderr, stdin, stdout, hSetBuffering, BufferMode(..), hPutStrLn, Handle, hGetEncoding, hSetEncoding)
import System.Process.Read
-- | Change the character encoding of the given Handle to transliterate
-- on unsupported characters instead of throwing an exception
hSetTranslit :: Handle -> IO ()
hSetTranslit h = do
menc <- hGetEncoding h
case fmap textEncodingName menc of
Just name
| '/' `notElem` name -> do
enc' <- mkTextEncoding $ name ++ "//TRANSLIT"
hSetEncoding h enc'
_ -> return ()
-- | Commandline dispatcher.
main :: IO ()
main = withInterpreterArgs stackProgName $ \args isInterpreter -> do
-- Line buffer the output by default, particularly for non-terminal runs.
-- See https://github.com/commercialhaskell/stack/pull/360
hSetBuffering stdout LineBuffering
hSetBuffering stdin LineBuffering
hSetBuffering stderr LineBuffering
hSetTranslit stdout
hSetTranslit stderr
progName <- getProgName
isTerminal <- hIsTerminalDevice stdout
execExtraHelp args
dockerHelpOptName
(dockerOptsParser True)
("Only showing --" ++ Docker.dockerCmdName ++ "* options.")
let versionString' = concat $ concat
[ [$(simpleVersion Meta.version)]
-- Leave out number of commits for --depth=1 clone
-- See https://github.com/commercialhaskell/stack/issues/792
, [" (" ++ $gitCommitCount ++ " commits)" | $gitCommitCount /= ("1"::String) &&
$gitCommitCount /= ("UNKNOWN" :: String)]
, [" ", display buildArch]
]
let numericVersion :: Parser (a -> a)
numericVersion =
infoOption
(showVersion Meta.version)
(long "numeric-version" <>
help "Show only version number")
eGlobalRun <- try $
simpleOptions
versionString'
"stack - The Haskell Tool Stack"
""
(numericVersion <*> extraHelpOption progName (Docker.dockerCmdName ++ "*") dockerHelpOptName <*>
globalOptsParser isTerminal)
(do addCommand "build"
"Build the project(s) in this directory/configuration"
buildCmd
(buildOptsParser Build)
addCommand "install"
"Shortcut for 'build --copy-bins'"
buildCmd
(buildOptsParser Install)
addCommand "uninstall"
"DEPRECATED: This command performs no actions, and is present for documentation only"
uninstallCmd
(many $ strArgument $ metavar "IGNORED")
addCommand "test"
"Shortcut for 'build --test'"
buildCmd
(buildOptsParser Test)
addCommand "bench"
"Shortcut for 'build --bench'"
buildCmd
(buildOptsParser Bench)
addCommand "haddock"
"Shortcut for 'build --haddock'"
buildCmd
(buildOptsParser Haddock)
addCommand "new"
"Create a new project from a template. Run `stack templates' to see available templates."
newCmd
newOptsParser
addCommand "templates"
"List the templates available for `stack new'."
templatesCmd
(pure ())
addCommand "init"
"Initialize a stack project based on one or more cabal packages"
initCmd
initOptsParser
addCommand "solver"
"Use a dependency solver to try and determine missing extra-deps"
solverCmd
solverOptsParser
addCommand "setup"
"Get the appropriate GHC for your project"
setupCmd
setupParser
addCommand "path"
"Print out handy path information"
pathCmd
(fmap
catMaybes
(sequenceA
(map
(\(desc,name,_) ->
flag Nothing
(Just name)
(long (T.unpack name) <>
help desc))
paths)))
addCommand "unpack"
"Unpack one or more packages locally"
unpackCmd
(some $ strArgument $ metavar "PACKAGE")
addCommand "update"
"Update the package index"
updateCmd
(pure ())
addCommand "upgrade"
"Upgrade to the latest stack (experimental)"
upgradeCmd
((,) <$> (switch
( long "git"
<> help "Clone from Git instead of downloading from Hackage (more dangerous)"
))
<*> (strOption
( long "git-repo"
<> help "Clone from specified git repository"
<> value "https://github.com/commercialhaskell/stack"
<> showDefault
)))
addCommand "upload"
"Upload a package to Hackage"
uploadCmd
((,)
<$> (many $ strArgument $ metavar "TARBALL/DIR")
<*> optional pvpBoundsOption)
addCommand "sdist"
"Create source distribution tarballs"
sdistCmd
((,)
<$> (many $ strArgument $ metavar "DIR")
<*> optional pvpBoundsOption)
addCommand "dot"
"Visualize your project's dependency graph using Graphviz dot"
dotCmd
dotOptsParser
addCommand "exec"
"Execute a command"
execCmd
(execOptsParser Nothing)
addCommand "ghc"
"Run ghc"
execCmd
(execOptsParser $ Just "ghc")
addCommand "ghci"
"Run ghci in the context of project(s) (experimental)"
ghciCmd
ghciOptsParser
addCommand "runghc"
"Run runghc"
execCmd
(execOptsParser $ Just "runghc")
addCommand "eval"
"Evaluate some haskell code inline. Shortcut for 'stack exec ghc -- -e CODE'"
evalCmd
(evalOptsParser $ Just "CODE") -- metavar = "CODE"
addCommand "clean"
"Clean the local packages"
cleanCmd
(pure ())
addCommand "list-dependencies"
"List the dependencies"
listDependenciesCmd
(textOption (long "separator" <>
metavar "SEP" <>
help ("Separator between package name " <>
"and package version.") <>
value " " <>
showDefault))
addCommand "query"
"Query general build information (experimental)"
queryCmd
(many $ strArgument $ metavar "SELECTOR...")
addSubCommands
"ide"
"IDE-specific commands"
(do addCommand
"start"
"Start the ide-backend service"
ideCmd
((,) <$> many (textArgument
(metavar "TARGET" <>
help ("If none specified, use all " <>
"packages defined in current directory")))
<*> argsOption (long "ghc-options" <>
metavar "OPTION" <>
help "Additional options passed to GHCi" <>
value []))
addCommand
"packages"
"List all available local loadable packages"
packagesCmd
(pure ())
addCommand
"load-targets"
"List all load targets for a package target"
targetsCmd
(textArgument
(metavar "TARGET")))
addSubCommands
Docker.dockerCmdName
"Subcommands specific to Docker use"
(do addCommand Docker.dockerPullCmdName
"Pull latest version of Docker image from registry"
dockerPullCmd
(pure ())
addCommand "reset"
"Reset the Docker sandbox"
dockerResetCmd
(switch (long "keep-home" <>
help "Do not delete sandbox's home directory"))
addCommand Docker.dockerCleanupCmdName
"Clean up Docker images and containers"
dockerCleanupCmd
dockerCleanupOptsParser)
addSubCommands
Image.imgCmdName
"Subcommands specific to imaging (EXPERIMENTAL)"
(addCommand Image.imgDockerCmdName
"Build a Docker image for the project"
imgDockerCmd
(pure ())))
case eGlobalRun of
Left (exitCode :: ExitCode) -> do
when isInterpreter $
hPutStrLn stderr $ concat
[ "\nIf you are trying to use "
, stackProgName
, " as a script interpreter, a\n'-- "
, stackProgName
, " [options] runghc [options]' comment is required."
, "\nSee https://github.com/commercialhaskell/stack/blob/release/doc/GUIDE.md#ghcrunghc" ]
throwIO exitCode
Right (global,run) -> do
when (globalLogLevel global == LevelDebug) $ hPutStrLn stderr versionString'
case globalReExecVersion global of
Just expectVersion
| expectVersion /= showVersion Meta.version ->
throwIO $ InvalidReExecVersion expectVersion (showVersion Meta.version)
_ -> return ()
run global `catch` \e -> do
-- This special handler stops "stack: " from being printed before the
-- exception
case fromException e of
Just ec -> exitWith ec
Nothing -> do
printExceptionStderr e
exitFailure
where
dockerHelpOptName = Docker.dockerCmdName ++ "-help"
-- | Print out useful path information in a human-readable format (and
-- support others later).
pathCmd :: [Text] -> GlobalOpts -> IO ()
pathCmd keys go =
withBuildConfig
go
(do env <- ask
let cfg = envConfig env
bc = envConfigBuildConfig cfg
menv <- getMinimalEnvOverride
snap <- packageDatabaseDeps
local <- packageDatabaseLocal
global <- getGlobalDB menv =<< getWhichCompiler
snaproot <- installationRootDeps
localroot <- installationRootLocal
distDir <- distRelativeDir
forM_
(filter
(\(_,key,_) ->
null keys || elem key keys)
paths)
(\(_,key,path) ->
liftIO $ T.putStrLn
((if length keys == 1
then ""
else key <> ": ") <>
path
(PathInfo
bc
menv
snap
local
global
snaproot
localroot
distDir))))
-- | Passed to all the path printers as a source of info.
data PathInfo = PathInfo
{piBuildConfig :: BuildConfig
,piEnvOverride :: EnvOverride
,piSnapDb :: Path Abs Dir
,piLocalDb :: Path Abs Dir
,piGlobalDb :: Path Abs Dir
,piSnapRoot :: Path Abs Dir
,piLocalRoot :: Path Abs Dir
,piDistDir :: Path Rel Dir
}
-- | The paths of interest to a user. The first tuple string is used
-- for a description that the optparse flag uses, and the second
-- string as a machine-readable key and also for @--foo@ flags. The user
-- can choose a specific path to list like @--global-stack-root@. But
-- really it's mainly for the documentation aspect.
--
-- When printing output we generate @PathInfo@ and pass it to the
-- function to generate an appropriate string. Trailing slashes are
-- removed, see #506
paths :: [(String, Text, PathInfo -> Text)]
paths =
[ ( "Global stack root directory"
, "global-stack-root"
, \pi ->
T.pack (toFilePathNoTrailingSep (configStackRoot (bcConfig (piBuildConfig pi)))))
, ( "Project root (derived from stack.yaml file)"
, "project-root"
, \pi ->
T.pack (toFilePathNoTrailingSep (bcRoot (piBuildConfig pi))))
, ( "Configuration location (where the stack.yaml file is)"
, "config-location"
, \pi ->
T.pack (toFilePath (bcStackYaml (piBuildConfig pi))))
, ( "PATH environment variable"
, "bin-path"
, \pi ->
T.pack (intercalate [searchPathSeparator] (eoPath (piEnvOverride pi))))
, ( "Installed GHCs (unpacked and archives)"
, "ghc-paths"
, \pi ->
T.pack (toFilePathNoTrailingSep (configLocalPrograms (bcConfig (piBuildConfig pi)))))
, ( "Local bin path where stack installs executables"
, "local-bin-path"
, \pi ->
T.pack (toFilePathNoTrailingSep (configLocalBin (bcConfig (piBuildConfig pi)))))
, ( "Extra include directories"
, "extra-include-dirs"
, \pi ->
T.intercalate
", "
(Set.elems (configExtraIncludeDirs (bcConfig (piBuildConfig pi)))))
, ( "Extra library directories"
, "extra-library-dirs"
, \pi ->
T.intercalate ", " (Set.elems (configExtraLibDirs (bcConfig (piBuildConfig pi)))))
, ( "Snapshot package database"
, "snapshot-pkg-db"
, \pi ->
T.pack (toFilePathNoTrailingSep (piSnapDb pi)))
, ( "Local project package database"
, "local-pkg-db"
, \pi ->
T.pack (toFilePathNoTrailingSep (piLocalDb pi)))
, ( "Global package database"
, "global-pkg-db"
, \pi ->
T.pack (toFilePathNoTrailingSep (piGlobalDb pi)))
, ( "GHC_PACKAGE_PATH environment variable"
, "ghc-package-path"
, \pi -> mkGhcPackagePath True (piLocalDb pi) (piSnapDb pi) (piGlobalDb pi))
, ( "Snapshot installation root"
, "snapshot-install-root"
, \pi ->
T.pack (toFilePathNoTrailingSep (piSnapRoot pi)))
, ( "Local project installation root"
, "local-install-root"
, \pi ->
T.pack (toFilePathNoTrailingSep (piLocalRoot pi)))
, ( "Snapshot documentation root"
, "snapshot-doc-root"
, \pi ->
T.pack (toFilePathNoTrailingSep (piSnapRoot pi </> docDirSuffix)))
, ( "Local project documentation root"
, "local-doc-root"
, \pi ->
T.pack (toFilePathNoTrailingSep (piLocalRoot pi </> docDirSuffix)))
, ( "Dist work directory"
, "dist-dir"
, \pi ->
T.pack (toFilePathNoTrailingSep (piDistDir pi)))]
data SetupCmdOpts = SetupCmdOpts
{ scoCompilerVersion :: !(Maybe CompilerVersion)
, scoForceReinstall :: !Bool
, scoUpgradeCabal :: !Bool
, scoStackSetupYaml :: !String
, scoGHCBindistURL :: !(Maybe String)
}
setupParser :: Parser SetupCmdOpts
setupParser = SetupCmdOpts
<$> (optional $ argument readVersion
(metavar "GHC_VERSION" <>
help ("Version of GHC to install, e.g. 7.10.2. " ++
"The default is to install the version implied by the resolver.")))
<*> boolFlags False
"reinstall"
"reinstalling GHC, even if available (implies no-system-ghc)"
idm
<*> boolFlags False
"upgrade-cabal"
"installing the newest version of the Cabal library globally"
idm
<*> strOption
( long "stack-setup-yaml"
<> help "Location of the main stack-setup.yaml file"
<> value defaultStackSetupYaml
<> showDefault
)
<*> (optional $ strOption
(long "ghc-bindist"
<> metavar "URL"
<> help "Alternate GHC binary distribution (requires custom --ghc-variant)"
))
where
readVersion = do
s <- readerAsk
case parseCompilerVersion ("ghc-" <> T.pack s) of
Nothing ->
case parseCompilerVersion (T.pack s) of
Nothing -> readerError $ "Invalid version: " ++ s
Just x -> return x
Just x -> return x
setupCmd :: SetupCmdOpts -> GlobalOpts -> IO ()
setupCmd SetupCmdOpts{..} go@GlobalOpts{..} = do
(manager,lc) <- loadConfigWithOpts go
withUserFileLock go (configStackRoot $ lcConfig lc) $ \lk ->
runStackTGlobal manager (lcConfig lc) go $
Docker.reexecWithOptionalContainer
(lcProjectRoot lc)
Nothing
(runStackLoggingTGlobal manager go $ do
(wantedCompiler, compilerCheck, mstack) <-
case scoCompilerVersion of
Just v -> return (v, MatchMinor, Nothing)
Nothing -> do
bc <- lcLoadBuildConfig lc globalResolver
return ( bcWantedCompiler bc
, configCompilerCheck (lcConfig lc)
, Just $ bcStackYaml bc
)
miniConfig <- loadMiniConfig (lcConfig lc)
mpaths <- runStackTGlobal manager miniConfig go $
ensureCompiler SetupOpts
{ soptsInstallIfMissing = True
, soptsUseSystem =
(configSystemGHC $ lcConfig lc)
&& not scoForceReinstall
, soptsWantedCompiler = wantedCompiler
, soptsCompilerCheck = compilerCheck
, soptsStackYaml = mstack
, soptsForceReinstall = scoForceReinstall
, soptsSanityCheck = True
, soptsSkipGhcCheck = False
, soptsSkipMsys = configSkipMsys $ lcConfig lc
, soptsUpgradeCabal = scoUpgradeCabal
, soptsResolveMissingGHC = Nothing
, soptsStackSetupYaml = scoStackSetupYaml
, soptsGHCBindistURL = scoGHCBindistURL
}
let compiler = case wantedCompiler of
GhcVersion _ -> "GHC"
GhcjsVersion {} -> "GHCJS"
case mpaths of
Nothing -> $logInfo $ "stack will use the " <> compiler <> " on your PATH"
Just _ -> $logInfo $ "stack will use a locally installed " <> compiler
$logInfo "For more information on paths, see 'stack path' and 'stack exec env'"
$logInfo $ "To use this " <> compiler <> " and packages outside of a project, consider using:"
$logInfo "stack ghc, stack ghci, stack runghc, or stack exec"
)
Nothing
(Just $ munlockFile lk)
-- | Unlock a lock file, if the value is Just
munlockFile :: MonadIO m => Maybe FileLock -> m ()
munlockFile Nothing = return ()
munlockFile (Just lk) = liftIO $ unlockFile lk
-- | Enforce mutual exclusion of every action running via this
-- function, on this path, on this users account.
--
-- A lock file is created inside the given directory. Currently,
-- stack uses locks per-snapshot. In the future, stack may refine
-- this to an even more fine-grain locking approach.
--
withUserFileLock :: (MonadBaseControl IO m, MonadIO m)
=> GlobalOpts
-> Path Abs Dir
-> (Maybe FileLock -> m a)
-> m a
withUserFileLock go@GlobalOpts{} dir act = do
env <- liftIO getEnvironment
let toLock = lookup "STACK_LOCK" env == Just "true"
if toLock
then do
let lockfile = $(mkRelFile "lockfile")
let pth = dir </> lockfile
liftIO $ createDirectoryIfMissing True (toFilePath dir)
-- Just in case of asynchronous exceptions, we need to be careful
-- when using tryLockFile here:
EL.bracket (liftIO $ tryLockFile (toFilePath pth) Exclusive)
(\fstTry -> maybe (return ()) (liftIO . unlockFile) fstTry)
(\fstTry ->
case fstTry of
Just lk -> EL.finally (act $ Just lk) (liftIO $ unlockFile lk)
Nothing ->
do let chatter = globalLogLevel go /= LevelOther "silent"
when chatter $
liftIO $ hPutStrLn stderr $ "Failed to grab lock ("++show pth++
"); other stack instance running. Waiting..."
EL.bracket (liftIO $ lockFile (toFilePath pth) Exclusive)
(liftIO . unlockFile)
(\lk -> do
when chatter $
liftIO $ hPutStrLn stderr "Lock acquired, proceeding."
act $ Just lk))
else act Nothing
withConfigAndLock :: GlobalOpts
-> StackT Config IO ()
-> IO ()
withConfigAndLock go@GlobalOpts{..} inner = do
(manager, lc) <- loadConfigWithOpts go
withUserFileLock go (configStackRoot $ lcConfig lc) $ \lk ->
runStackTGlobal manager (lcConfig lc) go $
Docker.reexecWithOptionalContainer (lcProjectRoot lc)
Nothing
(runStackTGlobal manager (lcConfig lc) go inner)
Nothing
(Just $ munlockFile lk)
-- For now the non-locking version just unlocks immediately.
-- That is, there's still a serialization point.
withBuildConfig :: GlobalOpts
-> (StackT EnvConfig IO ())
-> IO ()
withBuildConfig go inner =
withBuildConfigAndLock go (\lk -> do munlockFile lk
inner)
withBuildConfigAndLock :: GlobalOpts
-> (Maybe FileLock -> StackT EnvConfig IO ())
-> IO ()
withBuildConfigAndLock go inner =
withBuildConfigExt go Nothing inner Nothing
withBuildConfigExt
:: GlobalOpts
-> Maybe (StackT Config IO ())
-- ^ Action to perform after before build. This will be run on the host
-- OS even if Docker is enabled for builds. The build config is not
-- available in this action, since that would require build tools to be
-- installed on the host OS.
-> (Maybe FileLock -> StackT EnvConfig IO ())
-- ^ Action that uses the build config. If Docker is enabled for builds,
-- this will be run in a Docker container.
-> Maybe (StackT Config IO ())
-- ^ Action to perform after the build. This will be run on the host
-- OS even if Docker is enabled for builds. The build config is not
-- available in this action, since that would require build tools to be
-- installed on the host OS.
-> IO ()
withBuildConfigExt go@GlobalOpts{..} mbefore inner mafter = do
(manager, lc) <- loadConfigWithOpts go
withUserFileLock go (configStackRoot $ lcConfig lc) $ \lk0 -> do
-- A local bit of state for communication between callbacks:
curLk <- newIORef lk0
let inner' lk =
-- Locking policy: This is only used for build commands, which
-- only need to lock the snapshot, not the global lock. We
-- trade in the lock here.
do dir <- installationRootDeps
-- Hand-over-hand locking:
withUserFileLock go dir $ \lk2 -> do
liftIO $ writeIORef curLk lk2
liftIO $ munlockFile lk
inner lk2
let inner'' lk = do
bconfig <- runStackLoggingTGlobal manager go $
lcLoadBuildConfig lc globalResolver
envConfig <-
runStackTGlobal
manager bconfig go
(setupEnv Nothing)
runStackTGlobal
manager
envConfig
go
(inner' lk)
runStackTGlobal manager (lcConfig lc) go $
Docker.reexecWithOptionalContainer (lcProjectRoot lc) mbefore (inner'' lk0) mafter
(Just $ liftIO $
do lk' <- readIORef curLk
munlockFile lk')
cleanCmd :: () -> GlobalOpts -> IO ()
cleanCmd () go = withBuildConfigAndLock go (\_ -> clean)
-- | Helper for build and install commands
buildCmd :: BuildOpts -> GlobalOpts -> IO ()
buildCmd opts go = do
when (any (("-prof" `elem`) . either (const []) id . parseArgs Escaping) (boptsGhcOptions opts)) $ do
hPutStrLn stderr "When building with stack, you should not use the -prof GHC option"
hPutStrLn stderr "Instead, please use --enable-library-profiling and --enable-executable-profiling"
hPutStrLn stderr "See: https://github.com/commercialhaskell/stack/issues/1015"
error "-prof GHC option submitted"
case boptsFileWatch opts of
FileWatchPoll -> fileWatchPoll inner
FileWatch -> fileWatch inner
NoFileWatch -> inner $ const $ return ()
where
inner setLocalFiles = withBuildConfigAndLock go $ \lk ->
Stack.Build.build setLocalFiles lk opts
uninstallCmd :: [String] -> GlobalOpts -> IO ()
uninstallCmd _ go = withConfigAndLock go $ do
$logError "stack does not manage installations in global locations"
$logError "The only global mutation stack performs is executable copying"
$logError "For the default executable destination, please run 'stack path --local-bin-path'"
-- | Unpack packages to the filesystem
unpackCmd :: [String] -> GlobalOpts -> IO ()
unpackCmd names go = withConfigAndLock go $ do
menv <- getMinimalEnvOverride
Stack.Fetch.unpackPackages menv "." names
-- | Update the package index
updateCmd :: () -> GlobalOpts -> IO ()
updateCmd () go = withConfigAndLock go $
getMinimalEnvOverride >>= Stack.PackageIndex.updateAllIndices
upgradeCmd :: (Bool, String) -> GlobalOpts -> IO ()
upgradeCmd (fromGit, repo) go = withConfigAndLock go $
upgrade (if fromGit then Just repo else Nothing) (globalResolver go)
-- | Upload to Hackage
uploadCmd :: ([String], Maybe PvpBounds) -> GlobalOpts -> IO ()
uploadCmd ([], _) _ = error "To upload the current package, please run 'stack upload .'"
uploadCmd (args, mpvpBounds) go = do
let partitionM _ [] = return ([], [])
partitionM f (x:xs) = do
r <- f x
(as, bs) <- partitionM f xs
return $ if r then (x:as, bs) else (as, x:bs)
(files, nonFiles) <- partitionM doesFileExist args
(dirs, invalid) <- partitionM doesDirectoryExist nonFiles
when (not (null invalid)) $ error $
"stack upload expects a list sdist tarballs or cabal directories. Can't find " ++
show invalid
let getUploader :: (HasStackRoot config, HasPlatform config, HasConfig config) => StackT config IO Upload.Uploader
getUploader = do
config <- asks getConfig
manager <- asks envManager
let uploadSettings =
Upload.setGetManager (return manager) $
Upload.defaultUploadSettings
liftIO $ Upload.mkUploader config uploadSettings
if null dirs
then withConfigAndLock go $ do
uploader <- getUploader
liftIO $ forM_ files (canonicalizePath >=> Upload.upload uploader)
else withBuildConfigAndLock go $ \_ -> do
uploader <- getUploader
liftIO $ forM_ files (canonicalizePath >=> Upload.upload uploader)
forM_ dirs $ \dir -> do
pkgDir <- parseAbsDir =<< liftIO (canonicalizePath dir)
(tarName, tarBytes) <- getSDistTarball mpvpBounds pkgDir
liftIO $ Upload.uploadBytes uploader tarName tarBytes
sdistCmd :: ([String], Maybe PvpBounds) -> GlobalOpts -> IO ()
sdistCmd (dirs, mpvpBounds) go =
withBuildConfig go $ do -- No locking needed.
-- If no directories are specified, build all sdist tarballs.
dirs' <- if null dirs
then asks (Map.keys . envConfigPackages . getEnvConfig)
else mapM (parseAbsDir <=< liftIO . canonicalizePath) dirs
forM_ dirs' $ \dir -> do
(tarName, tarBytes) <- getSDistTarball mpvpBounds dir
distDir <- distDirFromDir dir
tarPath <- fmap (distDir </>) $ parseRelFile tarName
liftIO $ createTree $ parent tarPath
liftIO $ L.writeFile (toFilePath tarPath) tarBytes
$logInfo $ "Wrote sdist tarball to " <> T.pack (toFilePath tarPath)
-- | Execute a command.
execCmd :: ExecOpts -> GlobalOpts -> IO ()
execCmd ExecOpts {..} go@GlobalOpts{..} = do
(cmd, args) <-
case (eoCmd, eoArgs) of
(Just cmd, args) -> return (cmd, args)
(Nothing, cmd:args) -> return (cmd, args)
(Nothing, []) -> error "You must provide a command to exec, e.g. 'stack exec echo Hello World'"
case eoExtra of
ExecOptsPlain -> do
(manager,lc) <- liftIO $ loadConfigWithOpts go
withUserFileLock go (configStackRoot $ lcConfig lc) $ \lk ->
runStackTGlobal manager (lcConfig lc) go $
Docker.execWithOptionalContainer
(lcProjectRoot lc)
(\_ _ -> return (cmd, args, [], []))
-- Unlock before transferring control away, whether using docker or not:
(Just $ munlockFile lk)
(runStackTGlobal manager (lcConfig lc) go $ do
exec plainEnvSettings cmd args)
Nothing
Nothing -- Unlocked already above.
ExecOptsEmbellished {..} ->
withBuildConfigAndLock go $ \lk -> do
let targets = concatMap words eoPackages
unless (null targets) $
Stack.Build.build (const $ return ()) lk defaultBuildOpts
{ boptsTargets = map T.pack targets
}
munlockFile lk -- Unlock before transferring control away.
exec eoEnvSettings cmd args
-- | Evaluate some haskell code inline.
evalCmd :: EvalOpts -> GlobalOpts -> IO ()
evalCmd EvalOpts {..} go@GlobalOpts {..} = execCmd execOpts go
where
execOpts =
ExecOpts { eoCmd = Just "ghc"
, eoArgs = ["-e", evalArg]
, eoExtra = evalExtra
}
-- | Run GHCi in the context of a project.
ghciCmd :: GhciOpts -> GlobalOpts -> IO ()
ghciCmd ghciOpts go@GlobalOpts{..} =
withBuildConfigAndLock go $ \lk -> do
let packageTargets = concatMap words (ghciAdditionalPackages ghciOpts)
unless (null packageTargets) $
Stack.Build.build (const $ return ()) lk defaultBuildOpts
{ boptsTargets = map T.pack packageTargets
}
munlockFile lk -- Don't hold the lock while in the GHCI.
ghci ghciOpts
-- | Run ide-backend in the context of a project.
ideCmd :: ([Text], [String]) -> GlobalOpts -> IO ()
ideCmd (targets,args) go@GlobalOpts{..} =
withBuildConfig go $ -- No locking needed.
ide targets args
-- | List packages in the project.
packagesCmd :: () -> GlobalOpts -> IO ()
packagesCmd () go@GlobalOpts{..} =
withBuildConfig go $
do econfig <- asks getEnvConfig
locals <-
forM (M.toList (envConfigPackages econfig)) $
\(dir,_) ->
do cabalfp <- getCabalFileName dir
parsePackageNameFromFilePath cabalfp
forM_ locals (liftIO . putStrLn . packageNameString)
-- | List load targets for a package target.
targetsCmd :: Text -> GlobalOpts -> IO ()
targetsCmd target go@GlobalOpts{..} =
withBuildConfig go $
do (_realTargets,_,pkgs) <- ghciSetup Nothing [target]
pwd <- getWorkingDir
targets <-
fmap
(concat . snd . unzip)
(mapM (getPackageOptsAndTargetFiles pwd) pkgs)
forM_ targets (liftIO . putStrLn)
-- | Pull the current Docker image.
dockerPullCmd :: () -> GlobalOpts -> IO ()
dockerPullCmd _ go@GlobalOpts{..} = do
(manager,lc) <- liftIO $ loadConfigWithOpts go
-- TODO: can we eliminate this lock if it doesn't touch ~/.stack/?
withUserFileLock go (configStackRoot $ lcConfig lc) $ \_ ->
runStackTGlobal manager (lcConfig lc) go $
Docker.preventInContainer Docker.pull
-- | Reset the Docker sandbox.
dockerResetCmd :: Bool -> GlobalOpts -> IO ()
dockerResetCmd keepHome go@GlobalOpts{..} = do
(manager,lc) <- liftIO (loadConfigWithOpts go)
-- TODO: can we eliminate this lock if it doesn't touch ~/.stack/?
withUserFileLock go (configStackRoot $ lcConfig lc) $ \_ ->
runStackLoggingTGlobal manager go $
Docker.preventInContainer $ Docker.reset (lcProjectRoot lc) keepHome
-- | Cleanup Docker images and containers.
dockerCleanupCmd :: Docker.CleanupOpts -> GlobalOpts -> IO ()
dockerCleanupCmd cleanupOpts go@GlobalOpts{..} = do
(manager,lc) <- liftIO $ loadConfigWithOpts go
-- TODO: can we eliminate this lock if it doesn't touch ~/.stack/?
withUserFileLock go (configStackRoot $ lcConfig lc) $ \_ ->
runStackTGlobal manager (lcConfig lc) go $
Docker.preventInContainer $
Docker.cleanup cleanupOpts
imgDockerCmd :: () -> GlobalOpts -> IO ()
imgDockerCmd () go@GlobalOpts{..} = do
withBuildConfigExt
go
Nothing
(\lk ->
do Stack.Build.build
(const (return ()))
lk
defaultBuildOpts
Image.stageContainerImageArtifacts)
(Just Image.createContainerImageFromStage)
-- | Load the configuration with a manager. Convenience function used
-- throughout this module.
loadConfigWithOpts :: GlobalOpts -> IO (Manager,LoadConfig (StackLoggingT IO))
loadConfigWithOpts go@GlobalOpts{..} = do
manager <- newTLSManager
mstackYaml <-
case globalStackYaml of
Nothing -> return Nothing
Just fp -> do
path <- canonicalizePath fp >>= parseAbsFile
return $ Just path
lc <- runStackLoggingTGlobal
manager
go
(loadConfig globalConfigMonoid mstackYaml)
return (manager,lc)
-- | Project initialization
initCmd :: InitOpts -> GlobalOpts -> IO ()
initCmd initOpts go =
withConfigAndLock go $
do pwd <- getWorkingDir
config <- asks getConfig
miniConfig <- loadMiniConfig config
runReaderT (initProject pwd initOpts) miniConfig
-- | Create a project directory structure and initialize the stack config.
newCmd :: (NewOpts,InitOpts) -> GlobalOpts -> IO ()
newCmd (newOpts,initOpts) go@GlobalOpts{..} =
withConfigAndLock go $
do dir <- new newOpts
config <- asks getConfig
miniConfig <- loadMiniConfig config
runReaderT (initProject dir initOpts) miniConfig
-- | List the available templates.
templatesCmd :: () -> GlobalOpts -> IO ()
templatesCmd _ go@GlobalOpts{..} = withConfigAndLock go listTemplates
-- | Fix up extra-deps for a project
solverCmd :: Bool -- ^ modify stack.yaml automatically?
-> GlobalOpts
-> IO ()
solverCmd fixStackYaml go =
withBuildConfigAndLock go (\_ -> solveExtraDeps fixStackYaml)
-- | Visualize dependencies
dotCmd :: DotOpts -> GlobalOpts -> IO ()
dotCmd dotOpts go = withBuildConfigAndLock go (\_ -> dot dotOpts)
-- | List the dependencies
listDependenciesCmd :: Text -> GlobalOpts -> IO ()
listDependenciesCmd sep go = withBuildConfig go (listDependencies sep')
where sep' = T.replace "\\t" "\t" (T.replace "\\n" "\n" sep)
-- | Query build information
queryCmd :: [String] -> GlobalOpts -> IO ()
queryCmd selectors go = withBuildConfig go $ queryBuildInfo $ map T.pack selectors
data MainException = InvalidReExecVersion String String
deriving (Typeable)
instance Exception MainException
instance Show MainException where
show (InvalidReExecVersion expected actual) = concat
[ "When re-executing '"
, stackProgName
, "' in a container, the incorrect version was found\nExpected: "
, expected
, "; found: "
, actual]
| lukexi/stack | src/main/Main.hs | bsd-3-clause | 41,959 | 0 | 30 | 15,594 | 8,431 | 4,276 | 4,155 | -1 | -1 |
foo x y =
do c <- getChar
return c
| mpickering/ghc-exactprint | tests/examples/transform/Rename1.hs | bsd-3-clause | 47 | 1 | 7 | 22 | 28 | 10 | 18 | 3 | 1 |
module Main
( main
) where
import Test.Framework
import qualified UnitTests.Distribution.Compat.ReadP
tests :: [Test]
tests = [
testGroup "Distribution.Compat.ReadP"
UnitTests.Distribution.Compat.ReadP.tests
]
main :: IO ()
main = defaultMain tests
| jwiegley/ghc-release | libraries/Cabal/cabal/tests/UnitTests.hs | gpl-3.0 | 277 | 0 | 7 | 57 | 66 | 40 | 26 | 10 | 1 |
module Dotnet.System.Xml.XmlNodeList where
import Dotnet
import qualified Dotnet.System.Object
import Dotnet.System.Collections.IEnumerator
import Dotnet.System.Xml.XmlNodeTy
data XmlNodeList_ a
type XmlNodeList a = Dotnet.System.Object.Object (XmlNodeList_ a)
foreign import dotnet
"method Dotnet.System.Xml.XmlNodeList.GetEnumerator"
getEnumerator :: XmlNodeList obj -> IO (Dotnet.System.Collections.IEnumerator.IEnumerator a0)
foreign import dotnet
"method Dotnet.System.Xml.XmlNodeList.get_ItemOf"
get_ItemOf :: Int -> XmlNodeList obj -> IO (Dotnet.System.Xml.XmlNodeTy.XmlNode a1)
foreign import dotnet
"method Dotnet.System.Xml.XmlNodeList.get_Count"
get_Count :: XmlNodeList obj -> IO (Int)
foreign import dotnet
"method Dotnet.System.Xml.XmlNodeList.Item"
item :: Int -> XmlNodeList obj -> IO (Dotnet.System.Xml.XmlNodeTy.XmlNode a1)
| FranklinChen/Hugs | dotnet/lib/Dotnet/System/Xml/XmlNodeList.hs | bsd-3-clause | 866 | 0 | 11 | 101 | 188 | 109 | 79 | -1 | -1 |
{-# LANGUAGE OverloadedStrings, BangPatterns #-}
{-# LANGUAGE CPP #-}
-- |
-- Module : Crypto.PasswordStore
-- Copyright : (c) Peter Scott, 2011
-- License : BSD-style
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- Securely store hashed, salted passwords. If you need to store and verify
-- passwords, there are many wrong ways to do it, most of them all too
-- common. Some people store users' passwords in plain text. Then, when an
-- attacker manages to get their hands on this file, they have the passwords for
-- every user's account. One step up, but still wrong, is to simply hash all
-- passwords with SHA1 or something. This is vulnerable to rainbow table and
-- dictionary attacks. One step up from that is to hash the password along with
-- a unique salt value. This is vulnerable to dictionary attacks, since guessing
-- a password is very fast. The right thing to do is to use a slow hash
-- function, to add some small but significant delay, that will be negligible
-- for legitimate users but prohibitively expensive for someone trying to guess
-- passwords by brute force. That is what this library does. It iterates a
-- SHA256 hash, with a random salt, a few thousand times. This scheme is known
-- as PBKDF1, and is generally considered secure; there is nothing innovative
-- happening here.
--
-- The API here is very simple. What you store are called /password hashes/.
-- They are strings (technically, ByteStrings) that look like this:
--
-- > "sha256|14|jEWU94phx4QzNyH94Qp4CQ==|5GEw+jxP/4WLgzt9VS3Ee3nhqBlDsrKiB+rq7JfMckU="
--
-- Each password hash shows the algorithm, the strength (more on that later),
-- the salt, and the hashed-and-salted password. You store these on your server,
-- in a database, for when you need to verify a password. You make a password
-- hash with the 'makePassword' function. Here's an example:
--
-- > >>> makePassword "hunter2" 14
-- > "sha256|14|Zo4LdZGrv/HYNAUG3q8WcA==|zKjbHZoTpuPLp1lh6ATolWGIKjhXvY4TysuKvqtNFyk="
--
-- This will hash the password @\"hunter2\"@, with strength 14, which is a good
-- default value. The strength here determines how long the hashing will
-- take. When doing the hashing, we iterate the SHA256 hash function
-- @2^strength@ times, so increasing the strength by 1 makes the hashing take
-- twice as long. When computers get faster, you can bump up the strength a
-- little bit to compensate. You can strengthen existing password hashes with
-- the 'strengthenPassword' function. Note that 'makePassword' needs to generate
-- random numbers, so its return type is 'IO' 'ByteString'. If you want to avoid
-- the 'IO' monad, you can generate your own salt and pass it to
-- 'makePasswordSalt'.
--
-- Your strength value should not be less than 12, and 14 is a good default
-- value at the time of this writing, in 2013.
--
-- Once you've got your password hashes, the second big thing you need to do
-- with them is verify passwords against them. When a user gives you a password,
-- you compare it with a password hash using the 'verifyPassword' function:
--
-- > >>> verifyPassword "wrong guess" passwordHash
-- > False
-- > >>> verifyPassword "hunter2" passwordHash
-- > True
--
-- These two functions are really all you need. If you want to make existing
-- password hashes stronger, you can use 'strengthenPassword'. Just pass it an
-- existing password hash and a new strength value, and it will return a new
-- password hash with that strength value, which will match the same password as
-- the old password hash.
--
-- Note that, as of version 2.4, you can also use PBKDF2, and specify the exact
-- iteration count. This does not have a significant effect on security, but can
-- be handy for compatibility with other code.
module Yesod.PasswordStore (
-- * Algorithms
pbkdf1, -- :: ByteString -> Salt -> Int -> ByteString
pbkdf2, -- :: ByteString -> Salt -> Int -> ByteString
-- * Registering and verifying passwords
makePassword, -- :: ByteString -> Int -> IO ByteString
makePasswordWith, -- :: (ByteString -> Salt -> Int -> ByteString) ->
-- ByteString -> Int -> IO ByteString
makePasswordSalt, -- :: ByteString -> ByteString -> Int -> ByteString
makePasswordSaltWith, -- :: (ByteString -> Salt -> Int -> ByteString) ->
-- ByteString -> Salt -> Int -> ByteString
verifyPassword, -- :: ByteString -> ByteString -> Bool
verifyPasswordWith, -- :: (ByteString -> Salt -> Int -> ByteString) ->
-- (Int -> Int) -> ByteString -> ByteString -> Bool
-- * Updating password hash strength
strengthenPassword, -- :: ByteString -> Int -> ByteString
passwordStrength, -- :: ByteString -> Int
-- * Utilities
Salt,
isPasswordFormatValid, -- :: ByteString -> Bool
genSaltIO, -- :: IO Salt
genSaltRandom, -- :: (RandomGen b) => b -> (Salt, b)
makeSalt, -- :: ByteString -> Salt
exportSalt, -- :: Salt -> ByteString
importSalt -- :: ByteString -> Salt
) where
import qualified Crypto.Hash as CH
import qualified Crypto.Hash.SHA256 as H
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as BL
import qualified Data.Binary as Binary
import Control.Monad
import Control.Monad.ST
import Data.Byteable (toBytes)
import Data.STRef
import Data.Bits
import Data.ByteString.Char8 (ByteString)
import Data.ByteString.Base64 (encode, decodeLenient)
import System.IO
import System.Random
import Data.Maybe
import qualified Control.Exception
---------------------
-- Cryptographic base
---------------------
-- | PBKDF1 key-derivation function. Takes a password, a 'Salt', and a number of
-- iterations. The number of iterations should be at least 1000, and probably
-- more. 5000 is a reasonable number, computing almost instantaneously. This
-- will give a 32-byte 'ByteString' as output. Both the salt and this 32-byte
-- key should be stored in the password file. When a user wishes to authenticate
-- a password, just pass it and the salt to this function, and see if the output
-- matches.
pbkdf1 :: ByteString -> Salt -> Int -> ByteString
pbkdf1 password (SaltBS salt) iter = hashRounds first_hash (iter + 1)
where first_hash = H.finalize $ H.init `H.update` password `H.update` salt
-- | Hash a 'ByteString' for a given number of rounds. The number of rounds is 0
-- or more. If the number of rounds specified is 0, the ByteString will be
-- returned unmodified.
hashRounds :: ByteString -> Int -> ByteString
hashRounds (!bs) 0 = bs
hashRounds bs rounds = hashRounds (H.hash bs) (rounds - 1)
-- | Computes the hmacSHA256 of the given message, with the given 'Salt'.
hmacSHA256 :: ByteString
-- ^ The secret (the salt)
-> ByteString
-- ^ The clear-text message
-> ByteString
-- ^ The encoded message
hmacSHA256 secret msg =
toBytes (CH.hmacGetDigest (CH.hmac secret msg) :: CH.Digest CH.SHA256)
-- | PBKDF2 key-derivation function.
-- For details see @http://tools.ietf.org/html/rfc2898@.
-- @32@ is the most common digest size for @SHA256@, and is
-- what the algorithm internally uses.
-- @HMAC+SHA256@ is used as @PRF@, because @HMAC+SHA1@ is considered too weak.
pbkdf2 :: ByteString -> Salt -> Int -> ByteString
pbkdf2 password (SaltBS salt) c =
let hLen = 32
dkLen = hLen in go hLen dkLen
where
go hLen dkLen | dkLen > (2^32 - 1) * hLen = error "Derived key too long."
| otherwise =
let !l = ceiling ((fromIntegral dkLen / fromIntegral hLen) :: Double)
!r = dkLen - (l - 1) * hLen
chunks = [f i | i <- [1 .. l]]
in (B.concat . init $ chunks) `B.append` B.take r (last chunks)
-- The @f@ function, as defined in the spec.
-- It calls 'u' under the hood.
f :: Int -> ByteString
f i = let !u1 = hmacSHA256 password (salt `B.append` int i)
-- Using the ST Monad, for maximum performance.
in runST $ do
u <- newSTRef u1
accum <- newSTRef u1
forM_ [2 .. c] $ \_ -> do
modifySTRef' u (hmacSHA256 password)
currentU <- readSTRef u
modifySTRef' accum (`xor'` currentU)
readSTRef accum
-- int(i), as defined in the spec.
int :: Int -> ByteString
int i = let str = BL.unpack . Binary.encode $ i
in BS.pack $ drop (length str - 4) str
-- | A convenience function to XOR two 'ByteString' together.
xor' :: ByteString -> ByteString -> ByteString
xor' !b1 !b2 = BS.pack $ BS.zipWith xor b1 b2
-- | Generate a 'Salt' from 128 bits of data from @\/dev\/urandom@, with the
-- system RNG as a fallback. This is the function used to generate salts by
-- 'makePassword'.
genSaltIO :: IO Salt
genSaltIO =
Control.Exception.catch genSaltDevURandom def
where
def :: IOError -> IO Salt
def _ = genSaltSysRandom
-- | Generate a 'Salt' from @\/dev\/urandom@.
genSaltDevURandom :: IO Salt
genSaltDevURandom = withFile "/dev/urandom" ReadMode $ \h -> do
rawSalt <- B.hGet h 16
return $ makeSalt rawSalt
-- | Generate a 'Salt' from 'System.Random'.
genSaltSysRandom :: IO Salt
genSaltSysRandom = randomChars >>= return . makeSalt . B.pack
where randomChars = sequence $ replicate 16 $ randomRIO ('\NUL', '\255')
-----------------------
-- Password hash format
-----------------------
-- Format: "sha256|strength|salt|hash", where strength is an unsigned int, salt
-- is a base64-encoded 16-byte random number, and hash is a base64-encoded hash
-- value.
-- | Try to parse a password hash.
readPwHash :: ByteString -> Maybe (Int, Salt, ByteString)
readPwHash pw | length broken /= 4
|| algorithm /= "sha256"
|| B.length hash /= 44 = Nothing
| otherwise = case B.readInt strBS of
Just (strength, _) -> Just (strength, SaltBS salt, hash)
Nothing -> Nothing
where broken = B.split '|' pw
[algorithm, strBS, salt, hash] = broken
-- | Encode a password hash, from a @(strength, salt, hash)@ tuple, where
-- strength is an 'Int', and both @salt@ and @hash@ are base64-encoded
-- 'ByteString's.
writePwHash :: (Int, Salt, ByteString) -> ByteString
writePwHash (strength, SaltBS salt, hash) =
B.intercalate "|" ["sha256", B.pack (show strength), salt, hash]
-----------------
-- High level API
-----------------
-- | Hash a password with a given strength (14 is a good default). The output of
-- this function can be written directly to a password file or
-- database. Generates a salt using high-quality randomness from
-- @\/dev\/urandom@ or (if that is not available, for example on Windows)
-- 'System.Random', which is included in the hashed output.
makePassword :: ByteString -> Int -> IO ByteString
makePassword = makePasswordWith pbkdf1
-- | A generic version of 'makePassword', which allow the user
-- to choose the algorithm to use.
--
-- >>> makePasswordWith pbkdf1 "password" 14
--
makePasswordWith :: (ByteString -> Salt -> Int -> ByteString)
-- ^ The algorithm to use (e.g. pbkdf1)
-> ByteString
-- ^ The password to encrypt
-> Int
-- ^ log2 of the number of iterations
-> IO ByteString
makePasswordWith algorithm password strength = do
salt <- genSaltIO
return $ makePasswordSaltWith algorithm (2^) password salt strength
-- | A generic version of 'makePasswordSalt', meant to give the user
-- the maximum control over the generation parameters.
-- Note that, unlike 'makePasswordWith', this function takes the @raw@
-- number of iterations. This means the user will need to specify a
-- sensible value, typically @10000@ or @20000@.
makePasswordSaltWith :: (ByteString -> Salt -> Int -> ByteString)
-- ^ A function modeling an algorithm (e.g. 'pbkdf1')
-> (Int -> Int)
-- ^ A function to modify the strength
-> ByteString
-- ^ A password, given as clear text
-> Salt
-- ^ A hash 'Salt'
-> Int
-- ^ The password strength (e.g. @10000, 20000, etc.@)
-> ByteString
makePasswordSaltWith algorithm strengthModifier pwd salt strength = writePwHash (strength, salt, hash)
where hash = encode $ algorithm pwd salt (strengthModifier strength)
-- | Hash a password with a given strength (14 is a good default), using a given
-- salt. The output of this function can be written directly to a password file
-- or database. Example:
--
-- > >>> makePasswordSalt "hunter2" (makeSalt "72cd18b5ebfe6e96") 14
-- > "sha256|14|NzJjZDE4YjVlYmZlNmU5Ng==|yuiNrZW3KHX+pd0sWy9NTTsy5Yopmtx4UYscItSsoxc="
makePasswordSalt :: ByteString -> Salt -> Int -> ByteString
makePasswordSalt = makePasswordSaltWith pbkdf1 (2^)
-- | 'verifyPasswordWith' @algorithm userInput pwHash@ verifies
-- the password @userInput@ given by the user against the stored password
-- hash @pwHash@, with the hashing algorithm @algorithm@. Returns 'True' if the
-- given password is correct, and 'False' if it is not.
-- This function allows the programmer to specify the algorithm to use,
-- e.g. 'pbkdf1' or 'pbkdf2'.
-- Note: If you want to verify a password previously generated with
-- 'makePasswordSaltWith', but without modifying the number of iterations,
-- you can do:
--
-- > >>> verifyPasswordWith pbkdf2 id "hunter2" "sha256..."
-- > True
--
verifyPasswordWith :: (ByteString -> Salt -> Int -> ByteString)
-- ^ A function modeling an algorithm (e.g. pbkdf1)
-> (Int -> Int)
-- ^ A function to modify the strength
-> ByteString
-- ^ User password
-> ByteString
-- ^ The generated hash (e.g. sha256|14...)
-> Bool
verifyPasswordWith algorithm strengthModifier userInput pwHash =
case readPwHash pwHash of
Nothing -> False
Just (strength, salt, goodHash) ->
encode (algorithm userInput salt (strengthModifier strength)) == goodHash
-- | Like 'verifyPasswordWith', but uses 'pbkdf1' as algorithm.
verifyPassword :: ByteString -> ByteString -> Bool
verifyPassword = verifyPasswordWith pbkdf1 (2^)
-- | Try to strengthen a password hash, by hashing it some more
-- times. @'strengthenPassword' pwHash new_strength@ will return a new password
-- hash with strength at least @new_strength@. If the password hash already has
-- strength greater than or equal to @new_strength@, then it is returned
-- unmodified. If the password hash is invalid and does not parse, it will be
-- returned without comment.
--
-- This function can be used to periodically update your password database when
-- computers get faster, in order to keep up with Moore's law. This isn't hugely
-- important, but it's a good idea.
strengthenPassword :: ByteString -> Int -> ByteString
strengthenPassword pwHash newstr =
case readPwHash pwHash of
Nothing -> pwHash
Just (oldstr, salt, hashB64) ->
if oldstr < newstr then
writePwHash (newstr, salt, newHash)
else
pwHash
where newHash = encode $ hashRounds hash extraRounds
extraRounds = (2^newstr) - (2^oldstr)
hash = decodeLenient hashB64
-- | Return the strength of a password hash.
passwordStrength :: ByteString -> Int
passwordStrength pwHash = case readPwHash pwHash of
Nothing -> 0
Just (strength, _, _) -> strength
------------
-- Utilities
------------
-- | A salt is a unique random value which is stored as part of the password
-- hash. You can generate a salt with 'genSaltIO' or 'genSaltRandom', or if you
-- really know what you're doing, you can create them from your own ByteString
-- values with 'makeSalt'.
newtype Salt = SaltBS ByteString
deriving (Show, Eq, Ord)
-- | Create a 'Salt' from a 'ByteString'. The input must be at least 8
-- characters, and can contain arbitrary bytes. Most users will not need to use
-- this function.
makeSalt :: ByteString -> Salt
makeSalt = SaltBS . encode . check_length
where check_length salt | B.length salt < 8 =
error "Salt too short. Minimum length is 8 characters."
| otherwise = salt
-- | Convert a 'Salt' into a 'ByteString'. The resulting 'ByteString' will be
-- base64-encoded. Most users will not need to use this function.
exportSalt :: Salt -> ByteString
exportSalt (SaltBS bs) = bs
-- | Convert a raw 'ByteString' into a 'Salt'.
-- Use this function with caution, since using a weak salt will result in a
-- weak password.
importSalt :: ByteString -> Salt
importSalt = SaltBS
-- | Is the format of a password hash valid? Attempts to parse a given password
-- hash. Returns 'True' if it parses correctly, and 'False' otherwise.
isPasswordFormatValid :: ByteString -> Bool
isPasswordFormatValid = isJust . readPwHash
-- | Generate a 'Salt' with 128 bits of data taken from a given random number
-- generator. Returns the salt and the updated random number generator. This is
-- meant to be used with 'makePasswordSalt' by people who would prefer to either
-- use their own random number generator or avoid the 'IO' monad.
genSaltRandom :: (RandomGen b) => b -> (Salt, b)
genSaltRandom gen = (salt, newgen)
where rands _ 0 = []
rands g n = (a, g') : rands g' (n-1 :: Int)
where (a, g') = randomR ('\NUL', '\255') g
salt = makeSalt $ B.pack $ map fst (rands gen 16)
newgen = snd $ last (rands gen 16)
#if !MIN_VERSION_base(4, 6, 0)
-- | Strict version of 'modifySTRef'
modifySTRef' :: STRef s a -> (a -> a) -> ST s ()
modifySTRef' ref f = do
x <- readSTRef ref
let x' = f x
x' `seq` writeSTRef ref x'
#endif
#if MIN_VERSION_bytestring(0, 10, 0)
toStrict :: BL.ByteString -> BS.ByteString
toStrict = BL.toStrict
fromStrict :: BS.ByteString -> BL.ByteString
fromStrict = BL.fromStrict
#else
toStrict :: BL.ByteString -> BS.ByteString
toStrict = BS.concat . BL.toChunks
fromStrict :: BS.ByteString -> BL.ByteString
fromStrict = BL.fromChunks . return
#endif
| MaxGabriel/yesod | yesod-auth/Yesod/PasswordStore.hs | mit | 18,769 | 0 | 18 | 4,578 | 2,382 | 1,360 | 1,022 | 172 | 3 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Rules.Selftest (selftestRules) where
import Hadrian.Haskell.Cabal
import Test.QuickCheck
import Base
import Context
import Oracles.ModuleFiles
import Oracles.Setting
import Packages
import Settings
import Target
import Utilities
instance Arbitrary Way where
arbitrary = wayFromUnits <$> arbitrary
instance Arbitrary WayUnit where
arbitrary = arbitraryBoundedEnum
test :: Testable a => a -> Action ()
test = liftIO . quickCheck
selftestRules :: Rules ()
selftestRules =
"selftest" ~> do
testBuilder
testChunksOfSize
testDependencies
testLookupAll
testModuleName
testPackages
testWay
testBuilder :: Action ()
testBuilder = do
putBuild "==== trackArgument"
let make = target undefined (Make undefined) undefined undefined
test $ forAll (elements ["-j", "MAKEFLAGS=-j", "THREADS="])
$ \prefix (NonNegative n) ->
not (trackArgument make prefix) &&
not (trackArgument make ("-j" ++ show (n :: Int)))
testChunksOfSize :: Action ()
testChunksOfSize = do
putBuild "==== chunksOfSize"
test $ chunksOfSize 3 [ "a", "b", "c" , "defg" , "hi" , "jk" ]
== [ ["a", "b", "c"], ["defg"], ["hi"], ["jk"] ]
test $ \n xs ->
let res = chunksOfSize n xs
in concat res == xs && all (\r -> length r == 1 || length (concat r) <= n) res
testDependencies :: Action ()
testDependencies = do
putBuild "==== pkgDependencies"
let pkgs = ghcPackages \\ [libffi] -- @libffi@ does not have a Cabal file.
depLists <- mapM pkgDependencies pkgs
test $ and [ deps == sort deps | deps <- depLists ]
putBuild "==== Dependencies of the 'ghc-bin' binary"
ghcDeps <- pkgDependencies ghc
test $ pkgName compiler `elem` ghcDeps
stage0Deps <- contextDependencies (vanillaContext Stage0 ghc)
stage1Deps <- contextDependencies (vanillaContext Stage1 ghc)
stage2Deps <- contextDependencies (vanillaContext Stage2 ghc)
test $ vanillaContext Stage0 compiler `notElem` stage1Deps
test $ vanillaContext Stage1 compiler `elem` stage1Deps
test $ vanillaContext Stage2 compiler `notElem` stage1Deps
test $ stage1Deps /= stage0Deps
test $ stage1Deps == stage2Deps
testLookupAll :: Action ()
testLookupAll = do
putBuild "==== lookupAll"
test $ lookupAll ["b" , "c" ] [("a", 1), ("c", 3), ("d", 4)]
== [Nothing, Just (3 :: Int)]
test $ forAll dicts $ \dict -> forAll extras $ \extra ->
let items = sort $ map fst dict ++ extra
in lookupAll items (sort dict) == map (`lookup` dict) items
where
dicts :: Gen [(Int, Int)]
dicts = nubBy (\x y -> fst x == fst y) <$> vector 20
extras :: Gen [Int]
extras = vector 20
testModuleName :: Action ()
testModuleName = do
putBuild "==== Encode/decode module name"
test $ encodeModule "Data/Functor" "Identity.hs" == "Data.Functor.Identity"
test $ encodeModule "" "Prelude" == "Prelude"
test $ decodeModule "Data.Functor.Identity" == ("Data/Functor", "Identity")
test $ decodeModule "Prelude" == ("", "Prelude")
test $ forAll names $ \n -> uncurry encodeModule (decodeModule n) == n
where
names = intercalate "." <$> listOf1 (listOf1 $ elements "abcABC123_'")
testPackages :: Action ()
testPackages = do
putBuild "==== Check system configuration"
win <- windowsHost -- This depends on the @boot@ and @configure@ scripts.
putBuild "==== Packages, interpretInContext, configuration flags"
forM_ [Stage0 ..] $ \stage -> do
pkgs <- stagePackages stage
when (win32 `elem` pkgs) . test $ win
when (unix `elem` pkgs) . test $ not win
test $ pkgs == nubOrd pkgs
testWay :: Action ()
testWay = do
putBuild "==== Read Way, Show Way"
test $ \(x :: Way) -> read (show x) == x
| snowleopard/shaking-up-ghc | src/Rules/Selftest.hs | bsd-3-clause | 3,927 | 0 | 19 | 975 | 1,256 | 629 | 627 | -1 | -1 |
module DoIn1 where
io s
= do s <- getLine
let q = (s ++ s)
putStr q
putStr "foo"
| kmate/HaRe | old/testing/removeDef/DoIn1AST.hs | bsd-3-clause | 121 | 0 | 11 | 60 | 47 | 22 | 25 | 6 | 1 |
module Lit where
{-@ test :: {v:Int | v == 3} @-}
test = length "cat"
| abakst/liquidhaskell | tests/pos/lit.hs | bsd-3-clause | 71 | 0 | 5 | 17 | 13 | 8 | 5 | 2 | 1 |
module Foo
( foo
) where
foo :: IO ()
foo = putStrLn "foo2"
| juhp/stack | test/integration/tests/2781-shadow-bug/files/foo/v2/Foo.hs | bsd-3-clause | 69 | 0 | 6 | 23 | 27 | 15 | 12 | 4 | 1 |
-- (c) The GHC Team
--
-- Functions to evaluate whether or not a string is a valid identifier.
-- There is considerable overlap between the logic here and the logic
-- in Lexer.x, but sadly there seems to be way to merge them.
module Lexeme (
-- * Lexical characteristics of Haskell names
-- | Use these functions to figure what kind of name a 'FastString'
-- represents; these functions do /not/ check that the identifier
-- is valid.
isLexCon, isLexVar, isLexId, isLexSym,
isLexConId, isLexConSym, isLexVarId, isLexVarSym,
startsVarSym, startsVarId, startsConSym, startsConId,
-- * Validating identifiers
-- | These functions (working over plain old 'String's) check
-- to make sure that the identifier is valid.
okVarOcc, okConOcc, okTcOcc,
okVarIdOcc, okVarSymOcc, okConIdOcc, okConSymOcc
-- Some of the exports above are not used within GHC, but may
-- be of value to GHC API users.
) where
import FastString
import Data.Char
import qualified Data.Set as Set
{-
************************************************************************
* *
Lexical categories
* *
************************************************************************
These functions test strings to see if they fit the lexical categories
defined in the Haskell report.
Note [Classification of generated names]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Some names generated for internal use can show up in debugging output,
e.g. when using -ddump-simpl. These generated names start with a $
but should still be pretty-printed using prefix notation. We make sure
this is the case in isLexVarSym by only classifying a name as a symbol
if all its characters are symbols, not just its first one.
-}
isLexCon, isLexVar, isLexId, isLexSym :: FastString -> Bool
isLexConId, isLexConSym, isLexVarId, isLexVarSym :: FastString -> Bool
isLexCon cs = isLexConId cs || isLexConSym cs
isLexVar cs = isLexVarId cs || isLexVarSym cs
isLexId cs = isLexConId cs || isLexVarId cs
isLexSym cs = isLexConSym cs || isLexVarSym cs
-------------
isLexConId cs -- Prefix type or data constructors
| nullFS cs = False -- e.g. "Foo", "[]", "(,)"
| cs == (fsLit "[]") = True
| otherwise = startsConId (headFS cs)
isLexVarId cs -- Ordinary prefix identifiers
| nullFS cs = False -- e.g. "x", "_x"
| otherwise = startsVarId (headFS cs)
isLexConSym cs -- Infix type or data constructors
| nullFS cs = False -- e.g. ":-:", ":", "->"
| cs == (fsLit "->") = True
| otherwise = startsConSym (headFS cs)
isLexVarSym fs -- Infix identifiers e.g. "+"
| fs == (fsLit "~R#") = True
| otherwise
= case (if nullFS fs then [] else unpackFS fs) of
[] -> False
(c:cs) -> startsVarSym c && all isVarSymChar cs
-- See Note [Classification of generated names]
-------------
startsVarSym, startsVarId, startsConSym, startsConId :: Char -> Bool
startsVarSym c = startsVarSymASCII c || (ord c > 0x7f && isSymbol c) -- Infix Ids
startsConSym c = c == ':' -- Infix data constructors
startsVarId c = c == '_' || case generalCategory c of -- Ordinary Ids
LowercaseLetter -> True
OtherLetter -> True -- See #1103
_ -> False
startsConId c = isUpper c || c == '(' -- Ordinary type constructors and data constructors
startsVarSymASCII :: Char -> Bool
startsVarSymASCII c = c `elem` "!#$%&*+./<=>?@\\^|~-"
isVarSymChar :: Char -> Bool
isVarSymChar c = c == ':' || startsVarSym c
{-
************************************************************************
* *
Detecting valid names for Template Haskell
* *
************************************************************************
-}
----------------------
-- External interface
----------------------
-- | Is this an acceptable variable name?
okVarOcc :: String -> Bool
okVarOcc str@(c:_)
| startsVarId c
= okVarIdOcc str
| startsVarSym c
= okVarSymOcc str
okVarOcc _ = False
-- | Is this an acceptable constructor name?
okConOcc :: String -> Bool
okConOcc str@(c:_)
| startsConId c
= okConIdOcc str
| startsConSym c
= okConSymOcc str
| str == "[]"
= True
okConOcc _ = False
-- | Is this an acceptable type name?
okTcOcc :: String -> Bool
okTcOcc "[]" = True
okTcOcc "->" = True
okTcOcc "~" = True
okTcOcc str@(c:_)
| startsConId c
= okConIdOcc str
| startsConSym c
= okConSymOcc str
| startsVarSym c
= okVarSymOcc str
okTcOcc _ = False
-- | Is this an acceptable alphanumeric variable name, assuming it starts
-- with an acceptable letter?
okVarIdOcc :: String -> Bool
okVarIdOcc str = okIdOcc str &&
not (str `Set.member` reservedIds)
-- | Is this an acceptable symbolic variable name, assuming it starts
-- with an acceptable character?
okVarSymOcc :: String -> Bool
okVarSymOcc str = all okSymChar str &&
not (str `Set.member` reservedOps) &&
not (isDashes str)
-- | Is this an acceptable alphanumeric constructor name, assuming it
-- starts with an acceptable letter?
okConIdOcc :: String -> Bool
okConIdOcc str = okIdOcc str ||
is_tuple_name1 str
where
-- check for tuple name, starting at the beginning
is_tuple_name1 ('(' : rest) = is_tuple_name2 rest
is_tuple_name1 _ = False
-- check for tuple tail
is_tuple_name2 ")" = True
is_tuple_name2 (',' : rest) = is_tuple_name2 rest
is_tuple_name2 (ws : rest)
| isSpace ws = is_tuple_name2 rest
is_tuple_name2 _ = False
-- | Is this an acceptable symbolic constructor name, assuming it
-- starts with an acceptable character?
okConSymOcc :: String -> Bool
okConSymOcc ":" = True
okConSymOcc str = all okSymChar str &&
not (str `Set.member` reservedOps)
----------------------
-- Internal functions
----------------------
-- | Is this string an acceptable id, possibly with a suffix of hashes,
-- but not worrying about case or clashing with reserved words?
okIdOcc :: String -> Bool
okIdOcc str
= let hashes = dropWhile okIdChar str in
all (== '#') hashes -- -XMagicHash allows a suffix of hashes
-- of course, `all` says "True" to an empty list
-- | Is this character acceptable in an identifier (after the first letter)?
-- See alexGetByte in Lexer.x
okIdChar :: Char -> Bool
okIdChar c = case generalCategory c of
UppercaseLetter -> True
LowercaseLetter -> True
OtherLetter -> True
TitlecaseLetter -> True
DecimalNumber -> True
OtherNumber -> True
_ -> c == '\'' || c == '_'
-- | Is this character acceptable in a symbol (after the first char)?
-- See alexGetByte in Lexer.x
okSymChar :: Char -> Bool
okSymChar c
| c `elem` specialSymbols
= False
| c `elem` "_\"'"
= False
| otherwise
= case generalCategory c of
ConnectorPunctuation -> True
DashPunctuation -> True
OtherPunctuation -> True
MathSymbol -> True
CurrencySymbol -> True
ModifierSymbol -> True
OtherSymbol -> True
_ -> False
-- | All reserved identifiers. Taken from section 2.4 of the 2010 Report.
reservedIds :: Set.Set String
reservedIds = Set.fromList [ "case", "class", "data", "default", "deriving"
, "do", "else", "foreign", "if", "import", "in"
, "infix", "infixl", "infixr", "instance", "let"
, "module", "newtype", "of", "then", "type", "where"
, "_" ]
-- | All punctuation that cannot appear in symbols. See $special in Lexer.x.
specialSymbols :: [Char]
specialSymbols = "(),;[]`{}"
-- | All reserved operators. Taken from section 2.4 of the 2010 Report.
reservedOps :: Set.Set String
reservedOps = Set.fromList [ "..", ":", "::", "=", "\\", "|", "<-", "->"
, "@", "~", "=>" ]
-- | Does this string contain only dashes and has at least 2 of them?
isDashes :: String -> Bool
isDashes ('-' : '-' : rest) = all (== '-') rest
isDashes _ = False
| green-haskell/ghc | compiler/basicTypes/Lexeme.hs | bsd-3-clause | 8,645 | 0 | 10 | 2,491 | 1,566 | 836 | 730 | 136 | 8 |
{-# LANGUAGE OverloadedStrings, BangPatterns #-}
{-# LANGUAGE CPP #-}
-- |
-- Module : Crypto.PasswordStore
-- Copyright : (c) Peter Scott, 2011
-- License : BSD-style
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- Securely store hashed, salted passwords. If you need to store and verify
-- passwords, there are many wrong ways to do it, most of them all too
-- common. Some people store users' passwords in plain text. Then, when an
-- attacker manages to get their hands on this file, they have the passwords for
-- every user's account. One step up, but still wrong, is to simply hash all
-- passwords with SHA1 or something. This is vulnerable to rainbow table and
-- dictionary attacks. One step up from that is to hash the password along with
-- a unique salt value. This is vulnerable to dictionary attacks, since guessing
-- a password is very fast. The right thing to do is to use a slow hash
-- function, to add some small but significant delay, that will be negligible
-- for legitimate users but prohibitively expensive for someone trying to guess
-- passwords by brute force. That is what this library does. It iterates a
-- SHA256 hash, with a random salt, a few thousand times. This scheme is known
-- as PBKDF1, and is generally considered secure; there is nothing innovative
-- happening here.
--
-- The API here is very simple. What you store are called /password hashes/.
-- They are strings (technically, ByteStrings) that look like this:
--
-- > "sha256|14|jEWU94phx4QzNyH94Qp4CQ==|5GEw+jxP/4WLgzt9VS3Ee3nhqBlDsrKiB+rq7JfMckU="
--
-- Each password hash shows the algorithm, the strength (more on that later),
-- the salt, and the hashed-and-salted password. You store these on your server,
-- in a database, for when you need to verify a password. You make a password
-- hash with the 'makePassword' function. Here's an example:
--
-- > >>> makePassword "hunter2" 14
-- > "sha256|14|Zo4LdZGrv/HYNAUG3q8WcA==|zKjbHZoTpuPLp1lh6ATolWGIKjhXvY4TysuKvqtNFyk="
--
-- This will hash the password @\"hunter2\"@, with strength 12, which is a good
-- default value. The strength here determines how long the hashing will
-- take. When doing the hashing, we iterate the SHA256 hash function
-- @2^strength@ times, so increasing the strength by 1 makes the hashing take
-- twice as long. When computers get faster, you can bump up the strength a
-- little bit to compensate. You can strengthen existing password hashes with
-- the 'strengthenPassword' function. Note that 'makePassword' needs to generate
-- random numbers, so its return type is 'IO' 'ByteString'. If you want to avoid
-- the 'IO' monad, you can generate your own salt and pass it to
-- 'makePasswordSalt'.
--
-- Your strength value should not be less than 12, and 14 is a good default
-- value at the time of this writing, in 2013.
--
-- Once you've got your password hashes, the second big thing you need to do
-- with them is verify passwords against them. When a user gives you a password,
-- you compare it with a password hash using the 'verifyPassword' function:
--
-- > >>> verifyPassword "wrong guess" passwordHash
-- > False
-- > >>> verifyPassword "hunter2" passwordHash
-- > True
--
-- These two functions are really all you need. If you want to make existing
-- password hashes stronger, you can use 'strengthenPassword'. Just pass it an
-- existing password hash and a new strength value, and it will return a new
-- password hash with that strength value, which will match the same password as
-- the old password hash.
--
-- Note that, as of version 2.4, you can also use PBKDF2, and specify the exact
-- iteration count. This does not have a significant effect on security, but can
-- be handy for compatibility with other code.
module Yesod.PasswordStore (
-- * Algorithms
pbkdf1, -- :: ByteString -> Salt -> Int -> ByteString
pbkdf2, -- :: ByteString -> Salt -> Int -> ByteString
-- * Registering and verifying passwords
makePassword, -- :: ByteString -> Int -> IO ByteString
makePasswordWith, -- :: (ByteString -> Salt -> Int -> ByteString) ->
-- ByteString -> Int -> IO ByteString
makePasswordSalt, -- :: ByteString -> ByteString -> Int -> ByteString
makePasswordSaltWith, -- :: (ByteString -> Salt -> Int -> ByteString) ->
-- ByteString -> Salt -> Int -> ByteString
verifyPassword, -- :: ByteString -> ByteString -> Bool
verifyPasswordWith, -- :: (ByteString -> Salt -> Int -> ByteString) ->
-- (Int -> Int) -> ByteString -> ByteString -> Bool
-- * Updating password hash strength
strengthenPassword, -- :: ByteString -> Int -> ByteString
passwordStrength, -- :: ByteString -> Int
-- * Utilities
Salt,
isPasswordFormatValid, -- :: ByteString -> Bool
genSaltIO, -- :: IO Salt
genSaltRandom, -- :: (RandomGen b) => b -> (Salt, b)
makeSalt, -- :: ByteString -> Salt
exportSalt, -- :: Salt -> ByteString
importSalt -- :: ByteString -> Salt
) where
import qualified Crypto.Hash as CH
import qualified Crypto.Hash.SHA256 as H
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as BL
import qualified Data.Binary as Binary
import Control.Monad
import Control.Monad.ST
import Data.Byteable (toBytes)
import Data.STRef
import Data.Bits
import Data.ByteString.Char8 (ByteString)
import Data.ByteString.Base64 (encode, decodeLenient)
import System.IO
import System.Random
import Data.Maybe
import qualified Control.Exception
---------------------
-- Cryptographic base
---------------------
-- | PBKDF1 key-derivation function. Takes a password, a 'Salt', and a number of
-- iterations. The number of iterations should be at least 1000, and probably
-- more. 5000 is a reasonable number, computing almost instantaneously. This
-- will give a 32-byte 'ByteString' as output. Both the salt and this 32-byte
-- key should be stored in the password file. When a user wishes to authenticate
-- a password, just pass it and the salt to this function, and see if the output
-- matches.
pbkdf1 :: ByteString -> Salt -> Int -> ByteString
pbkdf1 password (SaltBS salt) iter = hashRounds first_hash (iter + 1)
where first_hash = H.finalize $ H.init `H.update` password `H.update` salt
-- | Hash a 'ByteString' for a given number of rounds. The number of rounds is 0
-- or more. If the number of rounds specified is 0, the ByteString will be
-- returned unmodified.
hashRounds :: ByteString -> Int -> ByteString
hashRounds (!bs) 0 = bs
hashRounds bs rounds = hashRounds (H.hash bs) (rounds - 1)
-- | Computes the hmacSHA256 of the given message, with the given 'Salt'.
hmacSHA256 :: ByteString
-- ^ The secret (the salt)
-> ByteString
-- ^ The clear-text message
-> ByteString
-- ^ The encoded message
hmacSHA256 secret msg =
toBytes (CH.hmacGetDigest (CH.hmac secret msg) :: CH.Digest CH.SHA256)
-- | PBKDF2 key-derivation function.
-- For details see @http://tools.ietf.org/html/rfc2898@.
-- @32@ is the most common digest size for @SHA256@, and is
-- what the algorithm internally uses.
-- @HMAC+SHA256@ is used as @PRF@, because @HMAC+SHA1@ is considered too weak.
pbkdf2 :: ByteString -> Salt -> Int -> ByteString
pbkdf2 password (SaltBS salt) c =
let hLen = 32
dkLen = hLen in go hLen dkLen
where
go hLen dkLen | dkLen > (2^32 - 1) * hLen = error "Derived key too long."
| otherwise =
let !l = ceiling ((fromIntegral dkLen / fromIntegral hLen) :: Double)
!r = dkLen - (l - 1) * hLen
chunks = [f i | i <- [1 .. l]]
in (B.concat . init $ chunks) `B.append` B.take r (last chunks)
-- The @f@ function, as defined in the spec.
-- It calls 'u' under the hood.
f :: Int -> ByteString
f i = let !u1 = hmacSHA256 password (salt `B.append` int i)
-- Using the ST Monad, for maximum performance.
in runST $ do
u <- newSTRef u1
accum <- newSTRef u1
forM_ [2 .. c] $ \_ -> do
modifySTRef' u (hmacSHA256 password)
currentU <- readSTRef u
modifySTRef' accum (`xor'` currentU)
readSTRef accum
-- int(i), as defined in the spec.
int :: Int -> ByteString
int i = let str = BL.unpack . Binary.encode $ i
in BS.pack $ drop (length str - 4) str
-- | A convenience function to XOR two 'ByteString' together.
xor' :: ByteString -> ByteString -> ByteString
xor' !b1 !b2 = BS.pack $ BS.zipWith xor b1 b2
-- | Generate a 'Salt' from 128 bits of data from @\/dev\/urandom@, with the
-- system RNG as a fallback. This is the function used to generate salts by
-- 'makePassword'.
genSaltIO :: IO Salt
genSaltIO =
Control.Exception.catch genSaltDevURandom def
where
def :: IOError -> IO Salt
def _ = genSaltSysRandom
-- | Generate a 'Salt' from @\/dev\/urandom@.
genSaltDevURandom :: IO Salt
genSaltDevURandom = withFile "/dev/urandom" ReadMode $ \h -> do
rawSalt <- B.hGet h 16
return $ makeSalt rawSalt
-- | Generate a 'Salt' from 'System.Random'.
genSaltSysRandom :: IO Salt
genSaltSysRandom = randomChars >>= return . makeSalt . B.pack
where randomChars = sequence $ replicate 16 $ randomRIO ('\NUL', '\255')
-----------------------
-- Password hash format
-----------------------
-- Format: "sha256|strength|salt|hash", where strength is an unsigned int, salt
-- is a base64-encoded 16-byte random number, and hash is a base64-encoded hash
-- value.
-- | Try to parse a password hash.
readPwHash :: ByteString -> Maybe (Int, Salt, ByteString)
readPwHash pw | length broken /= 4
|| algorithm /= "sha256"
|| B.length hash /= 44 = Nothing
| otherwise = case B.readInt strBS of
Just (strength, _) -> Just (strength, SaltBS salt, hash)
Nothing -> Nothing
where broken = B.split '|' pw
[algorithm, strBS, salt, hash] = broken
-- | Encode a password hash, from a @(strength, salt, hash)@ tuple, where
-- strength is an 'Int', and both @salt@ and @hash@ are base64-encoded
-- 'ByteString's.
writePwHash :: (Int, Salt, ByteString) -> ByteString
writePwHash (strength, SaltBS salt, hash) =
B.intercalate "|" ["sha256", B.pack (show strength), salt, hash]
-----------------
-- High level API
-----------------
-- | Hash a password with a given strength (14 is a good default). The output of
-- this function can be written directly to a password file or
-- database. Generates a salt using high-quality randomness from
-- @\/dev\/urandom@ or (if that is not available, for example on Windows)
-- 'System.Random', which is included in the hashed output.
makePassword :: ByteString -> Int -> IO ByteString
makePassword = makePasswordWith pbkdf1
-- | A generic version of 'makePassword', which allow the user
-- to choose the algorithm to use.
--
-- >>> makePasswordWith pbkdf1 "password" 14
--
makePasswordWith :: (ByteString -> Salt -> Int -> ByteString)
-- ^ The algorithm to use (e.g. pbkdf1)
-> ByteString
-- ^ The password to encrypt
-> Int
-- ^ log2 of the number of iterations
-> IO ByteString
makePasswordWith algorithm password strength = do
salt <- genSaltIO
return $ makePasswordSaltWith algorithm (2^) password salt strength
-- | A generic version of 'makePasswordSalt', meant to give the user
-- the maximum control over the generation parameters.
-- Note that, unlike 'makePasswordWith', this function takes the @raw@
-- number of iterations. This means the user will need to specify a
-- sensible value, typically @10000@ or @20000@.
makePasswordSaltWith :: (ByteString -> Salt -> Int -> ByteString)
-- ^ A function modeling an algorithm (e.g. 'pbkdf1')
-> (Int -> Int)
-- ^ A function to modify the strength
-> ByteString
-- ^ A password, given as clear text
-> Salt
-- ^ A hash 'Salt'
-> Int
-- ^ The password strength (e.g. @10000, 20000, etc.@)
-> ByteString
makePasswordSaltWith algorithm strengthModifier pwd salt strength = writePwHash (strength, salt, hash)
where hash = encode $ algorithm pwd salt (strengthModifier strength)
-- | Hash a password with a given strength (14 is a good default), using a given
-- salt. The output of this function can be written directly to a password file
-- or database. Example:
--
-- > >>> makePasswordSalt "hunter2" (makeSalt "72cd18b5ebfe6e96") 14
-- > "sha256|14|NzJjZDE4YjVlYmZlNmU5Ng==|yuiNrZW3KHX+pd0sWy9NTTsy5Yopmtx4UYscItSsoxc="
makePasswordSalt :: ByteString -> Salt -> Int -> ByteString
makePasswordSalt = makePasswordSaltWith pbkdf1 (2^)
-- | 'verifyPasswordWith' @algorithm userInput pwHash@ verifies
-- the password @userInput@ given by the user against the stored password
-- hash @pwHash@, with the hashing algorithm @algorithm@. Returns 'True' if the
-- given password is correct, and 'False' if it is not.
-- This function allows the programmer to specify the algorithm to use,
-- e.g. 'pbkdf1' or 'pbkdf2'.
-- Note: If you want to verify a password previously generated with
-- 'makePasswordSaltWith', but without modifying the number of iterations,
-- you can do:
--
-- > >>> verifyPasswordWith pbkdf2 id "hunter2" "sha256..."
-- > True
--
verifyPasswordWith :: (ByteString -> Salt -> Int -> ByteString)
-- ^ A function modeling an algorithm (e.g. pbkdf1)
-> (Int -> Int)
-- ^ A function to modify the strength
-> ByteString
-- ^ User password
-> ByteString
-- ^ The generated hash (e.g. sha256|14...)
-> Bool
verifyPasswordWith algorithm strengthModifier userInput pwHash =
case readPwHash pwHash of
Nothing -> False
Just (strength, salt, goodHash) ->
encode (algorithm userInput salt (strengthModifier strength)) == goodHash
-- | Like 'verifyPasswordWith', but uses 'pbkdf1' as algorithm.
verifyPassword :: ByteString -> ByteString -> Bool
verifyPassword = verifyPasswordWith pbkdf1 (2^)
-- | Try to strengthen a password hash, by hashing it some more
-- times. @'strengthenPassword' pwHash new_strength@ will return a new password
-- hash with strength at least @new_strength@. If the password hash already has
-- strength greater than or equal to @new_strength@, then it is returned
-- unmodified. If the password hash is invalid and does not parse, it will be
-- returned without comment.
--
-- This function can be used to periodically update your password database when
-- computers get faster, in order to keep up with Moore's law. This isn't hugely
-- important, but it's a good idea.
strengthenPassword :: ByteString -> Int -> ByteString
strengthenPassword pwHash newstr =
case readPwHash pwHash of
Nothing -> pwHash
Just (oldstr, salt, hashB64) ->
if oldstr < newstr then
writePwHash (newstr, salt, newHash)
else
pwHash
where newHash = encode $ hashRounds hash extraRounds
extraRounds = (2^newstr) - (2^oldstr)
hash = decodeLenient hashB64
-- | Return the strength of a password hash.
passwordStrength :: ByteString -> Int
passwordStrength pwHash = case readPwHash pwHash of
Nothing -> 0
Just (strength, _, _) -> strength
------------
-- Utilities
------------
-- | A salt is a unique random value which is stored as part of the password
-- hash. You can generate a salt with 'genSaltIO' or 'genSaltRandom', or if you
-- really know what you're doing, you can create them from your own ByteString
-- values with 'makeSalt'.
newtype Salt = SaltBS ByteString
deriving (Show, Eq, Ord)
-- | Create a 'Salt' from a 'ByteString'. The input must be at least 8
-- characters, and can contain arbitrary bytes. Most users will not need to use
-- this function.
makeSalt :: ByteString -> Salt
makeSalt = SaltBS . encode . check_length
where check_length salt | B.length salt < 8 =
error "Salt too short. Minimum length is 8 characters."
| otherwise = salt
-- | Convert a 'Salt' into a 'ByteString'. The resulting 'ByteString' will be
-- base64-encoded. Most users will not need to use this function.
exportSalt :: Salt -> ByteString
exportSalt (SaltBS bs) = bs
-- | Convert a raw 'ByteString' into a 'Salt'.
-- Use this function with caution, since using a weak salt will result in a
-- weak password.
importSalt :: ByteString -> Salt
importSalt = SaltBS
-- | Is the format of a password hash valid? Attempts to parse a given password
-- hash. Returns 'True' if it parses correctly, and 'False' otherwise.
isPasswordFormatValid :: ByteString -> Bool
isPasswordFormatValid = isJust . readPwHash
-- | Generate a 'Salt' with 128 bits of data taken from a given random number
-- generator. Returns the salt and the updated random number generator. This is
-- meant to be used with 'makePasswordSalt' by people who would prefer to either
-- use their own random number generator or avoid the 'IO' monad.
genSaltRandom :: (RandomGen b) => b -> (Salt, b)
genSaltRandom gen = (salt, newgen)
where rands _ 0 = []
rands g n = (a, g') : rands g' (n-1 :: Int)
where (a, g') = randomR ('\NUL', '\255') g
salt = makeSalt $ B.pack $ map fst (rands gen 16)
newgen = snd $ last (rands gen 16)
#if !MIN_VERSION_base(4, 6, 0)
-- | Strict version of 'modifySTRef'
modifySTRef' :: STRef s a -> (a -> a) -> ST s ()
modifySTRef' ref f = do
x <- readSTRef ref
let x' = f x
x' `seq` writeSTRef ref x'
#endif
#if MIN_VERSION_bytestring(0, 10, 0)
toStrict :: BL.ByteString -> BS.ByteString
toStrict = BL.toStrict
fromStrict :: BS.ByteString -> BL.ByteString
fromStrict = BL.fromStrict
#else
toStrict :: BL.ByteString -> BS.ByteString
toStrict = BS.concat . BL.toChunks
fromStrict :: BS.ByteString -> BL.ByteString
fromStrict = BL.fromChunks . return
#endif
| ygale/yesod | yesod-auth/Yesod/PasswordStore.hs | mit | 18,769 | 0 | 18 | 4,578 | 2,382 | 1,360 | 1,022 | 172 | 3 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE GADTs #-}
module T6137 where
data Sum a b = L a | R b
data Sum1 (a :: k1 -> *) (b :: k2 -> *) :: Sum k1 k2 -> * where
LL :: a i -> Sum1 a b (L i)
RR :: b i -> Sum1 a b (R i)
data Code i o = F (Code (Sum i o) o)
-- An interpretation for `Code` using a data family works:
data family In (f :: Code i o) :: (i -> *) -> (o -> *)
data instance In (F f) r o where
MkIn :: In f (Sum1 r (In (F f) r)) o -> In (F f) r o
-- Requires polymorphic recursion
data In' (f :: Code i o) :: (i -> *) -> o -> * where
MkIn' :: In' g (Sum1 r (In' (F g) r)) t -> In' (F g) r t
| urbanslug/ghc | testsuite/tests/polykinds/T6137.hs | bsd-3-clause | 699 | 0 | 13 | 186 | 334 | 184 | 150 | 16 | 0 |
{-# LANGUAGE UndecidableInstances #-}
module Tc173b where
import Tc173a
is :: ()
is = isFormValue (Just "") | urbanslug/ghc | testsuite/tests/typecheck/should_compile/Tc173b.hs | bsd-3-clause | 109 | 0 | 7 | 18 | 29 | 17 | 12 | 5 | 1 |
{-# LANGUAGE FlexibleInstances #-} -- exercise 5
module Calc where
import qualified Data.Map.Strict as M
import qualified ExprT as E -- exercise 1
import Parser -- exercise 2
import qualified StackVM as S -- exercise 5
-- exercise 1
eval :: E.ExprT -> Integer
eval (E.Lit a) = a
eval (E.Add e1 e2) = (eval e1) + (eval e2)
eval (E.Mul e1 e2) = (eval e1) * (eval e2)
-- exercise 2
evalStr :: String -> Maybe Integer
evalStr s = let expr = parseExp E.Lit E.Add E.Mul s
in case expr of
Just e -> Just $ eval e
otherwise -> Nothing
-- exercise 3
class Expr e where
lit :: Integer -> e
mul :: e -> e -> e
add :: e -> e -> e
instance Expr E.ExprT where
lit = E.Lit
mul = E.Mul
add = E.Add
-- exercise 4
instance Expr Integer where
lit = id
mul = (*)
add = (+)
instance Expr Bool where
lit i
| i <= 0 = True
| otherwise = False
add = (||)
mul = (&&)
newtype MinMax = MinMax Integer deriving (Eq, Show, Ord)
newtype Mod7 = Mod7 Integer deriving (Eq, Show)
instance Expr MinMax where
lit = MinMax
add = max
mul = min
mod7 :: Integer -> Mod7
mod7 n = Mod7 $ mod n 7
instance Expr Mod7 where
lit i
| i > 6 || i < 0 = error $ (show i) ++ " is out of range: 0..6"
| otherwise = Mod7 i
add (Mod7 m1) (Mod7 m2) = mod7 $ m1 + m2
mul (Mod7 m1) (Mod7 m2) = mod7 $ m1 * m2
testExp :: Expr a => Maybe a
testExp = parseExp lit add mul "(3 * -4) + 5"
testInteger = testExp :: Maybe Integer
testBool = testExp :: Maybe Bool
testMM = testExp :: Maybe MinMax
testSat = testExp :: Maybe Mod7
-- exercise 5
instance Expr S.Program where
lit i = [S.PushI i]
mul a b = a ++ b ++ [S.Mul]
add a b = a ++ b ++ [S.Add]
testStack = testExp :: Maybe S.Program
compile :: String -> Maybe S.Program
compile s = parseExp lit add mul s
-- exercise 6
class HasVars a where
var :: String -> a
data VarExprT = Lit Integer
| Add VarExprT VarExprT
| Mul VarExprT VarExprT
| Var String
deriving (Show, Eq)
instance Expr VarExprT where
lit = Lit
mul = Mul
add = Add
instance HasVars VarExprT where
var = Var
instance HasVars (M.Map String Integer -> Maybe Integer) where
var = M.lookup
type LookupFn = (M.Map String Integer -> Maybe Integer)
type OpFn = Integer -> Integer -> Integer
op :: OpFn -> LookupFn -> LookupFn -> M.Map String Integer -> Maybe Integer
op op f1 f2 m =
let a = f1 m
b = f2 m
in case (a,b) of
(Just n1, Just n2) -> Just $ op n1 n2
otherwise -> Nothing
instance Expr (M.Map String Integer -> Maybe Integer) where
lit = \x m -> Just x
mul = op (*)
add = op (+)
withVars :: [(String, Integer)]
-> (M.Map String Integer -> Maybe Integer)
-> Maybe Integer
withVars vs exp = exp $ M.fromList vs
| dirkz/haskell-cis-194 | 05/Calc.hs | isc | 2,867 | 0 | 11 | 843 | 1,150 | 607 | 543 | 92 | 2 |
-- | Defines readers for reading tags of BACnet values
module BACnet.Tag.Reader
(
readNullAPTag,
readNullCSTag,
readBoolAPTag,
readBoolCSTag,
readUnsignedAPTag,
readUnsignedCSTag,
readSignedAPTag,
readSignedCSTag,
readRealAPTag,
readRealCSTag,
readDoubleAPTag,
readDoubleCSTag,
readOctetStringAPTag,
readOctetStringCSTag,
readStringAPTag,
readStringCSTag,
readBitStringAPTag,
readBitStringCSTag,
readEnumeratedAPTag,
readEnumeratedCSTag,
readDateAPTag,
readDateCSTag,
readTimeAPTag,
readTimeCSTag,
readObjectIdentifierAPTag,
readObjectIdentifierCSTag,
readAnyAPTag,
readOpenTag,
readCloseTag
) where
import BACnet.Tag.Core
import BACnet.Reader.Core
import Data.Word
import Control.Monad (guard)
import Control.Applicative ((<|>))
-- | Like 'const' but applied twice. It takes three arguments
-- and returns the first.
const2 :: a -> b -> c -> a
const2 = const . const
readNullAPTag :: Reader Tag
readNullAPTag = sat (== 0x00) >> return NullAP
readNullCSTag :: TagNumber -> Reader Tag
readNullCSTag t = readCS t (==0) (flip $ const NullCS)
readBoolAPTag :: Reader Tag
readBoolAPTag = (sat (== 0x10) >> return (BoolAP False)) <|>
(sat (== 0x11) >> return (BoolAP True))
readBoolCSTag :: TagNumber -> Reader Tag
readBoolCSTag t = readCS t (==1) (flip $ const BoolCS)
readUnsignedAPTag :: Reader Tag
readUnsignedAPTag = readAP 2 UnsignedAP
readUnsignedCSTag :: TagNumber -> Reader Tag
readUnsignedCSTag t = readCS t (/=0) UnsignedCS
readSignedAPTag :: Reader Tag
readSignedAPTag = readAP 3 SignedAP
readSignedCSTag :: TagNumber -> Reader Tag
readSignedCSTag t = readCS t (/=0) SignedCS
readRealAPTag :: Reader Tag
readRealAPTag = sat (== 0x44) >> return RealAP
readRealCSTag :: TagNumber -> Reader Tag
readRealCSTag t = readCS t (==4) (const2 $ RealCS t)
readDoubleAPTag :: Reader Tag
readDoubleAPTag = sat (== 0x55) >> sat (== 0x08) >> return DoubleAP
readDoubleCSTag :: TagNumber -> Reader Tag
readDoubleCSTag t = readCS t (==8) (const2 $ DoubleCS t)
readOctetStringAPTag :: Reader Tag
readOctetStringAPTag = readAP 6 OctetStringAP
readOctetStringCSTag :: TagNumber -> Reader Tag
readOctetStringCSTag t = readCS t (const True) OctetStringCS
readStringAPTag :: Reader Tag
readStringAPTag = readAP 7 CharacterStringAP
readStringCSTag :: TagNumber -> Reader Tag
readStringCSTag t = readCS t (const True) CharacterStringCS
readBitStringAPTag :: Reader Tag
readBitStringAPTag = readAP 8 BitStringAP
readBitStringCSTag :: TagNumber -> Reader Tag
readBitStringCSTag t = readCS t (const True) BitStringCS
readEnumeratedAPTag :: Reader Tag
readEnumeratedAPTag = readAP 9 EnumeratedAP
readEnumeratedCSTag :: TagNumber -> Reader Tag
readEnumeratedCSTag tn = readCS tn (/=0) EnumeratedCS
readDateAPTag :: Reader Tag
readDateAPTag = sat (== 0xa4) >> return DateAP
readDateCSTag :: TagNumber -> Reader Tag
readDateCSTag tn = readCS tn (==4) (flip $ const DateCS)
readTimeAPTag :: Reader Tag
readTimeAPTag = sat (== 0xb4) >> return TimeAP
readTimeCSTag :: TagNumber -> Reader Tag
readTimeCSTag tn = readCS tn (==4) (flip $ const TimeCS)
readObjectIdentifierAPTag :: Reader Tag
readObjectIdentifierAPTag = sat (== 0xc4) >> return ObjectIdentifierAP
readObjectIdentifierCSTag :: TagNumber -> Reader Tag
readObjectIdentifierCSTag tn = readCS tn (==4) (flip $ const ObjectIdentifierCS)
readOpenTag :: TagNumber -> Reader Tag
readOpenTag tn = readTag (==tn) (==classCS) (const True) (==6) (flip $ const Open)
readCloseTag :: TagNumber -> Reader Tag
readCloseTag tn = readTag (==tn) (==classCS) (const True) (==7) (flip $ const Close)
peeksat :: (Word8 -> Bool) -> Reader Word8
peeksat p = peek >>= \b -> if p b then return b else fail "predicate failed"
readAnyAPTag :: Reader Tag
readAnyAPTag =
do
t <- peeksat isAP
case tagNumber t of
0 -> readNullAPTag
1 -> readBoolAPTag
2 -> readUnsignedAPTag
3 -> readSignedAPTag
4 -> readRealAPTag
5 -> readDoubleAPTag
6 -> readOctetStringAPTag
7 -> readStringAPTag
8 -> readBitStringAPTag
9 -> readEnumeratedAPTag
10 -> readDateAPTag
11 -> readTimeAPTag
12 -> readObjectIdentifierAPTag
_ -> fail "Invalid tag number for AP Tag"
type LengthPredicate = Length -> Bool
type APTagConstructor = Length -> Tag
type CSTagConstructor = TagConstructor
readAP :: TagNumber -> APTagConstructor -> Reader Tag
readAP tn co = readTag (==tn) (==classAP) (const True) (const True) (const co)
-- | @readCS tn pred co@ succeeds if tn matches the tag number that is read,
-- and the tag is CS encoded, and the length checking predicate returns true.
-- It constructs a Tag by using the given constructor @co@.
readCS :: TagNumber -> LengthPredicate -> CSTagConstructor -> Reader Tag
readCS tn p = readTag (==tn) (==classCS) p (const True)
type TagNumberPredicate = TagNumber -> Bool
type ClassPredicate = Class -> Bool
type TagConstructor = TagNumber -> Length -> Tag
type TypePredicate = Word8 -> Bool
readTag :: TagNumberPredicate -> ClassPredicate -> LengthPredicate ->
TypePredicate -> TagConstructor -> Reader Tag
readTag tagNumberP classP lengthP typeP co
= byte >>= \b ->
readClass b >>= \c ->
readExtendedTag b c >>= \tn ->
readExtendedLength b >>= \len ->
guard (tagNumberP tn && classP c && lengthP len && typeP b) >>
return (co tn len)
where readClass b = return $ if isCS b then classCS else classAP
readExtendedTag b c | c == classAP = readTagNumber b
| c == classCS =
(guard (tagNumber b == 15) >> byte) <|>
readTagNumber b
readTagNumber = return . tagNumber
readExtendedLength = lengthOfContent
type TagInitialOctet = Word8
-- | Given an initial octet of a tag, reads the length of the content
lengthOfContent :: TagInitialOctet -> Reader Word32
lengthOfContent b | lvt b < 5 = return . fromIntegral $ lvt b
| lvt b == 5 = lengthOfContent'
| otherwise = fail "Invalid length encoding"
-- | Reads the next byte. If it is < 254 it returns that value
-- If it is 254, then reads the next 2 bytes as a Word32
-- If it is 255, then reads the next 4 bytes as a Word32
lengthOfContent' :: Reader Word32
lengthOfContent' = byte >>= \b ->
if b < 254
then return $ fromIntegral b
else fmap foldbytes (bytes (if b == 254 then 2 else 4))
foldbytes :: [Word8] -> Word32
foldbytes = foldl (\acc w -> acc * 256 + fromIntegral w) 0
| michaelgwelch/bacnet | src/BACnet/Tag/Reader.hs | mit | 6,726 | 0 | 19 | 1,524 | 1,897 | 996 | 901 | 155 | 14 |
import Test.Hspec
import Language.Paradocs.Renderer
import Language.Paradocs.RendererState
import Language.Paradocs.MonadStorage
import qualified Data.HashMap.Strict as HashMap
main :: IO ()
main = hspec $ do
describe "%read" $ do
let storage = HashMap.fromList [
("a.pd", "content")
]
let rendered = runHashMapStorage (renderString "%read a.pd") storage
it "reads the content of a.pd" $ do
renderedToString rendered `shouldBe` "content"
| pasberth/paradocs | test/ReadInstructionSpec.hs | mit | 549 | 0 | 16 | 165 | 127 | 67 | 60 | 13 | 1 |
{-# LANGUAGE CPP #-}
module Language.Haskell.Source.Enumerator
( enumeratePath
) where
import Conduit
import Control.Applicative
import Control.Monad
import Data.List
import Distribution.PackageDescription
import qualified Distribution.Verbosity as Verbosity
import System.Directory
import System.FilePath
#if MIN_VERSION_Cabal(2,2,0)
import Distribution.PackageDescription.Parsec (readGenericPackageDescription)
#elif MIN_VERSION_Cabal(2,0,0)
import Distribution.PackageDescription.Parse (readGenericPackageDescription)
#else
import Distribution.PackageDescription.Parse (readPackageDescription)
readGenericPackageDescription ::
Verbosity.Verbosity -> FilePath -> IO GenericPackageDescription
readGenericPackageDescription = readPackageDescription
#endif
enumeratePath :: FilePath -> ConduitT () FilePath IO ()
enumeratePath path = enumPath path .| mapC normalise
enumPath :: FilePath -> ConduitT () FilePath IO ()
enumPath path = do
isDirectory <- lift $ doesDirectoryExist path
case isDirectory of
True -> enumDirectory path
False
| hasCabalExtension path -> enumPackage path
False
| hasHaskellExtension path -> yield path
False -> return ()
enumPackage :: FilePath -> ConduitT () FilePath IO ()
enumPackage cabalFile = readPackage cabalFile >>= expandPaths
where
readPackage = lift . readGenericPackageDescription Verbosity.silent
expandPaths = mapM_ (enumPath . mkFull) . sourcePaths
packageDir = dropFileName cabalFile
mkFull = (packageDir </>)
enumDirectory :: FilePath -> ConduitT () FilePath IO ()
enumDirectory path = do
contents <- lift $ getDirectoryContentFullPaths path
cabalFiles <- lift $ filterM isCabalFile contents
if null cabalFiles
then mapM_ enumPath contents
else mapM_ enumPackage cabalFiles
getDirectoryContentFullPaths :: FilePath -> IO [FilePath]
getDirectoryContentFullPaths path =
mkFull . notHidden . notMeta <$> getDirectoryContents path
where
mkFull = map (path </>)
notHidden = filter (not . isPrefixOf ".")
notMeta = (\\ [".", ".."])
isCabalFile :: FilePath -> IO Bool
isCabalFile path = return (hasCabalExtension path) <&&> doesFileExist path
hasCabalExtension :: FilePath -> Bool
hasCabalExtension path = ".cabal" `isSuffixOf` path
hasHaskellExtension :: FilePath -> Bool
hasHaskellExtension path = ".hs" `isSuffixOf` path || ".lhs" `isSuffixOf` path
sourcePaths :: GenericPackageDescription -> [FilePath]
sourcePaths pkg = nub $ concatMap ($ pkg) pathExtractors
where
pathExtractors =
[ maybe [] (hsSourceDirs . libBuildInfo . condTreeData) . condLibrary
, concatMap (hsSourceDirs . buildInfo . condTreeData . snd) .
condExecutables
, concatMap (hsSourceDirs . testBuildInfo . condTreeData . snd) .
condTestSuites
, concatMap (hsSourceDirs . benchmarkBuildInfo . condTreeData . snd) .
condBenchmarks
]
(<&&>) :: Applicative f => f Bool -> f Bool -> f Bool
(<&&>) = liftA2 (&&)
infixr 3 <&&> -- same as (&&)
| danstiner/hfmt | src/Language/Haskell/Source/Enumerator.hs | mit | 3,124 | 0 | 13 | 633 | 755 | 393 | 362 | 65 | 4 |
module BinaryTreesSpec (main, spec) where
import Test.Hspec
import BinaryTrees
import Control.Exception (evaluate)
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "Preparering" $ do
it "returns (Branch 1 Empty Empty) when x = 1" $ do
leaf (1 :: Int) `shouldBe` Branch 1 Empty Empty
describe "Problem 55" $ do
it "returns Empty when n = 0" $ do
cbalTree 0 `shouldBe` [Empty]
it "returns (B 'x' E E) when n = 1" $ do
cbalTree 1 `shouldBe` [Branch 'x' Empty Empty]
it "returns [(B 'x' (B 'x' E E) E), (B 'x' E (B 'x' E E))] when n = 2" $ do
cbalTree 2 `shouldBe` [Branch 'x' (Branch 'x' Empty Empty) Empty, Branch 'x' Empty (Branch 'x' Empty Empty)]
it "returns [(B 'x' (B 'x' E E) (B 'x' E (B 'x' E E))), (B 'x' (B 'x' E E) (B 'x' (B 'x' E E) E)), ...] when n = 4" $ do
let expected = [
Branch 'x' (Branch 'x' (Branch 'x' Empty Empty) Empty) (Branch 'x' Empty Empty),
Branch 'x' (Branch 'x' Empty Empty) (Branch 'x' (Branch 'x' Empty Empty) Empty),
Branch 'x' (Branch 'x' Empty (Branch 'x' Empty Empty)) (Branch 'x' Empty Empty),
Branch 'x' (Branch 'x' Empty Empty) (Branch 'x' Empty (Branch 'x' Empty Empty))
] in
cbalTree 4 `shouldBe` expected
describe "Problem 56" $ do
describe "mirror" $ do
it "returns True when (t1 t2) = (E, E)" $ do
mirror Empty Empty `shouldBe` True
it "returns False when (t1 t2) = (E, (B 'x' E E))" $ do
mirror Empty (Branch 'x' Empty Empty) `shouldBe` False
it "returns True when (t1, t2) = ((B 'x' E E), (B 'x' E E))" $ do
mirror (Branch 'x' Empty Empty) (Branch 'x' Empty Empty) `shouldBe` True
it "returns False when (t1, t2) = ((B 'x' (B 'x' E E) E), (B 'x' E E))" $ do
mirror (Branch 'x' (Branch 'x' Empty Empty) Empty) (Branch 'x' Empty Empty) `shouldBe` False
it "returns False when (t1, t2) = ((B 'x' (B 'x' E E) E), (B 'x' (B 'x' E E) E))" $ do
mirror (Branch 'x' (Branch 'x' Empty Empty) Empty) (Branch 'x' (Branch 'x' Empty Empty) Empty) `shouldBe` False
it "returns True when (t1, t2) = ((B 'x' E (B 'x' E E)), (B 'x' (B 'x' E E) E))" $ do
mirror (Branch 'x' Empty (Branch 'x' Empty Empty)) (Branch 'x' (Branch 'x' Empty Empty) Empty) `shouldBe` True
describe "symmetric" $ do
it "returns False when t = (B 'x' (B 'x' E E) E)" $ do
symmetric (Branch 'x' (Branch 'x' Empty Empty) Empty) `shouldBe` False
it "returns True when t = (B 'x' (B 'x' E E) (B 'x' E E))" $ do
symmetric (Branch 'x' (Branch 'x' Empty Empty) (Branch 'x' Empty Empty)) `shouldBe` True
it "returns False when t = (B 'x' (B 'x' E (B 'x' E E)) (B 'x' E (B 'x' E E)))" $ do
symmetric (Branch 'x' (Branch 'x' Empty (Branch 'x' Empty Empty)) (Branch 'x' Empty (Branch 'x' Empty Empty))) `shouldBe` False
it "returns True when t = (B 'x' (B 'x' (B 'x' E E) E) (B 'x' E (B 'x' E E)))" $ do
symmetric (Branch 'x' (Branch 'x' (Branch 'x' Empty Empty) Empty) (Branch 'x' Empty (Branch 'x' Empty Empty))) `shouldBe` True
describe "Problem 57" $ do
it "returns Empty when ns = []" $ do
construct [] `shouldBe` Empty
it "returns (B 1 E E) when ns = [1]" $ do
construct [1] `shouldBe` (Branch 1 Empty Empty)
it "returns (B 3 (B 2 (B 1 E E) E) (B 5 E (B 7 E E))) when ls = [3, 2, 5, 7, 1]" $ do
construct [3, 2, 5, 7, 1] `shouldBe` (Branch 3 (Branch 2 (Branch 1 Empty Empty) Empty) (Branch 5 Empty (Branch 7 Empty Empty)))
describe "symmetric test" $ do
it "returns True when ns = [5, 3, 18, 1, 4, 12, 21]" $ do
symmetric . construct $ [5, 3, 18, 1, 4, 12, 21]
it "returns True when ns = [3, 2, 5, 7, 1]" $ do
symmetric . construct $ [3, 2, 5, 7, 1]
describe "Problem 58" $ do
it "returns [E] when n = 0" $ do
symCbalTrees 0 `shouldBe` [Empty]
it "returns [(B 'x' E E)] when n = 1" $ do
symCbalTrees 1 `shouldBe` [Branch 'x' Empty Empty]
it "returns [] when n = 2" $ do
symCbalTrees 2 `shouldBe` []
it "returns [(B 'x' (B 'x' E E) (B 'x' E E))] when n = 3" $ do
symCbalTrees 3 `shouldBe` [Branch 'x' (Branch 'x' Empty Empty) (Branch 'x' Empty Empty)]
it "returns [(B 'x' (B 'x' E (B 'x' E E)) (B 'x' (B 'x' E E) E)), ...] when n = 5" $ do
let expected = [
Branch 'x' (Branch 'x' (Branch 'x' Empty Empty) Empty) (Branch 'x' Empty (Branch 'x' Empty Empty)),
Branch 'x' (Branch 'x' Empty (Branch 'x' Empty Empty)) (Branch 'x' (Branch 'x' Empty Empty) Empty)
] in
symCbalTrees 5 `shouldBe` expected
describe "Problem 59" $ do
it "returns [E] when (v, n) = ('x', 0)" $ do
hbalTree 'x' 0 `shouldBe` [Empty]
it "returns [(B 'x' E E)] when (v, n) = ('x', 1)" $ do
hbalTree 'x' 1 `shouldBe` [Branch 'x' Empty Empty]
it "returns [(B 'x' (B 'x' E E) E), (B 'x' E (B 'x' E E)), (B 'x' (B 'x' E E) (B 'x' E E))] when (v, n) = ('x', 2)" $ do
hbalTree 'x' 2 `shouldBe` [(Branch 'x' (Branch 'x' Empty Empty) Empty), (Branch 'x' Empty (Branch 'x' Empty Empty)), (Branch 'x' (Branch 'x' Empty Empty) (Branch 'x' Empty Empty))]
it "returns 315 patterns when (v, n) = ('x', 3)" $ do
(length $ hbalTree 'x' 4) `shouldBe` 315
describe "Problem 60" $ do
describe "minHbalNodes" $ do
it "returns 0 when h = 0" $ do
minHbalNodes 0 `shouldBe` 0
it "returns 1 when h = 1" $ do
minHbalNodes 1 `shouldBe` 1
it "returns 2 when h = 2" $ do
minHbalNodes 2 `shouldBe` 2
it "returns 4 when h = 3" $ do
minHbalNodes 3 `shouldBe` 4
it "returns 7 when h = 4" $ do
minHbalNodes 4 `shouldBe` 7
it "returns 12 when h = 5" $ do
minHbalNodes 5 `shouldBe` 12
describe "maxHbalHeight" $ do
it "returns 0 when h = 0" $ do
maxHbalHeight 0 `shouldBe` 0
it "returns 1 when h = 1" $ do
maxHbalHeight 1 `shouldBe` 1
it "returns 2 when h = 2" $ do
maxHbalHeight 2 `shouldBe` 2
it "returns 2 when h = 3" $ do
maxHbalHeight 3 `shouldBe` 2
it "returns 3 when h = 4" $ do
maxHbalHeight 4 `shouldBe` 3
it "returns 3 when h = 5" $ do
maxHbalHeight 5 `shouldBe` 3
it "returns 4 when h = 7" $ do
maxHbalHeight 7 `shouldBe` 4
it "returns 4 when h = 8" $ do
maxHbalHeight 8 `shouldBe` 4
describe "minHbalHeight" $ do
it "returns 0 when h = 0" $ do
minHbalHeight 0 `shouldBe` 0
it "returns 1 when h = 1" $ do
minHbalHeight 1 `shouldBe` 1
it "returns 2 when h = 2" $ do
minHbalHeight 2 `shouldBe` 2
it "returns 2 when h = 3" $ do
minHbalHeight 3 `shouldBe` 2
it "returns 3 when h = 4" $ do
minHbalHeight 4 `shouldBe` 3
it "returns 3 when h = 5" $ do
minHbalHeight 5 `shouldBe` 3
it "returns 4 when h = 7" $ do
minHbalHeight 7 `shouldBe` 3
it "returns 4 when h = 8" $ do
minHbalHeight 8 `shouldBe` 4
describe "nodeCount" $ do
it "returns 0 when t = E" $ do
nodeCount Empty `shouldBe` 0
it "returns 1 when t = (B 'x' E E)" $ do
nodeCount (Branch 'x' Empty Empty) `shouldBe` 1
it "returns 2 when t = (B 'x' (B 'x' E E) E)" $ do
nodeCount (Branch 'x' (Branch 'x' Empty Empty) Empty) `shouldBe` 2
it "returns 2 when t = (B 'x' E (B 'x' E E))" $ do
nodeCount (Branch 'x' Empty (Branch 'x' Empty Empty)) `shouldBe` 2
it "returns 3 when t = (B 'x' (B 'x' E E) (B 'x' E E))" $ do
nodeCount (Branch 'x' (Branch 'x' Empty Empty) (Branch 'x' Empty Empty)) `shouldBe` 3
it "returns 4 when t = (B 'x' (B 'x' (B 'x' E E) E) (B 'x' E E))" $ do
nodeCount (Branch 'x' (Branch 'x' (Branch 'x' Empty Empty) Empty) (Branch 'x' Empty Empty)) `shouldBe` 4
it "returns 4 when t = (B 'x' (B 'x' E (B 'x' E E)) (B 'x' E E))" $ do
nodeCount (Branch 'x' (Branch 'x' Empty (Branch 'x' Empty Empty)) (Branch 'x' Empty Empty)) `shouldBe` 4
it "returns 4 when t = (B 'x' (B 'x' E E) (B 'x' (B 'x' E E) E))" $ do
nodeCount (Branch 'x' (Branch 'x' Empty Empty) (Branch 'x' (Branch 'x' Empty Empty) Empty)) `shouldBe` 4
it "returns 4 when t = (B 'x' (B 'x' E E) (B 'x' E (B 'x' E E)))" $ do
nodeCount (Branch 'x' (Branch 'x' Empty Empty) (Branch 'x' Empty (Branch 'x' Empty Empty))) `shouldBe` 4
it "returns 5 when t = (B 'x' (B 'x' (B 'x' E E) (B 'x' E E)) (B 'x' E E))" $ do
nodeCount (Branch 'x' (Branch 'x' (Branch 'x' Empty Empty) (Branch 'x' Empty Empty)) (Branch 'x' Empty Empty)) `shouldBe` 5
it "returns 5 when t = (B 'x' (B 'x' (B 'x' E E) E) (B 'x' (B 'x' E E) E))" $ do
nodeCount (Branch 'x' (Branch 'x' (Branch 'x' Empty Empty) Empty) (Branch 'x' (Branch 'x' Empty Empty) Empty)) `shouldBe` 5
describe "hbalTreeNodes" $ do
it "returns [E] when (v, n) = ('x', 0)" $ do
hbalTreeNodes 'x' 0 `shouldBe` [Empty]
it "returns [(B 'x' E E)] when (v, n) = ('x', 1)" $ do
hbalTreeNodes 'x' 1 `shouldBe` [Branch 'x' Empty Empty]
it "returns [(B 'x' (B 'x' E E) E), (B 'x' E (B 'x' E E))] when (v, n) = ('x', 2)" $ do
hbalTreeNodes 'x' 2 `shouldBe` [Branch 'x' (Branch 'x' Empty Empty) Empty, Branch 'x' Empty (Branch 'x' Empty Empty)]
it "returns [(B 'x' (B 'x' E E) (B 'x' E E))] when (v, n) = ('x', 3)" $ do
hbalTreeNodes 'x' 3 `shouldBe` [Branch 'x' (Branch 'x' Empty Empty) (Branch 'x' Empty Empty)]
it "returns [(B 'x' (B 'x' (B 'x' E E) E) (B 'x' E E)), ...] when (v, n) = ('x', 4)" $ do
let expected = [
Branch 'x' (Branch 'x' (Branch 'x' Empty Empty) Empty) (Branch 'x' Empty Empty),
Branch 'x' (Branch 'x' Empty Empty) (Branch 'x' (Branch 'x' Empty Empty) Empty),
Branch 'x' (Branch 'x' Empty (Branch 'x' Empty Empty)) (Branch 'x' Empty Empty),
Branch 'x' (Branch 'x' Empty Empty) (Branch 'x' Empty (Branch 'x' Empty Empty))
] in
hbalTreeNodes 'x' 4 `shouldBe` expected
-- FIXME ちょっと時間かかるので少し消しておく
-- it "returns 1553 patterns when (v, n) = ('x', 15)" $ do
-- length (hbalTreeNodes 'x' 15) `shouldBe` 1553
describe "Problem 61" $ do
it "returns 0 when t = E" $ do
countLeaves Empty `shouldBe` 0
it "returns 1 when t = (B 'x' E E)" $ do
countLeaves (Branch 'x' Empty Empty) `shouldBe` 1
it "returns 1 when t = (B 'x' (B 'x' E E) E)" $ do
countLeaves (Branch 'x' (Branch 'x' Empty Empty) Empty) `shouldBe` 1
it "returns 1 when t = (B 'x' E (B 'x' E E))" $ do
countLeaves (Branch 'x' Empty (Branch 'x' Empty Empty)) `shouldBe` 1
it "returns 2 when t = (B 'x' (B 'x' E E) (B 'x' E E))" $ do
countLeaves (Branch 'x' (Branch 'x' Empty Empty) (Branch 'x' Empty Empty)) `shouldBe` 2
it "returns 2 when t = (B 'x' (B 'x' (B 'x' E E) E) (B 'x' E E))" $ do
countLeaves (Branch 'x' (Branch 'x' (Branch 'x' Empty Empty) Empty) (Branch 'x' Empty Empty)) `shouldBe` 2
it "returns 2 when t = (B 'x' (B 'x' E (B 'x' E E)) (B 'x' E E))" $ do
countLeaves (Branch 'x' (Branch 'x' Empty (Branch 'x' Empty Empty)) (Branch 'x' Empty Empty)) `shouldBe` 2
it "returns 2 when t = (B 'x' (B 'x' E E) (B 'x' (B 'x' E E) E))" $ do
countLeaves (Branch 'x' (Branch 'x' Empty Empty) (Branch 'x' (Branch 'x' Empty Empty) Empty)) `shouldBe` 2
it "returns 2 when t = (B 'x' (B 'x' E E) (B 'x' E (B 'x' E E)))" $ do
countLeaves (Branch 'x' (Branch 'x' Empty Empty) (Branch 'x' Empty (Branch 'x' Empty Empty))) `shouldBe` 2
it "returns 2 when t = (B 1 (B 2 E (B 4 E E)) (B 2 E E))" $ do
countLeaves (Branch (1 :: Int) (Branch 2 Empty (Branch 4 Empty Empty)) (Branch 2 Empty Empty)) `shouldBe` 2
it "returns 3 when t = (B 'x' (B 'x' (B 'x' E E) (B 'x' E E)) (B 'x' E E))" $ do
countLeaves (Branch 'x' (Branch 'x' (Branch 'x' Empty Empty) (Branch 'x' Empty Empty)) (Branch 'x' Empty Empty)) `shouldBe` 3
it "returns 2 when t = (B 'x' (B 'x' (B 'x' E E) E) (B 'x' (B 'x' E E) E))" $ do
countLeaves (Branch 'x' (Branch 'x' (Branch 'x' Empty Empty) Empty) (Branch 'x' (Branch 'x' Empty Empty) Empty)) `shouldBe` 2
describe "Problem 61A" $ do
it "returns [] when t = E" $ do
leaves Empty `shouldBe` ([] :: [Int])
it "returns [1] when t = (B 1 E E)" $ do
leaves (Branch (1 :: Int) Empty Empty) `shouldBe` [1]
it "returns [2] when t = (B 1 (B 2 E E) E)" $ do
leaves (Branch (1 :: Int) (Branch 2 Empty Empty) Empty) `shouldBe` [2]
it "returns [3] when t = (B 1 E (B 3 E E))" $ do
leaves (Branch (1 :: Int) Empty (Branch 3 Empty Empty)) `shouldBe` [3]
it "returns [2, 3] when t = (B 1 (B 2 E E) (B 3 E E))" $ do
leaves (Branch (1 :: Int) (Branch 2 Empty Empty) (Branch 3 Empty Empty)) `shouldBe` [2, 3]
it "returns [3, 4] when t = (B 1 (B 2 (B 3 E E) E) (B 4 E E))" $ do
leaves (Branch (1 :: Int) (Branch 2 (Branch 3 Empty Empty) Empty) (Branch 4 Empty Empty)) `shouldBe` [3, 4]
it "returns [3, 4] when t = (B 1 (B 2 E (B 3 E E)) (B 4 E E))" $ do
leaves (Branch (1 :: Int) (Branch 2 Empty (Branch 3 Empty Empty)) (Branch 4 Empty Empty)) `shouldBe` [3, 4]
it "returns [2, 4] when t = (B 1 (B 2 E E) (B 3 (B 4 E E) E))" $ do
leaves (Branch (1 :: Int) (Branch 2 Empty Empty) (Branch 3 (Branch 4 Empty Empty) Empty)) `shouldBe` [2, 4]
it "returns [2, 4] when t = (B 1 (B 2 E E) (B 3 E (B 4 E E)))" $ do
leaves (Branch (1 :: Int) (Branch 2 Empty Empty) (Branch 3 Empty (Branch 4 Empty Empty))) `shouldBe` [2, 4]
it "returns [4, 2] when t = (B 1 (B 2 E (B 4 E E)) (B 2 E E))" $ do
leaves (Branch (1 :: Int) (Branch 2 Empty (Branch 4 Empty Empty)) (Branch 2 Empty Empty)) `shouldBe` [4, 2]
it "returns [3, 4, 5] when t = (B 1 (B 2 (B 3 E E) (B 4 E E)) (B 5 E E))" $ do
leaves (Branch (1 :: Int) (Branch 2 (Branch 3 Empty Empty) (Branch 4 Empty Empty)) (Branch 5 Empty Empty)) `shouldBe` [3, 4, 5]
it "returns [3, 5] when t = (B 1 (B 2 (B 3 E E) E) (B 4 (B 5 E E) E))" $ do
leaves (Branch (1 :: Int) (Branch 2 (Branch 3 Empty Empty) Empty) (Branch 4 (Branch 5 Empty Empty) Empty)) `shouldBe` [3, 5]
describe "Problem 62" $ do
it "returns [] when t = E" $ do
internals Empty `shouldBe` ([] :: [Int])
it "returns [] when t = (B 1 E E)" $ do
internals (Branch (1 :: Int) Empty Empty) `shouldBe` []
it "returns [1] when t = (B 1 (B 2 E E) E)" $ do
internals (Branch (1 :: Int) (Branch 2 Empty Empty) Empty) `shouldBe` [1]
it "returns [1] when t = (B 1 E (B 3 E E))" $ do
internals (Branch (1 :: Int) Empty (Branch 3 Empty Empty)) `shouldBe` [1]
it "returns [1] when t = (B 1 (B 2 E E) (B 3 E E))" $ do
internals (Branch (1 :: Int) (Branch 2 Empty Empty) (Branch 3 Empty Empty)) `shouldBe` [1]
it "returns [1, 2] when t = (B 1 (B 2 (B 3 E E) E) (B 4 E E))" $ do
internals (Branch (1 :: Int) (Branch 2 (Branch 3 Empty Empty) Empty) (Branch 4 Empty Empty)) `shouldBe` [1, 2]
it "returns [1, 2] when t = (B 1 (B 2 E (B 3 E E)) (B 4 E E))" $ do
internals (Branch (1 :: Int) (Branch 2 Empty (Branch 3 Empty Empty)) (Branch 4 Empty Empty)) `shouldBe` [1, 2]
it "returns [1, 3] when t = (B 1 (B 2 E E) (B 3 (B 4 E E) E))" $ do
internals (Branch (1 :: Int) (Branch 2 Empty Empty) (Branch 3 (Branch 4 Empty Empty) Empty)) `shouldBe` [1, 3]
it "returns [1, 3] when t = (B 1 (B 2 E E) (B 3 E (B 4 E E)))" $ do
internals (Branch (1 :: Int) (Branch 2 Empty Empty) (Branch 3 Empty (Branch 4 Empty Empty))) `shouldBe` [1, 3]
it "returns [1, 2] when t = (B 1 (B 2 E (B 4 E E)) (B 2 E E))" $ do
internals (Branch (1 :: Int) (Branch 2 Empty (Branch 4 Empty Empty)) (Branch 2 Empty Empty)) `shouldBe` [1, 2]
it "returns [1, 2] when t = (B 1 (B 2 (B 3 E E) (B 4 E E)) (B 5 E E))" $ do
internals (Branch (1 :: Int) (Branch 2 (Branch 3 Empty Empty) (Branch 4 Empty Empty)) (Branch 5 Empty Empty)) `shouldBe` [1, 2]
it "returns [1, 2, 4] when t = (B 1 (B 2 (B 3 E E) E) (B 4 (B 5 E E) E))" $ do
internals (Branch (1 :: Int) (Branch 2 (Branch 3 Empty Empty) Empty) (Branch 4 (Branch 5 Empty Empty) Empty)) `shouldBe` [1, 2, 4]
describe "Problem 62B" $ do
it "returns [] when (t, n) = (E, 1)" $ do
atLevel Empty 1 `shouldBe` ([] :: [Int])
it "returns [1] when (t, n) = ((B 1 E E), 1)" $ do
atLevel (Branch (1 :: Int) Empty Empty) 1 `shouldBe` [1]
it "returns [] when (t, n) = ((B 1 E E), 2)" $ do
atLevel (Branch (1 :: Int) Empty Empty) 2 `shouldBe` []
it "returns [] when (t, n) = ((B 1 (B 2 E (B 4 E E)) (B 2 E E)), 0)" $ do
atLevel (Branch (1 :: Int) (Branch 2 Empty (Branch 4 Empty Empty)) (Branch 2 Empty Empty)) 0 `shouldBe` []
it "returns [1] when (t, n) = ((B 1 (B 2 E (B 4 E E)) (B 2 E E)), 1)" $ do
atLevel (Branch (1 :: Int) (Branch 2 Empty (Branch 4 Empty Empty)) (Branch 2 Empty Empty)) 1 `shouldBe` [1]
it "returns [2, 2] when (t, n) = ((B 1 (B 2 E (B 4 E E)) (B 2 E E)), 2)" $ do
atLevel (Branch (1 :: Int) (Branch 2 Empty (Branch 4 Empty Empty)) (Branch 2 Empty Empty)) 2 `shouldBe` [2, 2]
it "returns [4] when (t, n) = ((B 1 (B 2 E (B 4 E E)) (B 2 E E)), 3)" $ do
atLevel (Branch (1 :: Int) (Branch 2 Empty (Branch 4 Empty Empty)) (Branch 2 Empty Empty)) 3 `shouldBe` [4]
it "returns [] when (t, n) = ((B 1 (B 2 E (B 4 E E)) (B 2 E E)), 4)" $ do
atLevel (Branch (1 :: Int) (Branch 2 Empty (Branch 4 Empty Empty)) (Branch 2 Empty Empty)) 4 `shouldBe` []
describe "Problem 63" $ do
describe "completeBinaryTree" $ do
it "returns Empty when n = 0" $ do
completeBinaryTree 0 `shouldBe` Empty
it "returns (B 'x' E E) when n = 1" $ do
completeBinaryTree 1 `shouldBe` Branch 'x' Empty Empty
it "returns (B 'x' (B 'x' E E) E) when n = 2" $ do
completeBinaryTree 2 `shouldBe` Branch 'x' (Branch 'x' Empty Empty) Empty
it "returns (B 'x' (B 'x' E E) (B 'x' E E)) when n = 3" $ do
completeBinaryTree 3 `shouldBe` Branch 'x' (Branch 'x' Empty Empty) (Branch 'x' Empty Empty)
it "returns (B 'x' (B 'x' (B 'x' E E) E) (B 'x' E E)) when n = 4" $ do
completeBinaryTree 4 `shouldBe` Branch 'x' (Branch 'x' (Branch 'x' Empty Empty) Empty) (Branch 'x' Empty Empty)
it "returns (B 'x' (B 'x' (B 'x' E E) (B 'x' E E)) (B 'x' E E)) when n = 5" $ do
completeBinaryTree 5 `shouldBe` Branch 'x' (Branch 'x' (Branch 'x' Empty Empty) (Branch 'x' Empty Empty)) (Branch 'x' Empty Empty)
it "returns (B 'x' (B 'x' (B 'x' E E) (B 'x' E E)) (B 'x' (B 'x' E E) E)) when n = 6" $ do
completeBinaryTree 6 `shouldBe` Branch 'x' (Branch 'x' (Branch 'x' Empty Empty) (Branch 'x' Empty Empty)) (Branch 'x' (Branch 'x' Empty Empty) Empty)
it "returns (B 'x' (B 'x' (B 'x' E E) (B 'x' E E)) (B 'x' (B 'x' E E) (B 'x' E E))) when n = 7" $ do
completeBinaryTree 7 `shouldBe` Branch 'x' (Branch 'x' (Branch 'x' Empty Empty) (Branch 'x' Empty Empty)) (Branch 'x' (Branch 'x' Empty Empty) (Branch 'x' Empty Empty))
describe "isCompleteBinaryTree" $ do
it "returns True when t = Empty" $ do
isCompleteBinaryTree Empty `shouldBe` True
it "returns True when t = (B 'x' E E)" $ do
isCompleteBinaryTree (Branch 'x' Empty Empty) `shouldBe` True
it "returns True when t = (B 'x' (B 'x' E E) E)" $ do
isCompleteBinaryTree (Branch 'x' (Branch 'x' Empty Empty) Empty) `shouldBe` True
it "returns False when t = (B 'x' E (B 'x' E E))" $ do
isCompleteBinaryTree (Branch 'x' Empty (Branch 'x' Empty Empty)) `shouldBe` False
it "returns True when t = (B 'x' (B 'x' E E) (B 'x' E E))" $ do
isCompleteBinaryTree (Branch 'x' (Branch 'x' Empty Empty) (Branch 'x' Empty Empty)) `shouldBe` True
it "returns True when t = (B 'x' (B 'x' (B 'x' E E) E) (B 'x' E E))" $ do
isCompleteBinaryTree (Branch 'x' (Branch 'x' (Branch 'x' Empty Empty) Empty) (Branch 'x' Empty Empty)) `shouldBe` True
it "returns False when t = (B 'x' (B 'x' E (B 'x' E E)) (B 'x' E E))" $ do
isCompleteBinaryTree (Branch 'x' (Branch 'x' Empty (Branch 'x' Empty Empty)) (Branch 'x' Empty Empty)) `shouldBe` False
describe "isCompleteBinaryTree + completeBinaryTree" $ do
it "returns True" $ do
isCompleteBinaryTree (completeBinaryTree 4) `shouldBe` True
describe "Problem 64" $ do
it "returns Empty when t = E" $ do
layout (Empty :: Tree Char) `shouldBe` Empty
it "returns (B ('n', (1, 1)) Empty Empty) when t = (B 'n' E E)" $ do
layout (Branch 'n' Empty Empty) `shouldBe` (Branch ('n', (1, 1)) Empty Empty)
it "returns (B ('n', (2, 1)) (B ('k', (1, 2)) E E) E) when t = (B 'n' (B 'k' E E) E)" $ do
layout (Branch 'n' (Branch 'k' Empty Empty) Empty) `shouldBe` (Branch ('n', (2, 1)) (Branch ('k', (1, 2)) Empty Empty) Empty)
it "returns (B ('n', (1, 1)) E (B ('k', (2, 2)) E E)) when t = (B 'n' E (B 'k' E E))" $ do
layout (Branch 'n' Empty (Branch 'k' Empty Empty)) `shouldBe` (Branch ('n', (1, 1)) Empty (Branch ('k', (2, 2)) Empty Empty))
it "returns (B ('n', (2, 1)) (B ('k', (1, 2)) E E) (B ('u', (3, 2)) E E)) when t = (B 'n' (B 'k' E E) (B 'u' E E))" $ do
layout (Branch 'n' (Branch 'k' Empty Empty) (Branch 'u' Empty Empty)) `shouldBe` (Branch ('n', (2, 1)) (Branch ('k', (1, 2)) Empty Empty) (Branch ('u', (3, 2)) Empty Empty))
it "returns (B ('n', (3, 1)) (B ('k', (2, 2)) E E) (B ('u', (1, 3)) E E)) when t = (B 'n' (B 'k' (B 'u' E E) E) E)" $ do
layout (Branch 'n' (Branch 'k' (Branch 'u' Empty Empty) Empty) Empty) `shouldBe` (Branch ('n', (3, 1)) (Branch ('k', (2, 2)) (Branch ('u', (1, 3)) Empty Empty) Empty) Empty)
it "returns (B ('a', (1, 1)) E (B ('b', (2, 2)) E (B ('c', (3, 3)) E E))) when t = (B 'a' E (B 'b' E (B 'c' E E)))" $ do
layout (Branch 'a' Empty (Branch 'b' Empty (Branch 'c' Empty Empty))) `shouldBe` (Branch ('a', (1, 1)) Empty (Branch ('b', (2, 2)) Empty (Branch ('c', (3, 3)) Empty Empty)))
it "returns (B ('a', (3, 1)) (B ('b', (1, 2)) E (B ('c', (2, 3)) E E)) (B ('d', (4, 2) E E))) when t = (B 'a' (B 'b' E (B 'c' E E)) (B 'd' E E))" $ do
layout (Branch 'a' (Branch 'b' Empty (Branch 'c' Empty Empty)) (Branch 'd' Empty Empty)) `shouldBe` ((Branch ('a', (3, 1)) (Branch ('b', (1, 2)) Empty (Branch ('c', (2, 3)) Empty Empty)) (Branch ('d', (4, 2)) Empty Empty)))
it "returns layout when t = tree64(in problem)" $ do
let tree64 = Branch 'n'
(Branch 'k'
(Branch 'c'
(Branch 'a' Empty Empty)
(Branch 'h'
(Branch 'g'
(Branch 'e' Empty Empty)
Empty
)
Empty
)
)
(Branch 'm' Empty Empty)
)
(Branch 'u'
(Branch 'p'
Empty
(Branch 's'
(Branch 'q' Empty Empty)
Empty
)
)
Empty
)
expected = Branch ('n', (8, 1))
(Branch ('k', (6, 2))
(Branch ('c', (2, 3))
(Branch ('a', (1, 4)) Empty Empty)
(Branch ('h', (5, 4))
(Branch ('g', (4, 5))
(Branch ('e', (3, 6)) Empty Empty)
Empty
)
Empty
)
)
(Branch ('m', (7, 3)) Empty Empty)
)
(Branch ('u', (12, 2))
(Branch ('p', (9, 3))
Empty
(Branch ('s', (11, 4))
(Branch ('q', (10, 5)) Empty Empty)
Empty
)
)
Empty
)
in layout tree64 `shouldBe` expected
describe "Problem 65" $ do
it "returns Empty when t = E" $ do
layout2 (Empty :: Tree Int) `shouldBe` Empty
it "returns (B ('n', (1, 1)) Empty Empty) when t = (B 'n' E E)" $ do
layout2 (Branch 'n' Empty Empty) `shouldBe` (Branch ('n', (1, 1)) Empty Empty)
it "returns (B ('n', (2, 1)) (B ('k', (1, 2)) E E) E) when t = (B 'n' (B 'k' E E) E)" $ do
layout2 (Branch 'n' (Branch 'k' Empty Empty) Empty) `shouldBe` (Branch ('n', (2, 1)) (Branch ('k', (1, 2)) Empty Empty) Empty)
it "returns (B ('n', (1, 1)) E (B ('k', (2, 2)) E E)) when t = (B 'n' E (B 'k' E E))" $ do
layout2 (Branch 'n' Empty (Branch 'k' Empty Empty)) `shouldBe` (Branch ('n', (1, 1)) Empty (Branch ('k', (2, 2)) Empty Empty))
it "returns (B ('n', (2, 1)) (B ('k', (1, 2)) E E) (B ('u', (3, 2)) E E)) when t = (B 'n' (B 'k' E E) (B 'u' E E))" $ do
layout2 (Branch 'n' (Branch 'k' Empty Empty) (Branch 'u' Empty Empty)) `shouldBe` (Branch ('n', (2, 1)) (Branch ('k', (1, 2)) Empty Empty) (Branch ('u', (3, 2)) Empty Empty))
it "returns (B ('n', (4, 1)) (B ('k', (2, 2)) E E) (B ('u', (1, 3)) E E)) when t = (B 'n' (B 'k' (B 'u' E E) E) E)" $ do
layout2 (Branch 'n' (Branch 'k' (Branch 'u' Empty Empty) Empty) Empty) `shouldBe` (Branch ('n', (4, 1)) (Branch ('k', (2, 2)) (Branch ('u', (1, 3)) Empty Empty) Empty) Empty)
it "returns (B ('a', (1, 1)) E (B ('b', (3, 2)) E (B ('c', (4, 3)) E E))) when t = (B 'a' E (B 'b' E (B 'c' E E)))" $ do
layout2 (Branch 'a' Empty (Branch 'b' Empty (Branch 'c' Empty Empty))) `shouldBe` (Branch ('a', (1, 1)) Empty (Branch ('b', (3, 2)) Empty (Branch ('c', (4, 3)) Empty Empty)))
it "returns (B ('a', (3, 1)) (B ('b', (1, 2)) E (B ('c', (2, 3)) E E)) (B ('d', (5, 2) E E))) when t = (B 'a' (B 'b' E (B 'c' E E)) (B 'd' E E))" $ do
layout2 (Branch 'a' (Branch 'b' Empty (Branch 'c' Empty Empty)) (Branch 'd' Empty Empty)) `shouldBe` ((Branch ('a', (3, 1)) (Branch ('b', (1, 2)) Empty (Branch ('c', (2, 3)) Empty Empty)) (Branch ('d', (5, 2)) Empty Empty)))
it "returns layout when t = tree65(in problem)" $ do
let tree65 = Branch 'n'
(Branch 'k'
(Branch 'c'
(Branch 'a' Empty Empty)
(Branch 'e'
(Branch 'd' Empty Empty)
(Branch 'g' Empty Empty)
)
)
(Branch 'm' Empty Empty)
)
(Branch 'u'
(Branch 'p'
Empty
(Branch 'q' Empty Empty)
)
Empty
)
expected = Branch ('n', (15, 1))
(Branch ('k', (7, 2))
(Branch ('c', (3, 3))
(Branch ('a', (1, 4)) Empty Empty)
(Branch ('e', (5, 4))
(Branch ('d', (4, 5)) Empty Empty)
(Branch ('g', (6, 5)) Empty Empty)
)
)
(Branch ('m', (11, 3)) Empty Empty)
)
(Branch ('u', (23, 2))
(Branch ('p', (19, 3))
Empty
(Branch ('q', (21, 4)) Empty Empty)
)
Empty
)
in layout2 tree65 `shouldBe` expected
describe "Problem 66" $ do
it "pass" $ do
True `shouldBe` True
describe "Problem 67A" $ do
describe "treeToString" $ do
it "returns \"\" when t = E" $ do
treeToString Empty `shouldBe` ""
it "returns \"a\" when t = (B 'a' E E)" $ do
treeToString (Branch 'a' Empty Empty) `shouldBe` "a"
it "returns \"a(b,)\" when t = (B 'a' (B 'b' E E) E)" $ do
treeToString (Branch 'a' (Branch 'b' Empty Empty) Empty) `shouldBe` "a(b,)"
it "returns \"a(,c)\" when t = (B 'a' E (B 'c' E E))" $ do
treeToString (Branch 'a' Empty (Branch 'c' Empty Empty)) `shouldBe` "a(,c)"
it "returns \"a(b,c)\" when t = (B 'a' (B 'b' E E) (B 'c' E E))" $ do
treeToString (Branch 'a' (Branch 'b' Empty Empty) (Branch 'c' Empty Empty)) `shouldBe` "a(b,c)"
it "returns \"a(b(,c),d)\" when t = (B 'a' (B 'b' E (B 'c' E E)) (B 'd' E E))" $ do
treeToString (Branch 'a' (Branch 'b' Empty (Branch 'c' Empty Empty)) (Branch 'd' Empty Empty)) `shouldBe` "a(b(,c),d)"
it "returns \"a(b(d,e),c(,f(g,)))\" when t = (B 'a' (B 'b' (B 'd' E E) (B 'e' E E)) (B 'c' E (B 'f' (B 'g' E E) E)))" $ do
treeToString (Branch 'a' (Branch 'b' (Branch 'd' Empty Empty) (Branch 'e' Empty Empty)) (Branch 'c' Empty (Branch 'f' (Branch 'g' Empty Empty) Empty))) `shouldBe` "a(b(d,e),c(,f(g,)))"
describe "stringToTree" $ do
it "returns E when s = \"\"" $ do
stringToTree "" `shouldBe` Empty
it "returns (B 'a' E E) when s = \"a\"" $ do
stringToTree "a" `shouldBe` (Branch 'a' Empty Empty)
it "returns (B 'a' (B 'b' E E) E) when s = \"a(b,)\"" $ do
stringToTree "a(b,)" `shouldBe` (Branch 'a' (Branch 'b' Empty Empty) Empty)
it "returns (B 'a' E (B 'c' E E)) when s = \"a(,c)\"" $ do
stringToTree "a(,c)" `shouldBe` (Branch 'a' Empty (Branch 'c' Empty Empty))
it "returns (B 'a' (B 'b' E E) (B 'c' E E)) when s = \"a(b,c)\"" $ do
stringToTree "a(b,c)" `shouldBe` (Branch 'a' (Branch 'b' Empty Empty) (Branch 'c' Empty Empty))
it "returns (B 'a' (B 'b' E (B 'c' E E)) (B 'd' E E)) when s = \"a(b(,c),d)\"" $ do
stringToTree "a(b(,c),d)" `shouldBe` (Branch 'a' (Branch 'b' Empty (Branch 'c' Empty Empty)) (Branch 'd' Empty Empty))
it "returns (B 'a' (B 'b' (B 'd' E E) (B 'e' E E)) (B 'c' E (B 'f' (B 'g' E E) E))) when s = \"a(b(d,e),c(,f(g,)))\"" $ do
stringToTree "a(b(d,e),c(,f(g,)))" `shouldBe` (Branch 'a' (Branch 'b' (Branch 'd' Empty Empty) (Branch 'e' Empty Empty)) (Branch 'c' Empty (Branch 'f' (Branch 'g' Empty Empty) Empty)))
it "returns (B 'x' (B 'y' E E) (B 'a' E (B 'b' E E))) when s = \"x(y,a(,b))\"" $ do
stringToTree "x(y,a(,b))" `shouldBe` (Branch 'x' (Branch 'y' Empty Empty) (Branch 'a' Empty (Branch 'b' Empty Empty)))
it "throws exception when s = \"xy,a(,b))\" (illegal format)" $ do
evaluate (stringToTree "xy,a(,b))" ) `shouldThrow` errorCall "illegal format"
describe "treeToString + stringToTree" $ do
it "returns same tree" $ do
let t = Branch 'a' (Branch 'b' Empty (Branch 'c' Empty Empty)) (Branch 'd' (Branch 'e' (Branch 'f' Empty Empty) (Branch 'g' Empty Empty)) (Branch 'h' Empty Empty))
in (stringToTree . treeToString) t `shouldBe` t
describe "Problem 68" $ do
describe "treeToPreorder" $ do
it "returns [] when t = E" $ do
treeToPreorder (Empty :: Tree Int) `shouldBe` []
it "returns [1] when t = (B 1 E E)" $ do
treeToPreorder (Branch (1 :: Int) Empty Empty) `shouldBe` [1]
it "returns [1, 2] when t = (B 1 (B 2 E E) E)" $ do
treeToPreorder (Branch (1 :: Int) (Branch 2 Empty Empty) Empty) `shouldBe` [1, 2]
it "returns [1, 3] when t = (B 1 E (B 3 E E))" $ do
treeToPreorder (Branch (1 :: Int) Empty (Branch 3 Empty Empty)) `shouldBe` [1, 3]
it "returns [1, 2, 3] when t = (B 1 (B 2 E E) (B 3 E E))" $ do
treeToPreorder (Branch (1 :: Int) (Branch 2 Empty Empty) (Branch 3 Empty Empty)) `shouldBe` [1, 2, 3]
it "returns [1, 2, 3] when t = (B 1 (B 2 (B 3 E E) E) E)" $ do
treeToPreorder (Branch (1 :: Int) (Branch 2 (Branch 3 Empty Empty) Empty) Empty) `shouldBe` [1, 2, 3]
it "returns [1, 2, 3] when t = (B 1 E (B 2 E (B 3 E E)))" $ do
treeToPreorder (Branch (1 :: Int) Empty (Branch 2 Empty (Branch 3 Empty Empty))) `shouldBe` [1, 2, 3]
it "returns [1, 2, 3, 4] when t = (B 1 (B 2 E (B 3 E E)) (B 4 E E))" $ do
treeToPreorder (Branch (1 :: Int) (Branch 2 Empty (Branch 3 Empty Empty)) (Branch 4 Empty Empty)) `shouldBe` [1, 2, 3, 4]
it "returns [1, 2, 4, 5, 3, 6, 7] when t = (B 1 (B 2 (B 3 E E) (B 4 E E)) (B 5 E (B 6 (B 7 E E) E)))" $ do
treeToPreorder (Branch (1 :: Int) (Branch 2 (Branch 4 Empty Empty) (Branch 5 Empty Empty)) (Branch 3 Empty (Branch 6 (Branch 7 Empty Empty) Empty))) `shouldBe` [1, 2, 4, 5, 3, 6, 7]
describe "treeToInorder" $ do
it "returns [] when t = E" $ do
treeToInorder (Empty :: Tree Int) `shouldBe` []
it "returns [1] when t = (B 1 E E)" $ do
treeToInorder (Branch (1 :: Int) Empty Empty) `shouldBe` [1]
it "returns [2, 1] when t = (B 1 (B 2 E E) E)" $ do
treeToInorder (Branch (1 :: Int) (Branch 2 Empty Empty) Empty) `shouldBe` [2, 1]
it "returns [1, 3] when t = (B 1 E (B 3 E E))" $ do
treeToInorder (Branch (1 :: Int) Empty (Branch 3 Empty Empty)) `shouldBe` [1, 3]
it "returns [2, 1, 3] when t = (B 1 (B 2 E E) (B 3 E E))" $ do
treeToInorder (Branch (1 :: Int) (Branch 2 Empty Empty) (Branch 3 Empty Empty)) `shouldBe` [2, 1, 3]
it "returns [3, 2, 1] when t = (B 1 (B 2 (B 3 E E) E) E)" $ do
treeToInorder (Branch (1 :: Int) (Branch 2 (Branch 3 Empty Empty) Empty) Empty) `shouldBe` [3, 2, 1]
it "returns [1, 2, 3] when t = (B 1 E (B 2 E (B 3 E E)))" $ do
treeToInorder (Branch (1 :: Int) Empty (Branch 2 Empty (Branch 3 Empty Empty))) `shouldBe` [1, 2, 3]
it "returns [2, 3, 1, 4] when t = (B 1 (B 2 E (B 3 E E)) (B 4 E E))" $ do
treeToInorder (Branch (1 :: Int) (Branch 2 Empty (Branch 3 Empty Empty)) (Branch 4 Empty Empty)) `shouldBe` [2, 3, 1, 4]
it "returns [4, 2, 5, 1, 3, 7, 6] when t = (B 1 (B 2 (B 3 E E) (B 4 E E)) (B 5 E (B 6 (B 7 E E) E)))" $ do
treeToInorder (Branch (1 :: Int) (Branch 2 (Branch 4 Empty Empty) (Branch 5 Empty Empty)) (Branch 3 Empty (Branch 6 (Branch 7 Empty Empty) Empty))) `shouldBe` [4, 2, 5, 1, 3, 7, 6]
describe "preInTree" $ do
it "returns E when (po, io) = ([], [])" $ do
preInTree ([] :: [Char]) [] `shouldBe` Empty
it "returns E when (po, io) = ([1], [])" $ do
preInTree [1 :: Int] [] `shouldBe` Empty
it "returns E when (po, io) = ([], [1])" $ do
preInTree [] [1 :: Int] `shouldBe` Empty
it "returns E when (po, io) = ([1, 2], [1])" $ do
preInTree [1 :: Int, 2] [1] `shouldBe` Empty
it "returns E when (po, io) = ([1], [1, 2])" $ do
preInTree [1 :: Int] [1, 2] `shouldBe` Empty
it "returns (B 1 E E) when (po, io) = ([1], [1])" $ do
preInTree [1 :: Int] [1] `shouldBe` (Branch 1 Empty Empty)
it "returns (B 1 (B 2 E E) E) when (po, io) = ([1, 2], [2, 1])" $ do
preInTree [1 :: Int, 2] [2, 1] `shouldBe` (Branch 1 (Branch 2 Empty Empty) Empty)
it "returns (B 1 E (B 3 E E)) when (po, io) = ([1, 3], [1, 3])" $ do
preInTree [1 :: Int, 3] [1, 3] `shouldBe` (Branch 1 Empty (Branch 3 Empty Empty))
it "returns (B 1 (B 2 E E) (B 3 E E)) when (po, io) = ([1, 2, 3], [2, 1, 3])" $ do
preInTree [1 :: Int, 2, 3] [2, 1, 3] `shouldBe` (Branch 1 (Branch 2 Empty Empty) (Branch 3 Empty Empty))
it "returns (B 1 (B 2 (B 3 E E) E) E) when (po, io) = ([1, 2, 3], [3, 2, 1])" $ do
preInTree [1 :: Int, 2, 3] [3, 2, 1] `shouldBe` (Branch 1 (Branch 2 (Branch 3 Empty Empty) Empty) Empty)
it "returns (B 1 (B 2 (B 3 E E) E) E) when (po, io) = ([1, 2, 3], [1, 2, 3])" $ do
preInTree [1 :: Int, 2, 3] [1, 2, 3] `shouldBe` (Branch 1 Empty (Branch 2 Empty (Branch 3 Empty Empty)))
it "returns (B 1 (B 2 E (B 3 E E)) (B 4 E E)) when (po, io) = ([1, 2, 3, 4], [2, 3, 1, 4])" $ do
preInTree [1 :: Int, 2, 3, 4] [2, 3, 1, 4] `shouldBe` (Branch 1 (Branch 2 Empty (Branch 3 Empty Empty)) (Branch 4 Empty Empty))
it "returns (B 1 (B 2 E (B 3 E E)) (B 4 E E)) when (po, io) = ([1, 2, 3, 4, 5, 6, 7], [4, 2, 5, 1, 3, 7, 6])" $ do
preInTree [1 :: Int, 2, 4, 5, 3, 6, 7] [4, 2, 5, 1, 3, 7, 6] `shouldBe` (Branch 1 (Branch 2 (Branch 4 Empty Empty) (Branch 5 Empty Empty)) (Branch 3 Empty (Branch 6 (Branch 7 Empty Empty) Empty)))
describe "treeToPreorder + treeToInorder + preInTree" $ do
it "returns (B 'a' (B 'b' (B 'd' E E) (B 'e' E E)) (B 'c' E (B 'f' (B 'g' E E) E)))" $ do
let t = Branch 'a' (Branch 'b' (Branch 'd' Empty Empty) (Branch 'e' Empty Empty)) (Branch 'c' Empty (Branch 'f' (Branch 'g' Empty Empty) Empty))
po = treeToPreorder t
io = treeToInorder t
in preInTree po io `shouldBe` t
describe "Problem 69" $ do
describe "ds2tree" $ do
it "returns E when s = \".\"" $ do
ds2tree "." `shouldBe` Empty
it "returns (B 'a' E E) when s = \"a..\"" $ do
ds2tree "a.." `shouldBe` (Branch 'a' Empty Empty)
it "returns (B 'a' E E) when s = \"a...\"" $ do
ds2tree "a..." `shouldBe` (Branch 'a' Empty Empty)
it "returns (B 'a' (B 'b' E E) E) when s = \"ab...\"" $ do
ds2tree "ab..." `shouldBe` (Branch 'a' (Branch 'b' Empty Empty) Empty)
it "returns (B 'a' E (B 'c' E E)) when s = \"a.c..\"" $ do
ds2tree "a.c.." `shouldBe` (Branch 'a' Empty (Branch 'c' Empty Empty))
it "returns (B 'a' (B 'b' E E) (B 'c' E E)) when s = \"ab..c..\"" $ do
ds2tree "ab..c.." `shouldBe` (Branch 'a' (Branch 'b' Empty Empty) (Branch 'c' Empty Empty))
it "returns (B 'a' (B 'b' (B 'c' E E) E) E) when s = \"abc....\"" $ do
ds2tree "abc...." `shouldBe` (Branch 'a' (Branch 'b' (Branch 'c' Empty Empty) Empty) Empty)
it "returns (B 'a' E (B 'b' E (B 'c' E E))) when s = \"a.b.c..\"" $ do
ds2tree "a.b.c.." `shouldBe` (Branch 'a' Empty (Branch 'b' Empty (Branch 'c' Empty Empty)))
it "returns (B 'a' (B 'b' E (B 'c' E E)) (B 'd' E E)) when s = \"ab.c..d..\"" $ do
ds2tree "ab.c..d.." `shouldBe` (Branch 'a' (Branch 'b' Empty (Branch 'c' Empty Empty)) (Branch 'd' Empty Empty))
it "returns (B 'a' (B 'b' (B 'd' E E) (B 'e' E E)) (B 'c' E (B 'f' (B 'g' E E) E))) when s = \"abd..e..c.fg...\"" $ do
ds2tree "abd..e..c.fg..." `shouldBe` (Branch 'a' (Branch 'b' (Branch 'd' Empty Empty) (Branch 'e' Empty Empty)) (Branch 'c' Empty (Branch 'f' (Branch 'g' Empty Empty) Empty)))
it "throws exception when s = \"a.\" (1)" $ do
evaluate (ds2tree "a.") `shouldThrow` anyException
describe "tree2ds" $ do
it "returns \".\" when t = E" $ do
tree2ds (Empty :: Tree Char) `shouldBe` "."
it "returns \"a..\" when t = (B 'a' E E)" $ do
tree2ds (Branch 'a' Empty Empty) `shouldBe` "a.."
it "returns \"ab...\" when t = (B 'a' (B 'b' E E) E)" $ do
tree2ds (Branch 'a' (Branch 'b' Empty Empty) Empty) `shouldBe` "ab..."
it "returns \"a.c..\" when t = (B 'a' E (B 'c' E E))" $ do
tree2ds (Branch 'a' Empty (Branch 'c' Empty Empty)) `shouldBe` "a.c.."
it "returns \"ab..c..\" when t = (B 'a' (B 'b' E E) (B 'c' E E))" $ do
tree2ds (Branch 'a' (Branch 'b' Empty Empty) (Branch 'c' Empty Empty)) `shouldBe` "ab..c.."
it "returns \"abc....\" when t = (B 'a' (B 'b' (B 'c' E E) E) E)" $ do
tree2ds (Branch 'a' (Branch 'b' (Branch 'c' Empty Empty) Empty) Empty) `shouldBe` "abc...."
it "returns \"a.b.c..\" when t = (B 'a' E (B 'b' E (B 'c' E E)))" $ do
tree2ds (Branch 'a' Empty (Branch 'b' Empty (Branch 'c' Empty Empty))) `shouldBe` "a.b.c.."
it "returns \"ab.c..d..\" when t = (B 'a' (B 'b' E (B 'c' E E)) (B 'd' E E))" $ do
tree2ds (Branch 'a' (Branch 'b' Empty (Branch 'c' Empty Empty)) (Branch 'd' Empty Empty)) `shouldBe` "ab.c..d.."
it "returns \"abd..e..c.fg...\" when t = (B 'a' (B 'b' (B 'd' E E) (B 'e' E E)) (B 'c' E (B 'f' (B 'g' E E) E)))" $ do
tree2ds (Branch 'a' (Branch 'b' (Branch 'd' Empty Empty) (Branch 'e' Empty Empty)) (Branch 'c' Empty (Branch 'f' (Branch 'g' Empty Empty) Empty))) `shouldBe` "abd..e..c.fg..."
describe "tree2ds + ds2tree" $ do
it "returns same tree" $ do
let t = Branch 'a' (Branch 'b' Empty (Branch 'c' Empty Empty)) (Branch 'd' (Branch 'e' (Branch 'f' Empty Empty) (Branch 'g' Empty Empty)) (Branch 'h' Empty Empty))
in (ds2tree . tree2ds) t `shouldBe` t
| yyotti/99Haskell | src/test/BinaryTreesSpec.hs | mit | 41,856 | 0 | 29 | 13,530 | 13,314 | 6,667 | 6,647 | 557 | 1 |
-----------------------------------------------------------------------------
--
-- Module : Main
-- Copyright : (c) 2013-15 Phil Freeman, (c) 2014-15 Gary Burgess
-- License : MIT (http://opensource.org/licenses/MIT)
--
-- Maintainer : Phil Freeman <[email protected]>
-- Stability : experimental
-- Portability :
--
-- |
--
-----------------------------------------------------------------------------
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TupleSections #-}
module Main where
import Control.Applicative
import Control.Monad
import Control.Monad.Error.Class (MonadError(..))
import Control.Monad.Writer.Strict
import Data.List (isSuffixOf, partition)
import Data.Version (showVersion)
import qualified Data.Map as M
import Options.Applicative as Opts
import System.Exit (exitSuccess, exitFailure)
import System.IO (hPutStrLn, stderr)
import System.IO.UTF8
import System.FilePath.Glob (glob)
import qualified Language.PureScript as P
import qualified Paths_purescript as Paths
import Language.PureScript.Make
data PSCMakeOptions = PSCMakeOptions
{ pscmInput :: [FilePath]
, pscmForeignInput :: [FilePath]
, pscmOutputDir :: FilePath
, pscmOpts :: P.Options
, pscmUsePrefix :: Bool
}
data InputOptions = InputOptions
{ ioInputFiles :: [FilePath]
}
compile :: PSCMakeOptions -> IO ()
compile (PSCMakeOptions inputGlob inputForeignGlob outputDir opts usePrefix) = do
input <- globWarningOnMisses warnFileTypeNotFound inputGlob
when (null input) $ do
hPutStrLn stderr "psc: No input files."
exitFailure
let (jsFiles, pursFiles) = partition (isSuffixOf ".js") input
moduleFiles <- readInput (InputOptions pursFiles)
inputForeign <- globWarningOnMisses warnFileTypeNotFound inputForeignGlob
foreignFiles <- forM (inputForeign ++ jsFiles) (\inFile -> (inFile,) <$> readUTF8File inFile)
case runWriterT (parseInputs moduleFiles foreignFiles) of
Left errs -> do
hPutStrLn stderr (P.prettyPrintMultipleErrors (P.optionsVerboseErrors opts) errs)
exitFailure
Right ((ms, foreigns), warnings) -> do
when (P.nonEmpty warnings) $
hPutStrLn stderr (P.prettyPrintMultipleWarnings (P.optionsVerboseErrors opts) warnings)
let filePathMap = M.fromList $ map (\(fp, P.Module _ _ mn _ _) -> (mn, fp)) ms
makeActions = buildMakeActions outputDir filePathMap foreigns usePrefix
(e, warnings') <- runMake opts $ P.make makeActions (map snd ms)
when (P.nonEmpty warnings') $
hPutStrLn stderr (P.prettyPrintMultipleWarnings (P.optionsVerboseErrors opts) warnings')
case e of
Left errs -> do
hPutStrLn stderr (P.prettyPrintMultipleErrors (P.optionsVerboseErrors opts) errs)
exitFailure
Right _ -> exitSuccess
warnFileTypeNotFound :: String -> IO ()
warnFileTypeNotFound = hPutStrLn stderr . ("psc: No files found using pattern: " ++)
globWarningOnMisses :: (String -> IO ()) -> [FilePath] -> IO [FilePath]
globWarningOnMisses warn = concatMapM globWithWarning
where
globWithWarning pattern = do
paths <- glob pattern
when (null paths) $ warn pattern
return paths
concatMapM f = liftM concat . mapM f
readInput :: InputOptions -> IO [(Either P.RebuildPolicy FilePath, String)]
readInput InputOptions{..} = forM ioInputFiles $ \inFile -> (Right inFile, ) <$> readUTF8File inFile
parseInputs :: (Functor m, Applicative m, MonadError P.MultipleErrors m, MonadWriter P.MultipleErrors m)
=> [(Either P.RebuildPolicy FilePath, String)]
-> [(FilePath, P.ForeignJS)]
-> m ([(Either P.RebuildPolicy FilePath, P.Module)], M.Map P.ModuleName FilePath)
parseInputs modules foreigns =
(,) <$> P.parseModulesFromFiles (either (const "") id) modules
<*> P.parseForeignModulesFromFiles foreigns
inputFile :: Parser FilePath
inputFile = strArgument $
metavar "FILE"
<> help "The input .purs file(s)"
inputForeignFile :: Parser FilePath
inputForeignFile = strOption $
short 'f'
<> long "ffi"
<> help "The input .js file(s) providing foreign import implementations"
outputDirectory :: Parser FilePath
outputDirectory = strOption $
short 'o'
<> long "output"
<> Opts.value "output"
<> showDefault
<> help "The output directory"
requirePath :: Parser (Maybe FilePath)
requirePath = optional $ strOption $
short 'r'
<> long "require-path"
<> help "The path prefix to use for require() calls in the generated JavaScript"
noTco :: Parser Bool
noTco = switch $
long "no-tco"
<> help "Disable tail call optimizations"
noMagicDo :: Parser Bool
noMagicDo = switch $
long "no-magic-do"
<> help "Disable the optimization that overloads the do keyword to generate efficient code specifically for the Eff monad"
noOpts :: Parser Bool
noOpts = switch $
long "no-opts"
<> help "Skip the optimization phase"
comments :: Parser Bool
comments = switch $
short 'c'
<> long "comments"
<> help "Include comments in the generated code"
verboseErrors :: Parser Bool
verboseErrors = switch $
short 'v'
<> long "verbose-errors"
<> help "Display verbose error messages"
noPrefix :: Parser Bool
noPrefix = switch $
short 'p'
<> long "no-prefix"
<> help "Do not include comment header"
options :: Parser P.Options
options = P.Options <$> noTco
<*> noMagicDo
<*> pure Nothing
<*> noOpts
<*> verboseErrors
<*> (not <$> comments)
<*> requirePath
pscMakeOptions :: Parser PSCMakeOptions
pscMakeOptions = PSCMakeOptions <$> many inputFile
<*> many inputForeignFile
<*> outputDirectory
<*> options
<*> (not <$> noPrefix)
main :: IO ()
main = execParser opts >>= compile
where
opts = info (version <*> helper <*> pscMakeOptions) infoModList
infoModList = fullDesc <> headerInfo <> footerInfo
headerInfo = header "psc - Compiles PureScript to Javascript"
footerInfo = footer $ "psc " ++ showVersion Paths.version
version :: Parser (a -> a)
version = abortOption (InfoMsg (showVersion Paths.version)) $ long "version" <> help "Show the version number" <> hidden
| michaelficarra/purescript | psc/Main.hs | mit | 6,388 | 0 | 22 | 1,398 | 1,642 | 844 | 798 | 143 | 3 |
module Text.Docvim.Visitor.Options (extractOptions) where
import Control.Applicative
import Text.Docvim.AST
import Text.Docvim.Visitor
-- | Extracts a list of nodes (if any exist) from the `@options` section(s) of
-- the source code.
--
-- It is not recommended to have multiple `@options` sections in a project. If
-- multiple such sections (potentially across multiple translation units) exist,
-- there are no guarantees about order; they just get concatenated in the order
-- we see them.
extractOptions :: Alternative f => [Node] -> (f [Node], [Node])
extractOptions = extractBlocks f
where
f x = if x == OptionsAnnotation
then Just endSection
else Nothing
| wincent/docvim | lib/Text/Docvim/Visitor/Options.hs | mit | 690 | 0 | 9 | 127 | 104 | 63 | 41 | 9 | 2 |
module Main where
import System.Environment
main :: IO ()
main = do
-- args <- getArgs
-- (arg0:arg1:restArgs) <- getArgs
-- putStrLn $ "sum: " ++ show (read arg0 + read arg1)
name <- getLine
putStrLn $ "Your name is: " ++ name
| dreame4/scheme-in-haskell | hello.hs | mit | 236 | 0 | 8 | 51 | 45 | 25 | 20 | 6 | 1 |
module Network.Skype.Protocol.User where
import Data.Typeable (Typeable)
import Network.Skype.Protocol.Types
data UserProperty = UserHandle UserID
| UserFullName UserFullName
| UserBirthday (Maybe UserBirthday)
| UserSex UserSex
| UserLanguage (Maybe (UserLanguageISOCode, UserLanguage))
| UserCountry (Maybe (UserCountryISOCode, UserCountry))
| UserProvince UserProvince
| UserCity UserCity
| UserHomePhone UserPhone
| UserOfficePhone UserPhone
| UserMobilePhone UserPhone
| UserHomepage UserHomepage
| UserAbout UserAbout
| UserHasCallEquipment Bool
| UserIsVideoCapable Bool
| UserIsVoicemailCapable Bool
| UserBuddyStatus UserBuddyStatus
| UserIsAuthorized Bool
| UserIsBlocked Bool
| UserOnlineStatus UserOnlineStatus
| UserLastOnlineTimestamp Timestamp
| UserCanLeaveVoicemail Bool
| UserSpeedDial UserSpeedDial
| UserReceiveAuthRequest UserAuthRequestMessage
| UserMoodText UserMoodText
| UserRichMoodText UserRichMoodText
| UserTimezone UserTimezoneOffset
| UserIsCallForwardingActive Bool
| UserNumberOfAuthedBuddies Int
| UserDisplayName UserDisplayName
deriving (Eq, Show, Typeable)
data UserSex = UserSexUnknown
| UserSexMale
| UserSexFemale
deriving (Eq, Show, Typeable)
data UserStatus = UserStatusUnknown -- ^ no status information for current user.
| UserStatusOnline -- ^ current user is online.
| UserStatusOffline -- ^ current user is offline.
| UserStatusSkypeMe -- ^ current user is in "Skype Me" mode (Protocol 2).
| UserStatusAway -- ^ current user is away.
| UserStatusNotAvailable -- ^ current user is not available.
| UserStatusDoNotDisturb -- ^ current user is in "Do not disturb" mode.
| UserStatusInvisible -- ^ current user is invisible to others.
| UserStatusLoggedOut -- ^ current user is logged out. Clients are detached.
deriving (Eq, Show, Typeable)
data UserBuddyStatus = UserBuddyStatusNeverBeen
| UserBuddyStatusDeleted
| UserBuddyStatusPending
| UserBuddyStatusAdded
deriving (Eq, Show, Typeable)
data UserOnlineStatus = UserOnlineStatusUnknown
| UserOnlineStatusOffline
| UserOnlineStatusOnline
| UserOnlineStatusAway
| UserOnlineStatusNotAvailable
| UserOnlineStatusDoNotDisturb
deriving (Eq, Show, Typeable)
| emonkak/skype4hs | src/Network/Skype/Protocol/User.hs | mit | 3,059 | 0 | 9 | 1,158 | 375 | 227 | 148 | 60 | 0 |
{-# LANGUAGE CPP #-}
module TCDExtra where
import TCD
import Data.Functor ((<$>))
import Data.List
import System.Directory
import System.FilePath
import Text.Printf
-- This is designed to match libtcd's dump_tide_record as closely as possible
formatTideRecord :: TideRecord -> IO String
formatTideRecord r =
unlines . (++ concatMap showConstituent constituents) <$> mapM formatField fields
where
formatField :: (String, TideRecord -> IO String) -> IO String
formatField (n, f) = printf "%s = %s" n <$> f r
fields =
[ ("Record number" , return . show . tshNumber . trHeader)
, ("Record size" , return . show . tshSize . trHeader)
, ("Record type" , return . show . tshType . trHeader)
, ("Latitude" , return . showF . tshLatitude . trHeader)
, ("Longitude" , return . showF . tshLongitude . trHeader)
, ("Reference station" , return . show . tshReferenceStation . trHeader)
, ("Tzfile" , getTZFile . tshTZFile . trHeader)
, ("Name" , return . tshName . trHeader)
, ("Country" , getCountry . trCountry )
, ("Source" , return . trSource )
, ("Restriction" , getRestriction . trRestriction )
, ("Comments" , return . trComments )
, ("Notes" , return . trNotes )
, ("Legalese" , getLegalese . trLegalese )
, ("Station ID context" , return . trStationIdContext )
, ("Station ID" , return . trStationId )
, ("Date imported" , return . show . trDateImported )
, ("Xfields" , return . trXfields )
, ("Direction units" , getDirUnits . trDirectionUnits )
, ("Min direction" , return . show . trMinDirection )
, ("Max direction" , return . show . trMaxDirection )
, ("Level units" , getLevelUnits . trLevelUnits )
, ("Datum offset" , return . showF . trDatumOffset )
, ("Datum" , getDatum . trDatum )
, ("Zone offset" , return . show . trZoneOffset )
, ("Expiration date" , return . show . trExpirationDate )
, ("Months on station" , return . show . trMonthsOnStation )
, ("Last date on station" , return . show . trLastDateOnStation )
, ("Confidence" , return . show . trConfidence )
]
showConstituent :: (Int, Double, Double) -> [String]
showConstituent (i, amp, epoch) =
if amp /= 0.0
then [ printf "Amplitude[%d] = %.6f" i amp
, printf "Epoch[%d] = %.6f" i epoch]
else []
constituents = zip3 [0..] (trAmplitudes r) (trEpochs r)
showF x = printf "%.6f" x :: String
#ifndef DEFAULT_TIDE_DB_PATH
#define DEFAULT_TIDE_DB_PATH "/usr/share/xtide"
#endif
defaultTideDbPath :: String
defaultTideDbPath = DEFAULT_TIDE_DB_PATH
openDefaultTideDb :: IO Bool
openDefaultTideDb = do
filenames <- getDirectoryContents defaultTideDbPath
let tcds = filter (".tcd" `isSuffixOf`) filenames
if null tcds
then return False
else openTideDb $ defaultTideDbPath </> head tcds
| neilmayhew/Tides | TCDExtra.hs | mit | 3,769 | 0 | 11 | 1,555 | 809 | 463 | 346 | 60 | 2 |
{-# LANGUAGE NoImplicitPrelude, OverloadedStrings, DoAndIfThenElse #-}
-- | This module provides a way in which the Haskell standard input may be forwarded to the IPython
-- frontend and thus allows the notebook to use the standard input.
--
-- This relies on the implementation of file handles in GHC, and is generally unsafe and terrible.
-- However, it is difficult to find another way to do it, as file handles are generally meant to
-- point to streams and files, and not networked communication protocols.
--
-- In order to use this module, it must first be initialized with two things. First of all, in order
-- to know how to communicate with the IPython frontend, it must know the kernel profile used for
-- communication. For this, use @recordKernelProfile@ once the profile is known. Both this and
-- @recordParentHeader@ take a directory name where they can store this data.
--
--
-- Finally, the module must know what @execute_request@ message is currently being replied to (which
-- will request the input). Thus, every time the language kernel receives an @execute_request@
-- message, it should inform this module via @recordParentHeader@, so that the module may generate
-- messages with an appropriate parent header set. If this is not done, the IPython frontends will
-- not recognize the target of the communication.
--
-- Finally, in order to activate this module, @fixStdin@ must be called once. It must be passed the
-- same directory name as @recordParentHeader@ and @recordKernelProfile@. Note that if this is being
-- used from within the GHC API, @fixStdin@ /must/ be called from within the GHC session not from
-- the host code.
module IHaskell.IPython.Stdin (fixStdin, recordParentHeader, recordKernelProfile) where
import IHaskellPrelude
import Control.Concurrent
import Control.Applicative ((<$>))
import GHC.IO.Handle
import GHC.IO.Handle.Types
import System.FilePath ((</>))
import System.Posix.IO
import System.IO.Unsafe
import IHaskell.IPython.Types
import IHaskell.IPython.ZeroMQ
import IHaskell.IPython.Message.UUID as UUID
stdinInterface :: MVar ZeroMQStdin
{-# NOINLINE stdinInterface #-}
stdinInterface = unsafePerformIO newEmptyMVar
-- | Manipulate standard input so that it is sourced from the IPython frontend. This function is
-- build on layers of deep magical hackery, so be careful modifying it.
fixStdin :: String -> IO ()
fixStdin dir = do
-- Initialize the stdin interface.
let fpath = dir </> ".kernel-profile"
profile <- fromMaybe (error $ "fixStdin: Failed reading " ++ fpath)
. readMay <$> readFile fpath
interface <- serveStdin profile
putMVar stdinInterface interface
void $ forkIO $ stdinOnce dir
stdinOnce :: String -> IO ()
stdinOnce dir = do
-- Create a pipe using and turn it into handles.
(readEnd, writeEnd) <- createPipe
newStdin <- fdToHandle readEnd
stdinInput <- fdToHandle writeEnd
hSetBuffering newStdin NoBuffering
hSetBuffering stdinInput NoBuffering
-- Store old stdin and swap in new stdin.
oldStdin <- hDuplicate stdin
hDuplicateTo newStdin stdin
loop stdinInput oldStdin newStdin
where
loop stdinInput oldStdin newStdin = do
let FileHandle _ mvar = stdin
threadDelay $ 150 * 1000
e <- isEmptyMVar mvar
if not e
then loop stdinInput oldStdin newStdin
else do
line <- getInputLine dir
hPutStr stdinInput $ line ++ "\n"
loop stdinInput oldStdin newStdin
-- | Get a line of input from the IPython frontend.
getInputLine :: String -> IO String
getInputLine dir = do
StdinChannel req rep <- readMVar stdinInterface
-- Send a request for input.
uuid <- UUID.random
let fpath = dir </> ".last-req-header"
parentHdr <- fromMaybe (error $ "getInputLine: Failed reading " ++ fpath)
. readMay <$> readFile fpath
let hdr = MessageHeader (mhIdentifiers parentHdr) (Just parentHdr) mempty
uuid (mhSessionId parentHdr) (mhUsername parentHdr) InputRequestMessage
[]
let msg = RequestInput hdr ""
writeChan req msg
-- Get the reply.
InputReply _ value <- readChan rep
return value
recordParentHeader :: String -> MessageHeader -> IO ()
recordParentHeader dir hdr =
writeFile (dir ++ "/.last-req-header") $ show hdr
recordKernelProfile :: String -> Profile -> IO ()
recordKernelProfile dir profile =
writeFile (dir ++ "/.kernel-profile") $ show profile
| gibiansky/IHaskell | src/IHaskell/IPython/Stdin.hs | mit | 4,526 | 0 | 14 | 954 | 722 | 367 | 355 | 64 | 2 |
{-# LANGUAGE UnicodeSyntax #-}
module Data.BEncode.Parser
( string
, value
)
where
import Control.Applicative ((<|>))
import qualified Data.Attoparsec.ByteString.Char8 as AP
(Parser, char, decimal, take)
import qualified Data.Attoparsec.Combinator as AP (manyTill)
import Data.BEncode.Types
import Data.ByteString (ByteString)
import qualified Data.Map as Map (fromList)
--------------------------------------------------------------------------------
string ∷ AP.Parser ByteString
string = AP.decimal <* AP.char ':' >>= AP.take
value ∷ AP.Parser Value
value = Integer <$> (AP.char 'i' *> AP.decimal <* AP.char 'e')
<|> List <$> (AP.char 'l' *> AP.manyTill value (AP.char 'e'))
<|> Dict . Map.fromList
<$> (AP.char 'd' *> AP.manyTill ((,) <$> string <*> value) (AP.char 'e'))
<|> String <$> string
| drdo/swarm-bencode | Data/BEncode/Parser.hs | mit | 839 | 0 | 17 | 136 | 268 | 152 | 116 | -1 | -1 |
module Code where
type BlockName = String
type BlockId = Int
type BlockCode = String
| christiaanb/SoOSiM | examples/Twente/Code.hs | mit | 88 | 0 | 4 | 18 | 22 | 15 | 7 | 4 | 0 |
{-# LANGUAGE OverloadedStrings #-}
-- You need to `cabal install css`
import Language.CSS hiding (borderRadius, boxShadow, textShadow)
import Data.Text.Lazy (Text,append,intercalate,pack)
import qualified Data.Text.Lazy.IO as LIO
import System (getArgs)
main = do
[path] <- getArgs
LIO.writeFile path style
style = renderCSS $ runCSS $ do
reset
layout
cards
game
players
hand
drawOrNextButton
eineButton
games
message
-- Rules
-- =====
reset = rule "*" $ margin "0" >> padding "0"
layout = do
rule "html, body, .game" $ do
width "100%" >> height "100%"
overflow "hidden"
rule "body" $ do
font "16px Ubuntu, Helvetica, sans-serif"
background "#0d3502 url(\"background.png\")"
color white
cardRule = rule . (".card" `append`)
bigCard = do
width "100px" >> height "150px"
borderWidth "10px"
fontSize "67px" >> lineHeight "150px"
smallCard = do
width "60px" >> height "90px"
borderWidth "6px"
fontSize "40px" >> lineHeight "90px"
cards = do
cardRule "" $ do
borderStyle "solid" >> borderColor white >> borderRadius "10px"
boxShadow "2px 2px 10px #0a2d00"
background white
position "relative"
cursor "pointer"
rule "span" $ do
absolute "0" "0" "0" "0"
textAlign "center"
pointerEvents "none"
zIndex "42"
let colorCard colorStr = borderColor colorStr >> color colorStr
cardRule ".yellow" $ colorCard yellow
cardRule ".green" $ colorCard green
cardRule ".blue" $ colorCard blue
cardRule ".red" $ colorCard red
cardRule ".closed" $ colorCard "#888" >> background black
cardRule ".closed:hover" $ colorCard "#aaa"
rule ".card.special" $ color white
rule ".card.black .color" $ outlineOffset "-5px"
rule ".card.black .color:hover" $ outline "5px solid rgba(0,0,0,0.25)"
rule ".card .red" $ absolute "0%" "50%" "50%" "0%" >> background red
rule ".card .green" $ absolute "0%" "0%" "50%" "50%" >> background green
rule ".card .blue" $ absolute "50%" "50%" "0%" "0%" >> background blue
rule ".card .yellow" $ absolute "50%" "0%" "0%" "50%" >> background yellow
rule ".card.open" $ cursor "default"
game = do
rule ".win-message" $ do
position "absolute" >> top "80px" >> left "0" >> right "0"
fontSize "64px"
textAlign "center"
rule ".open, .closed" $ do
bigCard
position "absolute" >> left "50%" >> top "50%"
marginTop "-85px"
rule ".open" $ marginLeft "-130px"
rule ".closed" $ marginLeft "10px"
players = do
rule ".player" $ do
minWidth "150px"
textAlign "center"
position "absolute"
fontSize "18px" >> lineHeight "30px"
padding "0 10px"
background "#375b2d"
transition "background 0.3s linear"
rule ".number-of-cards" $ do
fontWeight "bold"
color "#ff9"
marginLeft "5px"
rule ".player.winner .number-of-cards" $ color black
rule ".player.current" $ background "#609352"
rule ".player.winner" $ background white >> color black
rule ".player.left, .player.right" $ top "50%"
rule ".player.left" $ left "0" >> transform "rotate(90deg) translate(-15px, 70px)" >> margin "0 0 -70px"
rule ".player.right" $ right "0" >> transform "rotate(-90deg) translate(15px, 70px)" >> margin "0 0 -70px"
rule ".player.top" $ left "50%" >> top "0" >> marginLeft "-85px"
rule ".player.bottom" $ do
bottom "0" >> left "50px" >> right "50px"
padding "15px"
height "100px" >> lineHeight "100px"
textAlign "right"
hand :: CSS Rule
hand = rule ".hand" $ do
listStyle "none"
rule "li" (float "left")
rule "li .card" (smallCard >> margin "0 2px" >> transform "rotate(2deg)" >> transition "all 0.3s ease")
rule "li:nth-child(2n) .card" (transform "rotate(-4deg)")
rule "li:nth-child(3n) .card" (transform "rotate(12deg)")
rule "li .card:hover" (transform "rotate(0) translate(0, -10px)")
rules ["li.fade-out .card", "li.fade-in .card"] $ do
margin "0 -36px"
transform "translate(0, 150px)"
rule ".card:not(.matching)" $ do
transform "translate(0, 50px) !important"
cursor "default"
drawOrNextButton = do
rule ".draw-or-next-button" $ do
fontSize "18px"
margin "0 30px 0 0"
color "inherit"
textDecoration "none"
rule ".draw-or-next-button:hover" $ do
fontWeight "bold"
-- http://css3button.net/5232
eineButton = do
let purple = "#570071"
let lightGrey = "#bbb"
rule ".eine-button" $ do
--position "absolute" >> top "30px" >> right "30px"
color purple >> fontSize "32px" >> textDecoration "none"
padding "20px" >> margin "0 15px"
border ("3px solid " `append` purple) >> borderRadius "10px"
boxShadow "0px 1px 3px rgba(000,000,000,0.5), inset 0px 0px 3px rgba(255,255,255,1)"
verticalGradient white [(0.5,white)] lightGrey
rule ".eine-button:hover" $ do
verticalGradient lightGrey [(0.5,white)] white
rule ".eine-button:active" $ do
verticalGradient "#000" [(0.5,"#333")] "#333"
color white
textShadow "none"
rules [".eine-button:active", ".eine-button:focus"] $ outline "none"
rule ".eine-button.active" $ do
color white
borderColor white
background purple
games = do
rule "#games" $ do
background "#042600"
width "400px" >> minHeight "400px"
margin "64px auto" >> padding "32px"
boxShadow "inset 0 0 16px #020"
lineHeight "32px"
rule "input" $ marginLeft "5px"
rule "h1" $ do
textAlign "center"
fontSize "48px"
margin "0 0 26px"
rule "p" $ margin "2px"
rule "#name" $ do
padding "2px"
rule "ul#open-games" $ do
minHeight "300px"
listStyle "none"
rule "li" $ do
borderTop "1px solid #fff"
padding "2px 8px"
rule "li:hover" $ do
cursor "pointer"
background "rgba(255,255,255,0.25)"
rule "#new-game" $ do
padding "4px"
message = rule ".message" $ do
position "absolute" >> bottom "150px" >> left "0" >> right "0"
textAlign "center"
fontSize "14px"
-- Colors
-- ======
white = "#fff"
black = "#000"
yellow = "#ffa200"
green = "#089720"
blue = "#0747ff"
red = "#d50b00"
-- Helpers
-- =======
absolute t r b l = position "absolute" >> top t >> right r >> bottom b >> left l
vendor name value = do
prop ("-moz-" `append` name) value
prop ("-webkit-" `append` name) value
prop name value
-- Properties
-- ==========
-- CSS3
-- ----
borderRadius = vendor "border-radius"
transform = vendor "transform"
transition = vendor "transition"
boxShadow = vendor "box-shadow"
textShadow = vendor "text-shadow"
pointerEvents = prop "pointer-events"
outlineOffset = prop "outline-offset"
verticalGradient :: Text -> [(Float, Text)] -> Text -> CSS (Either Property Rule)
verticalGradient top stops bottom = do
let (++) = append
let stopToGecko (percentage, color) = color ++ " " ++ (pack $ show (percentage*100)) ++ "%"
let stopsToGecko = intercalate "," . map stopToGecko
background $ "-moz-linear-gradient(top, " ++ top ++ " 0%, " ++ stopsToGecko stops ++ "," ++ bottom ++ ")"
let stopToWebkit (percentage, color) = "color-stop(" ++ (pack $ show percentage) ++ ", " ++ color ++ ")"
let stopsToWebkit = intercalate "," . map stopToWebkit
background $ "-webkit-gradient(linear, left top, left bottom, from(" ++ top ++ "), " ++ stopsToWebkit stops ++ ", to(" ++ bottom ++ "))"
| timjb/eine | public/style.hs | mit | 7,314 | 0 | 16 | 1,578 | 2,230 | 967 | 1,263 | 199 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.