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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
data Lista a = Nill | Cost a (Lista a) deriving (Show, Eq, Ord)
ordenada :: (Ord a) => [Int] -> Bool
ordenada [] = error "La lista esta vacia"
ordenada [n] = True
ordenada (n:m:p) = if n<m then ordenada (m:p) else False
| josegury/HaskellFuntions | Listas/Boolean-ListaOrdenadaAsc.hs | mit | 222 | 0 | 8 | 46 | 123 | 66 | 57 | 5 | 2 |
module GHCJS.DOM.SVGComponentTransferFunctionElement (
) where
| manyoo/ghcjs-dom | ghcjs-dom-webkit/src/GHCJS/DOM/SVGComponentTransferFunctionElement.hs | mit | 65 | 0 | 3 | 7 | 10 | 7 | 3 | 1 | 0 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Codegen where
import Data.Word
import Data.String
import Data.List
import Data.Function
import qualified Data.Map as Map
import Control.Monad.State
import Control.Applicative
import LLVM.General.AST
import LLVM.General.AST.Global
import qualified LLVM.General.AST as AST
import qualified LLVM.General.AST.Constant as C
import qualified LLVM.General.AST.Attribute as A
import qualified LLVM.General.AST.CallingConvention as CC
import qualified LLVM.General.AST.FloatingPointPredicate as FP
newtype LLVM a = LLVM { unLLVM :: State AST.Module a }
deriving (Functor, Applicative, Monad, MonadState AST.Module)
runLLVM :: AST.Module -> LLVM a -> AST.Module
runLLVM = flip (execState . unLLVM)
emptyModule :: String -> AST.Module
emptyModule label = defaultModule { moduleName = label }
addDefn :: Definition -> LLVM ()
addDefn d = do
defs <- gets moduleDefinitions
modify $ \s -> s { moduleDefinitions = defs ++ [d] }
define :: Type -> String -> [(Type, Name)] -> [BasicBlock] -> LLVM ()
define retty label argtys body = addDefn $
GlobalDefinition $ functionDefaults {
name = Name label
, parameters = ([Parameter ty nm [] | (ty, nm) <- argtys], False)
, returnType = retty
, basicBlocks = body
}
external :: Type -> String -> [(Type, Name)] -> LLVM ()
external retty label argtys = addDefn $
GlobalDefinition $ functionDefaults {
name = Name label
, parameters = ([Parameter ty nm [] | (ty, nm) <- argtys], False)
, returnType = retty
, basicBlocks = []
}
double :: Type
double = FloatingPointType 64 IEEE
type Names = Map.Map String Int
uniqueName :: String -> Names -> (String, Names)
uniqueName nm ns =
case Map.lookup nm ns of
Nothing -> (nm, Map.insert nm 1 ns)
Just ix -> (nm ++ show ix, Map.insert nm (ix + 1) ns)
instance IsString Name where
fromString = Name . fromString
type SymbolTable = [(String, Operand)]
data CodegenState = CodegenState {
currentBlock :: Name
, blocks :: Map.Map Name BlockState
, symtab :: SymbolTable
, blockCount :: Int
, count :: Word
, names :: Names
} deriving Show
data BlockState = BlockState {
idx :: Int
, stack :: [Named Instruction]
, term :: Maybe (Named Terminator)
} deriving Show
newtype Codegen a = Codegen { runCodegen :: State CodegenState a }
deriving (Functor, Applicative, Monad, MonadState CodegenState)
sortBlocks :: [(Name, BlockState)] -> [(Name, BlockState)]
sortBlocks = sortBy (compare `on` (idx . snd))
createBlocks :: CodegenState -> [BasicBlock]
createBlocks m = map makeBlock $ sortBlocks $ Map.toList (blocks m)
makeBlock :: (Name, BlockState) -> BasicBlock
makeBlock (l, (BlockState _ s t)) = BasicBlock l s (maketerm t)
where maketerm (Just x) = x
maketerm Nothing = error $ "Block has no terminator: " ++ (show l)
entryBlockName :: String
entryBlockName = "entry"
emptyBlock :: Int -> BlockState
emptyBlock i = BlockState i [] Nothing
emptyCodegen :: CodegenState
emptyCodegen = CodegenState (Name entryBlockName) Map.empty [] 1 0 Map.empty
execCodegen :: Codegen a -> CodegenState
execCodegen m = execState (runCodegen m) emptyCodegen
fresh :: Codegen Word
fresh = do
i <- gets count
modify $ \s -> s { count = 1 + i }
return $ i + 1
instr :: Instruction -> Codegen (Operand)
instr ins = do
n <- fresh
let ref = (UnName n)
blk <- current
let i = stack blk
modifyBlock (blk { stack = i ++ [ref := ins] })
return $ local ref
terminator :: Named Terminator -> Codegen (Named Terminator)
terminator trm = do
blk <- current
modifyBlock (blk { term = Just trm })
return trm
entry :: Codegen Name
entry = gets currentBlock
addBlock :: String -> Codegen Name
addBlock bname = do
bls <- gets blocks
ix <- gets blockCount
nms <- gets names
let new = emptyBlock ix
(qname, supply) = uniqueName bname nms
modify $ \s -> s { blocks = Map.insert (Name qname) new bls
, blockCount = ix + 1
, names = supply
}
return (Name qname)
setBlock :: Name -> Codegen Name
setBlock bname = do
modify $ \s -> s { currentBlock = bname }
return bname
getBlock :: Codegen Name
getBlock = gets currentBlock
modifyBlock :: BlockState -> Codegen ()
modifyBlock new = do
active <- gets currentBlock
modify $ \s -> s { blocks = Map.insert active new (blocks s) }
current :: Codegen BlockState
current = do
c <- gets currentBlock
blks <- gets blocks
case Map.lookup c blks of
Just x -> return x
Nothing -> error $ "No such block: " ++ show c
assign :: String -> Operand -> Codegen ()
assign var x = do
lcls <- gets symtab
modify $ \s -> s { symtab = [(var, x)] ++ lcls }
getvar :: String -> Codegen Operand
getvar var = do
syms <- gets symtab
case lookup var syms of
Just x -> return x
Nothing -> error $ "Local variable not in scope: " ++ show var
local :: Name -> Operand
local = LocalReference double
global :: Name -> C.Constant
global = C.GlobalReference double
externf :: Name -> Operand
externf = ConstantOperand . C.GlobalReference double
fadd :: Operand -> Operand -> Codegen Operand
fadd a b = instr $ FAdd NoFastMathFlags a b []
fsub :: Operand -> Operand -> Codegen Operand
fsub a b = instr $ FSub NoFastMathFlags a b []
fmul :: Operand -> Operand -> Codegen Operand
fmul a b = instr $ FMul NoFastMathFlags a b []
fdiv :: Operand -> Operand -> Codegen Operand
fdiv a b = instr $ FDiv NoFastMathFlags a b []
fcmp :: FP.FloatingPointPredicate -> Operand -> Operand -> Codegen Operand
fcmp cond a b = instr $ FCmp cond a b []
cons :: C.Constant -> Operand
cons = ConstantOperand
uitofp :: Type -> Operand -> Codegen Operand
uitofp ty a = instr $ UIToFP a ty []
toArgs :: [Operand] -> [(Operand, [A.ParameterAttribute])]
toArgs = map (\x -> (x, []))
-- Effects
call :: Operand -> [Operand] -> Codegen Operand
call fn args = instr $ Call False CC.C [] (Right fn) (toArgs args) [] []
alloca :: Type -> Codegen Operand
alloca ty = instr $ Alloca ty Nothing 0 []
store :: Operand -> Operand -> Codegen Operand
store ptr val = instr $ Store False ptr val Nothing 0 []
load :: Operand -> Codegen Operand
load ptr = instr $ Load False ptr Nothing 0 []
-- Control Flow
br :: Name -> Codegen (Named Terminator)
br val = terminator $ Do $ Br val []
cbr :: Operand -> Name -> Name -> Codegen (Named Terminator)
cbr cond tr fl = terminator $ Do $ CondBr cond tr fl []
ret :: Operand -> Codegen (Named Terminator)
ret val = terminator $ Do $ Ret (Just val) []
| kkspeed/Kaleidoscope | Codegen.hs | mit | 6,633 | 0 | 13 | 1,471 | 2,529 | 1,326 | 1,203 | 177 | 2 |
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FunctionalDependencies #-}
module Control.Disruptor.DataProvider where
import Control.Disruptor.Sequence
class DataProvider p a | p -> a where
get :: p -> SequenceId a -> IO a
| iand675/disruptor | src/Control/Disruptor/DataProvider.hs | mit | 233 | 0 | 9 | 36 | 51 | 29 | 22 | 6 | 0 |
-- Consecutive strings
-- http://www.codewars.com/kata/56a5d994ac971f1ac500003e/
module Codewars.G964.Longestconsec where
import Data.List (unfoldr, maximumBy)
import Control.Arrow ((&&&))
import Data.Function (on)
longestConsec :: [String] -> Int -> String
longestConsec strarr k | n == 0 || k > n || k <= 0 = ""
| otherwise = snd . maximumBy (compare `on` fst) . map (length &&& id) . unfoldr f $ (strarr, n)
where n = length strarr
f (strs, n) = let (ss, sf) = splitAt (n - k) strs in if length sf < k then Nothing else Just (concat sf, (ss ++ init sf, pred n))
| gafiatulin/codewars | src/6 kyu/Longestconsec.hs | mit | 644 | 0 | 14 | 177 | 249 | 134 | 115 | 9 | 2 |
-----------------------------------------------------------------------------
--
-- Module : Network.Google.Picasa
-- Copyright : (c) 2013 Brian W Bush
-- License : MIT
--
-- Maintainer : Brian W Bush <[email protected]>
-- Stability : Stable
-- Portability : Portable
--
-- | Functions for accessing the Picasa API, see <https://developers.google.com/picasa-web/docs/2.0/developers_guide_protocol>.
--
-----------------------------------------------------------------------------
module Network.Google.Picasa (
-- * Types
UserId
, defaultUser
, AlbumId
-- * Functions
, listAlbums
, listPhotos
) where
import Control.Monad (liftM)
import Data.Maybe (mapMaybe)
import Network.Google (AccessToken, ProjectId, doRequest, makeRequest)
import Network.HTTP.Conduit (Request)
import Text.XML.Light (Element(elContent), QName(..), filterChildrenName, findChild, strContent)
-- | The host for API access.
picasaHost :: String
picasaHost = "picasaweb.google.com"
-- | The API version used here.
picasaApi :: (String, String)
picasaApi = ("Gdata-version", "2")
-- | Picasa user ID.
type UserId = String
-- | Default Picasa user ID
defaultUser :: UserId
defaultUser = "default"
-- | Picasa album ID.
type AlbumId = String
-- | List the albums, see <https://developers.google.com/picasa-web/docs/2.0/developers_guide_protocol#ListAlbums>.
listAlbums ::
AccessToken -- ^ The OAuth 2.0 access token.
-> UserId -- ^ The user ID for the photos.
-> IO Element -- ^ The action returning the albums metadata in XML format.
listAlbums accessToken userId =
doRequest $ picasaFeedRequest accessToken userId Nothing
-- | Extract the album IDs from the list of albums.
extractAlbumIds ::
Element -- ^ The root element of the list of albums.
-> [AlbumId] -- ^ The list of album IDs.
extractAlbumIds root =
let
idQname = QName {qName = "id", qURI = Just "http://schemas.google.com/photos/2007", qPrefix = Just "gphoto"}
entries :: [Element]
entries = filterChildrenName ((== "entry") . qName) root
extractAlbumId :: Element -> Maybe String
extractAlbumId = liftM strContent . findChild idQname
in
mapMaybe extractAlbumId entries
-- | List the photos in albums, see <https://developers.google.com/picasa-web/docs/2.0/developers_guide_protocol#ListAlbumPhotos>.
listPhotos ::
AccessToken -- ^ The OAuth 2.0 access token.
-> UserId -- ^ The user ID for the photos.
-> [AlbumId] -- ^ The album ID for the photos, or all photos if null.
-> IO Element -- ^ The action returning the photo metadata in XML format.
listPhotos accessToken userId albumIds =
do
albumIds' <-
if null albumIds
then liftM extractAlbumIds $ listAlbums accessToken userId
else return albumIds
results <- mapM (listAlbumPhotos accessToken userId) albumIds'
let
root = head results
return $ root {elContent = concatMap elContent results}
-- | List the photos in an album, see <https://developers.google.com/picasa-web/docs/2.0/developers_guide_protocol#ListAlbumPhotos>.
listAlbumPhotos ::
AccessToken -- ^ The OAuth 2.0 access token.
-> UserId -- ^ The user ID for the photos.
-> AlbumId -- ^ The album ID for the photos.
-> IO Element -- ^ The action returning the contacts in XML format.
listAlbumPhotos accessToken userId albumId =
doRequest $ picasaFeedRequest accessToken userId (Just albumId)
-- | Make an HTTP request for a Picasa feed.
picasaFeedRequest ::
AccessToken -- ^ The OAuth 2.0 access token.
-> UserId -- ^ The user ID for the photos.
-> Maybe AlbumId -- ^ The album ID for the photos.
-> Request m -- ^ The request.
picasaFeedRequest accessToken userId albumId =
makeRequest accessToken picasaApi "GET"
(
picasaHost
, "/data/feed/api/user/" ++ userId ++ maybe "" ("/albumid/" ++) albumId
)
| rrnewton/hgdata_trash | src/Network/Google/Picasa.hs | mit | 3,897 | 0 | 12 | 760 | 594 | 341 | 253 | 68 | 2 |
module Handler.Game where
import Import
import Api.StatusResponse
import Game.GameState
import Game.Lexicon
import Text.Shakespeare.Text
import Util.Message
import Yesod.Auth
getGameR :: Handler Html
getGameR = do
mUserId <- maybeAuthId
case mUserId of
Just userId -> do
gameState <- runDB $ loadGameState userId
let latestMessage = gameMessage gameState
defaultLayout $ do
setTitle "Game - Word Guesser"
$(widgetFile "game")
Nothing -> do
setMessageWarning "You must log in to play."
redirect $ AuthR LoginR
guessForm :: Form Text
guessForm = renderDivs $ areq textField "Guess" Nothing
postGameR :: Handler Value
postGameR = do
mUserId <- maybeAuthId
case mUserId of
Just userId -> do
guessParams <- lookupPostParams "guess"
case guessParams of
rawWord : _ -> do
let word = canonicalize rawWord
lexicon <- getLexicon
if isValidGuess word lexicon
then do
newState <- runDB $ insertGuessAndGet userId word
return $ toJSON $ fromGameState newState
else do
state <- runDB $ loadGameState userId
return $ unknownWordResponse state word
_ -> return Null
Nothing -> return Null
where
unknownWordResponse state word = toJSON
$ StatusResponse [st|I don't know the word "#{word}". Try again.|]
$ statusEnum state
insertGuessAndGet :: UserId -> Text -> YesodDB App GameState
insertGuessAndGet userId word = do
gameState <- loadGameState userId
let c = stateGuessCount gameState + 1
gameId = entityKey $ stateGameEntity gameState
newGuess = Guess gameId word c
insert_ $ Guess gameId word c
return gameState {stateLatestGuess = Just newGuess}
| dphilipson/word_guesser_web | Handler/Game.hs | mit | 2,008 | 0 | 22 | 701 | 482 | 227 | 255 | -1 | -1 |
-- file: ch04/EfficientList.hs
-- From chapter 4, http://book.realworldhaskell.org/read/functional-programming.html
myDumbExample xs = if length xs > 0
then head xs
else 'Z'
mySmartExample xs = if not (null xs)
then head xs
else 'Z'
myOtherExample [] = 'Z'
myOtherExample (x:_) = x
| Sgoettschkes/learning | haskell/RealWorldHaskell/ch04/EfficientList.hs | mit | 365 | 0 | 8 | 124 | 82 | 42 | 40 | 8 | 2 |
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
-- | How each type of message is sent (within a Hetcons Transaction).
-- In the simplest case, we simply `add_sent`, which merely adds the message to the set of messages to be sent at the completion of the transaction.
-- However, for some message types, we expect to `receive` the message sent within the same transaction.
-- In particular, when we `receive` a 1A, we `send` a corresponding 1B, and expect it to be added to the state all within one transaction.
module Hetcons.Send () where
import Hetcons.Receive_Message
( Hetcons_Transaction,
get_my_crypto_id,
get_my_private_key,
Add_Sent,
add_sent,
Receivable,
receive,
Sendable,
send )
import Hetcons.Signed_Message
( Parsable,
Encodable,
Monad_Verify(verify),
Recursive_1a,
Recursive_1b,
Recursive_2a,
Recursive_2b,
Recursive_Proof_of_Consensus,
Verified,
Recursive,
sign )
import Hetcons.Hetcons_State
( Hetcons_State, Participant_State, Observer_State )
import Hetcons.Value (Value)
import Charlotte_Consts ( sUPPORTED_SIGNED_HASH_TYPE_DESCRIPTOR )
import Charlotte_Types
( Proposal_1a, Phase_1b, Phase_2a, Phase_2b, Proof_of_Consensus )
import Crypto.Random ( drgNew )
import Data.Hashable (Hashable)
-- | A utility function to sign a message using the `Crypto_ID` and private key from the monad, and produce a `Verified` version.
sign_and_verify :: (Value v, Monad_Verify b (Hetcons_Transaction s v), Encodable a, Parsable (Hetcons_Transaction s v b), Hetcons_State s, Recursive a b) =>
a -> Hetcons_Transaction s v (Verified b)
sign_and_verify m = do { crypto_id <- get_my_crypto_id
; private_key <- get_my_private_key
; gen <- drgNew
; signed <- sign crypto_id private_key sUPPORTED_SIGNED_HASH_TYPE_DESCRIPTOR gen m
; verify signed}
-- | In general, when possible, send a `Verified` message by first receiving it yourself, and then adding it to the messages to be sent at the end of the transaction.
-- Note that sending a message will inherently involve receiving it BEFORE the transaction is finished.
-- Infinite loops of messages would be bad.
instance {-# OVERLAPPABLE #-} (Hetcons_State s, Receivable s v a, Add_Sent a v) => Sendable s v a where
send m = do { receive m
; add_sent m}
--------------------------------------------------------------------------------
-- Participants --
--------------------------------------------------------------------------------
-- | Participants can receive 1as, so this send will run a receive within the same transaction.
-- Also, they shouldn't be sending 1as, but whatever...
instance {-# OVERLAPPING #-} forall v . (Value v, Parsable (Hetcons_Transaction (Participant_State v) v v), Receivable (Participant_State v) v (Verified (Recursive_1a v))) =>
Sendable (Participant_State v) v Proposal_1a where
send m = do { (verified :: Verified (Recursive_1a v)) <- sign_and_verify m
; send verified}
-- | Participants can receive 1bs, so this send will run a receive within the same transaction.
instance {-# OVERLAPPING #-} forall v . (Value v, Hashable v, Eq v, Parsable (Hetcons_Transaction (Participant_State v) v v),
Receivable (Participant_State v) v (Verified (Recursive_1b v))) =>
Sendable (Participant_State v) v Phase_1b where
send m = do { (verified :: Verified (Recursive_1b v)) <- sign_and_verify m
; send verified}
-- | Participants can receive 2as, so this send will run a receive within the same transaction.
instance {-# OVERLAPPING #-} forall v . (Value v, Hashable v, Eq v, Parsable (Hetcons_Transaction (Participant_State v) v v),
Receivable (Participant_State v) v (Verified (Recursive_2a v))) =>
Sendable (Participant_State v) v Phase_2a where
send m = do { (verified :: Verified (Recursive_2a v)) <- sign_and_verify m
; send verified}
-- | Participants can't receive 2bs, so this send will not run a receive
instance {-# OVERLAPPING #-} forall v . (Value v, Hashable v, Eq v, Parsable (Hetcons_Transaction (Participant_State v) v v)) => Sendable (Participant_State v) v Phase_2b where
send m = do { (verified :: Verified (Recursive_2b v)) <- sign_and_verify m
; add_sent verified}
-- | Participants can't receive Proof_of_Consensus, so this send will not run a receive
-- Also, Participants really should never send a proof of consensus...
instance {-# OVERLAPPING #-} forall v . (Value v, Hashable v, Eq v, Parsable (Hetcons_Transaction (Participant_State v) v v)) =>
Sendable (Participant_State v) v Proof_of_Consensus where
send m = do { (verified :: Verified (Recursive_Proof_of_Consensus v)) <- sign_and_verify m
; add_sent verified}
--------------------------------------------------------------------------------
-- Observers --
--------------------------------------------------------------------------------
-- | Observers can't receive 1as, so this send won't run a receive
-- Also, they shouldn't be sending 1as, but whatever...
instance {-# OVERLAPPING #-} forall v . (Value v, Parsable (Hetcons_Transaction (Observer_State v) v v)) => Sendable (Observer_State v) v Proposal_1a where
send m = do { (verified :: Verified (Recursive_1a v)) <- sign_and_verify m
; add_sent verified}
-- | Observers can't receive 1bs, so this send won't run a receive
-- Also, they shouldn't be sending 1bs, but whatever...
instance {-# OVERLAPPING #-} forall v . (Value v, Hashable v, Eq v, Parsable (Hetcons_Transaction (Observer_State v) v v)) => Sendable (Observer_State v) v Phase_1b where
send m = do { (verified :: Verified (Recursive_1b v)) <- sign_and_verify m
; add_sent verified}
-- | Observers can't receive 2as, so this send won't run a receive
-- Also, they shouldn't be sending 2as, but whatever...
instance {-# OVERLAPPING #-} forall v . (Value v, Hashable v, Eq v, Parsable (Hetcons_Transaction (Observer_State v) v v)) => Sendable (Observer_State v) v Phase_2a where
send m = do { (verified :: Verified (Recursive_2a v)) <- sign_and_verify m
; add_sent verified}
-- | Observers can receive 2bs, so this send will run a receive
instance {-# OVERLAPPING #-} forall v . (Value v, Hashable v, Eq v, Parsable (Hetcons_Transaction (Observer_State v) v v),
Receivable (Observer_State v) v (Verified (Recursive_2b v))) =>
Sendable (Observer_State v) v Phase_2b where
send m = do { (verified :: Verified (Recursive_2b v)) <- sign_and_verify m
; send verified}
-- | Observers can receive Proof_of_Consensus, so this send will run a receive
instance {-# OVERLAPPING #-} forall v . (Value v, Hashable v, Eq v, Parsable (Hetcons_Transaction (Observer_State v) v v),
Receivable (Observer_State v) v (Verified (Recursive_Proof_of_Consensus v))) =>
Sendable (Observer_State v) v Proof_of_Consensus where
send m = do { (verified :: Verified (Recursive_Proof_of_Consensus v)) <- sign_and_verify m
; send verified}
| isheff/hetcons | src/Hetcons/Send.hs | mit | 7,711 | 0 | 13 | 1,874 | 1,616 | 858 | 758 | 86 | 1 |
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.SVGAnimatedString
(js_setBaseVal, setBaseVal, js_getBaseVal, getBaseVal,
js_getAnimVal, getAnimVal, SVGAnimatedString,
castToSVGAnimatedString, gTypeSVGAnimatedString)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSRef(..), JSString, castRef)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSRef(..), FromJSRef(..))
import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.Enums
foreign import javascript unsafe "$1[\"baseVal\"] = $2;"
js_setBaseVal :: JSRef SVGAnimatedString -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGAnimatedString.baseVal Mozilla SVGAnimatedString.baseVal documentation>
setBaseVal ::
(MonadIO m, ToJSString val) => SVGAnimatedString -> val -> m ()
setBaseVal self val
= liftIO
(js_setBaseVal (unSVGAnimatedString self) (toJSString val))
foreign import javascript unsafe "$1[\"baseVal\"]" js_getBaseVal ::
JSRef SVGAnimatedString -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGAnimatedString.baseVal Mozilla SVGAnimatedString.baseVal documentation>
getBaseVal ::
(MonadIO m, FromJSString result) => SVGAnimatedString -> m result
getBaseVal self
= liftIO
(fromJSString <$> (js_getBaseVal (unSVGAnimatedString self)))
foreign import javascript unsafe "$1[\"animVal\"]" js_getAnimVal ::
JSRef SVGAnimatedString -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGAnimatedString.animVal Mozilla SVGAnimatedString.animVal documentation>
getAnimVal ::
(MonadIO m, FromJSString result) => SVGAnimatedString -> m result
getAnimVal self
= liftIO
(fromJSString <$> (js_getAnimVal (unSVGAnimatedString self))) | plow-technologies/ghcjs-dom | src/GHCJS/DOM/JSFFI/Generated/SVGAnimatedString.hs | mit | 2,368 | 20 | 11 | 330 | 562 | 334 | 228 | 40 | 1 |
t1 = [True, True]
t2 = [True, False]
t3 = []
and0 :: [Bool] -> Bool
and0 [] = True
and0 (b:bs) = b && and0(bs)
concat0 :: [[a]] -> [a]
concat0 [] = []
concat0 (a : as) | null as = a
| otherwise = a ++ concat0 as
replicate0 :: Int -> a -> [a]
replicate0 0 x = []
replicate0 n x = x : replicate (n-1) x
select :: [a] -> Int -> a
select (x:xs) (0 ) = x
select (x:xs) (n+1) = select xs n
elem0 :: Eq a => a -> [a] -> Bool
elem0 n [] = False
elem0 n (x:xs) | n == x = True
| otherwise = elem0 n xs
merge0 :: Ord a => [a] -> [a] -> [a]
halve0 :: [a] -> ([a],[a])
msort0 :: Ord a => [a] -> [a]
merge0 [] xs = xs
merge0 xs [] = xs
-- | expects two sorted lists
-- but because we filter the second one like qsort
-- and gradually reduce the first
-- we may not need to have them sorted at all
-- if they are both non empty
merge0 (x:xs) ys = merge0 xs ( smaller_y ++ [x] ++ larger_y)
where smaller_y = [sy | sy <- ys, sy <= x]
larger_y = [ly | ly <- ys, ly > x]
halve0 xs = (take h xs, drop h xs)
where h = length xs `div` 2
msort0 [ ] = [ ]
msort0 [x] = [x]
msort0 xs = merge0 ( msort0 first) (msort0 second)
where (first, second) = halve0 (xs)
{-
- 1. define types
- 2. enumerate the cases
- 3. define simple cases
- 4. define the rest
- 5. generalise and simplify
-
-}
sum0 :: Num a => [a] -> a
last0 :: [a] -> a
take0 :: Int -> [a] -> [a]
sum0 [] = 0
sum0 (x:xs) = x + sum0 xs
take0 0 _ = []
take0 (n+1) (x:xs) = x : take0 n xs
last0 (x:xs) | null xs = x
| otherwise = last0 xs
| codingSteve/fp101x | 20151019/recursion.hs | cc0-1.0 | 1,742 | 2 | 9 | 622 | 810 | 426 | 384 | -1 | -1 |
module Stack
( Stack (..)
, StackElem
, poppush
, push
, top
) where
data Stack = Stack { values :: [Double] }
type StackElem = Double
poppush :: Int -> StackElem -> Stack -> Stack
poppush n el st = Stack $ drop n (values st) ++ [el]
push :: StackElem -> Stack -> Stack
push = poppush 0
top :: Stack -> Maybe StackElem
top st = if 0 < (length $ values st)
then Just $ values st !! 0
else Nothing
| matthiasbeyer/rpnc | src/Stack.hs | gpl-2.0 | 423 | 0 | 9 | 113 | 174 | 96 | 78 | 16 | 2 |
{-# LANGUAGE CPP, ScopedTypeVariables, OverloadedStrings #-}
module OfficialServer.DBInteraction
(
startDBConnection
) where
import Prelude hiding (catch);
import Control.Concurrent
import Control.Monad
import Data.List as L
import Data.ByteString.Char8 as B
#if defined(OFFICIAL_SERVER)
import System.Process
import System.IO as SIO
import qualified Control.Exception as Exception
import qualified Data.Map as Map
import Data.Maybe
import Data.Time
import System.Log.Logger
#endif
------------------------
import CoreTypes
#if defined(OFFICIAL_SERVER)
import Utils
#endif
localAddressList :: [B.ByteString]
localAddressList = ["127.0.0.1", "0:0:0:0:0:0:0:1", "0:0:0:0:0:ffff:7f00:1"]
fakeDbConnection :: forall b. ServerInfo -> IO b
fakeDbConnection si = forever $ do
q <- readChan $ dbQueries si
case q of
CheckAccount clId clUid _ clHost ->
writeChan (coreChan si) $ ClientAccountInfo clId clUid (if clHost `L.elem` localAddressList then Admin else Guest)
ClearCache -> return ()
SendStats {} -> return ()
dbConnectionLoop :: ServerInfo -> IO ()
#if defined(OFFICIAL_SERVER)
flushRequests :: ServerInfo -> IO ()
flushRequests si = do
e <- isEmptyChan $ dbQueries si
unless e $ do
q <- readChan $ dbQueries si
case q of
CheckAccount clId clUid _ clHost ->
writeChan (coreChan si) $ ClientAccountInfo clId clUid (if clHost `L.elem` localAddressList then Admin else Guest)
ClearCache -> return ()
SendStats {} -> return ()
flushRequests si
pipeDbConnectionLoop :: Chan DBQuery -> Chan CoreMessage -> Handle -> Handle -> Map.Map ByteString (UTCTime, AccountInfo) -> Int -> IO (Map.Map ByteString (UTCTime, AccountInfo), Int)
pipeDbConnectionLoop queries cChan hIn hOut accountsCache req =
Exception.handle (\(e :: Exception.IOException) -> warningM "Database" (show e) >> return (accountsCache, req)) $
do
q <- readChan queries
(updatedCache, newReq) <- case q of
CheckAccount clId clUid clNick _ -> do
let cacheEntry = clNick `Map.lookup` accountsCache
currentTime <- getCurrentTime
if (isNothing cacheEntry) || (currentTime `diffUTCTime` (fst . fromJust) cacheEntry > 2 * 24 * 60 * 60) then
do
SIO.hPutStrLn hIn $ show q
hFlush hIn
(clId', clUid', accountInfo) <- SIO.hGetLine hOut >>= (maybeException . maybeRead)
writeChan cChan $ ClientAccountInfo clId' clUid' accountInfo
return $ (Map.insert clNick (currentTime, accountInfo) accountsCache, req + 1)
`Exception.onException`
(unGetChan queries q)
else
do
writeChan cChan $ ClientAccountInfo clId clUid (snd $ fromJust cacheEntry)
return (accountsCache, req)
ClearCache -> return (Map.empty, req)
SendStats {} -> (
(SIO.hPutStrLn hIn $ show q) >>
hFlush hIn >>
return (accountsCache, req))
`Exception.onException`
(unGetChan queries q)
pipeDbConnectionLoop queries cChan hIn hOut updatedCache newReq
where
maybeException (Just a) = return a
maybeException Nothing = ioError (userError "Can't read")
pipeDbConnection ::
Map.Map ByteString (UTCTime, AccountInfo)
-> ServerInfo
-> Int
-> IO ()
pipeDbConnection accountsCache si errNum = do
(updatedCache, newErrNum) <-
Exception.handle (\(e :: Exception.IOException) -> warningM "Database" (show e) >> return (accountsCache, errNum + 1)) $ do
(Just hIn, Just hOut, _, _) <- createProcess (proc "./OfficialServer/extdbinterface" [])
{std_in = CreatePipe,
std_out = CreatePipe}
hSetBuffering hIn LineBuffering
hSetBuffering hOut LineBuffering
B.hPutStrLn hIn $ dbHost si
B.hPutStrLn hIn $ dbName si
B.hPutStrLn hIn $ dbLogin si
B.hPutStrLn hIn $ dbPassword si
(c, r) <- pipeDbConnectionLoop (dbQueries si) (coreChan si) hIn hOut accountsCache 0
return (c, if r > 0 then 0 else errNum + 1)
when (newErrNum > 1) $ flushRequests si
threadDelay (3000000)
pipeDbConnection updatedCache si newErrNum
dbConnectionLoop si =
if (not . B.null $ dbHost si) then
pipeDbConnection Map.empty si 0
else
fakeDbConnection si
#else
dbConnectionLoop = fakeDbConnection
#endif
startDBConnection :: ServerInfo -> IO ()
startDBConnection serverInfo =
forkIO (dbConnectionLoop serverInfo) >> return ()
| jeffchao/hedgewars-accessible | gameServer/OfficialServer/DBInteraction.hs | gpl-2.0 | 4,779 | 0 | 24 | 1,342 | 1,407 | 716 | 691 | 25 | 4 |
module AntBrain where
import AntSkull
import Prelude hiding (drop, Right, Left, (&&), (||))
-- The markers
_FOEHOME = 0
_FOOD = 1
_PATH = 5
main = debug $ program 0
test _this = do
search 0 0 0
-- Our strategy
program :: Entry -> M ()
program _Search = do
_TellFoeHome <- alloc
_TellFood <- alloc
_GetFood <- alloc
_ReturnFood <- alloc
_StoreFood <- alloc
_CheckDefend <- alloc
_Defend <- alloc
-- We start by searching anything, food, enemies, whatever. CURRENTLY FOOD ONLY
search _Search _TellFoeHome _TellFood
-- After we found anything, lets go tell the others what we found
tellFoehome _TellFoeHome
tellFood _TellFood _GetFood _ReturnFood _CheckDefend
-- Now either continue to set a trap, or to get food
getFood _GetFood _ReturnFood
returnFood _ReturnFood _StoreFood
storeFood _StoreFood _GetFood _CheckDefend _ReturnFood
checkDefend _CheckDefend _Defend _GetFood
defend _Defend
-- The implementation functions for our strategy
search :: Entry -> Cont -> Cont -> M ()
search _this _TellFoeHome _TellFood = do
_checkFoe <- alloc
_turnAroundFoe <- alloc
_checkFood <- alloc
_pickUp <- alloc
_turnAroundFood <- alloc
_randomWalk <- alloc
-- Mark our current path
mark _this _PATH _checkFoe
-- If se see the FoeHome, run away and _TellFoeHome
senseAdj _checkFoe _turnAroundFoe _checkFood FoeHome
turnAround _turnAroundFoe _TellFoeHome
-- If we see Food (not on our Home), pick it up and _TellFood
senseAdjMoveAndNot _checkFood _pickUp _randomWalk _randomWalk Food Home
pickup _pickUp _turnAroundFood _randomWalk
turnAround _turnAroundFood _TellFood
-- Otherwise do a random walk and continue searching
randomMove _randomWalk _this
tellFoehome :: Entry -> M ()
tellFoehome _this = do
move _this 0 0
tellFood :: Entry -> Cont -> Cont -> Cont -> M ()
tellFood _this _GetFood _ReturnFood _CheckDefend = do
_mark <- alloc
_checkHome <- alloc
_dropFood <- alloc
_followTrail <- alloc
_checkAnyway <- alloc
-- Check if there already is a food marker (if so, _ReturnFood)
senseAdj _this _ReturnFood _mark (Marker _FOOD)
-- If we didn't find another marker, mark the current spot
mark _mark _FOOD _checkHome
-- Check if we are home and move there, if so, drop the food and _CheckDefend
senseAdjMove _checkHome _dropFood _followTrail _followTrail Home
drop _dropFood _CheckDefend
-- If we did not find home or another food marker, return to home along our previous path
tryFollowTrail _followTrail (Marker _PATH) _checkAnyway
sense _checkAnyway Here _dropFood _this Home
getFood :: Entry -> Cont -> M ()
getFood _this _ReturnFood = do
_pickUp <- alloc
_turnAround <- alloc
_tryFollowTrail <- alloc
-- Check if we found food, if so, get it, turn around and _ReturnFood
senseAdjMoveAndNot _this _pickUp _tryFollowTrail _tryFollowTrail Food Home
pickup _pickUp _turnAround _tryFollowTrail
turnAround _turnAround _ReturnFood
-- If we didn't find food, follow the trail to the food
tryFollowTrail _tryFollowTrail (Marker _FOOD) _this
returnFood :: Entry -> Cont -> M ()
returnFood _this _StoreFood = do
_tryFollowTrail <- alloc
_checkAnyway <- alloc
-- Check if we found home, if so _StoreFood
senseAdjMove _this _StoreFood _tryFollowTrail _tryFollowTrail Home
-- If we didn't find home, follow the trail
tryFollowTrail _tryFollowTrail (Marker _FOOD) _this
sense _checkAnyway Here _StoreFood _this Home
storeFood :: Entry -> Cont -> Cont -> Cont -> M ()
storeFood _this _GetFood _CheckDefend _ReturnFood = do
_dropFood <- alloc
_followHomeBorder <- alloc
_ifBorderRandomDrop <- alloc
_randomDrop <- alloc
-- COMMENT
senseAdjMove _this _dropFood _followHomeBorder _ifBorderRandomDrop Food
drop _dropFood _CheckDefend
-- With a small chance, drop food anyway
when _ifBorderRandomDrop (notIf LeftAhead Home && If Here Home) _randomDrop _followHomeBorder
random _randomDrop 5 _dropFood _followHomeBorder
-- COMMENT
followHomeBorder _followHomeBorder _this _ReturnFood
-- Follow a trail in front, or fail
followHomeBorder :: Entry -> Cont -> Cont -> M ()
followHomeBorder _this k1 k2 = do
_turnLeft <- alloc
_checkRight <- alloc
_checkRightAgain <- alloc
_TurnRightAndCheckAgain<- alloc
_turnRight <- alloc
_moveForward <- alloc
_ahead <- alloc
when _this (If LeftAhead Home) _turnLeft _ahead
turn _turnLeft Left _ahead
when _ahead (If Ahead Home) _moveForward _checkRight
when _checkRight (If RightAhead Home) _turnRight _TurnRightAndCheckAgain
turn _turnRight Right _moveForward
turn _TurnRightAndCheckAgain Right _checkRightAgain
when _checkRightAgain (If RightAhead Home) _turnRight k2
move _moveForward k1 _checkRight
checkDefend :: Entry -> Cont -> Cont -> M ()
checkDefend _this _Defend _GetFood = do
_or2 <- alloc
_or3 <- alloc
_turnOr4 <- alloc
_or4 <- alloc
_turnOr5 <- alloc
_or5 <- alloc
_turnRightMoveForward <- alloc
_turnLeftMoveForward <- alloc
_moveForward <- alloc
_turnAroundGetFood <- alloc
-- We are with our back to the opening -- check if there is one spot in the defence that needs reinforcement
when _this (notIf Ahead Friend) _moveForward _or2
when _or2 (notIf RightAhead Friend) _turnRightMoveForward _or3
when _or3 (notIf LeftAhead Friend) _turnLeftMoveForward _turnOr4
turn _turnOr4 Right _or4
when _or4 (notIf RightAhead Friend) _turnRightMoveForward _turnOr5
turn2 _turnOr5 Left _or5
when _or5 (notIf LeftAhead Friend) _turnLeftMoveForward _turnAroundGetFood
-- Reinforce the spot
turn _turnRightMoveForward Right _moveForward
turn _turnLeftMoveForward Left _moveForward
move _moveForward _Defend _moveForward -- POSSIBLE DEADLOCK (fix: also try moving backwards in the opening, or take another spot)
-- If everything is defended, turn around and _GetFood
turnAround _turnAroundGetFood _GetFood
defend :: Entry -> M ()
defend _this = do
-- Infinite loop
turn _this Right _this
| Chiel92/ants | AntBrain.hs | gpl-2.0 | 6,462 | 0 | 10 | 1,605 | 1,405 | 647 | 758 | 127 | 1 |
-- | Memory for P
-- | Juan García Garland
module Memory (Index,
Memory,
lookUp,
update,
emptyMemory,
singletonMemory) where
-- | Variables in P are of the form Xk where k is an integer,
-- | The memory is a function from Int (the k idex) to Integer
-- | Since there is no way to declare variables, when an index is accesed for
-- | the first time the value is 0
-- | Performance is NOT important, this structure is O(n) in every operation
type Index = Int
newtype Memory = M { runM :: [(Index,Integer)]}
deriving Show
lookUp :: Index -> Memory -> Integer
lookUp i (M []) = 0
lookUp i (M ((i',v):ms)) = if i==i'
then v
else lookUp i (M ms)
update :: Index -> Integer -> Memory -> Memory
update i v (M []) = M [(i,v)]
update i v (M (h@(i',_):ms)) = M (if i == i'
then (i, v) : ms
else h : runM (update i v (M ms)))
{- TOD0: test the stricter: if i == i'
then M $ (i,v):ms
else M (h: ((\(M s) -> s) (update i v (M ms))))-}
{- TODO:
reimplement update, so indexes are ordered (or maybe use a dictionary) -}
emptyMemory :: Memory
emptyMemory = M []
-- these function/s is/are not abstract
singletonMemory :: Index -> Integer -> Memory
singletonMemory i v = update i v emptyMemory
-- tests
memtest = M [(0,1),(1,3),(2,5),(3,5),(4,5)]
| jota191/PLang | src/Memory.hs | gpl-3.0 | 1,532 | 0 | 13 | 543 | 381 | 221 | 160 | 24 | 2 |
{-# LANGUAGE BangPatterns #-}
module Main where
import Control.Monad.State.Strict (State, evalState, state)
import Data.Vector (Vector, replicate, replicateM, sum, zipWith)
import System.Environment (getArgs)
import System.Exit (die)
import System.Random (Random, RandomGen, mkStdGen, randomR)
import Text.Read (readMaybe)
import Prelude hiding (replicate, sum, zipWith)
sq :: Num a => a -> a
sq !x = x * x
{-# INLINE sq #-}
normSquared :: Num a => Vector a -> a
normSquared !xs = sum (sq <$> xs)
{-# INLINABLE normSquared #-}
data World a = World
{ walker :: !(Vector a),
cachedTrial :: !a,
moves :: !Int,
attempts :: !Int,
displacement :: !a,
expectedEnergy :: !a,
expectedEnergySquared :: !a}
data WorldSpec a = WorldSpec
{ dimension :: Int,
trialWaveFunction :: Vector a -> a,
trialLocalEnergy :: Vector a -> a,
isFinished :: World a -> Bool}
expectedEnergyError :: Floating a => World a -> a
expectedEnergyError !World {attempts = j, expectedEnergySquared = eE2} =
let !sigma2 = eE2 / fromIntegral (j - 1) in
sqrt (sigma2 / fromIntegral j)
vmc ::
(Fractional a, Ord a, Random a, RandomGen g) =>
WorldSpec a -> World a -> State g (World a)
vmc WorldSpec
{ dimension = d,
trialWaveFunction = psiT,
trialLocalEnergy = eT,
isFinished = f} =
let vmc'
!World
{ walker = r,
cachedTrial = psi,
moves = i,
attempts = j,
displacement = dr,
expectedEnergy = eE,
expectedEnergySquared = eE2} =
do !x <- replicateM d . state $ randomR (-1, 1)
let !rP = zipWith (\ !r !x -> r + x * dr) r x
!psiP = psiT rP
!c = sq (psiP / psi)
!move <-
if c > 1 then
return True else
do !p <- state $ randomR (0, 1)
return $ c > p
let !(r', psi', i')
| move = (rP, psiP, i + 1)
| otherwise = (r, psi, i)
!j' = j + 1
!dr' = dr * (fromIntegral i' / fromIntegral j' + 1 / 2)
!e' = eT r'
!de = e' - eE
!eE' = eE + de / fromIntegral j'
!de' = e' - eE'
!eE2' = eE2 + de * de'
!w' = World
{ walker = r',
cachedTrial = psi',
moves = i',
attempts = j',
displacement = dr',
expectedEnergy = eE',
expectedEnergySquared = eE2'}
if f w' then
return w' else
vmc' w' in
vmc'
harmonicPotential :: Fractional a => Vector a -> a
harmonicPotential !r = (1 / 2) * normSquared r
waveFunction :: Floating a => a -> Vector a -> a
waveFunction alpha !r = exp (-alpha * normSquared r)
localEnergy :: Num a => a -> (Vector a -> a) -> Int -> Vector a -> a
localEnergy alpha v d !r =
v r - alpha * (2 * alpha * normSquared r - fromIntegral d)
main :: IO ()
main =
do as <- getArgs
case sequence $ readMaybe <$> as of
Just [n, d] | n >= 0 && d >= 0 ->
let alpha = 2 / 3
ws = WorldSpec
{ dimension = d,
trialWaveFunction = waveFunction alpha,
trialLocalEnergy = localEnergy alpha harmonicPotential d,
isFinished = \ !World {attempts = j} -> j == n}
w = World
{ walker = replicate d 0,
cachedTrial = 0,
moves = 0,
attempts = 0,
displacement = 1,
expectedEnergy = 0,
expectedEnergySquared = 0}
w' = evalState (vmc ws w) (mkStdGen 0) in
putStrLn $
show (expectedEnergy w' :: Double) ++ " \xb1 " ++
show (expectedEnergyError w' :: Double)
_ -> die "Invalid argument list."
| Tuplanolla/ties341-profiling | Step6.hs | gpl-3.0 | 4,191 | 7 | 21 | 1,765 | 1,361 | 713 | 648 | 124 | 3 |
module Reexport2 where
import Reexport3
q = 4
| roberth/uu-helium | test/correct/Reexport2.hs | gpl-3.0 | 48 | 0 | 4 | 10 | 12 | 8 | 4 | 3 | 1 |
-- |
-- Copyright : (c) 2010, 2011 Benedikt Schmidt & Simon Meier
-- License : GPL v3 (see LICENSE)
--
-- Maintainer : Simon Meier <[email protected]>
-- Portability : GHC only
--
-- Support for interaction with the console: argument parsing.
{-# LANGUAGE TemplateHaskell #-}
module Main.Console (
defaultMain
-- * Static information about the Tamarin prover
, programName
-- * Constructing interaction modes for Tamarin prover
, TamarinMode
, tamarinMode
, helpAndExit
-- * Argument parsing
, Arguments
, ArgKey
, ArgVal
-- ** Setting arguments
, updateArg
, addEmptyArg
, helpFlag
-- ** Retrieving arguments
, getArg
, findArg
, argExists
-- * Pretty printing and console output
, lineWidth
, shortLineWidth
, renderDoc
) where
import Data.Maybe
import Data.Version (showVersion)
import Data.Time
import Safe
import Control.Monad
import System.Console.CmdArgs.Explicit
import System.Console.CmdArgs.Text
import System.Exit
import qualified Text.PrettyPrint.Class as PP
import Paths_tamarin_prover (version)
import Language.Haskell.TH
import Development.GitRev
------------------------------------------------------------------------------
-- Static constants for the tamarin-prover
------------------------------------------------------------------------------
-- | Program name
programName :: String
programName = "tamarin-prover"
-- | Version string
versionStr :: String
versionStr = unlines
[ concat
[ programName
, " "
, showVersion version
, ", (C) David Basin, Cas Cremers, Jannik Dreier, Simon Meier, Ralf Sasse, Benedikt Schmidt, ETH Zurich 2010-2019"
]
, concat
[ "Git revision: "
, $(gitHash)
, case $(gitDirty) of
True -> " (with uncommited changes)"
False -> ""
, ", branch: "
, $(gitBranch)
]
, concat
[ "Compiled at: "
, $(stringE =<< runIO (show `fmap` Data.Time.getCurrentTime))
]
, ""
, "This program comes with ABSOLUTELY NO WARRANTY. It is free software, and you"
, "are welcome to redistribute it according to its LICENSE, see"
, "'https://github.com/tamarin-prover/tamarin-prover/blob/master/LICENSE'."
]
-- | Line width to use.
lineWidth :: Int
lineWidth = 110
shortLineWidth :: Int
shortLineWidth = 78
------------------------------------------------------------------------------
-- A simple generic representation of arguments
------------------------------------------------------------------------------
-- | A name of an argument.
type ArgKey = String
-- | A value of an argument.
type ArgVal = String
-- | It is most convenient to view arguments just as 'String' based key-value
-- pairs. If there are multiple values for the same key, then the left-most
-- one is preferred.
type Arguments = [(ArgKey,ArgVal)]
-- | Does an argument exist.
argExists :: String -> Arguments -> Bool
argExists a = isJust . findArg a
-- | Find the value(s) corresponding to the given key.
findArg :: MonadPlus m => ArgKey -> Arguments -> m ArgVal
findArg a' as = msum [ return v | (a,v) <- as, a == a' ]
-- | Find the value corresponding to the given key. Throw an error if no value
-- exists.
getArg :: ArgKey -> Arguments -> ArgVal
getArg a =
fromMaybe (error $ "getArg: argument '" ++ a ++ "' not found") . findArg a
-- | Add an argument to the from of the list of arguments.
addArg :: ArgKey -> ArgVal -> Arguments -> Arguments
addArg a v = ((a,v):)
-- | Add an argument with the empty string as the value.
addEmptyArg :: String -> Arguments -> Arguments
addEmptyArg a = addArg a ""
-- | Update an argument.
updateArg :: ArgKey -> ArgVal -> Arguments -> Either a Arguments
updateArg a v = Right . addArg a v
-- | Add the help flag.
helpFlag :: Flag Arguments
helpFlag = flagHelpSimple (addEmptyArg "help")
------------------------------------------------------------------------------
-- Modes for using the Tamarin prover
------------------------------------------------------------------------------
-- | A representation of an interaction mode with the Tamarin prover.
data TamarinMode = TamarinMode
{ tmName :: String
, tmCmdArgsMode :: Mode Arguments
-- ^ Run is given a reference to the mode. This enables changing the
-- static information of a mode and keeping the same 'run' function.
-- We use this for implementing the 'main' mode.
, tmRun :: TamarinMode -> Arguments -> IO ()
, tmIsMainMode :: Bool
}
-- | Smart constructor for a 'TamarinMode'.
tamarinMode :: String -> Help
-> (Mode Arguments -> Mode Arguments) -- ^ Changes to default mode.
-> (TamarinMode -> Arguments -> IO ())
-> TamarinMode
tamarinMode name help adaptMode run0 = TamarinMode
{ tmName = name
, tmCmdArgsMode = adaptMode $ Mode
{ modeGroupModes = toGroup []
, modeNames = [name]
, modeValue = []
, modeCheck = updateArg "mode" name
, modeExpandAt = False
, modeReform = const Nothing-- no reform possibility
, modeHelp = help
, modeHelpSuffix = []
, modeArgs = ([], Nothing) -- no positional arguments
, modeGroupFlags = toGroup [] -- no flags
}
, tmRun = run
, tmIsMainMode = False
}
where
run thisMode as
| argExists "help" as = helpAndExit thisMode Nothing
| argExists "version" as = putStrLn versionStr
| otherwise = run0 thisMode as
-- | Disply help message of a tamarin mode and exit.
helpAndExit :: TamarinMode -> Maybe String -> IO ()
helpAndExit tmode mayMsg = do
putStrLn $ showText (Wrap lineWidth)
$ helpText header HelpFormatOne (tmCmdArgsMode tmode)
-- output example info
when (tmIsMainMode tmode) $ do
putStrLn $ unlines
[ separator
, "See 'https://github.com/tamarin-prover/tamarin-prover/blob/master/README.md'"
, "for usage instructions and pointers to examples."
, separator
]
end
where
separator = replicate shortLineWidth '-'
(header, end) = case mayMsg of
Nothing -> ([], return ())
Just msg -> (["error: " ++ msg], exitFailure)
-- | Main function.
defaultMain :: TamarinMode -> [TamarinMode] -> IO ()
defaultMain firstMode otherModes = do
as <- processArgs $ tmCmdArgsMode mainMode
case findArg "mode" as of
Nothing -> error $ "defaultMain: impossible - mode not set"
Just name -> headNote "defaultMain: impossible - no mode found" $ do
tmode <- (mainMode : otherModes)
guard (tmName tmode == name)
return $ tmRun tmode tmode as
where
mainMode = firstMode
{ tmName = programName
, tmCmdArgsMode = (tmCmdArgsMode firstMode)
{ modeNames = [programName]
, modeCheck = updateArg "mode" programName
, modeGroupModes = toGroup (map tmCmdArgsMode $ otherModes)
, modeGroupFlags = (modeGroupFlags $ tmCmdArgsMode firstMode)
{ groupNamed =
[ ("About"
, [ helpFlag
, flagVersion (addEmptyArg "version")
] )
]
}
}
, tmIsMainMode = True
}
------------------------------------------------------------------------------
-- Pretty printing
------------------------------------------------------------------------------
-- | Render a pretty-printing document.
renderDoc :: PP.Doc -> String
renderDoc = PP.renderStyle (PP.defaultStyle { PP.lineLength = lineWidth })
| kmilner/tamarin-prover | src/Main/Console.hs | gpl-3.0 | 7,752 | 0 | 18 | 1,999 | 1,397 | 786 | 611 | 143 | 2 |
{-# LANGUAGE BangPatterns #-}
import System.Directory
import System.FilePath
import Control.DeepSeq
import Criterion.Main
import Brnfckr.Parse (parseBrainFuck)
import Brnfckr.Eval
import Paths_brnfckr
sourceBlacklist :: [FilePath]
sourceBlacklist = [
"tests.bf"
]
runBlacklist = sourceBlacklist ++ [
"mandelbrot.bf"
-- , "bottles.bf"
, "rot13.bf"
, "bench.bf"
, "bench2.bf"
]
programNames :: IO (FilePath, [FilePath])
programNames = do
dir <- getDataFileName "programs"
files <- getDirectoryContents dir
return $ (dir, filter isNormalProgram files)
where
isNormalProgram f = takeExtension f == ".bf" &&
-- takeFileName f == "bottles.bf"
readFile' :: FilePath -> IO String
readFile' fn = do
c <- readFile fn
return (force c)
main :: IO ()
main = do
(dir, names) <- programNames
contents <- mapM (readFile' . (dir </>)) names
print names
let sources = zip names contents
asts = fmap parseBrainFuck <$> sources
opt_asts = fmap (fmap compress) <$> asts
makeBenches f progs bl =
[bench name $ nf f prg | (name, prg) <- progs, name `notElem` bl]
forceRun ast = let ((_, _), output) = runBrainFuck' ast []
in output
defaultMain [
bgroup "Parsing" $ makeBenches parseBrainFuck sources sourceBlacklist
, bgroup "Optimizing" $ makeBenches (fmap compress) asts sourceBlacklist
, bgroup "Evaluating" $ makeBenches forceRun opt_asts runBlacklist
]
| johntyree/brnfckr | src/benchmarks/ParseBench.hs | gpl-3.0 | 1,491 | 1 | 15 | 351 | 458 | 233 | 225 | -1 | -1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Debugger.Types.Sum
-- 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)
--
module Network.Google.Debugger.Types.Sum where
import Network.Google.Prelude
-- | Reference to which the message applies.
data StatusMessageRefersTo
= Unspecified
-- ^ @UNSPECIFIED@
-- Status doesn\'t refer to any particular input.
| BreakpointSourceLocation
-- ^ @BREAKPOINT_SOURCE_LOCATION@
-- Status applies to the breakpoint and is related to its location.
| BreakpointCondition
-- ^ @BREAKPOINT_CONDITION@
-- Status applies to the breakpoint and is related to its condition.
| BreakpointExpression
-- ^ @BREAKPOINT_EXPRESSION@
-- Status applies to the breakpoint and is related to its expressions.
| BreakpointAge
-- ^ @BREAKPOINT_AGE@
-- Status applies to the breakpoint and is related to its age.
| VariableName
-- ^ @VARIABLE_NAME@
-- Status applies to the entire variable.
| VariableValue
-- ^ @VARIABLE_VALUE@
-- Status applies to variable value (variable name is valid).
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable StatusMessageRefersTo
instance FromHttpApiData StatusMessageRefersTo where
parseQueryParam = \case
"UNSPECIFIED" -> Right Unspecified
"BREAKPOINT_SOURCE_LOCATION" -> Right BreakpointSourceLocation
"BREAKPOINT_CONDITION" -> Right BreakpointCondition
"BREAKPOINT_EXPRESSION" -> Right BreakpointExpression
"BREAKPOINT_AGE" -> Right BreakpointAge
"VARIABLE_NAME" -> Right VariableName
"VARIABLE_VALUE" -> Right VariableValue
x -> Left ("Unable to parse StatusMessageRefersTo from: " <> x)
instance ToHttpApiData StatusMessageRefersTo where
toQueryParam = \case
Unspecified -> "UNSPECIFIED"
BreakpointSourceLocation -> "BREAKPOINT_SOURCE_LOCATION"
BreakpointCondition -> "BREAKPOINT_CONDITION"
BreakpointExpression -> "BREAKPOINT_EXPRESSION"
BreakpointAge -> "BREAKPOINT_AGE"
VariableName -> "VARIABLE_NAME"
VariableValue -> "VARIABLE_VALUE"
instance FromJSON StatusMessageRefersTo where
parseJSON = parseJSONText "StatusMessageRefersTo"
instance ToJSON StatusMessageRefersTo where
toJSON = toJSONText
-- | Indicates the severity of the log. Only relevant when action is \`LOG\`.
data BreakpointLogLevel
= Info
-- ^ @INFO@
-- Information log message.
| Warning
-- ^ @WARNING@
-- Warning log message.
| Error'
-- ^ @ERROR@
-- Error log message.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable BreakpointLogLevel
instance FromHttpApiData BreakpointLogLevel where
parseQueryParam = \case
"INFO" -> Right Info
"WARNING" -> Right Warning
"ERROR" -> Right Error'
x -> Left ("Unable to parse BreakpointLogLevel from: " <> x)
instance ToHttpApiData BreakpointLogLevel where
toQueryParam = \case
Info -> "INFO"
Warning -> "WARNING"
Error' -> "ERROR"
instance FromJSON BreakpointLogLevel where
parseJSON = parseJSONText "BreakpointLogLevel"
instance ToJSON BreakpointLogLevel where
toJSON = toJSONText
-- | V1 error format.
data Xgafv
= X1
-- ^ @1@
-- v1 error format
| X2
-- ^ @2@
-- v2 error format
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable Xgafv
instance FromHttpApiData Xgafv where
parseQueryParam = \case
"1" -> Right X1
"2" -> Right X2
x -> Left ("Unable to parse Xgafv from: " <> x)
instance ToHttpApiData Xgafv where
toQueryParam = \case
X1 -> "1"
X2 -> "2"
instance FromJSON Xgafv where
parseJSON = parseJSONText "Xgafv"
instance ToJSON Xgafv where
toJSON = toJSONText
-- | Action that the agent should perform when the code at the breakpoint
-- location is hit.
data BreakpointAction
= Capture
-- ^ @CAPTURE@
-- Capture stack frame and variables and update the breakpoint. The data is
-- only captured once. After that the breakpoint is set in a final state.
| Log
-- ^ @LOG@
-- Log each breakpoint hit. The breakpoint remains active until deleted or
-- expired.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable BreakpointAction
instance FromHttpApiData BreakpointAction where
parseQueryParam = \case
"CAPTURE" -> Right Capture
"LOG" -> Right Log
x -> Left ("Unable to parse BreakpointAction from: " <> x)
instance ToHttpApiData BreakpointAction where
toQueryParam = \case
Capture -> "CAPTURE"
Log -> "LOG"
instance FromJSON BreakpointAction where
parseJSON = parseJSONText "BreakpointAction"
instance ToJSON BreakpointAction where
toJSON = toJSONText
-- | The alias kind.
data AliasContextKind
= Any
-- ^ @ANY@
-- Do not use.
| Fixed
-- ^ @FIXED@
-- Git tag
| Movable
-- ^ @MOVABLE@
-- Git branch
| Other
-- ^ @OTHER@
-- OTHER is used to specify non-standard aliases, those not of the kinds
-- above. For example, if a Git repo has a ref named \"refs\/foo\/bar\", it
-- is considered to be of kind OTHER.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable AliasContextKind
instance FromHttpApiData AliasContextKind where
parseQueryParam = \case
"ANY" -> Right Any
"FIXED" -> Right Fixed
"MOVABLE" -> Right Movable
"OTHER" -> Right Other
x -> Left ("Unable to parse AliasContextKind from: " <> x)
instance ToHttpApiData AliasContextKind where
toQueryParam = \case
Any -> "ANY"
Fixed -> "FIXED"
Movable -> "MOVABLE"
Other -> "OTHER"
instance FromJSON AliasContextKind where
parseJSON = parseJSONText "AliasContextKind"
instance ToJSON AliasContextKind where
toJSON = toJSONText
| rueshyna/gogol | gogol-debugger/gen/Network/Google/Debugger/Types/Sum.hs | mpl-2.0 | 6,467 | 0 | 11 | 1,604 | 1,004 | 543 | 461 | 122 | 0 |
{-# 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.ServiceUsage.Operations.Delete
-- 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)
--
-- Deletes a long-running operation. This method indicates that the client
-- is no longer interested in the operation result. It does not cancel the
-- operation. If the server doesn\'t support this method, it returns
-- \`google.rpc.Code.UNIMPLEMENTED\`.
--
-- /See:/ <https://cloud.google.com/service-usage/ Service Usage API Reference> for @serviceusage.operations.delete@.
module Network.Google.Resource.ServiceUsage.Operations.Delete
(
-- * REST Resource
OperationsDeleteResource
-- * Creating a Request
, operationsDelete
, OperationsDelete
-- * Request Lenses
, odXgafv
, odUploadProtocol
, odAccessToken
, odUploadType
, odName
, odCallback
) where
import Network.Google.Prelude
import Network.Google.ServiceUsage.Types
-- | A resource alias for @serviceusage.operations.delete@ method which the
-- 'OperationsDelete' request conforms to.
type OperationsDeleteResource =
"v1" :>
Capture "name" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :> Delete '[JSON] Empty
-- | Deletes a long-running operation. This method indicates that the client
-- is no longer interested in the operation result. It does not cancel the
-- operation. If the server doesn\'t support this method, it returns
-- \`google.rpc.Code.UNIMPLEMENTED\`.
--
-- /See:/ 'operationsDelete' smart constructor.
data OperationsDelete =
OperationsDelete'
{ _odXgafv :: !(Maybe Xgafv)
, _odUploadProtocol :: !(Maybe Text)
, _odAccessToken :: !(Maybe Text)
, _odUploadType :: !(Maybe Text)
, _odName :: !Text
, _odCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'OperationsDelete' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'odXgafv'
--
-- * 'odUploadProtocol'
--
-- * 'odAccessToken'
--
-- * 'odUploadType'
--
-- * 'odName'
--
-- * 'odCallback'
operationsDelete
:: Text -- ^ 'odName'
-> OperationsDelete
operationsDelete pOdName_ =
OperationsDelete'
{ _odXgafv = Nothing
, _odUploadProtocol = Nothing
, _odAccessToken = Nothing
, _odUploadType = Nothing
, _odName = pOdName_
, _odCallback = Nothing
}
-- | V1 error format.
odXgafv :: Lens' OperationsDelete (Maybe Xgafv)
odXgafv = lens _odXgafv (\ s a -> s{_odXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
odUploadProtocol :: Lens' OperationsDelete (Maybe Text)
odUploadProtocol
= lens _odUploadProtocol
(\ s a -> s{_odUploadProtocol = a})
-- | OAuth access token.
odAccessToken :: Lens' OperationsDelete (Maybe Text)
odAccessToken
= lens _odAccessToken
(\ s a -> s{_odAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
odUploadType :: Lens' OperationsDelete (Maybe Text)
odUploadType
= lens _odUploadType (\ s a -> s{_odUploadType = a})
-- | The name of the operation resource to be deleted.
odName :: Lens' OperationsDelete Text
odName = lens _odName (\ s a -> s{_odName = a})
-- | JSONP
odCallback :: Lens' OperationsDelete (Maybe Text)
odCallback
= lens _odCallback (\ s a -> s{_odCallback = a})
instance GoogleRequest OperationsDelete where
type Rs OperationsDelete = Empty
type Scopes OperationsDelete =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/service.management"]
requestClient OperationsDelete'{..}
= go _odName _odXgafv _odUploadProtocol
_odAccessToken
_odUploadType
_odCallback
(Just AltJSON)
serviceUsageService
where go
= buildClient
(Proxy :: Proxy OperationsDeleteResource)
mempty
| brendanhay/gogol | gogol-serviceusage/gen/Network/Google/Resource/ServiceUsage/Operations/Delete.hs | mpl-2.0 | 4,853 | 0 | 15 | 1,099 | 703 | 413 | 290 | 100 | 1 |
{-# LANGUAGE FlexibleContexts, FlexibleInstances, TypeFamilies #-}
module Math.Topology.KnotTh.Tangle.CascadeCode
( CascadePattern(..)
, decodeCascadeCode
, decodeCascadeCodeFromPairs
) where
import Control.Arrow (first)
import Data.Char (isSpace)
import Text.Printf
import Math.Topology.KnotTh.Knotted
import Math.Topology.KnotTh.Knotted.Crossings.Projection
import Math.Topology.KnotTh.Knotted.Crossings.Diagram
import Math.Topology.KnotTh.Tangle.TangleDef
class (Enum (CascadePattern a)) => CascadeCodePattern a where
data CascadePattern a :: *
cascadeCodeRoot :: Tangle a
decodeCrossing :: CascadePattern a -> (CascadePattern ProjectionCrossing, Int, Int, a)
instance CascadeCodePattern ProjectionCrossing where
data CascadePattern ProjectionCrossing = W | X | M
deriving (Eq, Enum, Show, Read)
cascadeCodeRoot = toTangle lonerProjection
decodeCrossing W = (W, 1, 0, ProjectionCrossing)
decodeCrossing X = (X, 1, 0, ProjectionCrossing)
decodeCrossing M = (M, 0, -1, ProjectionCrossing)
instance CascadeCodePattern DiagramCrossing where
data CascadePattern DiagramCrossing = WO | WU | XO | XU | MO | MU
deriving (Eq, Enum)
cascadeCodeRoot = toTangle lonerOverCrossing
decodeCrossing WO = (W, 1, 0, UnderCrossing)
decodeCrossing WU = (W, 1, 0, OverCrossing)
decodeCrossing XO = (X, 1, 0, OverCrossing)
decodeCrossing XU = (X, 1, 0, UnderCrossing)
decodeCrossing MO = (M, 0, -1, OverCrossing)
decodeCrossing MU = (M, 0, -1, UnderCrossing)
instance Show (CascadePattern DiagramCrossing) where
show p = case p of
WO -> "W+"
WU -> "W-"
XO -> "X+"
XU -> "X-"
MO -> "M+"
MU -> "M-"
instance Read (CascadePattern DiagramCrossing) where
readsPrec _ s = case dropWhile isSpace s of
'W' : '+' : t -> [(WO, t)]
'W' : '-' : t -> [(WU, t)]
'X' : '+' : t -> [(XO, t)]
'X' : '-' : t -> [(XU, t)]
'M' : '+' : t -> [(MO, t)]
'M' : '-' : t -> [(MU, t)]
_ -> []
decodeCascadeCode :: (CascadeCodePattern a) => [(CascadePattern a, Int)] -> Tangle a
decodeCascadeCode =
foldl (\ prev (pattern, offset) ->
let (gl, shift, rot, c) = decodeCrossing pattern
in rotateBy rot $ vertexOwner $
glueToBorder
(case gl of { W -> 3 ; X -> 2 ; M -> 1 })
(prev, offset + shift)
c
) cascadeCodeRoot
decodeCascadeCodeFromPairs :: [(Int, Int)] -> Tangle ProjectionCrossing
decodeCascadeCodeFromPairs =
let encode (-1) = W
encode 0 = X
encode 1 = M
encode p = error $ printf "decodeCascadeCodeFromPairs: expected -1, 0 or 1 as pattern, %i received" p
in decodeCascadeCode . map (first encode)
| mishun/tangles | src/Math/Topology/KnotTh/Tangle/CascadeCode.hs | lgpl-3.0 | 2,844 | 0 | 15 | 755 | 915 | 514 | 401 | 67 | 4 |
{-# LANGUAGE FlexibleInstances #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
{- |
Module : Data.DRS.Show
Copyright : (c) Harm Brouwer and Noortje Venhuizen
License : Apache-2.0
Maintainer : [email protected], [email protected]
Stability : provisional
Portability : portable
DRS pretty printing
-}
module Data.DRS.Show
(
-- * Show DRS (pretty printing)
DRSNotation (..)
, showCond
, showDRS
, printDRS
, showMerge
, printMerge
, showDRSBetaReduct
, printDRSBetaReduct
, showDRSRefBetaReduct
, printDRSRefBetaReduct
-- ** DRS Operator symbols
, opNeg
, opImp
, opOr
, opDiamond
, opBox
, opLambda
-- ** DRS Box Construction
, boxTopLeft
, boxTopRight
, boxBottomLeft
, boxBottomRight
, boxMiddleLeft
, boxMiddleRight
, boxHorLine
, boxVerLine
, showConcat
, showContent
, showHorizontalLine
, showModifier
, showPadding
) where
import Data.DRS.DataType
import Data.DRS.Merge
import Data.DRS.Structure
import Data.DRS.Variables
import Data.List (intercalate, union)
---------------------------------------------------------------------------
-- * Exported
---------------------------------------------------------------------------
---------------------------------------------------------------------------
-- ** Show DRS
---------------------------------------------------------------------------
---------------------------------------------------------------------------
-- | Derive an instance of the 'Show' typeclass for 'DRS'.
---------------------------------------------------------------------------
instance Show DRS where
show d = '\n' : showDRS (Boxes d)
---------------------------------------------------------------------------
-- | Typeclass for 'showableDRS's, that are unresolved.
---------------------------------------------------------------------------
class ShowableDRS d where
resolve :: d -> Int -> Int -> DRS
-- | Derive appropriate instances of 'ShowableDRS'.
instance ShowableDRS DRS where
resolve d _ _ = d
instance (ShowableDRS d) => ShowableDRS (DRSRef -> d) where
resolve ud nr nd = resolve (ud rv) (nr + 1) nd
where rv = LambdaDRSRef (('r' : show nr,[]), nr + nd)
instance (ShowableDRS d) => ShowableDRS (DRS -> d) where
resolve ud nr nd = resolve (ud lv) nr (nd + 1)
where lv = LambdaDRS (('k' : show nd,[]), nr + nd)
instance (ShowableDRS d) => ShowableDRS ((DRSRef -> DRS) -> d) where
resolve ud nr nd = resolve (ud lv) nr (nd + 1)
where lv x = LambdaDRS (('k' : show nd,[drsRefToDRSVar x]), nr + nd)
instance (ShowableDRS d) => ShowableDRS (DRSRel -> d) where
resolve ud nr nd = resolve (ud lv) nr (nd + 1)
where lv = LambdaDRSRel (('P' : show nd,[]), nr + nd)
-- | Derive appropriate instances of 'Show' for 'ShowableDRS's.
instance (ShowableDRS d) => Show (DRSRef -> d) where
show d = show (resolve d 0 0)
instance (ShowableDRS d) => Show (DRS -> d) where
show d = show (resolve d 0 0)
instance (ShowableDRS d) => Show ((DRSRef -> DRS) -> d) where
show d = show (resolve d 0 0)
instance (ShowableDRS d) => Show (DRSRel -> d) where
show d = show (resolve d 0 0)
---------------------------------------------------------------------------
-- | 'DRS' notations.
---------------------------------------------------------------------------
data DRSNotation d =
Set d -- ^ Set notation
| Linear d -- ^ Linear notation
| Boxes d -- ^ Box notation
| Debug d -- ^ Debug notation
-- | Derive an instance of Show for 'DRSNotation'.
instance (ShowableDRS d) => Show (DRSNotation d) where
show (Boxes d) = '\n' : showDRS (Boxes (resolve d 0 0))
show (Linear d) = '\n' : showDRS (Linear (resolve d 0 0))
show (Set d) = '\n' : showDRS (Set (resolve d 0 0))
show (Debug d) = '\n' : showDRS (Debug (resolve d 0 0))
---------------------------------------------------------------------------
-- | Shows a 'DRS'.
---------------------------------------------------------------------------
showDRS :: DRSNotation DRS -> String
showDRS n =
case n of
(Boxes d) -> showModifier (showDRSLambdas d) 2 (showDRSBox d)
(Linear d) -> showDRSLambdas d ++ showDRSLinear d ++ "\n"
(Set d) -> showDRSLambdas d ++ showDRSSet d ++ "\n"
(Debug d) -> showDRSDebug d ++ "\n"
---------------------------------------------------------------------------
-- | Prints a 'DRS'.
---------------------------------------------------------------------------
printDRS :: DRS -> IO ()
printDRS d = putStrLn $ '\n' : showDRS (Boxes d)
---------------------------------------------------------------------------
-- ** Show Merge
---------------------------------------------------------------------------
---------------------------------------------------------------------------
-- | Shows a merge between two 'DRS's.
---------------------------------------------------------------------------
showMerge :: DRS -> DRS -> String
showMerge d1 d2 = showConcat (showConcat b1 (showModifier "+" 2 b2)) (showModifier "=" 2 mr)
where b1 = showDRS (Boxes d1)
b2 = showDRS (Boxes d2)
mr = showDRS (Boxes (d1 <<+>> d2))
---------------------------------------------------------------------------
-- | Prints a merge between two 'DRS's.
---------------------------------------------------------------------------
printMerge :: DRS -> DRS -> IO ()
printMerge d1 d2 = putStrLn $ '\n' : showMerge d1 d2
---------------------------------------------------------------------------
-- ** Show Beta Reduction
---------------------------------------------------------------------------
---------------------------------------------------------------------------
-- | Shows the beta reduction of an 'unresolved DRS' @d1@ with a 'DRS'
-- @d2@.
---------------------------------------------------------------------------
showDRSBetaReduct :: (ShowableDRS d) => (DRS -> d) -> DRS -> String
showDRSBetaReduct d1 d2
= showConcat (showConcat (showModifier "(" 2 b1) (showModifier ")" 2 b2)) (showModifier "=" 2 br)
where b1 = showDRS (Boxes (resolve d1 0 0))
b2 = showDRS (Boxes d2)
br = showDRS (Boxes (resolve (d1 d2) 0 0))
---------------------------------------------------------------------------
-- | Prints the beta reduction of an 'unresolved DRS' @d1@ with a 'DRS'
-- @d2@.
---------------------------------------------------------------------------
printDRSBetaReduct :: (ShowableDRS d) => (DRS -> d) -> DRS -> IO ()
printDRSBetaReduct d1 d2 = putStrLn $ '\n' : showDRSBetaReduct d1 d2
---------------------------------------------------------------------------
-- | Shows the beta reduction of an 'unresolved DRS' @d@ with a 'DRSRef'
-- @r@.
---------------------------------------------------------------------------
showDRSRefBetaReduct :: (ShowableDRS d) => (DRSRef -> d) -> DRSRef -> String
showDRSRefBetaReduct _ (LambdaDRSRef _) = error "impossible beta reduction"
showDRSRefBetaReduct d r@(DRSRef v) = showConcat (showConcat (showModifier "(" 2 bx) (showModifier ")" 2 rv)) (showModifier "=" 2 br)
where bx = showDRS (Boxes (resolve d 0 0))
rv = showPadding (v ++ "\n")
br = showDRS (Boxes (resolve (d r) 0 0))
---------------------------------------------------------------------------
-- | Prints the beta reduction of an 'unresolved DRS' @d@ with a 'DRSRef'
-- @r@.
---------------------------------------------------------------------------
printDRSRefBetaReduct :: (ShowableDRS d) => (DRSRef -> d) -> DRSRef -> IO ()
printDRSRefBetaReduct d r = putStrLn $ '\n' : showDRSRefBetaReduct d r
---------------------------------------------------------------------------
-- ** Operators
---------------------------------------------------------------------------
-- | Negation symbol
opNeg :: String
opNeg = "\x00AC"
-- | Implication symbol
opImp :: String
opImp = "\x21D2"
-- | Disjunction symbol
opOr :: String
opOr = "\x2228"
-- | Diamond symbol
opDiamond :: String
opDiamond = "\x25C7"
-- | Box symbol
opBox :: String
opBox = "\x25FB"
-- | Lambda symbol
opLambda :: String
opLambda = "\x03BB"
-- | Merge symbol
opMerge :: String
opMerge = "\x002B"
---------------------------------------------------------------------------
-- ** Box Construction
---------------------------------------------------------------------------
-- | Top left corner symbol
boxTopLeft :: Char
boxTopLeft = '\x250C'
-- | Top right corner symbol
boxTopRight :: Char
boxTopRight = '\x2510'
-- | Bottom left corner symbol
boxBottomLeft :: Char
boxBottomLeft = '\x2514'
-- | Bottom right corner symbol
boxBottomRight :: Char
boxBottomRight = '\x2518'
-- | Middle left corner symbol
boxMiddleLeft :: Char
boxMiddleLeft = '\x251C'
-- | Middle right corner symbol
boxMiddleRight :: Char
boxMiddleRight = '\x2524'
-- | Horizontal line symbol
boxHorLine :: Char
boxHorLine = '-'
-- | Vertical line symbol
boxVerLine :: Char
boxVerLine = '|'
---------------------------------------------------------------------------
-- | Shows the line by line concatenation of two 'String's.
---------------------------------------------------------------------------
showConcat :: String -> String -> String
showConcat s1 s2 = unlines (conc ls1 ls2)
where conc :: [String] -> [String] -> [String]
conc [] [] = []
conc (a:as) [] = (a ++ " " ++ showWhitespace (length (head ls2))) : conc as []
conc [] (b:bs) = (showWhitespace (length (head ls1)) ++ " " ++ b) : conc [] bs
conc (a:as) (b:bs) = (a ++ " " ++ b) : conc as bs
ls1 = lines s1
ls2 = lines s2
---------------------------------------------------------------------------
-- | Shows the content of a 'DRS' box surrounded by vertical bars.
---------------------------------------------------------------------------
showContent :: Int -> String -> String
showContent l s = unlines (map show' (lines s))
where show' :: String -> String
show' s' = [boxVerLine] ++ " " ++ s' ++ showWhitespace (l - 4 - length s') ++ " " ++ [boxVerLine]
---------------------------------------------------------------------------
-- | Shows a horizontal line of length @l@ with left corner symbol @lc@ and
-- right corner symbol @rc@.
---------------------------------------------------------------------------
showHorizontalLine :: Int -> Char -> Char -> String
showHorizontalLine l lc rc = [lc] ++ replicate (l - 2) boxHorLine ++ [rc] ++ "\n"
---------------------------------------------------------------------------
-- | Shows a modifier @m@ at line number @p@ in front of 'String' @s@.
---------------------------------------------------------------------------
showModifier :: String -> Int -> String -> String
showModifier [] _ s = s
showModifier m p s = unlines (modifier 0 (lines s))
where modifier :: Int -> [String] -> [String]
modifier _ [] = []
modifier n (l:ls)
| n == p = (m ++ " " ++ l) : modifier (n + 1) ls
| otherwise = (showWhitespace (length m + 1) ++ l) : modifier (n + 1) ls
---------------------------------------------------------------------------
-- | Adds two lines of whitespace to the beginning of 'String' @s@.
---------------------------------------------------------------------------
showPadding :: String -> String
showPadding s = showWhitespace l ++ "\n" ++ showWhitespace l ++ "\n" ++ s
where l = length s - 1
---------------------------------------------------------------------------
-- * Private
---------------------------------------------------------------------------
---------------------------------------------------------------------------
-- ** Notations for showing DRSs
---------------------------------------------------------------------------
---------------------------------------------------------------------------
-- | Shows a 'DRS' in 'Boxes' notation.
---------------------------------------------------------------------------
showDRSBox :: DRS -> String
showDRSBox (LambdaDRS ((v,d),_))
| not (null d) = v ++ "(" ++ intercalate "," d ++ ")" ++ "\n"
| otherwise = v ++ "\n"
showDRSBox (Merge d1 d2)
| isLambdaDRS d1 && isLambdaDRS d2 = showModifier "(" 0 (showConcat (showConcat (showDRSBox d1) (showModifier opMerge 0 (showDRSBox d2))) ")")
| not(isLambdaDRS d1) && isLambdaDRS d2 = showBrackets (showConcat (showDRSBox d1) (showModifier opMerge 2 (showPadding (showDRSBox d2))))
| isLambdaDRS d1 && not(isLambdaDRS d2) = showBrackets (showConcat (showPadding (showDRSBox d1)) (showModifier opMerge 2 (showDRSBox d2)))
| otherwise = showBrackets (showConcat (showDRSBox d1) (showModifier opMerge 2 (showDRSBox d2)))
where showBrackets :: String -> String
showBrackets s = showModifier "(" 2 (showConcat s (showPadding ")\n"))
showDRSBox (DRS u c) = showHorizontalLine l boxTopLeft boxTopRight
++ showContent l ul ++ showHorizontalLine l boxMiddleLeft boxMiddleRight
++ showContent l cl ++ showHorizontalLine l boxBottomLeft boxBottomRight
where ul
| not(null u) = showUniverse u " "
| otherwise = " "
cl = showConditions c
l = 4 + maximum (map length (lines ul) `union` map length (lines cl))
---------------------------------------------------------------------------
-- | Shows a DRS in 'Linear' notation.
---------------------------------------------------------------------------
showDRSLinear :: DRS -> String
showDRSLinear (LambdaDRS ((v,d),_))
| not (null d) = v ++ "(" ++ intercalate "," d ++ ")"
| otherwise = v
showDRSLinear (Merge d1 d2)
| not(isLambdaDRS d1) && not(isLambdaDRS d2) = showDRSLinear (d1 <<+>> d2)
| otherwise = showDRSLinear d1 ++ " " ++ opMerge ++ " " ++ showDRSLinear d2
showDRSLinear (DRS u c) = "[" ++ showUniverse u "," ++ ": " ++ intercalate "," (map showCon c) ++ "]"
where showCon :: DRSCon -> String
showCon (Rel r d) = drsRelToString r ++ "(" ++ intercalate "," (map drsRefToDRSVar d) ++ ")"
showCon (Neg d1) = opNeg ++ showDRSLinear d1
showCon (Imp d1 d2) = showDRSLinear d1 ++ " " ++ opImp ++ " " ++ showDRSLinear d2
showCon (Or d1 d2) = showDRSLinear d1 ++ " " ++ opOr ++ " " ++ showDRSLinear d2
showCon (Prop r d1) = drsRefToDRSVar r ++ ": " ++ showDRSLinear d1
showCon (Diamond d1) = opNeg ++ showDRSLinear d1
showCon (Box d1) = opNeg ++ showDRSLinear d1
---------------------------------------------------------------------------
-- | Shows a 'DRS' in 'Set' notation.
---------------------------------------------------------------------------
showDRSSet :: DRS -> String
showDRSSet (LambdaDRS ((v,d),_))
| not (null d) = v ++ "(" ++ intercalate "," d ++ ")"
| otherwise = v
showDRSSet (Merge d1 d2)
| not(isLambdaDRS d1) && not(isLambdaDRS d2) = showDRSSet (d1 <<+>> d2)
| otherwise = showDRSSet d1 ++ " " ++ opMerge ++ " " ++ showDRSSet d2
showDRSSet (DRS u c) = "<{" ++ showUniverse u "," ++ "},{" ++ intercalate "," (map showCon c) ++ "}>"
where showCon :: DRSCon -> String
showCon (Rel r d) = drsRelToString r ++ "(" ++ intercalate "," (map drsRefToDRSVar d) ++ ")"
showCon (Neg d1) = opNeg ++ showDRSSet d1
showCon (Imp d1 d2) = showDRSSet d1 ++ " " ++ opImp ++ " " ++ showDRSSet d2
showCon (Or d1 d2) = showDRSSet d1 ++ " " ++ opOr ++ " " ++ showDRSSet d2
showCon (Prop r d1) = drsRefToDRSVar r ++ ": " ++ showDRSSet d1
showCon (Diamond d1) = opNeg ++ showDRSSet d1
showCon (Box d1) = opNeg ++ showDRSSet d1
---------------------------------------------------------------------------
-- | Show a 'DRS' in 'Debug' notation.
---------------------------------------------------------------------------
showDRSDebug :: DRS -> String
showDRSDebug (LambdaDRS l) = "LambdaDRS" ++ " " ++ show l
showDRSDebug (Merge d1 d2) = "Merge" ++ " (" ++ showDRSDebug d1 ++ ") (" ++ showDRSDebug d2 ++ ")"
showDRSDebug (DRS u c) = "DRS" ++ " " ++ show u ++ " [" ++ intercalate "," (map showCon c) ++ "]"
where showCon :: DRSCon -> String
showCon (Rel r d) = "Rel (" ++ show r ++ ")" ++ " " ++ show d
showCon (Neg d1) = "Neg (" ++ showDRSDebug d1 ++ ")"
showCon (Imp d1 d2) = "Imp (" ++ showDRSDebug d1 ++ ") (" ++ showDRSDebug d2 ++ ")"
showCon (Or d1 d2) = "Or (" ++ showDRSDebug d1 ++ ") (" ++ showDRSDebug d2 ++ ")"
showCon (Box d1) = "Box (" ++ showDRSDebug d1 ++ ")"
showCon (Diamond d1) = "Diamond (" ++ showDRSDebug d1 ++ ")"
showCon (Prop r d1) = "Prop (" ++ show r ++ ") (" ++ showDRSDebug d1 ++ ")"
---------------------------------------------------------------------------
-- ** Showing the subparts of a DRS
---------------------------------------------------------------------------
---------------------------------------------------------------------------
-- | Shows whitespace of width @l@.
---------------------------------------------------------------------------
showWhitespace :: Int -> String
showWhitespace l = replicate l ' '
---------------------------------------------------------------------------
-- | Shows the universe @u@ of a 'DRS', using 'String' @d@ as a delimiter
-- between referents.
---------------------------------------------------------------------------
showUniverse :: [DRSRef] -> String -> String
showUniverse u d = intercalate d (map drsRefToDRSVar u)
showCond :: DRSCon -> String
showCond c = showConditions [c]
---------------------------------------------------------------------------
-- | Shows the conditions @c@ of a 'DRS'.
---------------------------------------------------------------------------
showConditions :: [DRSCon] -> String
showConditions [] = " "
showConditions c = foldr ((++) . showCon) "" c
where showCon :: DRSCon -> String
showCon (Rel r d) = drsRelToString r ++ "(" ++ intercalate "," (map drsRefToDRSVar d) ++ ")\n"
showCon (Neg d1)
| isLambdaDRS d1 = showModifier opNeg 0 b1
| otherwise = showModifier opNeg 2 b1
where b1 = showDRSBox d1
showCon (Imp d1 d2)
| isLambdaDRS d1 && isLambdaDRS d2 = showConcat b1 (showModifier opImp 0 b2)
| not(isLambdaDRS d1) && isLambdaDRS d2 = showConcat b1 (showModifier opImp 2 (showPadding b2))
| isLambdaDRS d1 && not(isLambdaDRS d2) = showConcat (showPadding b1) (showModifier opImp 2 b2)
| otherwise = showConcat b1 (showModifier opImp 2 b2)
where b1 = showDRSBox d1
b2 = showDRSBox d2
showCon (Or d1 d2)
| isLambdaDRS d1 && isLambdaDRS d2 = showConcat b1 (showModifier opOr 0 b2)
| not(isLambdaDRS d1) && isLambdaDRS d2 = showConcat b1 (showModifier opOr 2 (showPadding b2))
| isLambdaDRS d1 && not(isLambdaDRS d2) = showConcat (showPadding b1) (showModifier opOr 2 b2)
| otherwise = showConcat b1 (showModifier opOr 2 b2)
where b1 = showDRSBox d1
b2 = showDRSBox d2
showCon (Prop r d1)
| isLambdaDRS d1 = showModifier (drsRefToDRSVar r ++ ":") 0 b1
| otherwise = showModifier (drsRefToDRSVar r ++ ":") 2 b1
where b1 = showDRSBox d1
showCon (Diamond d1)
| isLambdaDRS d1 = showModifier opDiamond 0 b1
| otherwise = showModifier opDiamond 2 b1
where b1 = showDRSBox d1
showCon (Box d1)
| isLambdaDRS d1 = showModifier opBox 0 b1
| otherwise = showModifier opBox 2 b1
where b1 = showDRSBox d1
---------------------------------------------------------------------------
-- | Shows lambda abstractions over 'DRS' @d@.
---------------------------------------------------------------------------
showDRSLambdas :: DRS -> String
showDRSLambdas d = show' (drsLambdas d)
where show' :: [(DRSVar,[DRSVar])] -> String
show' [] = []
show' ((l,_):ls) = opLambda ++ l ++ "." ++ show' ls
| drbean/pdrt-sandbox | src/Data/DRS/Show.hs | apache-2.0 | 20,058 | 0 | 15 | 3,888 | 5,317 | 2,723 | 2,594 | 271 | 7 |
import System.Random
rndSelect :: [a] -> Int -> IO [a]
rndSelect vals n = do g <- newStdGen
let indices = take n $ randomRs (0, length vals - 1) g
return (map (\i -> vals !! i) indices)
| plilja/h99 | p23.hs | apache-2.0 | 231 | 0 | 14 | 84 | 105 | 52 | 53 | 5 | 1 |
module Main where
import Digits
import Lists
import Primes
import Data.List
import Debug.Trace
findPandigitalsWithDivisibility = map digitsToNum $ filter (\pd -> notStartingWith0 pd && subStringDivisible pd) allPandigitals
where
allPandigitals = permutations [0..9] -- [digits 1406357289]
notStartingWith0 = not . (== 0) . head
subStringDivisible num = all divisible $ zip (allWindows num) primes
allWindows = windowed 3 . tail
divisible (window,prime) = ((digitsToNum window) `mod` prime) == 0
main = print $ sum findPandigitalsWithDivisibility
| kliuchnikau/project-euler | 043/Main.hs | apache-2.0 | 571 | 0 | 11 | 99 | 174 | 94 | 80 | 13 | 1 |
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{- |
Module : Neovim.User.Choice
Description : Ask the user for an answer
Copyright : (c) Sebastian Witte
License : Apache-2.0
Maintainer : [email protected]
Stability : experimental
Portability : GHC
-}
module Neovim.User.Choice
where
import Neovim
import Neovim.API.String
import Data.Char (toLower)
import Data.List (isPrefixOf)
-- | Call @inputlist()@ on the neovim side and ask the user for a choice. This
-- function returns 'Nothing' if the user input was invalid or 'Just' the chosen
-- element. The elements are rendered via 'Pretty'.
oneOf :: [String] -> Neovim env (Maybe String)
oneOf cs = fmap (\i -> cs !! (i-1)) <$> askForIndex (zipWith mkChoice cs [1..])
where
mkChoice :: String -> Int -> Object
mkChoice c i = toObject $ show i <> ". " <> c
-- | Ask user for a choice and 'Maybe' return the index of that choice
-- (1-based).
askForIndex :: [Object] -> Neovim env (Maybe Int)
askForIndex cs = vim_call_function "inputlist" [ObjectArray cs] >>= \case
a -> case fromObject a of
Right i | i >= 1 && i <= length cs ->
return $ Just i
Right _ ->
return Nothing
Left e ->
err e
-- | Same as 'oneOf' only that @a@ is constrained by 'Show' insted of 'Pretty'.
oneOfS :: Show a => [a] -> Neovim env (Maybe a)
oneOfS cs = fmap (\i -> cs !! (i-1)) <$> askForIndex (zipWith mkChoice cs [1..])
where
mkChoice c i = toObject $ show (i :: Int) ++ ". " ++ show c
-- | Open @inputdialog@s inside neovim until the user has successfully typed any
-- prefix of @yes@ or @no@ or alternatively aborted the dialog. Defaults to
-- @yes@ for the empty input.
yesOrNo :: String -- ^ Question to the user
-> Neovim env Bool
yesOrNo message = do
spec <- vim_call_function
"inputdialog" $ (message ++ " (Y/n) ")
+: ("" :: String) +: ("no" :: String) +: []
case fromObject spec of
Right s | map toLower s `isPrefixOf` "yes" ->
return True
Right s | map toLower s `isPrefixOf` "no" ->
return False
Left e ->
err e
_ ->
yesOrNo message
| neovimhaskell/nvim-hs-contrib | library/Neovim/User/Choice.hs | apache-2.0 | 2,290 | 0 | 17 | 664 | 558 | 284 | 274 | 38 | 4 |
module Import
( module Import
) where
import Prelude as Import hiding (head, init, last,
readFile, tail, writeFile)
import Yesod as Import hiding (Route (..))
import Control.Applicative as Import (pure, (<$>), (<*>))
import Data.Text as Import (Text)
import Foundation as Import
import Model as Import
import Settings as Import
import Settings.Development as Import
import Settings.StaticFiles as Import
import Data.Aeson as Import (toJSON)
#if __GLASGOW_HASKELL__ >= 704
import Data.Monoid as Import
(Monoid (mappend, mempty, mconcat),
(<>))
#else
import Data.Monoid as Import
(Monoid (mappend, mempty, mconcat))
infixr 5 <>
(<>) :: Monoid m => m -> m -> m
(<>) = mappend
#endif
import Utils as Import
| HairyDude/heal | Import.hs | bsd-2-clause | 1,023 | 0 | 6 | 425 | 159 | 116 | 43 | -1 | -1 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE NoImplicitPrelude #-}
module System.IO (
IO, Handle, IOMode, SeekMode, FilePath, HandlePosn,
IOException (..), IOErrorType (..),
stdin, stdout, stderr,
withFile, openFile, hClose, readFile, writeFile, appendFile, doesFileExist,
hFileSize, hSetFileSize, hIsEOF, isEOF, hReady, hAvailable, hWaitForInput,
hGetPosn, hSetPosn, hSeek, hTell, hGetBuffering, hSetBuffering, hFlush,
hIsOpen, hIsClosed, hIsReadable, hIsWritable, hIsSeekable, hIsTerminalDevice, hShow,
hGetChar, hGetLine, hLookAhead, hGetContents,
hPutChar, hPutStr, hPutStrLn, hPrint,
putChar, putStr, putStrLn, print,
ioError, ioException, userError,
getChar, getLine, getContents, readIO, readLn, interact,
isAlreadyExistsError, isDoesNotExistError, isAlreadyInUseError, isFullError, isEOFError, isIllegalOperation,
isPermissionError, isUserError, ioeGetErrorType, ioeGetLocation, ioeGetErrorString, ioeGetHandle, ioeGetFileName
) where
import System.Mock.IO.Internal
| 3of8/mockio | New_IO.hs | bsd-2-clause | 1,035 | 0 | 5 | 154 | 244 | 164 | 80 | 18 | 0 |
{-# LANGUAGE BangPatterns, CPP, FlexibleContexts, FlexibleInstances, GeneralizedNewtypeDeriving, InstanceSigs,
RankNTypes, ScopedTypeVariables, TypeFamilies, UndecidableInstances #-}
module Text.Grampa.ContextFree.SortedMemoizing.Transformer (ResultListT(..), ParserT(..), (<<|>),
tbind, lift, tmap, longest, peg, terminalPEG)
where
import Control.Applicative
import Control.Monad (MonadPlus(..), join, void)
#if MIN_VERSION_base(4,13,0)
import Control.Monad (MonadFail(fail))
#endif
import qualified Control.Monad.Trans.Class as Trans (lift)
import Control.Monad.Trans.State.Strict (StateT, evalStateT)
import Data.Either (partitionEithers)
import Data.Function (on)
import Data.Functor.Compose (Compose(..))
import Data.Functor.Identity (Identity(..))
import Data.List.NonEmpty (NonEmpty((:|)), groupBy, nonEmpty, fromList, toList)
import Data.Monoid.Null (MonoidNull(null))
import Data.Monoid.Factorial (FactorialMonoid, splitPrimePrefix)
import Data.Monoid.Textual (TextualMonoid)
import qualified Data.Monoid.Factorial as Factorial
import qualified Data.Monoid.Textual as Textual
import Data.Ord (Down(Down))
import Data.Semigroup (Semigroup((<>)))
import Data.Semigroup.Cancellative (LeftReductive(isPrefixOf))
import Data.String (fromString)
import Witherable (Filterable(mapMaybe))
import Debug.Trace (trace)
import qualified Text.Parser.Char
import Text.Parser.Char (CharParsing)
import Text.Parser.Combinators (Parsing(..))
import Text.Parser.LookAhead (LookAheadParsing(..))
import qualified Rank2
import Text.Grampa.Class (GrammarParsing(..), InputParsing(..), InputCharParsing(..), MultiParsing(..),
ConsumedInputParsing(..), CommittedParsing(..), DeterministicParsing(..),
AmbiguousParsing(..), Ambiguous(Ambiguous),
TailsParsing(..), ParseResults, ParseFailure(..), FailureDescription(..), Pos)
import Text.Grampa.Internal (expected, FallibleResults(..), AmbiguousAlternative(..), TraceableParsing(..))
import qualified Text.Grampa.PEG.Backtrack.Measured as Backtrack
import Prelude hiding (iterate, null, showList, span, takeWhile)
-- | Parser for a context-free grammar with packrat-like sharing that carries a monadic computation as part of the
-- parse result.
newtype ParserT m g s r = Parser{applyParser :: [(s, g (ResultListT m g s))] -> ResultListT m g s r}
newtype ResultsOfLengthT m g s r = ResultsOfLengthT{getResultsOfLength :: ResultsOfLength m g s (m r)}
data ResultsOfLength m g s a = ROL !Int ![(s, g (ResultListT m g s))] !(NonEmpty a)
data ResultListT m g s r = ResultList{resultSuccesses :: ![ResultsOfLengthT m g s r],
resultFailures :: !(ParseFailure Pos s)}
singleResult :: (Applicative m, Ord s) => Int -> [(s, g (ResultListT m g s))] -> r -> ResultListT m g s r
singleResult len rest a = ResultList [ResultsOfLengthT $ ROL len rest (pure a:|[])] mempty
instance Functor m => Functor (ParserT m g s) where
fmap f (Parser p) = Parser (fmap f . p)
{-# INLINE fmap #-}
instance (Applicative m, Ord s) => Applicative (ParserT m g s) where
pure a = Parser (\rest-> singleResult 0 rest a)
Parser p <*> Parser q = Parser r where
r rest = case p rest
of ResultList results failure -> ResultList mempty failure <> foldMap continue results
continue (ResultsOfLengthT (ROL l rest' fs)) = foldMap (continue' l $ q rest') fs
continue' l (ResultList rs failure) f = ResultList (adjust l f <$> rs) failure
adjust l f (ResultsOfLengthT (ROL l' rest' as)) = ResultsOfLengthT (ROL (l+l') rest' ((f <*>) <$> as))
{-# INLINABLE pure #-}
{-# INLINABLE (<*>) #-}
instance (Applicative m, Ord s) => Alternative (ParserT m g s) where
empty = Parser (\rest-> ResultList mempty $ ParseFailure (Down $ length rest) [] [])
Parser p <|> Parser q = Parser r where
r rest = p rest <> q rest
{-# INLINE (<|>) #-}
{-# INLINABLE empty #-}
instance (Applicative m, Traversable m) => Filterable (ParserT m g s) where
mapMaybe f (Parser p) = Parser (mapMaybe f . p)
-- | The 'StateT' instance dangerously assumes that the filtered parser is stateless.
instance {-# overlaps #-} (Monad m, Traversable m, Monoid state) => Filterable (ParserT (StateT state m) g s) where
mapMaybe f (Parser p) = Parser (mapMaybe f . p)
instance (Monad m, Traversable m, Ord s) => Monad (ParserT m g s) where
return = pure
(>>) = (*>)
Parser p >>= f = Parser q where
q rest = case p rest
of ResultList results failure -> ResultList mempty failure <> foldMap continue results
continue (ResultsOfLengthT (ROL l rest' rs)) = foldMap (continue' l . flip applyParser rest' . rejoin . fmap f) rs
continue' l (ResultList rs failure) = ResultList (adjust l <$> rs) failure
adjust l (ResultsOfLengthT (ROL l' rest' rs)) = ResultsOfLengthT (ROL (l+l') rest' rs)
rejoin :: forall a. m (ParserT m g s a) -> ParserT m g s a
rejoinResults :: forall a. m (ResultListT m g s a) -> ResultListT m g s a
rejoinResultsOfLengthT :: forall a. m (ResultsOfLengthT m g s a) -> ResultsOfLengthT m g s a
rejoin m = Parser (\rest-> rejoinResults $ flip applyParser rest <$> m)
rejoinResults m = ResultList (fmap rejoinResultsOfLengthT $ sequence $ resultSuccesses <$> m) (foldMap resultFailures m)
rejoinResultsOfLengthT m = ResultsOfLengthT (join <$> traverse getResultsOfLength m)
#if MIN_VERSION_base(4,13,0)
instance (Monad m, Traversable m, Ord s) => MonadFail (ParserT m g s) where
#endif
fail msg = Parser p
where p rest = ResultList mempty (ParseFailure (Down $ length rest) [] [StaticDescription msg])
instance (Foldable m, Monad m, Traversable m, Ord s) => MonadPlus (ParserT m g s) where
mzero = empty
mplus = (<|>)
-- | Lift a parse-free computation into the parser.
lift :: Ord s => m a -> ParserT m g s a
lift m = Parser (\rest-> ResultList [ResultsOfLengthT $ ROL 0 rest (m:|[])] mempty)
-- | Transform the computation carried by the parser using the monadic bind ('>>=').
tbind :: Monad m => ParserT m g s a -> (a -> m b) -> ParserT m g s b
tbind (Parser p) f = Parser (bindResultList f . p)
-- | Transform the computation carried by the parser.
tmap :: (m a -> m b) -> ParserT m g s a -> ParserT m g s b
tmap f (Parser p) = Parser (mapResultList f . p)
bindResultList :: Monad m => (a -> m b) -> ResultListT m g s a -> ResultListT m g s b
bindResultList f (ResultList successes failures) = ResultList (bindResults f <$> successes) failures
mapResultList :: (m a -> m b) -> ResultListT m g s a -> ResultListT m g s b
mapResultList f (ResultList successes failures) = ResultList (mapResults f <$> successes) failures
bindResults :: Monad m => (a -> m b) -> ResultsOfLengthT m g s a -> ResultsOfLengthT m g s b
bindResults f (ResultsOfLengthT (ROL len rest as)) = ResultsOfLengthT (ROL len rest ((>>= f) <$> as))
mapResults :: (m a -> m b) -> ResultsOfLengthT m g s a -> ResultsOfLengthT m g s b
mapResults f (ResultsOfLengthT rol) = ResultsOfLengthT (f <$> rol)
instance (Applicative m, Semigroup x, Ord s) => Semigroup (ParserT m g s x) where
(<>) = liftA2 (<>)
instance (Applicative m, Monoid x, Ord s) => Monoid (ParserT m g s x) where
mempty = pure mempty
mappend = liftA2 mappend
-- | Memoizing parser that carries an applicative computation. Can be wrapped with
-- 'Text.Grampa.ContextFree.LeftRecursive.Fixed' to provide left recursion support.
--
-- @
-- 'parseComplete' :: ("Rank2".'Rank2.Functor' g, 'FactorialMonoid' s) =>
-- g (Memoizing.'Parser' g s) -> s -> g ('Compose' ('ParseResults' s) [])
-- @
instance (Applicative m, LeftReductive s, FactorialMonoid s, Ord s) => MultiParsing (ParserT m g s) where
type GrammarConstraint (ParserT m g s) g' = (g ~ g', Rank2.Functor g)
type ResultFunctor (ParserT m g s) = Compose (Compose (ParseResults s) []) m
-- | Returns the list of all possible input prefix parses paired with the remaining input suffix.
parsePrefix g input = Rank2.fmap (Compose . Compose . Compose . fmap (fmap sequenceA) . fromResultList)
(snd $ head $ parseGrammarTails g input)
-- parseComplete :: (ParserInput (ParserT m g s) ~ s, Rank2.Functor g, Eq s, FactorialMonoid s) =>
-- g (ParserT m g s) -> s -> g (Compose (Compose (ParseResults s) []) m)
parseComplete g input = Rank2.fmap (Compose . fmap snd . Compose . fromResultList)
(snd $ head $ parseAllTails close $ parseGrammarTails g input)
where close = Rank2.fmap (<* eof) g
-- | Memoizing parser that carries an applicative computation. Can be wrapped with
-- 'Text.Grampa.ContextFree.LeftRecursive.Fixed' to provide left recursion support.
instance (Applicative m, Ord s, LeftReductive s, FactorialMonoid s) => GrammarParsing (ParserT m g s) where
type ParserGrammar (ParserT m g s) = g
type GrammarFunctor (ParserT m g s) = ResultListT m g s
parsingResult _ = Compose . Compose . fmap (fmap sequenceA) . fromResultList
nonTerminal :: (ParserInput (ParserT m g s) ~ s) => (g (ResultListT m g s) -> ResultListT m g s a) -> ParserT m g s a
nonTerminal f = Parser p where
p input@((_, d) : _) = ResultList rs' failure
where ResultList rs failure = f d
rs' = sync <$> rs
-- in left-recursive grammars the stored input remainder may be wrong, so revert to the complete input
sync (ResultsOfLengthT (ROL 0 _remainder r)) = ResultsOfLengthT (ROL 0 input r)
sync rols = rols
p _ = ResultList mempty (expected 0 "NonTerminal at endOfInput")
{-# INLINE nonTerminal #-}
instance (Applicative m, Ord s, LeftReductive s, FactorialMonoid s, Rank2.Functor g) =>
TailsParsing (ParserT m g s) where
parseTails = applyParser
parseGrammarTails :: (Rank2.Functor g, FactorialMonoid s) => g (ParserT m g s) -> s -> [(s, g (ResultListT m g s))]
parseGrammarTails g input = foldr parseTail [] (Factorial.tails input)
where parseTail s parsedTail = parsed
where parsed = (s,d):parsedTail
d = Rank2.fmap (($ parsed) . applyParser) g
instance (Applicative m, LeftReductive s, FactorialMonoid s, Ord s) => InputParsing (ParserT m g s) where
type ParserInput (ParserT m g s) = s
getInput = Parser p
where p rest@((s, _):_) = singleResult 0 rest s
p [] = singleResult 0 [] mempty
anyToken = Parser p
where p rest@((s, _):t) = case splitPrimePrefix s
of Just (first, _) -> singleResult 1 t first
_ -> ResultList mempty (expected (Down $ length rest) "anyToken")
p [] = ResultList mempty (expected 0 "anyToken")
satisfy predicate = Parser p
where p rest@((s, _):t) =
case splitPrimePrefix s
of Just (first, _) | predicate first -> singleResult 1 t first
_ -> ResultList mempty (expected (Down $ length rest) "satisfy")
p [] = ResultList mempty (expected 0 "satisfy")
scan s0 f = Parser (p s0)
where p s rest@((i, _) : _) = singleResult l (drop l rest) prefix
where (prefix, _, _) = Factorial.spanMaybe' s f i
l = Factorial.length prefix
p _ [] = singleResult 0 [] mempty
takeWhile predicate = Parser p
where p rest@((s, _) : _)
| x <- Factorial.takeWhile predicate s, l <- Factorial.length x =
singleResult l (drop l rest) x
p [] = singleResult 0 [] mempty
take 0 = mempty
take n = Parser p
where p rest@((s, _) : _)
| x <- Factorial.take n s, l <- Factorial.length x, l == n =
singleResult l (drop l rest) x
p rest = ResultList mempty (expected (Down $ length rest) $ "take " ++ show n)
takeWhile1 predicate = Parser p
where p rest@((s, _) : _)
| x <- Factorial.takeWhile predicate s, l <- Factorial.length x, l > 0 =
singleResult l (drop l rest) x
p rest = ResultList mempty (expected (Down $ length rest) "takeWhile1")
string s = Parser p where
p rest@((s', _) : _)
| s `isPrefixOf` s' = singleResult l (drop l rest) s
p rest = ResultList mempty (ParseFailure (Down $ length rest) [LiteralDescription s] [])
l = Factorial.length s
notSatisfy predicate = Parser p
where p rest@((s, _):_)
| Just (first, _) <- splitPrimePrefix s,
predicate first = ResultList mempty (expected (Down $ length rest) "notSatisfy")
p rest = singleResult 0 rest ()
{-# INLINABLE string #-}
instance InputParsing (ParserT m g s) => TraceableParsing (ParserT m g s) where
traceInput description (Parser p) = Parser q
where q rest = case traceWith "Parsing " (p rest)
of rl@(ResultList [] _) -> traceWith "Failed " rl
rl -> traceWith "Parsed " rl
where traceWith prefix = trace (prefix <> case rest of ((s, _):_) -> description s; [] -> "EOF")
instance (Applicative m, Ord s, Show s, TextualMonoid s) => InputCharParsing (ParserT m g s) where
satisfyCharInput predicate = Parser p
where p rest@((s, _):t) =
case Textual.characterPrefix s
of Just first
| predicate first -> singleResult 1 t (Factorial.primePrefix s)
_ -> ResultList mempty (expected (Down $ length rest) "satisfyCharInput")
p [] = ResultList mempty (expected 0 "satisfyCharInput")
scanChars s0 f = Parser (p s0)
where p s rest@((i, _) : _) = singleResult l (drop l rest) prefix
where (prefix, _, _) = Textual.spanMaybe_' s f i
l = Factorial.length prefix
p _ [] = singleResult 0 [] mempty
takeCharsWhile predicate = Parser p
where p rest@((s, _) : _)
| x <- Textual.takeWhile_ False predicate s, l <- Factorial.length x =
singleResult l (drop l rest) x
p [] = singleResult 0 [] mempty
takeCharsWhile1 predicate = Parser p
where p rest@((s, _) : _)
| x <- Textual.takeWhile_ False predicate s, l <- Factorial.length x, l > 0 =
singleResult l (drop l rest) x
p rest = ResultList mempty (expected (Down $ length rest) "takeCharsWhile1")
notSatisfyChar predicate = Parser p
where p rest@((s, _):_)
| Just first <- Textual.characterPrefix s,
predicate first = ResultList mempty (expected (Down $ length rest) "notSatisfyChar")
p rest = singleResult 0 rest ()
instance (Applicative m, LeftReductive s, FactorialMonoid s, Ord s) => ConsumedInputParsing (ParserT m g s) where
match (Parser p) = Parser q
where q [] = addConsumed mempty (p [])
q rest@((s, _) : _) = addConsumed s (p rest)
addConsumed input (ResultList rl failure) = ResultList (add1 <$> rl) failure
where add1 (ResultsOfLengthT (ROL l t rs)) =
ResultsOfLengthT (ROL l t $ ((,) (Factorial.take l input) <$>) <$> rs)
instance (Applicative m, MonoidNull s, Ord s) => Parsing (ParserT m g s) where
try (Parser p) = Parser q
where q rest = rewindFailure (p rest)
where rewindFailure (ResultList rl _) = ResultList rl (ParseFailure (Down $ length rest) [] [])
Parser p <?> msg = Parser q
where q rest = replaceFailure (p rest)
where replaceFailure (ResultList [] (ParseFailure pos msgs erroneous)) =
ResultList [] (ParseFailure pos (if pos == Down (length rest) then [StaticDescription msg]
else msgs) erroneous)
replaceFailure rl = rl
notFollowedBy (Parser p) = Parser (\input-> rewind input (p input))
where rewind t (ResultList [] _) = singleResult 0 t ()
rewind t ResultList{} = ResultList mempty (expected (Down $ length t) "notFollowedBy")
skipMany p = go
where go = pure () <|> try p *> go
unexpected msg = Parser (\t-> ResultList mempty $ expected (Down $ length t) msg)
eof = Parser f
where f rest@((s, _):_)
| null s = singleResult 0 rest ()
| otherwise = ResultList mempty (expected (Down $ length rest) "end of input")
f [] = singleResult 0 [] ()
instance (Applicative m, MonoidNull s, Ord s) => DeterministicParsing (ParserT m g s) where
Parser p <<|> Parser q = Parser r where
r rest = case p rest
of rl@(ResultList [] _failure) -> rl <> q rest
rl -> rl
takeSome p = (:) <$> p <*> takeMany p
takeMany (Parser p) = Parser (q 0 (pure id)) where
q !len acc rest = case p rest
of ResultList [] _failure
-> ResultList [ResultsOfLengthT $ ROL len rest (fmap ($ []) acc :| [])] mempty
ResultList rl _ -> foldMap continue rl
where continue (ResultsOfLengthT (ROL len' rest' results)) =
foldMap (\r-> q (len + len') (liftA2 (.) acc ((:) <$> r)) rest') results
skipAll (Parser p) = Parser (q 0 (pure ())) where
q !len effects rest = case p rest
of ResultList [] _failure -> ResultList [ResultsOfLengthT $ ROL len rest (effects:|[])] mempty
ResultList rl _failure -> foldMap continue rl
where continue (ResultsOfLengthT (ROL len' rest' results)) =
foldMap (\r-> q (len + len') (effects <* r) rest') results
instance (Applicative m, Traversable m, Ord s) => CommittedParsing (ParserT m g s) where
type CommittedResults (ParserT m g s) = ParseResults s
commit (Parser p) = Parser q
where q rest = case p rest
of ResultList [] failure -> ResultList [ResultsOfLengthT
$ ROL 0 rest (pure (Left failure) :| [])] mempty
ResultList rl failure -> ResultList (mapResults (fmap Right) <$> rl) failure
admit (Parser p) = Parser q
where q rest = case p rest
of ResultList [] failure -> ResultList [] failure
ResultList rl failure -> foldMap expose rl <> ResultList [] failure
expose (ResultsOfLengthT (ROL len t rs)) = case nonEmpty successes of
Nothing -> ResultList [] (mconcat failures)
Just successes' -> ResultList [ResultsOfLengthT $ ROL len t successes'] (mconcat failures)
where (failures, successes) = partitionEithers (sequenceA <$> toList rs)
instance (Applicative m, MonoidNull s, Ord s) => LookAheadParsing (ParserT m g s) where
lookAhead (Parser p) = Parser (\input-> rewind input (p input))
where rewind _ rl@(ResultList [] _) = rl
rewind t (ResultList rl failure) =
ResultList [ResultsOfLengthT $ ROL 0 t $ foldr1 (<>) (results <$> rl)] failure
results (ResultsOfLengthT (ROL _ _ r)) = r
instance (Applicative m, Ord s, Show s, TextualMonoid s) => CharParsing (ParserT m g s) where
satisfy predicate = Parser p
where p rest@((s, _):t) =
case Textual.characterPrefix s
of Just first | predicate first -> singleResult 1 t first
_ -> ResultList mempty (expected (Down $ length rest) "Char.satisfy")
p [] = ResultList mempty (expected 0 "Char.satisfy")
string s = Textual.toString (error "unexpected non-character") <$> string (fromString s)
text t = (fromString . Textual.toString (error "unexpected non-character")) <$> string (Textual.fromText t)
instance (Applicative m, Eq (m ()), Ord s) => AmbiguousParsing (ParserT m g s) where
ambiguous (Parser p) = Parser q
where q rest | ResultList rs failure <- p rest = ResultList (groupByLength <$> rs) failure
groupByLength :: ResultsOfLengthT m g s r -> ResultsOfLengthT m g s (Ambiguous r)
groupByLength (ResultsOfLengthT (ROL l rest rs)) =
ResultsOfLengthT (ROL l rest $ (Ambiguous <$>) <$> fromList (sequenceA <$> groupBy ((==) `on` void) rs))
-- | Turns a context-free parser into a backtracking PEG parser that consumes the longest possible prefix of the list
-- of input tails, opposite of 'peg'
longest :: ParserT Identity g s a -> Backtrack.Parser g [(s, g (ResultListT Identity g s))] a
longest p = Backtrack.Parser q where
q rest = case applyParser p rest
of ResultList [] (ParseFailure pos positive negative)
-> Backtrack.NoParse (ParseFailure pos (map message positive) (map message negative))
ResultList rs _ -> parsed (last rs)
parsed (ResultsOfLengthT (ROL l s (Identity r:|_))) = Backtrack.Parsed l r s
message (StaticDescription msg) = StaticDescription msg
message (LiteralDescription s) = LiteralDescription [(s, error "longest")]
-- | Turns a backtracking PEG parser of the list of input tails into a context-free parser, opposite of 'longest'
peg :: (Applicative m, Ord s) => Backtrack.Parser g [(s, g (ResultListT m g s))] a -> ParserT m g s a
peg p = Parser q where
q rest = case Backtrack.applyParser p rest
of Backtrack.Parsed l result suffix -> singleResult l suffix result
Backtrack.NoParse (ParseFailure pos positive negative) ->
ResultList mempty (ParseFailure pos ((fst . head <$>) <$> positive) ((fst . head <$>) <$> negative))
-- | Turns a backtracking PEG parser into a context-free parser
terminalPEG :: (Applicative m, Monoid s, Ord s) => Backtrack.Parser g s a -> ParserT m g s a
terminalPEG p = Parser q where
q [] = case Backtrack.applyParser p mempty
of Backtrack.Parsed l result _ -> singleResult l [] result
Backtrack.NoParse failure -> ResultList mempty failure
q rest@((s, _):_) = case Backtrack.applyParser p s
of Backtrack.Parsed l result _ -> singleResult l (drop l rest) result
Backtrack.NoParse failure -> ResultList mempty failure
fromResultList :: (Functor m, Eq s, FactorialMonoid s) => ResultListT m g s r -> ParseResults s [(s, m r)]
fromResultList (ResultList [] (ParseFailure pos positive negative)) = Left (ParseFailure (pos - 1) positive negative)
fromResultList (ResultList rl _failure) = Right (foldMap f rl)
where f (ResultsOfLengthT (ROL _ ((s, _):_) r)) = (,) s <$> toList r
f (ResultsOfLengthT (ROL _ [] r)) = (,) mempty <$> toList r
{-# INLINABLE fromResultList #-}
instance Functor (ResultsOfLength m g s) where
fmap f (ROL l t a) = ROL l t (f <$> a)
{-# INLINE fmap #-}
instance Functor m => Functor (ResultsOfLengthT m g s) where
fmap f (ResultsOfLengthT rol) = ResultsOfLengthT (fmap f <$> rol)
{-# INLINE fmap #-}
instance Functor m => Functor (ResultListT m g s) where
fmap f (ResultList l failure) = ResultList ((f <$>) <$> l) failure
{-# INLINE fmap #-}
instance (Applicative m, Ord s) => Applicative (ResultsOfLength m g s) where
pure = ROL 0 mempty . pure
ROL l1 _ fs <*> ROL l2 t2 xs = ROL (l1 + l2) t2 (fs <*> xs)
{-# INLINE pure #-}
{-# INLINE (<*>) #-}
instance (Applicative m, Ord s) => Applicative (ResultsOfLengthT m g s) where
pure = ResultsOfLengthT . pure . pure
ResultsOfLengthT rol1 <*> ResultsOfLengthT rol2 = ResultsOfLengthT (liftA2 (<*>) rol1 rol2)
instance (Applicative m, Ord s) => Applicative (ResultListT m g s) where
pure a = ResultList [pure a] mempty
ResultList rl1 f1 <*> ResultList rl2 f2 = ResultList ((<*>) <$> rl1 <*> rl2) (f1 <> f2)
instance (Applicative m, Ord s) => Alternative (ResultListT m g s) where
empty = ResultList mempty mempty
(<|>) = (<>)
instance (Applicative m, Ord s) => AmbiguousAlternative (ResultListT m g s) where
ambiguousOr (ResultList rl1 f1) (ResultList rl2 f2) = ResultList (merge rl1 rl2) (f1 <> f2)
where merge [] rl = rl
merge rl [] = rl
merge rl1'@(rol1@(ResultsOfLengthT (ROL l1 s1 r1)) : rest1)
rl2'@(rol2@(ResultsOfLengthT (ROL l2 _ r2)) : rest2)
| l1 < l2 = rol1 : merge rest1 rl2'
| l1 > l2 = rol2 : merge rl1' rest2
| otherwise = ResultsOfLengthT (ROL l1 s1 $ liftA2 (liftA2 collect) r1 r2) : merge rest1 rest2
collect (Ambiguous xs) (Ambiguous ys) = Ambiguous (xs <> ys)
instance Traversable m => Filterable (ResultListT m g s) where
mapMaybe :: forall a b. (a -> Maybe b) -> ResultListT m g s a -> ResultListT m g s b
mapMaybe f (ResultList rs failure) = ResultList (mapMaybe filterResults rs) failure
where filterResults :: ResultsOfLengthT m g s a -> Maybe (ResultsOfLengthT m g s b)
filterResults (ResultsOfLengthT (ROL l t as)) =
ResultsOfLengthT . ROL l t <$> nonEmpty (mapMaybe (traverse f) $ toList as)
instance {-# overlaps #-} (Monad m, Traversable m, Monoid state) => Filterable (ResultListT (StateT state m) g s) where
mapMaybe :: forall a b. (a -> Maybe b) -> ResultListT (StateT state m) g s a -> ResultListT (StateT state m) g s b
mapMaybe f (ResultList rs failure) = ResultList (mapMaybe filterResults rs) failure
where filterResults :: ResultsOfLengthT (StateT state m) g s a -> Maybe (ResultsOfLengthT (StateT state m) g s b)
filterResults (ResultsOfLengthT (ROL l t as)) =
ResultsOfLengthT . ROL l t <$> nonEmpty (mapMaybe traverseWithMonoid $ toList as)
traverseWithMonoid :: StateT state m a -> Maybe (StateT state m b)
traverseWithMonoid m = Trans.lift <$> traverse f (evalStateT m mempty)
instance Ord s => Semigroup (ResultListT m g s r) where
ResultList rl1 f1 <> ResultList rl2 f2 = ResultList (merge rl1 rl2) (f1 <> f2)
where merge [] rl = rl
merge rl [] = rl
merge rl1'@(rol1@(ResultsOfLengthT (ROL l1 s1 r1)) : rest1)
rl2'@(rol2@(ResultsOfLengthT (ROL l2 _ r2)) : rest2)
| l1 < l2 = rol1 : merge rest1 rl2'
| l1 > l2 = rol2 : merge rl1' rest2
| otherwise = ResultsOfLengthT (ROL l1 s1 (r1 <> r2)) : merge rest1 rest2
instance Ord s => Monoid (ResultListT m g s r) where
mempty = ResultList mempty mempty
mappend = (<>)
instance FallibleResults (ResultListT m g) where
hasSuccess (ResultList [] _) = False
hasSuccess _ = True
failureOf (ResultList _ failure) = failure
failWith = ResultList []
| blamario/grampa | grammatical-parsers/src/Text/Grampa/ContextFree/SortedMemoizing/Transformer.hs | bsd-2-clause | 26,644 | 67 | 20 | 6,991 | 9,826 | 5,040 | 4,786 | 397 | 4 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QGraphicsSceneWheelEvent.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:24
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QGraphicsSceneWheelEvent (
setDelta
,qGraphicsSceneWheelEvent_delete
)
where
import Qth.ClassTypes.Core
import Qtc.Enums.Base
import Qtc.Enums.Core.Qt
import Qtc.Enums.Core.QEvent
import Qtc.Classes.Base
import Qtc.Classes.Qccs
import Qtc.Classes.Core
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui
import Qtc.ClassTypes.Gui
instance Qbuttons (QGraphicsSceneWheelEvent a) (()) (IO (MouseButtons)) where
buttons x0 ()
= withQFlagsResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsSceneWheelEvent_buttons cobj_x0
foreign import ccall "qtc_QGraphicsSceneWheelEvent_buttons" qtc_QGraphicsSceneWheelEvent_buttons :: Ptr (TQGraphicsSceneWheelEvent a) -> IO CLong
instance Qdelta (QGraphicsSceneWheelEvent a) (()) where
delta x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsSceneWheelEvent_delta cobj_x0
foreign import ccall "qtc_QGraphicsSceneWheelEvent_delta" qtc_QGraphicsSceneWheelEvent_delta :: Ptr (TQGraphicsSceneWheelEvent a) -> IO CInt
instance Qmodifiers (QGraphicsSceneWheelEvent a) (()) where
modifiers x0 ()
= withQFlagsResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsSceneWheelEvent_modifiers cobj_x0
foreign import ccall "qtc_QGraphicsSceneWheelEvent_modifiers" qtc_QGraphicsSceneWheelEvent_modifiers :: Ptr (TQGraphicsSceneWheelEvent a) -> IO CLong
instance Qorientation (QGraphicsSceneWheelEvent a) (()) (IO (QtOrientation)) where
orientation x0 ()
= withQEnumResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsSceneWheelEvent_orientation cobj_x0
foreign import ccall "qtc_QGraphicsSceneWheelEvent_orientation" qtc_QGraphicsSceneWheelEvent_orientation :: Ptr (TQGraphicsSceneWheelEvent a) -> IO CLong
instance Qpos (QGraphicsSceneWheelEvent a) (()) (IO (PointF)) where
pos x0 ()
= withPointFResult $ \cpointf_ret_x cpointf_ret_y ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsSceneWheelEvent_pos_qth cobj_x0 cpointf_ret_x cpointf_ret_y
foreign import ccall "qtc_QGraphicsSceneWheelEvent_pos_qth" qtc_QGraphicsSceneWheelEvent_pos_qth :: Ptr (TQGraphicsSceneWheelEvent a) -> Ptr CDouble -> Ptr CDouble -> IO ()
instance Qqpos (QGraphicsSceneWheelEvent a) (()) (IO (QPointF ())) where
qpos x0 ()
= withQPointFResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsSceneWheelEvent_pos cobj_x0
foreign import ccall "qtc_QGraphicsSceneWheelEvent_pos" qtc_QGraphicsSceneWheelEvent_pos :: Ptr (TQGraphicsSceneWheelEvent a) -> IO (Ptr (TQPointF ()))
instance QscenePos (QGraphicsSceneWheelEvent a) (()) where
scenePos x0 ()
= withPointFResult $ \cpointf_ret_x cpointf_ret_y ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsSceneWheelEvent_scenePos_qth cobj_x0 cpointf_ret_x cpointf_ret_y
foreign import ccall "qtc_QGraphicsSceneWheelEvent_scenePos_qth" qtc_QGraphicsSceneWheelEvent_scenePos_qth :: Ptr (TQGraphicsSceneWheelEvent a) -> Ptr CDouble -> Ptr CDouble -> IO ()
instance QqscenePos (QGraphicsSceneWheelEvent a) (()) where
qscenePos x0 ()
= withQPointFResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsSceneWheelEvent_scenePos cobj_x0
foreign import ccall "qtc_QGraphicsSceneWheelEvent_scenePos" qtc_QGraphicsSceneWheelEvent_scenePos :: Ptr (TQGraphicsSceneWheelEvent a) -> IO (Ptr (TQPointF ()))
instance QscreenPos (QGraphicsSceneWheelEvent a) (()) where
screenPos x0 ()
= withPointResult $ \cpoint_ret_x cpoint_ret_y ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsSceneWheelEvent_screenPos_qth cobj_x0 cpoint_ret_x cpoint_ret_y
foreign import ccall "qtc_QGraphicsSceneWheelEvent_screenPos_qth" qtc_QGraphicsSceneWheelEvent_screenPos_qth :: Ptr (TQGraphicsSceneWheelEvent a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QqscreenPos (QGraphicsSceneWheelEvent a) (()) where
qscreenPos x0 ()
= withQPointResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsSceneWheelEvent_screenPos cobj_x0
foreign import ccall "qtc_QGraphicsSceneWheelEvent_screenPos" qtc_QGraphicsSceneWheelEvent_screenPos :: Ptr (TQGraphicsSceneWheelEvent a) -> IO (Ptr (TQPoint ()))
instance QsetButtons (QGraphicsSceneWheelEvent a) ((MouseButtons)) where
setButtons x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsSceneWheelEvent_setButtons cobj_x0 (toCLong $ qFlags_toInt x1)
foreign import ccall "qtc_QGraphicsSceneWheelEvent_setButtons" qtc_QGraphicsSceneWheelEvent_setButtons :: Ptr (TQGraphicsSceneWheelEvent a) -> CLong -> IO ()
setDelta :: QGraphicsSceneWheelEvent a -> ((Int)) -> IO ()
setDelta x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsSceneWheelEvent_setDelta cobj_x0 (toCInt x1)
foreign import ccall "qtc_QGraphicsSceneWheelEvent_setDelta" qtc_QGraphicsSceneWheelEvent_setDelta :: Ptr (TQGraphicsSceneWheelEvent a) -> CInt -> IO ()
instance QsetModifiers (QGraphicsSceneWheelEvent a) ((KeyboardModifiers)) where
setModifiers x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsSceneWheelEvent_setModifiers cobj_x0 (toCLong $ qFlags_toInt x1)
foreign import ccall "qtc_QGraphicsSceneWheelEvent_setModifiers" qtc_QGraphicsSceneWheelEvent_setModifiers :: Ptr (TQGraphicsSceneWheelEvent a) -> CLong -> IO ()
instance QsetOrientation (QGraphicsSceneWheelEvent a) ((QtOrientation)) where
setOrientation x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsSceneWheelEvent_setOrientation cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QGraphicsSceneWheelEvent_setOrientation" qtc_QGraphicsSceneWheelEvent_setOrientation :: Ptr (TQGraphicsSceneWheelEvent a) -> CLong -> IO ()
instance QsetPos (QGraphicsSceneWheelEvent a) ((PointF)) where
setPos x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCPointF x1 $ \cpointf_x1_x cpointf_x1_y ->
qtc_QGraphicsSceneWheelEvent_setPos_qth cobj_x0 cpointf_x1_x cpointf_x1_y
foreign import ccall "qtc_QGraphicsSceneWheelEvent_setPos_qth" qtc_QGraphicsSceneWheelEvent_setPos_qth :: Ptr (TQGraphicsSceneWheelEvent a) -> CDouble -> CDouble -> IO ()
instance QqsetPos (QGraphicsSceneWheelEvent a) ((QPointF t1)) where
qsetPos x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsSceneWheelEvent_setPos cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsSceneWheelEvent_setPos" qtc_QGraphicsSceneWheelEvent_setPos :: Ptr (TQGraphicsSceneWheelEvent a) -> Ptr (TQPointF t1) -> IO ()
instance QsetScenePos (QGraphicsSceneWheelEvent a) ((PointF)) where
setScenePos x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCPointF x1 $ \cpointf_x1_x cpointf_x1_y ->
qtc_QGraphicsSceneWheelEvent_setScenePos_qth cobj_x0 cpointf_x1_x cpointf_x1_y
foreign import ccall "qtc_QGraphicsSceneWheelEvent_setScenePos_qth" qtc_QGraphicsSceneWheelEvent_setScenePos_qth :: Ptr (TQGraphicsSceneWheelEvent a) -> CDouble -> CDouble -> IO ()
instance QqsetScenePos (QGraphicsSceneWheelEvent a) ((QPointF t1)) where
qsetScenePos x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsSceneWheelEvent_setScenePos cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsSceneWheelEvent_setScenePos" qtc_QGraphicsSceneWheelEvent_setScenePos :: Ptr (TQGraphicsSceneWheelEvent a) -> Ptr (TQPointF t1) -> IO ()
instance QsetScreenPos (QGraphicsSceneWheelEvent a) ((Point)) where
setScreenPos x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
qtc_QGraphicsSceneWheelEvent_setScreenPos_qth cobj_x0 cpoint_x1_x cpoint_x1_y
foreign import ccall "qtc_QGraphicsSceneWheelEvent_setScreenPos_qth" qtc_QGraphicsSceneWheelEvent_setScreenPos_qth :: Ptr (TQGraphicsSceneWheelEvent a) -> CInt -> CInt -> IO ()
instance QqsetScreenPos (QGraphicsSceneWheelEvent a) ((QPoint t1)) where
qsetScreenPos x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsSceneWheelEvent_setScreenPos cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsSceneWheelEvent_setScreenPos" qtc_QGraphicsSceneWheelEvent_setScreenPos :: Ptr (TQGraphicsSceneWheelEvent a) -> Ptr (TQPoint t1) -> IO ()
qGraphicsSceneWheelEvent_delete :: QGraphicsSceneWheelEvent a -> IO ()
qGraphicsSceneWheelEvent_delete x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsSceneWheelEvent_delete cobj_x0
foreign import ccall "qtc_QGraphicsSceneWheelEvent_delete" qtc_QGraphicsSceneWheelEvent_delete :: Ptr (TQGraphicsSceneWheelEvent a) -> IO ()
| uduki/hsQt | Qtc/Gui/QGraphicsSceneWheelEvent.hs | bsd-2-clause | 8,775 | 0 | 12 | 1,142 | 2,162 | 1,103 | 1,059 | -1 | -1 |
{-# LANGUAGE FlexibleInstances #-}
module Model.ImageCache where
import Prelude
import Data.Convertible
import Data.Text (Text)
import Database.HDBC
import qualified Data.ByteString as B
import Model.Query
data CachedImage = CachedImage B.ByteString
| CachedError String
instance Convertible [SqlValue] CachedImage where
safeConvert [data_, error]
| not (B.null $ fromBytea data_) =
Right $ CachedImage $ fromBytea data_
| otherwise =
Right $ CachedError $ fromSql error
safeConvert _ = Right $ CachedError "safeConvert CachedImage error"
getImage :: Text -> Int -> Query CachedImage
getImage url size =
query "SELECT \"data\", \"error\" FROM cached_images WHERE \"url\"=? AND \"size\"=?"
[toSql url, toSql size]
putImage :: IConnection conn =>
Text -> Int -> CachedImage -> conn -> IO ()
putImage url size cached db =
do 1 <- case cached of
CachedError error ->
run db "INSERT INTO cached_images (\"url\", \"size\", \"error\", \"time\") VALUES (?, ?, ?, NOW())"
[toSql url, toSql size, toSql error]
CachedImage data_ ->
run db "INSERT INTO cached_images (\"url\", \"size\", \"data\", \"time\") VALUES (?, ?, ?, NOW())"
[toSql url, toSql size, toBytea data_]
return ()
| jannschu/bitlove-ui | Model/ImageCache.hs | bsd-2-clause | 1,376 | 0 | 13 | 378 | 330 | 166 | 164 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module HerokuBuild.API
( ApiKey
, getHeroku
, postHeroku
, postHeroku'
) where
import Data.Aeson
import Data.ByteString (ByteString)
import Network.HTTP.Conduit
import Network.HTTP.Types
import qualified Data.ByteString.Lazy as L
type ApiKey = ByteString
getHeroku :: FromJSON a => ApiKey -> String -> IO (Maybe a)
getHeroku k p = heroku k p $ \r -> r { method = "GET" }
postHeroku :: (ToJSON a, FromJSON b) => ApiKey -> String -> a -> IO (Maybe b)
postHeroku k p resource = heroku k p $ \r -> r
{ method = "POST", requestBody = RequestBodyLBS $ encode resource }
-- | Same as @'postHeroku'@ but discards the response body
postHeroku' :: ToJSON a => ApiKey -> String -> a -> IO ()
postHeroku' k p resource = heroku' k p $ \r -> r
{ method = "POST", requestBody = RequestBodyLBS $ encode resource }
heroku :: FromJSON a => ApiKey -> String -> (Request -> Request) -> IO (Maybe a)
heroku k p modify = fmap decode $ herokuReq k p modify
heroku' :: ApiKey -> String -> (Request -> Request) -> IO ()
heroku' k p modify = herokuReq k p modify >> return ()
herokuReq :: ApiKey -> String -> (Request -> Request) -> IO L.ByteString
herokuReq k p modify = do
req <- parseUrlThrow $ herokuApi ++ p
mgr <- newManager tlsManagerSettings
rsp <- httpLbs (modify $ req { requestHeaders = herokuHeaders k }) mgr
return $ responseBody rsp
herokuApi :: String
herokuApi = "https://api.heroku.com"
herokuHeaders :: ApiKey -> [Header]
herokuHeaders key =
[ (hContentType, "application/json")
, (hAccept, "application/vnd.heroku+json; version=3")
, (hAuthorization, key)
]
| pbrisbin/heroku-build | src/HerokuBuild/API.hs | bsd-3-clause | 1,657 | 0 | 13 | 341 | 575 | 305 | 270 | 37 | 1 |
{-|
Copyright : (c) Dave Laing, 2017
License : BSD3
Maintainer : [email protected]
Stability : experimental
Portability : non-portable
-}
{-# LANGUAGE ConstraintKinds #-}
module Fragment.If.Rules.Term (
IfEvalConstraint
, ifEvalRules
) where
import Control.Lens (review, preview)
import Rules.Term
import Ast.Term
import Fragment.Bool.Ast.Term
import Fragment.If.Ast.Term
stepIf1 :: AsTmIf ki ty pt tm => (Term ki ty pt tm a -> Maybe (Term ki ty pt tm a)) -> Term ki ty pt tm a -> Maybe (Term ki ty pt tm a)
stepIf1 stepFn tm = do
(tmB, tmT, tmE) <- preview _TmIf tm
tmB' <- stepFn tmB
return $ review _TmIf (tmB', tmT, tmE)
stepIf2 :: (AsTmIf ki ty pt tm, AsTmBool ki ty pt tm) => (Term ki ty pt tm a -> Maybe (Term ki ty pt tm a)) -> Term ki ty pt tm a -> Maybe (Term ki ty pt tm a)
stepIf2 valueFn tm = do
(tmB, tmT, tmF) <- preview _TmIf tm
vB <- valueFn tmB
b <- preview _TmBool vB
return $
if b then tmT else tmF
type IfEvalConstraint ki ty pt tm a =
( AsTmBool ki ty pt tm
, AsTmIf ki ty pt tm
)
ifEvalRules :: IfEvalConstraint ki ty pt tm a
=> EvalInput ki ty pt tm a
ifEvalRules =
EvalInput [] [ StepRecurse stepIf1, StepValue stepIf2] []
| dalaing/type-systems | src/Fragment/If/Rules/Term.hs | bsd-3-clause | 1,216 | 0 | 11 | 283 | 471 | 245 | 226 | 28 | 2 |
import Data.List (unfoldr, foldl')
import Data.Bool (bool)
mapRaw, mapF, mapU :: (a -> b) -> [a] -> [b]
mapRaw f (x : xs) = f x : mapRaw f xs
mapRaw _ _ = []
mapF f = foldr ((:) . f) []
mapU f = unfoldr $ \l -> case l of
x : xs -> Just (f x, xs)
_ -> Nothing
filterRaw, filterF :: (a -> Bool) -> [a] -> [a]
filterRaw p (x : xs)
| p x = x : filterRaw p xs
| otherwise = filterRaw p xs
filterRaw _ [] = []
filterF p = foldr (\x -> bool id (x :) (p x)) []
partitionRaw, partitionF :: (a -> Bool) -> [a] -> ([a], [a])
partitionRaw p (x : xs)
| p x = (x : ts, es)
| otherwise = (ts, x : es)
where (ts, es) = partitionRaw p xs
partitionRaw _ _ = ([], [])
partitionF p = foldr
(\x (ts, es) -> bool (ts, x : es) (x : ts, es) (p x))
([], [])
takeRaw, takeU :: Int -> [a] -> [a]
takeRaw n (x : xs) | n > 0 = x : takeRaw (n - 1) xs
takeRaw _ _ = []
takeU = curry . unfoldr $ \nl -> case nl of
(n, x : xs) | n > 0 -> Just (x, (n - 1, xs))
_ -> Nothing
dropRaw :: Int -> [a] -> [a]
dropRaw n (_ : xs) | n > 0 = dropRaw (n - 1) xs
dropRaw _ xs = xs
splitAtRaw :: Int -> [a] -> ([a], [a])
splitAtRaw n (x : xs) | n > 0 = (x : t, d)
where (t, d) = splitAtRaw (n - 1) xs
splitAtRaw _ xs = ([], xs)
takeWhileRaw, takeWhileF, takeWhileU :: (a -> Bool) -> [a] -> [a]
takeWhileRaw p (x : xs) | p x = x : takeWhileRaw p xs
takeWhileRaw _ _ = []
takeWhileF p = foldr (\x -> bool (const []) (x :) (p x)) []
takeWhileU p = unfoldr $ \l -> case l of
x : xs | p x -> Just (x, xs)
_ -> Nothing
dropWhileRaw :: (a -> Bool) -> [a] -> [a]
dropWhileRaw p (x : xs) | p x = dropWhileRaw p xs
dropWhileRaw _ xs = xs
spanRaw :: (a -> Bool) -> [a] -> ([a], [a])
spanRaw p (x : xs) | p x = (x : t, d)
where (t, d) = spanRaw p xs
spanRaw _ xs = ([], xs)
zipRaw, zipU :: [a] -> [b] -> [(a, b)]
zipRaw (x : xs) (y : ys) = (x, y) : zipRaw xs ys
zipRaw _ _ = []
zipU = curry . unfoldr $ \l -> case l of
(x : xs, y : ys) -> Just ((x, y), (xs, ys))
_ -> Nothing
zipWithRaw, zipWithU :: (a -> b -> c) -> [a] -> [b] -> [c]
zipWithRaw op (x : xs) (y : ys) = x `op` y : zipWithRaw op xs ys
zipWithRaw _ _ _ = []
zipWithU op = curry . unfoldr $ \l -> case l of
(x : xs, y : ys) -> Just (x `op` y, (xs, ys))
_ -> Nothing
zipZW :: [a] -> [b] -> [(a, b)]
zipZW = zipWith (,)
unzipRaw, unzipF :: [(a, b)] -> ([a], [b])
unzipRaw ((x, y) : xys) = (x : xs, y : ys)
where (xs, ys) = unzipRaw xys
unzipRaw _ = ([], [])
unzipF = foldr (\(x, y) (xs, ys) -> (x : xs, y : ys)) ([], [])
(.++), (.++.) :: [a] -> [a] -> [a]
(x : xs) .++ ys = x : (xs .++ ys)
[] .++ ys = ys
-- xs .++. ys = foldr (:) ys xs
(.++.) = flip $ foldr (:)
concatRaw, concatF :: [[a]] -> [a]
concatRaw (xs : xss) = xs ++ concatRaw xss
concatRaw [] = []
concatF = foldr (++) []
reverseRaw, reverseF :: [a] -> [a]
reverseRaw = rv []
where
rv rs (x : xs) = rv (x : rs) xs
rv rs [] = rs
reverseF = foldl' (flip (:)) []
repeatRaw, repeatU :: a -> [a]
repeatRaw x = x : repeatRaw x
repeatU = unfoldr $ \x -> Just (x, x)
replicateRaw, replicateU :: Int -> a -> [a]
replicateRaw n x | n > 0 = x : replicateRaw (n - 1) x
replicateRaw _ _ = []
replicateU = curry . unfoldr $ \(n, x) ->
bool Nothing (Just (x, (n - 1, x))) (n > 0)
cycleRaw, cycleC :: [a] -> [a]
cycleRaw xs = xs ++ cycleRaw xs
cycleC = concat . repeat
| YoshikuniJujo/funpaala | samples/18_list_std_fun/stdFun.hs | bsd-3-clause | 3,276 | 6 | 14 | 851 | 2,168 | 1,185 | 983 | 94 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module CouchGames.ResistanceSpec (resistanceSpec) where
import Test.Hspec
import Data.Either
import Control.Monad
import CouchGames.Game
import CouchGames.Player
import qualified CouchGames.Resistance as R
comOnlyConfig = R.GameConfig { R.commander = True, R.bodyGuard = False }
bodyGuardConfig = R.GameConfig { R.commander = True, R.bodyGuard = True }
p1 = Player 1 "Player1"
p2 = Player 2 "Player2"
p3 = Player 3 "Player3"
p4 = Player 4 "Player4"
p5 = Player 5 "Player5"
p6 = Player 6 "Player6"
p7 = Player 7 "Player7"
p8 = Player 8 "Player8"
p9 = Player 9 "Player9"
p10 = Player 10 "Player10"
p11 = Player 11 "Player11"
fivePlayers = [p1, p2, p3, p4, p5]
sixPlayers = [p1, p2, p3, p4, p5, p6]
sevenPlayers = [p1, p2, p3, p4, p5, p6, p7]
eightPlayers = [p1, p2, p3, p4, p5, p6, p7, p8]
ninePlayers = [p1, p2, p3, p4, p5, p6, p7, p8, p9]
tenPlayers = [p1, p2, p3, p4, p5, p6, p7, p8, p9, p10]
playersToRoles = [
(R.defaultConfig, fivePlayers,
[R.Resistance, R.Resistance, R.Resistance, R.Spy, R.Spy])
, (R.defaultConfig, sixPlayers,
[R.Resistance, R.Resistance, R.Resistance, R.Resistance, R.Spy, R.Spy])
, (R.defaultConfig, sevenPlayers,
[R.Resistance, R.Resistance, R.Resistance, R.Resistance, R.Spy, R.Spy, R.Spy])
, (R.defaultConfig, eightPlayers,
[R.Resistance, R.Resistance, R.Resistance, R.Resistance, R.Resistance, R.Spy, R.Spy, R.Spy])
, (R.defaultConfig, ninePlayers,
[R.Resistance, R.Resistance, R.Resistance, R.Resistance, R.Resistance, R.Resistance, R.Spy, R.Spy, R.Spy])
, (R.defaultConfig, tenPlayers,
[R.Resistance, R.Resistance, R.Resistance, R.Resistance, R.Resistance, R.Resistance, R.Spy, R.Spy, R.Spy, R.Spy])
, (comOnlyConfig, fivePlayers,
[R.Commander, R.Resistance, R.Resistance, R.Assassin, R.Spy])
, (comOnlyConfig, sixPlayers,
[R.Commander, R.Resistance, R.Resistance, R.Resistance, R.Assassin, R.Spy])
, (comOnlyConfig, sevenPlayers,
[R.Commander, R.Resistance, R.Resistance, R.Resistance, R.Assassin, R.Spy, R.Spy])
, (comOnlyConfig, eightPlayers,
[R.Commander, R.Resistance, R.Resistance, R.Resistance, R.Resistance, R.Assassin, R.Spy, R.Spy])
, (comOnlyConfig, ninePlayers,
[R.Commander, R.Resistance, R.Resistance, R.Resistance, R.Resistance, R.Resistance, R.Assassin, R.Spy, R.Spy])
, (comOnlyConfig, tenPlayers,
[R.Commander, R.Resistance, R.Resistance, R.Resistance, R.Resistance, R.Resistance, R.Assassin, R.Spy, R.Spy, R.Spy])
, (bodyGuardConfig, fivePlayers,
[R.Commander, R.BodyGuard, R.Resistance, R.Assassin, R.FalseCommander])
, (bodyGuardConfig, sixPlayers,
[R.Commander, R.BodyGuard, R.Resistance, R.Resistance, R.Assassin, R.FalseCommander])
, (bodyGuardConfig, sevenPlayers,
[R.Commander, R.BodyGuard, R.Resistance, R.Resistance, R.Assassin, R.FalseCommander, R.Spy])
, (bodyGuardConfig, eightPlayers,
[R.Commander, R.BodyGuard, R.Resistance, R.Resistance, R.Resistance, R.Assassin, R.FalseCommander, R.Spy])
, (bodyGuardConfig, ninePlayers,
[R.Commander, R.BodyGuard, R.Resistance, R.Resistance, R.Resistance, R.Resistance, R.Assassin, R.FalseCommander, R.Spy])
, (bodyGuardConfig, tenPlayers,
[R.Commander, R.BodyGuard, R.Resistance, R.Resistance, R.Resistance, R.Resistance, R.Assassin, R.FalseCommander, R.Spy, R.Spy])
]
nextLeader :: Int -> Player -> Player
nextLeader n lead
| lead == p1 = p2
| lead == p2 = p3
| lead == p3 = p4
| lead == p4 = p5
| n == 5 && lead == p5 = p1
| lead == p5 = p6
| n == 6 && lead == p6 = p1
| lead == p6 = p7
| n == 7 && lead == p7 = p1
| lead == p7 = p8
| n == 8 && lead == p8 = p1
| lead == p8 = p9
| n == 9 && lead == p9 = p1
| lead == p9 = p10
| lead == p10 = p1
leaders :: Int -> Player -> [Player]
leaders n lead = lead : leaders n (nextLeader n lead)
withNewGame :: [Player] -> R.GameConfig -> (R.GameState -> Expectation) -> Expectation
withNewGame ps config f = do
g <- (initGame R.resistance) config ps
case g of
Left err -> expectationFailure "Failed to init game"
Right gs -> f gs
withAction :: R.GameState -> Player -> R.Action -> (R.GameState -> Expectation) -> Expectation
withAction g p a f = do
g' <- (gameAction R.resistance) p a g
case g' of
Left err -> do
putStrLn (show p)
putStrLn (show a)
putStrLn (show g)
expectationFailure $ "An action failed unexpectedly (" ++ err ++ ")"
Right gs -> f gs
withActions :: R.GameState -> [(Player, R.Action)] -> (R.GameState -> Expectation) -> Expectation
withActions g [] f = f g
withActions g ((p, a):as) f = withAction g p a (\g -> withActions g as f)
mapFst :: (a -> c) -> (a, b) -> (c, b)
mapFst f (a, b) = (f a, b)
mapSnd :: (b -> c) -> (a, b) -> (a, c)
mapSnd f (a, b) = (a, f b)
resistanceSpec = do
describe "Resistance" $ do
it "fails to make games with the wrong number of players" $ do
g1 <- (initGame R.resistance) R.defaultConfig []
g1 `shouldBe` (Left "Wrong number of players")
g2 <- (initGame R.resistance) R.defaultConfig [p1, p2, p3, p4]
g2 `shouldBe` (Left "Wrong number of players")
g3 <- (initGame R.resistance) R.defaultConfig [p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11]
g3 `shouldBe` (Left "Wrong number of players")
it "creates games with the correct roles" $ do
forM_ playersToRoles $ \(config, players, roles) -> do
g <- (initGame R.resistance) config players
case g of
Left err -> expectationFailure "Failed to init game"
Right gs -> (map snd (R.players gs)) `shouldMatchList` roles
it "Won't allow proposal of the wrong number of players" $ do
withNewGame fivePlayers R.defaultConfig $ \gs -> do
let lead = R.leader gs
g1 <- (gameAction R.resistance) lead (R.ProposeMission []) gs
g1 `shouldBe` (Left "Wrong number of players in mission proposal")
g2 <- (gameAction R.resistance) lead (R.ProposeMission [p1]) gs
g2 `shouldBe` (Left "Wrong number of players in mission proposal")
g3 <- (gameAction R.resistance) lead (R.ProposeMission [p1, p2, p3]) gs
g3 `shouldBe` (Left "Wrong number of players in mission proposal")
it "Won't allow proposal by a player that's not the leader" $ do
withNewGame fivePlayers R.defaultConfig $ \gs -> do
let lead = R.leader gs
let notLead = if lead == p1 then p2 else p1
g1 <- (gameAction R.resistance) notLead (R.ProposeMission [p1, p2]) gs
g1 `shouldBe` (Left "Only the leader can propose a mission")
it "Won't allow proposal during voting" $ do
withNewGame fivePlayers R.defaultConfig $ \gs -> do
let lead = R.leader gs
withAction gs lead (R.ProposeMission [p1, p2]) $ \g1 -> do
g2 <- (gameAction R.resistance) lead (R.ProposeMission [p1, p2]) g1
g2 `shouldBe` Left "Wrong game phase"
it "Allows a mission proposal" $ do
withNewGame fivePlayers R.defaultConfig $ \gs -> do
let lead = R.leader gs
withAction gs lead (R.ProposeMission [p1, p2]) $ \g1 -> do
length (R.proposals g1) `shouldBe` 1
let (proposed, votes) = last (R.proposals g1)
proposed `shouldContain` [p1, p2]
votes `shouldBe` []
it "Won't allow voting before a proposal" $ do
withNewGame fivePlayers R.defaultConfig $ \gs -> do
let p = head fivePlayers
g1 <- (gameAction R.resistance) p (R.VoteOnProposal R.Reject) gs
g1 `shouldBe` Left "Wrong game phase"
it "Allows voting" $ do
withNewGame fivePlayers R.defaultConfig $ \gs -> do
let lead = R.leader gs
withAction gs lead (R.ProposeMission [p1, p2]) $ \g1 -> do
let p = head fivePlayers
withAction g1 p (R.VoteOnProposal R.Reject) $ \g2 -> do
fst (head (snd (head (R.proposals g2)))) `shouldBe` p
snd (head (snd (head (R.proposals g2)))) `shouldBe` R.Reject
it "Won't allow double voting" $ do
withNewGame fivePlayers R.defaultConfig $ \gs -> do
let lead = R.leader gs
let p = head fivePlayers
withAction gs lead (R.ProposeMission [p1, p2]) $ \g1 -> do
withAction g1 p (R.VoteOnProposal R.Reject) $ \g2 -> do
g3 <- (gameAction R.resistance) p (R.VoteOnProposal R.Reject) g2
g3 `shouldBe` Left "Player has already voted"
it "Rejects a proposal on a minority" $ do
withNewGame fivePlayers R.defaultConfig $ \g0 -> do
let lead = R.leader g0
let votes = [ (fivePlayers !! 0, R.Reject)
, (fivePlayers !! 1, R.Reject)
, (fivePlayers !! 2, R.Reject)
, (fivePlayers !! 3, R.Accept)
, (fivePlayers !! 4, R.Accept)]
let actions = map (mapSnd R.VoteOnProposal) votes
withAction g0 lead (R.ProposeMission [p1, p2]) $ \g1 -> do
withActions g1 actions $ \g2 -> do
R.phase g2 `shouldBe` R.Propose
R.missions g2 `shouldBe` []
fst (last (R.proposals g2)) `shouldContain` [p1, p2]
snd (last (R.proposals g2)) `shouldContain` votes
it "Accepts a proposal on a majority" $ do
withNewGame fivePlayers R.defaultConfig $ \g0 -> do
let lead = R.leader g0
let votes = [ (fivePlayers !! 0, R.Reject)
, (fivePlayers !! 1, R.Accept)
, (fivePlayers !! 2, R.Reject)
, (fivePlayers !! 3, R.Accept)
, (fivePlayers !! 4, R.Accept)]
let actions = map (mapSnd R.VoteOnProposal) votes
withAction g0 lead (R.ProposeMission [p1, p2]) $ \g1 -> do
withActions g1 actions $ \g2 -> do
R.phase g2 `shouldBe` R.DoMission
R.missionPlayers (last (R.missions g2)) `shouldContain` [p1, p2]
R.missionTokens (last (R.missions g2)) `shouldBe` []
fst (last (R.proposals g2)) `shouldContain` [p1, p2]
snd (last (R.proposals g2)) `shouldContain` votes
it "Won't allow putting two tokens in for a mission" $ do
withNewGame fivePlayers R.defaultConfig $ \g0 -> do
let lead = R.leader g0
let votes = [ (fivePlayers !! 0, R.Accept)
, (fivePlayers !! 1, R.Accept)
, (fivePlayers !! 2, R.Accept)
, (fivePlayers !! 3, R.Accept)
, (fivePlayers !! 4, R.Accept)]
let vActions = map (mapSnd R.VoteOnProposal) votes
let actions = (lead, R.ProposeMission [p1, p2])
: vActions ++ [(p1, R.GoOnMission R.Succeed)]
withActions g0 actions $ \g1 -> do
R.phase g1 `shouldBe` R.DoMission
fst (last (R.proposals g1)) `shouldContain` [p1, p2]
snd (last (R.proposals g1)) `shouldContain` votes
g2 <- (gameAction R.resistance) p1 (R.GoOnMission R.Succeed) g1
g2 `shouldBe` Left "Player has already put in a token"
it "Allows succeeding a mission" $ do
withNewGame fivePlayers R.defaultConfig $ \g0 -> do
let lead = R.leader g0
let votes = [ (fivePlayers !! 0, R.Accept)
, (fivePlayers !! 1, R.Accept)
, (fivePlayers !! 2, R.Accept)
, (fivePlayers !! 3, R.Accept)
, (fivePlayers !! 4, R.Accept)]
let tokens = [ (p1, R.Succeed)
, (p2, R.Succeed)]
let actions = (lead, R.ProposeMission [p1, p2])
: (map (mapSnd R.VoteOnProposal) votes)
++ (map (mapSnd R.GoOnMission) tokens)
withActions g0 actions $ \g1 -> do
R.phase g1 `shouldBe` R.Propose
it "Allows failing a mission" $ do
withNewGame fivePlayers R.defaultConfig $ \g0 -> do
let lead = R.leader g0
let votes = [ (fivePlayers !! 0, R.Accept)
, (fivePlayers !! 1, R.Accept)
, (fivePlayers !! 2, R.Accept)
, (fivePlayers !! 3, R.Accept)
, (fivePlayers !! 4, R.Accept)]
let tokens = [ (p1, R.Succeed)
, (p2, R.Fail)]
let actions = (lead, R.ProposeMission [p1, p2])
: (map (mapSnd R.VoteOnProposal) votes)
++ (map (mapSnd R.GoOnMission) tokens)
withActions g0 actions $ \g1 -> do
R.phase g1 `shouldBe` R.Propose
it "Won't allow a Resistance player to fail a mission" $ do
withNewGame fivePlayers R.defaultConfig $ \g0 -> do
True `shouldBe` False
it "Allows the Resistance to win" $ do
withNewGame fivePlayers R.defaultConfig $ \g0 -> do
let lead = R.leader g0
let missions = [[p1, p2], [p1, p2, p3], [p1, p2]]
let proposals = zip (leaders 5 lead) (map R.ProposeMission missions)
let votes = map (\p -> (p, R.VoteOnProposal R.Accept)) fivePlayers
let tokens = map (map (\p -> (p, R.GoOnMission R.Succeed))) missions
let actions = concat $ zipWith (\p t -> p : votes ++ t) proposals tokens
withActions g0 actions $ \g1 -> do
R.phase g1 `shouldBe` R.GameOver
it "Allows the Spies to win" $ do
withNewGame fivePlayers R.defaultConfig $ \g0 -> do
let lead = R.leader g0
let missions = [[p1, p2], [p1, p2, p3], [p1, p2]]
let proposals = zip (leaders 5 lead) (map R.ProposeMission missions)
let votes = map (\p -> (p, R.VoteOnProposal R.Accept)) fivePlayers
let tokens = map (map (\p -> (p, R.GoOnMission R.Fail))) missions
let actions = concat $ zipWith (\p t -> p : votes ++ t) proposals tokens
withActions g0 actions $ \g1 -> do
R.phase g1 `shouldBe` R.GameOver
| alexlegg/couchgames | test/CouchGames/ResistanceSpec.hs | bsd-3-clause | 15,371 | 0 | 39 | 5,318 | 5,388 | 2,846 | 2,542 | 272 | 3 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
{- |
Module : Kiosk.Backend.Data.DataTemplateEntry
Description : Individual Entries for Data Templates
Copyright : Plow Technologies LLC
License : MIT License
Maintainer :
Stability : experimental
Portability : portable
description
-}
module Kiosk.Backend.Data.DataTemplateEntry ( DataTemplateEntry(..)
, dataTemplateEntryKey
, dataTemplateEntryValue
, getListOfSortedTemplateItems
, fromDataTemplateEntryToCsv
, fromDataTemplateEntryToS3Csv
, fromDataTemplateEntryToXlsxWorksheet
) where
import Control.Applicative ((<$>), (<*>))
import Control.Lens (makeLenses, view)
import Data.Aeson (FromJSON, ToJSON,
Value (..), object,
parseJSON, toJSON,
(.:), (.=))
import Data.ByteString.Lazy (ByteString)
--import qualified Data.ByteString as BS (ByteString)
import qualified Data.ByteString.Lazy as LBS
import Data.Foldable (foldl, foldr)
import qualified Data.List as L
import Data.Text (Text)
import Data.Text.Encoding (decodeUtf8)
import qualified Data.Csv as C (Field, ToRecord,
ToRecord, encode,
toField,
toRecord)
import Codec.Xlsx (Cell (_cellValue),
CellMap,
CellValue (CellText),
Worksheet (_wsCells),
def)
import Data.Map (empty, insert, union)
import Data.Monoid (mempty)
import qualified Data.Vector as V
import Kiosk.Backend.Data.DataTemplate (DataTemplate (..),
InputText (..),
InputType (..),
TemplateItem (..),
fromDataTemplateToCSV,
_templateItems)
import Kiosk.Backend.Data.DataTemplateEntryKey
import Prelude hiding (foldl, foldr)
-- |Data Template Entry defines a return value of a form
data DataTemplateEntry = DataTemplateEntry {
_dataTemplateEntryKey :: DataTemplateEntryKey,
_dataTemplateEntryValue :: DataTemplate
}
deriving (Show,Eq,Ord)
instance C.ToRecord DataTemplateEntry where
toRecord (DataTemplateEntry dtk dtv) = C.toRecord dtk V.++ C.toRecord dtv
makeLenses ''DataTemplateEntry
-- | Query Helpers
getListOfSortedTemplateItems :: DataTemplate -> [TemplateItem]
getListOfSortedTemplateItems dts = L.sort $ templateItems dts
-- | Aeson Instances
instance ToJSON DataTemplateEntry where
toJSON (DataTemplateEntry k v) = object ["key" .= k
,"value" .= v]
instance FromJSON DataTemplateEntry where
parseJSON (Object o) = DataTemplateEntry <$> o .: "key"
<*> o .: "value"
parseJSON _ = fail "Expecting DateTemplateEntry object, Received Other"
-- | CSV Stuff
fromDataTemplateEntryToCsv :: [DataTemplateEntry] -> ByteString
fromDataTemplateEntryToCsv templateEntries = LBS.append (appendKeyHeaders . getHeaders $ templatesWithSortedItems templateEntries)
(C.encode . sortDataTemplatesEntries $ templateEntries)
templatesWithSortedItems :: [DataTemplateEntry] -> [DataTemplate]
templatesWithSortedItems dataTemplateEntries =
sortDataTemplatesWRemoveField `fmap`
(fromDataTemplatesEntryToDataTemplates dataTemplateEntries)
sortDataTemplatesWRemoveField :: DataTemplate -> DataTemplate
sortDataTemplatesWRemoveField dts = dts {templateItems = newDts}
where newDts = L.sort . filterTemplateItems $ view _templateItems dts
-- | Remove the signature from a CSV file
notSignature :: TemplateItem -> Bool
notSignature (TemplateItem ("Driver_Signature"::Text) (InputTypeText (InputText _))) = False
notSignature _ = True
-- notUUID (TemplateItem ("UUID"::Text) (InputTypeText (InputText _))) = False
-- notUUID _ = True
defaultKeyHeaders :: ByteString
defaultKeyHeaders = "Date,FormId,TicketId,UUID,"
appendKeyHeaders :: ByteString -> ByteString
appendKeyHeaders = LBS.append defaultKeyHeaders
-- |Header Creation
getHeaders :: [DataTemplate] -> ByteString
getHeaders [] = ""
getHeaders lstOfTemplates = LBS.append dropComma "\r\n"
where bs = LBS.concat . fromLabelsToHeaders . templateItems . head $ lstOfTemplates
dropComma = LBS.take (LBS.length bs -1) bs
-- | Transformations
fromDataTemplateEntryToS3Csv :: [DataTemplateEntry] -> ByteString
fromDataTemplateEntryToS3Csv templateEntries = LBS.append (getHeaders templatesWithSortedItems_) (fromDataTemplateToCSV templatesWithSortedItems_)
where dataTemplates = fromDataTemplatesEntryToDataTemplates templateEntries
templatesWithSortedItems_ = sortDataTemplates <$> dataTemplates
fromDataTemplatesEntryToDataTemplates :: [DataTemplateEntry] -> [DataTemplate]
fromDataTemplatesEntryToDataTemplates dtes = view dataTemplateEntryValue <$> dtes
fromLabelsToHeaders :: [TemplateItem] -> [ByteString]
fromLabelsToHeaders tis = flip LBS.append "," <$> (LBS.fromStrict . C.toField . label <$> tis)
-- | Ordering
sortDataTemplatesEntries :: [DataTemplateEntry] -> [DataTemplateEntry]
sortDataTemplatesEntries dtes = sortDataTemplatesEntry <$> dtes
sortDataTemplatesEntry :: DataTemplateEntry -> DataTemplateEntry
sortDataTemplatesEntry dte = dte {_dataTemplateEntryValue =s}
where s = sortDataTemplatesWRemoveField $ view dataTemplateEntryValue dte
sortDataTemplates :: DataTemplate -> DataTemplate
sortDataTemplates dts = dts {templateItems = newDts}
where newDts = L.sort . filterTemplateItems $ view _templateItems dts
filterTemplateItems :: [TemplateItem] -> [TemplateItem]
filterTemplateItems = filter notSignature
type RowIndex = Int
type ColumnIndex = Int
type Row = CellMap
type Header = Text
dataTemplateDefaultHeaders :: [Text]
dataTemplateDefaultHeaders = ["Date","FormId","TicketId","UUID"]
-- |Excel Related files
-- Double List can be reduced in a head like operation without exception
headDoubleList :: [[a]] -> [a]
headDoubleList (a:_) = a
headDoubleList [] = []
fromDataTemplateEntryToXlsxWorksheet :: [DataTemplateEntry] -> Worksheet
fromDataTemplateEntryToXlsxWorksheet [] = def
fromDataTemplateEntryToXlsxWorksheet dataTemplateEntries = fromDataTemplateEntryToXlsxWithHeaders
dataTemplateHeaders
sortedDataTemplateEntries
where
sortedDataTemplateEntries :: [DataTemplateEntry]
sortedDataTemplateEntries = sortDataTemplatesEntries dataTemplateEntries
dataTemplateItems :: [TemplateItem]
dataTemplateItems = headDoubleList (map (templateItems . _dataTemplateEntryValue) sortedDataTemplateEntries)
dataTemplateHeaders = dataTemplateDefaultHeaders ++ dataTemplateCustomHeaders
dataTemplateCustomHeaders = map label dataTemplateItems
fromDataTemplateEntryToXlsxWithHeaders :: [Text] -> [DataTemplateEntry] -> Worksheet
fromDataTemplateEntryToXlsxWithHeaders headers_ data_ = def { _wsCells = headerCells `union` dataCells }
where
dataCells = snd $ foldr (mkCellsFromRecord columnIndexes) (dataCellsStartRow, empty) data_
headerCells = mkHeaderCells headers_
dataCellsStartRow = 2
numDefaultKeyHeaders = length dataTemplateDefaultHeaders
columnIndexes = zip (drop numDefaultKeyHeaders headers_)
[numDefaultKeyHeaders+1..]
mkHeaderCells :: [Text] -> CellMap
mkHeaderCells names = fst $ foldl fn (mempty, 1) names
fn :: (CellMap, ColumnIndex) -> Text -> (CellMap, ColumnIndex)
fn (cellMap, col) name = (cellMap', col + 1)
where
cell = def{ _cellValue = Just (CellText name) }
cellMap' = insert (1,col) cell cellMap
mkCellsFromRecord :: [(Header,ColumnIndex)]
-> DataTemplateEntry
-> (RowIndex, Row)
-> (RowIndex, Row)
mkCellsFromRecord columnIndexes a (rowIndex, acc) =(rowIndex + 1,union acc row)
where
row = union keyRow valueRow
(_, keyRow) = foldl rowFromField
(1, empty)
(C.toRecord (_dataTemplateEntryKey a))
rowFromField (columnIndex, acc') field =
mkCellFromFields rowIndex columnIndex field acc'
valueItems = templateItems (_dataTemplateEntryValue a)
valueRow = makeRowFromTemplateItems rowIndex columnIndexes valueItems
mkCellFromFields :: RowIndex
-> ColumnIndex
-> C.Field
-> Row
-> (ColumnIndex, Row)
mkCellFromFields rowIndex
columnIndex
field
row =
(columnIndex + 1, insert (rowIndex,columnIndex) cell row)
where
cell = def { _cellValue = Just (CellText cellValue) }
cellValue = decodeUtf8 field
makeRowFromTemplateItems
:: RowIndex
-> [(Header,ColumnIndex)]
-> [TemplateItem]
-> Row
makeRowFromTemplateItems rowIndex columnIndexes =
foldl (flip (insertTemplateItemInRow rowIndex columnIndexes)) empty
insertTemplateItemInRow
:: RowIndex
-> [(Header,ColumnIndex)]
-> TemplateItem
-> Row
-> Row
insertTemplateItemInRow rowIndex columnIndexes templateItem row =
case lookup header columnIndexes of
Nothing -> row
Just columnIndex -> insert (rowIndex,columnIndex) cell row
where
header = label templateItem
cell = def { _cellValue = Just (CellText cellValue) }
cellValue = decodeUtf8 (C.toField templateItem)
| plow-technologies/cobalt-kiosk-data-template | src/Kiosk/Backend/Data/DataTemplateEntry.hs | bsd-3-clause | 11,240 | 0 | 11 | 3,769 | 2,035 | 1,147 | 888 | 180 | 2 |
{-# LANGUAGE FlexibleContexts #-}
module Control.Concurrent.Timer.Lifted
( Timer
, TimerIO
, oneShotTimer
, oneShotStart
, oneShotRestart
, repeatedTimer
, repeatedStart
, repeatedRestart
, newTimer
, stopTimer
) where
------------------------------------------------------------------------------
import Control.Applicative
import Control.Concurrent.Lifted (ThreadId, fork, killThread)
import Control.Concurrent.MVar.Lifted (newMVar, tryTakeMVar, putMVar, modifyMVar_)
import Control.Concurrent.Suspend.Lifted (Delay, suspend)
import Control.Monad
import Control.Monad.Base (MonadBase)
import Control.Monad.Trans.Control (MonadBaseControl)
------------------------------------------------------------------------------
import Control.Concurrent.Timer.Types (Timer(..), TimerImmutable(..))
------------------------------------------------------------------------------
-- | Attempts to start a timer.
-- The started timer will have the given delay and action associated and will be one-shot timer.
--
-- If the timer was already initialized, it the previous timer will be stoped (the thread killed) and the timer will be started anew.
--
-- Returns True if the strat was successful,
-- otherwise (e.g. other thread is attempting to manipulate the timer) returns False.
oneShotStart :: MonadBaseControl IO m
=> Timer m
-> m () -- ^ The action the timer will start with.
-> Delay -- ^ The dealy the timer will start with.
-> m Bool
oneShotStart (Timer mvmtim) a d = do
mtim <- tryTakeMVar mvmtim
case mtim of
Just (Just (TimerImmutable _ _ tid)) -> do
killThread tid
oneShotTimerImmutable a d >>= putMVar mvmtim . Just
return True
Just (Nothing) -> do
oneShotTimerImmutable a d >>= putMVar mvmtim . Just
return True
Nothing -> return False
{-# INLINEABLE oneShotStart #-}
-- | Attempts to start a timer.
-- The started timer will have the given delay and action associated and will be repeated timer.
--
-- If the timer was already initialized, it the previous timer will be stoped (the thread killed) and the timer will be started anew.
--
-- Returns True if the strat was successful,
-- otherwise (e.g. other thread is attempting to manipulate the timer) returns False.
repeatedStart :: MonadBaseControl IO m
=> Timer m
-> m () -- ^ The action the timer will start with.
-> Delay -- ^ The dealy the timer will start with.
-> m Bool
repeatedStart (Timer mvmtim) a d = do
mtim <- tryTakeMVar mvmtim
case mtim of
Just (Just (TimerImmutable _ _ tid)) -> do
killThread tid
repeatedTimerImmutable a d >>= putMVar mvmtim . Just
return True
Just (Nothing) -> do
repeatedTimerImmutable a d >>= putMVar mvmtim . Just
return True
Nothing -> return False
{-# INLINEABLE repeatedStart #-}
-- | Attempts to restart already initialized timer.
-- The restarted timer will have the same delay and action associated and will be one-shot timer.
--
-- Returns True if the restrat was successful,
-- otherwise (e.g. other thread is attempting to manipulate the timer or the timer was not initialized) returns False.
oneShotRestart :: MonadBaseControl IO m
=> Timer m
-> m Bool
oneShotRestart (Timer mvmtim) = do
mtim <- tryTakeMVar mvmtim
case mtim of
Just (Just (TimerImmutable a d tid)) -> do
killThread tid
oneShotTimerImmutable a d >>= putMVar mvmtim . Just
return True
_ -> return False
{-# INLINEABLE oneShotRestart #-}
-- | Attempts to restart already initialized timer.
-- The restarted timer will have the same delay and action associated and will be one-shot timer.
--
-- Returns True if the restrat was successful,
-- otherwise (e.g. other thread is attempting to manipulate the timer or the timer was not initialized) returns False.
repeatedRestart :: MonadBaseControl IO m
=> Timer m
-> m Bool
repeatedRestart (Timer mvmtim) = do
mtim <- tryTakeMVar mvmtim
case mtim of
Just (Just (TimerImmutable a d tid)) -> do
killThread tid
repeatedTimerImmutable a d >>= putMVar mvmtim . Just
return True
_ -> return False
{-# INLINEABLE repeatedRestart #-}
-- | Executes the the given action once after the given delay elapsed, no sooner, maybe later.
oneShotTimer :: MonadBaseControl IO m
=> m () -- ^ The action to be executed.
-> Delay -- ^ The (minimal) time until the execution in microseconds.
-> m (Timer m)
oneShotTimer a d = Timer <$> (oneShotTimerImmutable a d >>= newMVar . Just)
{-# INLINE oneShotTimer #-}
-- | Executes the the given action repeatedly with at least the given delay between executions.
repeatedTimer :: MonadBaseControl IO m
=> m () -- ^ The action to be executed.
-> Delay -- ^ The (minimal) delay between executions.
-> m (Timer m)
repeatedTimer a d = Timer <$> (repeatedTimerImmutable a d >>= newMVar . Just)
{-# INLINE repeatedTimer #-}
-- | This function is blocking. It waits until it can stop the timer
-- (until there is a value in the MVar), then it kills the timer's thread.
--
-- After this action completes, the Timer is not innitialized anymore (the MVar contains Nothing).
stopTimer :: MonadBaseControl IO m
=> Timer m
-> m ()
stopTimer (Timer mvmtim) = modifyMVar_ mvmtim $
maybe (return Nothing)
(\(TimerImmutable _ _ tid) -> killThread tid >> return Nothing)
{-# INLINE stopTimer #-}
-- | Creates a new timer. This does not start the timer.
newTimer :: MonadBase IO m
=> m (Timer m)
newTimer = Timer <$> newMVar Nothing
{-# INLINE newTimer #-}
------------------------------------------------------------------------------
-- | Utility
type TimerIO = Timer IO
-- | Forks a new thread that runs the supplied action
-- (at least) after the given delay and stores the action,
-- delay and thread id in the immutable TimerImmutable value.
oneShotTimerImmutable :: MonadBaseControl IO m
=> m () -- ^ The action to be executed.
-> Delay -- ^ The (minimal) time until the execution in microseconds.
-> m (TimerImmutable m)
oneShotTimerImmutable a d = TimerImmutable a d <$> oneShotAction a d
{-# INLINE oneShotTimerImmutable #-}
-- | Forks a new thread that repeats the supplied action
-- with (at least) the given delay between each execution and stores the action,
-- delay and thread id in the immutable TimerImmutable value.
repeatedTimerImmutable :: MonadBaseControl IO m
=> m () -- ^ The action to be executed.
-> Delay -- ^ The (minimal) time until the execution in microseconds.
-> m (TimerImmutable m)
repeatedTimerImmutable a d = TimerImmutable a d <$> repeatedAction a d
{-# INLINE repeatedTimerImmutable #-}
-- | Forks a new thread that runs the supplied action
-- (at least) after the given delay.
oneShotAction :: MonadBaseControl IO m
=> m ()
-> Delay
-> m ThreadId
oneShotAction action delay = fork (suspend delay >> action)
{-# INLINE oneShotAction #-}
-- | Forks a new thread that repeats the supplied action
-- with (at least) the given delay between each execution.
repeatedAction :: MonadBaseControl IO m
=> m ()
-> Delay
-> m ThreadId
repeatedAction action delay = fork (forever $ suspend delay >> action)
{-# INLINE repeatedAction #-}
| uwap/timers | src/Control/Concurrent/Timer/Lifted.hs | bsd-3-clause | 7,919 | 0 | 14 | 2,129 | 1,300 | 665 | 635 | 122 | 3 |
module Blog.FrontEnd.Urls where
import Blog.Constants as C
import List (intersperse)
all_posts :: String
all_posts = C.base_url ++ "/articles"
posts_by_tag :: String -> String
posts_by_tag t = "/t/" ++ t
posts_by_tags :: [String] -> String
posts_by_tags t = "/t/" ++ (tags_fragment t)
post :: String -> String
post p = C.base_url ++ "/p" ++ p
add_comment :: String -> String
add_comment p = C.base_url ++ "/c/add-comment/" ++ p
pending_comments :: Maybe Int -> String
pending_comments Nothing = C.base_url ++ "/z/review-comments"
pending_comments (Just n) = C.base_url ++ "/z/review-comments/p/" ++ (show n)
add_comment_target :: String -> String
add_comment_target p = C.base_url ++ "/e/add-comment/" ++ p
post_comment :: String -> String
post_comment _ = C.base_url ++ "/x/post-comment"
review_comment :: String -> String
review_comment i = C.base_url ++ "/z/review-comment/" ++ i
edit_comment_target :: Int -> String
edit_comment_target i = C.base_url ++ "/x/edit-comment/" ++ (show i)
delete_comment :: String
delete_comment = C.base_url ++ "/x/delete-comment"
delete_comments :: String
delete_comments = C.base_url ++ "/x/delete-comments"
comments :: String -> String
comments p = p ++ "#comments"
tags_fragment :: [String] -> String
tags_fragment = concat . (intersperse ",") | prb/perpubplat | src/Blog/FrontEnd/Urls.hs | bsd-3-clause | 1,297 | 0 | 7 | 193 | 389 | 208 | 181 | 32 | 1 |
{-# LANGUAGE
TypeOperators
, FlexibleContexts
, FlexibleInstances
, OverloadedStrings
#-}
module Xml.XPath.Evaluator where
import Control.Category
import Control.Arrow
import Control.Arrow.ArrowF
import Control.Arrow.List
import Data.Attoparsec.Text (Number)
import Data.Text (Text)
import Text.XmlHtml (Node)
import Prelude hiding ((.), id, elem, const)
import Text.XmlHtml (nodeText)
import Xml.XPath.Arrow
import Xml.XPath.Types
import Xml.XPath.Parser (parser)
import qualified Data.Text as T
{-
todo:
- What about Ord and Num instances for non-numeric values?
- What about parent selectors et al?
-}
data Value
= NodeValue (Z Node)
| AttrValue (Z Attr)
| TextValue Text
| NumValue Number
deriving Show
instance Eq Value where
NumValue n == NumValue m = n == m
a == b = stringValue a == stringValue b
instance Ord Value where
compare (NumValue n) (NumValue m) = compare n m
compare a b = compare (stringValue a) (stringValue b)
instance Num Value where
NumValue a + NumValue b = NumValue (a + b)
NumValue a * NumValue b = NumValue (a * b)
abs (NumValue a) = NumValue (abs a)
signum (NumValue a) = NumValue (signum a)
fromInteger = NumValue . fromInteger
instance Fractional Value where
fromRational = NumValue . fromRational
type Result = (Integer, Value)
nodeV :: ArrowF [] (~>) => Value ~> Z Node
nodeV = embed . arr (\n -> case n of NodeValue z -> [z]; _ -> [])
attrV :: ArrowF [] (~>) => Value ~> Z Attr
attrV = embed . arr (\n -> case n of AttrValue z -> [z]; _ -> [])
textV :: ArrowF [] (~>) => Value ~> Text
textV = embed . arr (\n -> case n of TextValue t -> [t]; _ -> [])
numV :: ArrowF [] (~>) => Value ~> Number
numV = embed . arr (\n -> case n of NumValue m -> [m]; _ -> [])
reindex :: ArrowF [] (~>) => (a ~> Value) -> a ~> Result
reindex ar = embed . arr (\xs -> zip [1..] xs) . observe ar
-------------------------------------------------------------------------------
evaluate :: Text -> Node -> [Node]
evaluate path = runListArrow (unZ . nodeV . run path . arr NodeValue . mkZ)
run :: (ArrowF [] (~>), ArrowChoice (~>), ArrowPlus (~>)) => Text -> Value ~> Value
run path =
case parser path of
Left e -> error (show e)
Right (XPath e) -> arr snd . expression e . (const 1 &&& id)
locationPath :: (ArrowF [] (~>), ArrowChoice (~>), ArrowPlus (~>)) => LocationPath -> Z Node ~> Value
locationPath path =
case path of
Relative xs -> steps xs
Absolute xs -> steps xs . root
steps :: (ArrowF [] (~>), ArrowChoice (~>), ArrowPlus (~>)) => [Step] -> Z Node ~> Value
steps xs = foldr (\s b -> step s (nodeV . b)) (arr NodeValue) (reverse xs)
step :: (ArrowF [] (~>), ArrowChoice (~>), ArrowPlus (~>)) => Step -> (Z Node ~> Z Node) -> Z Node ~> Value
step (Step axis test exprs) prev
= foldr (\e b -> arr snd . filterA (expression e) . reindex b)
(filterA (nodeTest test) . axisSpecifier axis . prev)
(reverse exprs)
nodeTest :: (ArrowF [] (~>), ArrowPlus (~>), ArrowChoice (~>)) => NodeTest -> Value ~> Value
nodeTest (NameTest t) = filterA (nameTest t . name . nodeV)
<+> filterA (nameTest t . key . attrV)
nodeTest (NodeType t) = filterA (nodeType t . nodeV)
nodeTest (PiTest _) = none
nameTest :: ArrowF [] (~>) => NameTest -> Z Text ~> Z Text
nameTest Star = id
nameTest (NsStar ns) = isA ((== ns) . T.takeWhile (/= ':') . focus)
nameTest (QName ns) = isA ((== ns) . focus)
axisSpecifier :: (ArrowF [] (~>), ArrowPlus (~>)) => AxisSpecifier -> Z Node ~> Value
axisSpecifier (NamedAxis axis) = axisName axis
nodeType :: ArrowF [] (~>) => NodeType -> Z Node ~> Z Node
nodeType Comment = isComment
nodeType Text = isText
nodeType ProcessingInstruction = none
nodeType Node = id
axisName :: (ArrowF [] (~>), ArrowPlus (~>)) => AxisName -> Z Node ~> Value
axisName Ancestor = arr NodeValue . ancestors
axisName AncestorOrSelf = arr NodeValue . (ancestors <+> id)
axisName Attribute = arr AttrValue . attributes
axisName Child = arr NodeValue . children
axisName Descendant = arr NodeValue . deep id . children
axisName DescendantOrSelf = arr NodeValue . deep id
axisName FollowingSibling = arr NodeValue . rights
axisName Parent = arr NodeValue . parent
axisName PrecedingSibling = arr NodeValue . lefts
axisName Self = arr NodeValue . id
-- axisName Preceding = arr NodeValue
-- axisName Following = arr NodeValue
-- axisName Namespace = none
expression :: (ArrowF [] (~>), ArrowChoice (~>), ArrowPlus (~>)) => Expr -> Result ~> Result
expression expr = reindex (go expr)
where go :: (ArrowF [] (~>), ArrowChoice (~>), ArrowPlus (~>)) => Expr -> Result ~> Value
go ( Is a b ) = arr fst . isA (uncurry (==)) . (go a &&& go b)
go ( IsNot a b ) = arr fst . isA (uncurry (/=)) . (go a &&& go b)
go ( Lt a b ) = arr fst . isA (uncurry (< )) . (go a &&& go b)
go ( Gt a b ) = arr fst . isA (uncurry (> )) . (go a &&& go b)
go ( Lte a b ) = arr fst . isA (uncurry (<=)) . (go a &&& go b)
go ( Gte a b ) = arr fst . isA (uncurry (>=)) . (go a &&& go b)
go ( Add a b ) = arr (uncurry (+)) . (go a &&& go b)
go ( Sub a b ) = arr (uncurry (-)) . (go a &&& go b)
go ( Mul a b ) = arr (uncurry (*)) . (go a &&& go b)
go ( Div a b ) = arr (uncurry (/)) . (go a &&& go b)
go ( Or a b ) = go a <+> go b
go ( And a b ) = arr fst . (go a &&& go b)
go ( Literal t ) = arr TextValue . const t
go ( Path p ) = locationPath p . nodeV . arr snd
go ( Filter e p ) = arr snd . filterA (go p) . expression e
go ( FunctionCall n as ) = fun n as
go ( Number n ) = const (NumValue n)
fun :: ArrowF [] (~>) => Text -> [Expr] -> (Integer, Value) ~> Value
fun "position" _ = arr (NumValue . fromIntegral . fst)
fun nm _ = error $ "function " ++ T.unpack nm ++ " not implemented."
stringValue :: Value -> Text
stringValue (NodeValue a) = nodeText (focus a)
stringValue (TextValue a) = a
stringValue (AttrValue a) = snd (focus a)
stringValue (NumValue a) = T.pack (show a)
| silkapp/xmlhtml-xpath | src/Xml/XPath/Evaluator.hs | bsd-3-clause | 6,398 | 0 | 12 | 1,770 | 2,818 | 1,450 | 1,368 | 124 | 18 |
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE CPP #-}
{-# OPTIONS_GHC -fspec-constr-count=5 #-}
-- | Module used for JPEG file loading and writing.
module Codec.Picture.Jpg( decodeJpeg
, decodeJpegWithMetadata
, encodeJpegAtQuality
, encodeJpegAtQualityWithMetadata
, encodeDirectJpegAtQualityWithMetadata
, encodeJpeg
, JpgEncodable
) where
#if !MIN_VERSION_base(4,8,0)
import Data.Foldable( foldMap )
import Data.Monoid( mempty )
import Control.Applicative( pure, (<$>) )
#endif
import Control.Applicative( (<|>) )
import Control.Arrow( (>>>) )
import Control.Monad( when, forM_ )
import Control.Monad.ST( ST, runST )
import Control.Monad.Trans( lift )
import Control.Monad.Trans.RWS.Strict( RWS, modify, tell, gets, execRWS )
import Data.Bits( (.|.), unsafeShiftL )
import Data.Monoid( (<>) )
import Data.Int( Int16, Int32 )
import Data.Word(Word8, Word32)
import Data.Binary( Binary(..), encode )
import Data.STRef( newSTRef, writeSTRef, readSTRef )
import Data.Vector( (//) )
import Data.Vector.Unboxed( (!) )
import qualified Data.Vector as V
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Storable as VS
import qualified Data.Vector.Storable.Mutable as M
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as L
import Codec.Picture.InternalHelper
import Codec.Picture.BitWriter
import Codec.Picture.Types
import Codec.Picture.Metadata( Metadatas
, SourceFormat( SourceJpeg )
, basicMetadata )
import Codec.Picture.Tiff.Types
import Codec.Picture.Tiff.Metadata
import Codec.Picture.Jpg.Types
import Codec.Picture.Jpg.Common
import Codec.Picture.Jpg.Progressive
import Codec.Picture.Jpg.DefaultTable
import Codec.Picture.Jpg.FastDct
import Codec.Picture.Jpg.Metadata
quantize :: MacroBlock Int16 -> MutableMacroBlock s Int32
-> ST s (MutableMacroBlock s Int32)
quantize table block = update 0
where update 64 = return block
update idx = do
val <- block `M.unsafeRead` idx
let q = fromIntegral (table `VS.unsafeIndex` idx)
finalValue = (val + (q `div` 2)) `quot` q -- rounded integer division
(block `M.unsafeWrite` idx) finalValue
update $ idx + 1
powerOf :: Int32 -> Word32
powerOf 0 = 0
powerOf n = limit 1 0
where val = abs n
limit range i | val < range = i
limit range i = limit (2 * range) (i + 1)
encodeInt :: BoolWriteStateRef s -> Word32 -> Int32 -> ST s ()
{-# INLINE encodeInt #-}
encodeInt st ssss n | n > 0 = writeBits' st (fromIntegral n) (fromIntegral ssss)
encodeInt st ssss n = writeBits' st (fromIntegral $ n - 1) (fromIntegral ssss)
-- | Assume the macro block is initialized with zeroes
acCoefficientsDecode :: HuffmanPackedTree -> MutableMacroBlock s Int16
-> BoolReader s (MutableMacroBlock s Int16)
acCoefficientsDecode acTree mutableBlock = parseAcCoefficient 1 >> return mutableBlock
where parseAcCoefficient n | n >= 64 = return ()
| otherwise = do
rrrrssss <- decodeRrrrSsss acTree
case rrrrssss of
( 0, 0) -> return ()
(0xF, 0) -> parseAcCoefficient (n + 16)
(rrrr, ssss) -> do
decoded <- fromIntegral <$> decodeInt ssss
lift $ (mutableBlock `M.unsafeWrite` (n + rrrr)) decoded
parseAcCoefficient (n + rrrr + 1)
-- | Decompress a macroblock from a bitstream given the current configuration
-- from the frame.
decompressMacroBlock :: HuffmanPackedTree -- ^ Tree used for DC coefficient
-> HuffmanPackedTree -- ^ Tree used for Ac coefficient
-> MacroBlock Int16 -- ^ Current quantization table
-> MutableMacroBlock s Int16 -- ^ A zigzag table, to avoid allocation
-> DcCoefficient -- ^ Previous dc value
-> BoolReader s (DcCoefficient, MutableMacroBlock s Int16)
decompressMacroBlock dcTree acTree quantizationTable zigzagBlock previousDc = do
dcDeltaCoefficient <- dcCoefficientDecode dcTree
block <- lift createEmptyMutableMacroBlock
let neoDcCoefficient = previousDc + dcDeltaCoefficient
lift $ (block `M.unsafeWrite` 0) neoDcCoefficient
fullBlock <- acCoefficientsDecode acTree block
decodedBlock <- lift $ decodeMacroBlock quantizationTable zigzagBlock fullBlock
return (neoDcCoefficient, decodedBlock)
pixelClamp :: Int16 -> Word8
pixelClamp n = fromIntegral . min 255 $ max 0 n
unpack444Y :: Int -- ^ component index
-> Int -- ^ x
-> Int -- ^ y
-> MutableImage s PixelYCbCr8
-> MutableMacroBlock s Int16
-> ST s ()
unpack444Y _ x y (MutableImage { mutableImageWidth = imgWidth, mutableImageData = img })
block = blockVert baseIdx 0 zero
where zero = 0 :: Int
baseIdx = x * dctBlockSize + y * dctBlockSize * imgWidth
blockVert _ _ j | j >= dctBlockSize = return ()
blockVert writeIdx readingIdx j = blockHoriz writeIdx readingIdx zero
where blockHoriz _ readIdx i | i >= dctBlockSize = blockVert (writeIdx + imgWidth) readIdx $ j + 1
blockHoriz idx readIdx i = do
val <- pixelClamp <$> (block `M.unsafeRead` readIdx)
(img `M.unsafeWrite` idx) val
blockHoriz (idx + 1) (readIdx + 1) $ i + 1
unpack444Ycbcr :: Int -- ^ Component index
-> Int -- ^ x
-> Int -- ^ y
-> MutableImage s PixelYCbCr8
-> MutableMacroBlock s Int16
-> ST s ()
unpack444Ycbcr compIdx x y
(MutableImage { mutableImageWidth = imgWidth, mutableImageData = img })
block = blockVert baseIdx 0 zero
where zero = 0 :: Int
baseIdx = (x * dctBlockSize + y * dctBlockSize * imgWidth) * 3 + compIdx
blockVert _ _ j | j >= dctBlockSize = return ()
blockVert idx readIdx j = do
val0 <- pixelClamp <$> (block `M.unsafeRead` readIdx)
val1 <- pixelClamp <$> (block `M.unsafeRead` (readIdx + 1))
val2 <- pixelClamp <$> (block `M.unsafeRead` (readIdx + 2))
val3 <- pixelClamp <$> (block `M.unsafeRead` (readIdx + 3))
val4 <- pixelClamp <$> (block `M.unsafeRead` (readIdx + 4))
val5 <- pixelClamp <$> (block `M.unsafeRead` (readIdx + 5))
val6 <- pixelClamp <$> (block `M.unsafeRead` (readIdx + 6))
val7 <- pixelClamp <$> (block `M.unsafeRead` (readIdx + 7))
(img `M.unsafeWrite` idx) val0
(img `M.unsafeWrite` (idx + 3 )) val1
(img `M.unsafeWrite` (idx + (3 * 2))) val2
(img `M.unsafeWrite` (idx + (3 * 3))) val3
(img `M.unsafeWrite` (idx + (3 * 4))) val4
(img `M.unsafeWrite` (idx + (3 * 5))) val5
(img `M.unsafeWrite` (idx + (3 * 6))) val6
(img `M.unsafeWrite` (idx + (3 * 7))) val7
blockVert (idx + 3 * imgWidth) (readIdx + dctBlockSize) $ j + 1
{-where blockHoriz _ readIdx i | i >= 8 = blockVert (writeIdx + imgWidth * 3) readIdx $ j + 1-}
{-blockHoriz idx readIdx i = do-}
{-val <- pixelClamp <$> (block `M.unsafeRead` readIdx) -}
{-(img `M.unsafeWrite` idx) val-}
{-blockHoriz (idx + 3) (readIdx + 1) $ i + 1-}
unpack421Ycbcr :: Int -- ^ Component index
-> Int -- ^ x
-> Int -- ^ y
-> MutableImage s PixelYCbCr8
-> MutableMacroBlock s Int16
-> ST s ()
unpack421Ycbcr compIdx x y
(MutableImage { mutableImageWidth = imgWidth,
mutableImageHeight = _, mutableImageData = img })
block = blockVert baseIdx 0 zero
where zero = 0 :: Int
baseIdx = (x * dctBlockSize + y * dctBlockSize * imgWidth) * 3 + compIdx
lineOffset = imgWidth * 3
blockVert _ _ j | j >= dctBlockSize = return ()
blockVert idx readIdx j = do
v0 <- pixelClamp <$> (block `M.unsafeRead` readIdx)
v1 <- pixelClamp <$> (block `M.unsafeRead` (readIdx + 1))
v2 <- pixelClamp <$> (block `M.unsafeRead` (readIdx + 2))
v3 <- pixelClamp <$> (block `M.unsafeRead` (readIdx + 3))
v4 <- pixelClamp <$> (block `M.unsafeRead` (readIdx + 4))
v5 <- pixelClamp <$> (block `M.unsafeRead` (readIdx + 5))
v6 <- pixelClamp <$> (block `M.unsafeRead` (readIdx + 6))
v7 <- pixelClamp <$> (block `M.unsafeRead` (readIdx + 7))
(img `M.unsafeWrite` idx) v0
(img `M.unsafeWrite` (idx + 3)) v0
(img `M.unsafeWrite` (idx + 6 )) v1
(img `M.unsafeWrite` (idx + 6 + 3)) v1
(img `M.unsafeWrite` (idx + 6 * 2)) v2
(img `M.unsafeWrite` (idx + 6 * 2 + 3)) v2
(img `M.unsafeWrite` (idx + 6 * 3)) v3
(img `M.unsafeWrite` (idx + 6 * 3 + 3)) v3
(img `M.unsafeWrite` (idx + 6 * 4)) v4
(img `M.unsafeWrite` (idx + 6 * 4 + 3)) v4
(img `M.unsafeWrite` (idx + 6 * 5)) v5
(img `M.unsafeWrite` (idx + 6 * 5 + 3)) v5
(img `M.unsafeWrite` (idx + 6 * 6)) v6
(img `M.unsafeWrite` (idx + 6 * 6 + 3)) v6
(img `M.unsafeWrite` (idx + 6 * 7)) v7
(img `M.unsafeWrite` (idx + 6 * 7 + 3)) v7
blockVert (idx + lineOffset) (readIdx + dctBlockSize) $ j + 1
type Unpacker s = Int -- ^ component index
-> Int -- ^ x
-> Int -- ^ y
-> MutableImage s PixelYCbCr8
-> MutableMacroBlock s Int16
-> ST s ()
type JpgScripter s a =
RWS () [([(JpgUnpackerParameter, Unpacker s)], L.ByteString)] JpgDecoderState a
data JpgDecoderState = JpgDecoderState
{ dcDecoderTables :: !(V.Vector HuffmanPackedTree)
, acDecoderTables :: !(V.Vector HuffmanPackedTree)
, quantizationMatrices :: !(V.Vector (MacroBlock Int16))
, currentRestartInterv :: !Int
, currentFrame :: Maybe JpgFrameHeader
, app14Marker :: !(Maybe JpgAdobeApp14)
, app0JFifMarker :: !(Maybe JpgJFIFApp0)
, app1ExifMarker :: !(Maybe [ImageFileDirectory])
, componentIndexMapping :: ![(Word8, Int)]
, isProgressive :: !Bool
, maximumHorizontalResolution :: !Int
, maximumVerticalResolution :: !Int
, seenBlobs :: !Int
}
emptyDecoderState :: JpgDecoderState
emptyDecoderState = JpgDecoderState
{ dcDecoderTables =
let (_, dcLuma) = prepareHuffmanTable DcComponent 0 defaultDcLumaHuffmanTable
(_, dcChroma) = prepareHuffmanTable DcComponent 1 defaultDcChromaHuffmanTable
in
V.fromList [ dcLuma, dcChroma, dcLuma, dcChroma ]
, acDecoderTables =
let (_, acLuma) = prepareHuffmanTable AcComponent 0 defaultAcLumaHuffmanTable
(_, acChroma) = prepareHuffmanTable AcComponent 1 defaultAcChromaHuffmanTable
in
V.fromList [acLuma, acChroma, acLuma, acChroma]
, quantizationMatrices = V.replicate 4 (VS.replicate (8 * 8) 1)
, currentRestartInterv = -1
, currentFrame = Nothing
, componentIndexMapping = []
, app14Marker = Nothing
, app0JFifMarker = Nothing
, app1ExifMarker = Nothing
, isProgressive = False
, maximumHorizontalResolution = 0
, maximumVerticalResolution = 0
, seenBlobs = 0
}
-- | This pseudo interpreter interpret the Jpg frame for the huffman,
-- quant table and restart interval parameters.
jpgMachineStep :: JpgFrame -> JpgScripter s ()
jpgMachineStep (JpgAdobeAPP14 app14) = modify $ \s ->
s { app14Marker = Just app14 }
jpgMachineStep (JpgExif exif) = modify $ \s ->
s { app1ExifMarker = Just exif }
jpgMachineStep (JpgJFIF app0) = modify $ \s ->
s { app0JFifMarker = Just app0 }
jpgMachineStep (JpgAppFrame _ _) = pure ()
jpgMachineStep (JpgExtension _ _) = pure ()
jpgMachineStep (JpgScanBlob hdr raw_data) = do
let scanCount = length $ scans hdr
params <- concat <$> mapM (scanSpecifier scanCount) (scans hdr)
modify $ \st -> st { seenBlobs = seenBlobs st + 1 }
tell [(params, raw_data) ]
where (selectionLow, selectionHigh) = spectralSelection hdr
approxHigh = fromIntegral $ successiveApproxHigh hdr
approxLow = fromIntegral $ successiveApproxLow hdr
scanSpecifier scanCount scanSpec = do
compMapping <- gets componentIndexMapping
comp <- case lookup (componentSelector scanSpec) compMapping of
Nothing -> fail "Jpg decoding error - bad component selector in blob."
Just v -> return v
let maximumHuffmanTable = 4
dcIndex = min (maximumHuffmanTable - 1)
. fromIntegral $ dcEntropyCodingTable scanSpec
acIndex = min (maximumHuffmanTable - 1)
. fromIntegral $ acEntropyCodingTable scanSpec
dcTree <- gets $ (V.! dcIndex) . dcDecoderTables
acTree <- gets $ (V.! acIndex) . acDecoderTables
isProgressiveImage <- gets isProgressive
maxiW <- gets maximumHorizontalResolution
maxiH <- gets maximumVerticalResolution
restart <- gets currentRestartInterv
frameInfo <- gets currentFrame
blobId <- gets seenBlobs
case frameInfo of
Nothing -> fail "Jpg decoding error - no previous frame"
Just v -> do
let compDesc = jpgComponents v !! comp
compCount = length $ jpgComponents v
xSampling = fromIntegral $ horizontalSamplingFactor compDesc
ySampling = fromIntegral $ verticalSamplingFactor compDesc
componentSubSampling =
(maxiW - xSampling + 1, maxiH - ySampling + 1)
(xCount, yCount)
| scanCount > 1 || isProgressiveImage = (xSampling, ySampling)
| otherwise = (1, 1)
pure [ (JpgUnpackerParameter
{ dcHuffmanTree = dcTree
, acHuffmanTree = acTree
, componentIndex = comp
, restartInterval = fromIntegral restart
, componentWidth = xSampling
, componentHeight = ySampling
, subSampling = componentSubSampling
, successiveApprox = (approxLow, approxHigh)
, readerIndex = blobId
, indiceVector =
if scanCount == 1 then 0 else 1
, coefficientRange =
( fromIntegral selectionLow
, fromIntegral selectionHigh )
, blockIndex = y * ySampling + x
, blockMcuX = x
, blockMcuY = y
}, unpackerDecision compCount componentSubSampling)
| y <- [0 .. yCount - 1]
, x <- [0 .. xCount - 1] ]
jpgMachineStep (JpgScans kind hdr) = modify $ \s ->
s { currentFrame = Just hdr
, componentIndexMapping =
[(componentIdentifier comp, ix) | (ix, comp) <- zip [0..] $ jpgComponents hdr]
, isProgressive = case kind of
JpgProgressiveDCTHuffman -> True
_ -> False
, maximumHorizontalResolution =
fromIntegral $ maximum horizontalResolutions
, maximumVerticalResolution =
fromIntegral $ maximum verticalResolutions
}
where components = jpgComponents hdr
horizontalResolutions = map horizontalSamplingFactor components
verticalResolutions = map verticalSamplingFactor components
jpgMachineStep (JpgIntervalRestart restart) =
modify $ \s -> s { currentRestartInterv = fromIntegral restart }
jpgMachineStep (JpgHuffmanTable tables) = mapM_ placeHuffmanTrees tables
where placeHuffmanTrees (spec, tree) = case huffmanTableClass spec of
DcComponent -> modify $ \s ->
if idx >= V.length (dcDecoderTables s) then s
else
let neu = dcDecoderTables s // [(idx, tree)] in
s { dcDecoderTables = neu }
where idx = fromIntegral $ huffmanTableDest spec
AcComponent -> modify $ \s ->
if idx >= V.length (acDecoderTables s) then s
else
s { acDecoderTables = acDecoderTables s // [(idx, tree)] }
where idx = fromIntegral $ huffmanTableDest spec
jpgMachineStep (JpgQuantTable tables) = mapM_ placeQuantizationTables tables
where placeQuantizationTables table = do
let idx = fromIntegral $ quantDestination table
tableData = quantTable table
modify $ \s ->
s { quantizationMatrices = quantizationMatrices s // [(idx, tableData)] }
unpackerDecision :: Int -> (Int, Int) -> Unpacker s
unpackerDecision 1 (1, 1) = unpack444Y
unpackerDecision 3 (1, 1) = unpack444Ycbcr
unpackerDecision _ (2, 1) = unpack421Ycbcr
unpackerDecision compCount (xScalingFactor, yScalingFactor) =
unpackMacroBlock compCount xScalingFactor yScalingFactor
decodeImage :: JpgFrameHeader
-> V.Vector (MacroBlock Int16)
-> [([(JpgUnpackerParameter, Unpacker s)], L.ByteString)]
-> MutableImage s PixelYCbCr8 -- ^ Result image to write into
-> ST s (MutableImage s PixelYCbCr8)
decodeImage frame quants lst outImage = do
let compCount = length $ jpgComponents frame
zigZagArray <- createEmptyMutableMacroBlock
dcArray <- M.replicate compCount 0 :: ST s (M.STVector s DcCoefficient)
resetCounter <- newSTRef restartIntervalValue
forM_ lst $ \(params, str) -> do
let componentsInfo = V.fromList params
compReader = initBoolStateJpg . B.concat $ L.toChunks str
maxiW = maximum [fst $ subSampling c | (c,_) <- params]
maxiH = maximum [snd $ subSampling c | (c,_) <- params]
imageBlockWidth = (imgWidth + 7) `div` 8
imageBlockHeight = (imgHeight + 7) `div` 8
imageMcuWidth = (imageBlockWidth + (maxiW - 1)) `div` maxiW
imageMcuHeight = (imageBlockHeight + (maxiH - 1)) `div` maxiH
execBoolReader compReader $ rasterMap imageMcuWidth imageMcuHeight $ \x y -> do
resetLeft <- lift $ readSTRef resetCounter
if resetLeft == 0 then do
lift $ M.set dcArray 0
byteAlignJpg
_restartCode <- decodeRestartInterval
lift $ resetCounter `writeSTRef` (restartIntervalValue - 1)
else
lift $ resetCounter `writeSTRef` (resetLeft - 1)
V.forM_ componentsInfo $ \(comp, unpack) -> do
let compIdx = componentIndex comp
dcTree = dcHuffmanTree comp
acTree = acHuffmanTree comp
quantId = fromIntegral . quantizationTableDest
$ jpgComponents frame !! compIdx
qTable = quants V.! min 3 quantId
xd = blockMcuX comp
yd = blockMcuY comp
(subX, subY) = subSampling comp
dc <- lift $ dcArray `M.unsafeRead` compIdx
(dcCoeff, block) <-
decompressMacroBlock dcTree acTree qTable zigZagArray $ fromIntegral dc
lift $ (dcArray `M.unsafeWrite` compIdx) dcCoeff
let verticalLimited = y == imageMcuHeight - 1
if (x == imageMcuWidth - 1) || verticalLimited then
lift $ unpackMacroBlock imgComponentCount
subX subY compIdx
(x * maxiW + xd) (y * maxiH + yd) outImage block
else
lift $ unpack compIdx (x * maxiW + xd) (y * maxiH + yd) outImage block
return outImage
where imgComponentCount = length $ jpgComponents frame
imgWidth = fromIntegral $ jpgWidth frame
imgHeight = fromIntegral $ jpgHeight frame
restartIntervalValue = case lst of
((p,_):_,_): _ -> restartInterval p
_ -> -1
gatherImageKind :: [JpgFrame] -> Maybe JpgImageKind
gatherImageKind lst = case [k | JpgScans k _ <- lst, isDctSpecifier k] of
[JpgBaselineDCTHuffman] -> Just BaseLineDCT
[JpgProgressiveDCTHuffman] -> Just ProgressiveDCT
_ -> Nothing
where isDctSpecifier JpgProgressiveDCTHuffman = True
isDctSpecifier JpgBaselineDCTHuffman = True
isDctSpecifier _ = False
gatherScanInfo :: JpgImage -> (JpgFrameKind, JpgFrameHeader)
gatherScanInfo img = head [(a, b) | JpgScans a b <- jpgFrame img]
dynamicOfColorSpace :: (Monad m)
=> Maybe JpgColorSpace -> Int -> Int -> VS.Vector Word8
-> m DynamicImage
dynamicOfColorSpace Nothing _ _ _ = fail "Unknown color space"
dynamicOfColorSpace (Just color) w h imgData = case color of
JpgColorSpaceCMYK -> return . ImageCMYK8 $ Image w h imgData
JpgColorSpaceYCCK ->
let ymg = Image w h $ VS.map (255-) imgData :: Image PixelYCbCrK8 in
return . ImageCMYK8 $ convertImage ymg
JpgColorSpaceYCbCr -> return . ImageYCbCr8 $ Image w h imgData
JpgColorSpaceRGB -> return . ImageRGB8 $ Image w h imgData
JpgColorSpaceYA -> return . ImageYA8 $ Image w h imgData
JpgColorSpaceY -> return . ImageY8 $ Image w h imgData
colorSpace -> fail $ "Wrong color space : " ++ show colorSpace
colorSpaceOfAdobe :: Int -> JpgAdobeApp14 -> Maybe JpgColorSpace
colorSpaceOfAdobe compCount app = case (compCount, _adobeTransform app) of
(3, AdobeYCbCr) -> pure JpgColorSpaceYCbCr
(1, AdobeUnknown) -> pure JpgColorSpaceY
(3, AdobeUnknown) -> pure JpgColorSpaceRGB
(4, AdobeYCck) -> pure JpgColorSpaceYCCK
{-(4, AdobeUnknown) -> pure JpgColorSpaceCMYKInverted-}
_ -> Nothing
colorSpaceOfState :: JpgDecoderState -> Maybe JpgColorSpace
colorSpaceOfState st = do
hdr <- currentFrame st
let compStr = [toEnum . fromEnum $ componentIdentifier comp
| comp <- jpgComponents hdr]
app14 = do
marker <- app14Marker st
colorSpaceOfAdobe (length compStr) marker
app14 <|> colorSpaceOfComponentStr compStr
colorSpaceOfComponentStr :: String -> Maybe JpgColorSpace
colorSpaceOfComponentStr s = case s of
[_] -> pure JpgColorSpaceY
[_,_] -> pure JpgColorSpaceYA
"\0\1\2" -> pure JpgColorSpaceYCbCr
"\1\2\3" -> pure JpgColorSpaceYCbCr
"RGB" -> pure JpgColorSpaceRGB
"YCc" -> pure JpgColorSpaceYCC
[_,_,_] -> pure JpgColorSpaceYCbCr
"RGBA" -> pure JpgColorSpaceRGBA
"YCcA" -> pure JpgColorSpaceYCCA
"CMYK" -> pure JpgColorSpaceCMYK
"YCcK" -> pure JpgColorSpaceYCCK
[_,_,_,_] -> pure JpgColorSpaceCMYK
_ -> Nothing
-- | Try to decompress a jpeg file and decompress. The colorspace is still
-- YCbCr if you want to perform computation on the luma part. You can
-- convert it to RGB using 'convertImage' from the 'ColorSpaceConvertible'
-- typeclass.
--
-- This function can output the following pixel types :
--
-- * PixelY8
--
-- * PixelYA8
--
-- * PixelRGB8
--
-- * PixelCMYK8
--
-- * PixelYCbCr8
--
decodeJpeg :: B.ByteString -> Either String DynamicImage
decodeJpeg = fmap fst . decodeJpegWithMetadata
-- | Equivalent to 'decodeJpeg' but also extracts metadatas.
--
-- Extract the following metadatas from the JFIF bloc:
--
-- * DpiX
--
-- * DpiY
--
-- Exif metadata are also extracted if present.
--
decodeJpegWithMetadata :: B.ByteString -> Either String (DynamicImage, Metadatas)
decodeJpegWithMetadata file = case runGetStrict get file of
Left err -> Left err
Right img -> case imgKind of
Just BaseLineDCT ->
let (st, arr) = decodeBaseline
jfifMeta = foldMap extractMetadatas $ app0JFifMarker st
exifMeta = foldMap extractTiffMetadata $ app1ExifMarker st
meta = sizeMeta <> jfifMeta <> exifMeta
in
(, meta) <$>
dynamicOfColorSpace (colorSpaceOfState st) imgWidth imgHeight arr
Just ProgressiveDCT ->
let (st, arr) = decodeProgressive
jfifMeta = foldMap extractMetadatas $ app0JFifMarker st
exifMeta = foldMap extractTiffMetadata $ app1ExifMarker st
meta = sizeMeta <> jfifMeta <> exifMeta
in
(, meta) <$>
dynamicOfColorSpace (colorSpaceOfState st) imgWidth imgHeight arr
_ -> Left "Unknown JPG kind"
where
compCount = length $ jpgComponents scanInfo
(_,scanInfo) = gatherScanInfo img
imgKind = gatherImageKind $ jpgFrame img
imgWidth = fromIntegral $ jpgWidth scanInfo
imgHeight = fromIntegral $ jpgHeight scanInfo
sizeMeta = basicMetadata SourceJpeg imgWidth imgHeight
imageSize = imgWidth * imgHeight * compCount
decodeProgressive = runST $ do
let (st, wrotten) =
execRWS (mapM_ jpgMachineStep (jpgFrame img)) () emptyDecoderState
Just fHdr = currentFrame st
fimg <-
progressiveUnpack
(maximumHorizontalResolution st, maximumVerticalResolution st)
fHdr
(quantizationMatrices st)
wrotten
frozen <- unsafeFreezeImage fimg
return (st, imageData frozen)
decodeBaseline = runST $ do
let (st, wrotten) =
execRWS (mapM_ jpgMachineStep (jpgFrame img)) () emptyDecoderState
Just fHdr = currentFrame st
resultImage <- M.new imageSize
let wrapped = MutableImage imgWidth imgHeight resultImage
fImg <- decodeImage
fHdr
(quantizationMatrices st)
wrotten
wrapped
frozen <- unsafeFreezeImage fImg
return (st, imageData frozen)
extractBlock :: forall s px. (PixelBaseComponent px ~ Word8)
=> Image px -- ^ Source image
-> MutableMacroBlock s Int16 -- ^ Mutable block where to put extracted block
-> Int -- ^ Plane
-> Int -- ^ X sampling factor
-> Int -- ^ Y sampling factor
-> Int -- ^ Sample per pixel
-> Int -- ^ Block x
-> Int -- ^ Block y
-> ST s (MutableMacroBlock s Int16)
extractBlock (Image { imageWidth = w, imageHeight = h, imageData = src })
block 1 1 sampCount plane bx by | (bx * dctBlockSize) + 7 < w && (by * 8) + 7 < h = do
let baseReadIdx = (by * dctBlockSize * w) + bx * dctBlockSize
sequence_ [(block `M.unsafeWrite` (y * dctBlockSize + x)) val
| y <- [0 .. dctBlockSize - 1]
, let blockReadIdx = baseReadIdx + y * w
, x <- [0 .. dctBlockSize - 1]
, let val = fromIntegral $ src `VS.unsafeIndex` ((blockReadIdx + x) * sampCount + plane)
]
return block
extractBlock (Image { imageWidth = w, imageHeight = h, imageData = src })
block sampWidth sampHeight sampCount plane bx by = do
let accessPixel x y | x < w && y < h = let idx = (y * w + x) * sampCount + plane in src `VS.unsafeIndex` idx
| x >= w = accessPixel (w - 1) y
| otherwise = accessPixel x (h - 1)
pixelPerCoeff = fromIntegral $ sampWidth * sampHeight
blockVal x y = sum [fromIntegral $ accessPixel (xBase + dx) (yBase + dy)
| dy <- [0 .. sampHeight - 1]
, dx <- [0 .. sampWidth - 1] ] `div` pixelPerCoeff
where xBase = blockXBegin + x * sampWidth
yBase = blockYBegin + y * sampHeight
blockXBegin = bx * dctBlockSize * sampWidth
blockYBegin = by * dctBlockSize * sampHeight
sequence_ [(block `M.unsafeWrite` (y * dctBlockSize + x)) $ blockVal x y | y <- [0 .. 7], x <- [0 .. 7] ]
return block
serializeMacroBlock :: BoolWriteStateRef s
-> HuffmanWriterCode -> HuffmanWriterCode
-> MutableMacroBlock s Int32
-> ST s ()
serializeMacroBlock !st !dcCode !acCode !blk =
(blk `M.unsafeRead` 0) >>= (fromIntegral >>> encodeDc) >> writeAcs (0, 1) >> return ()
where writeAcs acc@(_, 63) =
(blk `M.unsafeRead` 63) >>= (fromIntegral >>> encodeAcCoefs acc) >> return ()
writeAcs acc@(_, i ) =
(blk `M.unsafeRead` i) >>= (fromIntegral >>> encodeAcCoefs acc) >>= writeAcs
encodeDc n = writeBits' st (fromIntegral code) (fromIntegral bitCount)
>> when (ssss /= 0) (encodeInt st ssss n)
where ssss = powerOf $ fromIntegral n
(bitCount, code) = dcCode `V.unsafeIndex` fromIntegral ssss
encodeAc 0 0 = writeBits' st (fromIntegral code) $ fromIntegral bitCount
where (bitCount, code) = acCode `V.unsafeIndex` 0
encodeAc zeroCount n | zeroCount >= 16 =
writeBits' st (fromIntegral code) (fromIntegral bitCount) >> encodeAc (zeroCount - 16) n
where (bitCount, code) = acCode `V.unsafeIndex` 0xF0
encodeAc zeroCount n =
writeBits' st (fromIntegral code) (fromIntegral bitCount) >> encodeInt st ssss n
where rrrr = zeroCount `unsafeShiftL` 4
ssss = powerOf $ fromIntegral n
rrrrssss = rrrr .|. ssss
(bitCount, code) = acCode `V.unsafeIndex` fromIntegral rrrrssss
encodeAcCoefs ( _, 63) 0 = encodeAc 0 0 >> return (0, 64)
encodeAcCoefs (zeroRunLength, i) 0 = return (zeroRunLength + 1, i + 1)
encodeAcCoefs (zeroRunLength, i) n =
encodeAc zeroRunLength n >> return (0, i + 1)
encodeMacroBlock :: QuantificationTable
-> MutableMacroBlock s Int32
-> MutableMacroBlock s Int32
-> Int16
-> MutableMacroBlock s Int16
-> ST s (Int32, MutableMacroBlock s Int32)
encodeMacroBlock quantTableOfComponent workData finalData prev_dc block = do
-- the inverse level shift is performed internally by the fastDCT routine
blk <- fastDctLibJpeg workData block
>>= zigZagReorderForward finalData
>>= quantize quantTableOfComponent
dc <- blk `M.unsafeRead` 0
(blk `M.unsafeWrite` 0) $ dc - fromIntegral prev_dc
return (dc, blk)
divUpward :: (Integral a) => a -> a -> a
divUpward n dividor = val + (if rest /= 0 then 1 else 0)
where (val, rest) = n `divMod` dividor
prepareHuffmanTable :: DctComponent -> Word8 -> HuffmanTable
-> (JpgHuffmanTableSpec, HuffmanPackedTree)
prepareHuffmanTable classVal dest tableDef =
(JpgHuffmanTableSpec { huffmanTableClass = classVal
, huffmanTableDest = dest
, huffSizes = sizes
, huffCodes = V.fromListN 16
[VU.fromListN (fromIntegral $ sizes ! i) lst
| (i, lst) <- zip [0..] tableDef ]
}, VS.singleton 0)
where sizes = VU.fromListN 16 $ map (fromIntegral . length) tableDef
-- | Encode an image in jpeg at a reasonnable quality level.
-- If you want better quality or reduced file size, you should
-- use `encodeJpegAtQuality`
encodeJpeg :: Image PixelYCbCr8 -> L.ByteString
encodeJpeg = encodeJpegAtQuality 50
defaultHuffmanTables :: [(JpgHuffmanTableSpec, HuffmanPackedTree)]
defaultHuffmanTables =
[ prepareHuffmanTable DcComponent 0 defaultDcLumaHuffmanTable
, prepareHuffmanTable AcComponent 0 defaultAcLumaHuffmanTable
, prepareHuffmanTable DcComponent 1 defaultDcChromaHuffmanTable
, prepareHuffmanTable AcComponent 1 defaultAcChromaHuffmanTable
]
lumaQuantTableAtQuality :: Int -> QuantificationTable
lumaQuantTableAtQuality qual = scaleQuantisationMatrix qual defaultLumaQuantizationTable
chromaQuantTableAtQuality :: Int -> QuantificationTable
chromaQuantTableAtQuality qual =
scaleQuantisationMatrix qual defaultChromaQuantizationTable
zigzaggedQuantificationSpec :: Int -> [JpgQuantTableSpec]
zigzaggedQuantificationSpec qual =
[ JpgQuantTableSpec { quantPrecision = 0, quantDestination = 0, quantTable = luma }
, JpgQuantTableSpec { quantPrecision = 0, quantDestination = 1, quantTable = chroma }
]
where
luma = zigZagReorderForwardv $ lumaQuantTableAtQuality qual
chroma = zigZagReorderForwardv $ chromaQuantTableAtQuality qual
-- | Function to call to encode an image to jpeg.
-- The quality factor should be between 0 and 100 (100 being
-- the best quality).
encodeJpegAtQuality :: Word8 -- ^ Quality factor
-> Image PixelYCbCr8 -- ^ Image to encode
-> L.ByteString -- ^ Encoded JPEG
encodeJpegAtQuality quality = encodeJpegAtQualityWithMetadata quality mempty
-- | Record gathering all information to encode a component
-- from the source image. Previously was a huge tuple
-- burried in the code
data EncoderState = EncoderState
{ _encComponentIndex :: !Int
, _encBlockWidth :: !Int
, _encBlockHeight :: !Int
, _encQuantTable :: !QuantificationTable
, _encDcHuffman :: !HuffmanWriterCode
, _encAcHuffman :: !HuffmanWriterCode
}
-- | Helper type class describing all JPG-encodable pixel types
class (Pixel px, PixelBaseComponent px ~ Word8) => JpgEncodable px where
additionalBlocks :: Image px -> [JpgFrame]
additionalBlocks _ = []
componentsOfColorSpace :: Image px -> [JpgComponent]
encodingState :: Int -> Image px -> V.Vector EncoderState
imageHuffmanTables :: Image px -> [(JpgHuffmanTableSpec, HuffmanPackedTree)]
imageHuffmanTables _ = defaultHuffmanTables
scanSpecificationOfColorSpace :: Image px -> [JpgScanSpecification]
quantTableSpec :: Image px -> Int -> [JpgQuantTableSpec]
quantTableSpec _ qual = take 1 $ zigzaggedQuantificationSpec qual
maximumSubSamplingOf :: Image px -> Int
maximumSubSamplingOf _ = 1
instance JpgEncodable Pixel8 where
scanSpecificationOfColorSpace _ =
[ JpgScanSpecification { componentSelector = 1
, dcEntropyCodingTable = 0
, acEntropyCodingTable = 0
}
]
componentsOfColorSpace _ =
[ JpgComponent { componentIdentifier = 1
, horizontalSamplingFactor = 1
, verticalSamplingFactor = 1
, quantizationTableDest = 0
}
]
imageHuffmanTables _ =
[ prepareHuffmanTable DcComponent 0 defaultDcLumaHuffmanTable
, prepareHuffmanTable AcComponent 0 defaultAcLumaHuffmanTable
]
encodingState qual _ = V.singleton EncoderState
{ _encComponentIndex = 0
, _encBlockWidth = 1
, _encBlockHeight = 1
, _encQuantTable = zigZagReorderForwardv $ lumaQuantTableAtQuality qual
, _encDcHuffman = makeInverseTable defaultDcLumaHuffmanTree
, _encAcHuffman = makeInverseTable defaultAcLumaHuffmanTree
}
instance JpgEncodable PixelYCbCr8 where
maximumSubSamplingOf _ = 2
quantTableSpec _ qual = zigzaggedQuantificationSpec qual
scanSpecificationOfColorSpace _ =
[ JpgScanSpecification { componentSelector = 1
, dcEntropyCodingTable = 0
, acEntropyCodingTable = 0
}
, JpgScanSpecification { componentSelector = 2
, dcEntropyCodingTable = 1
, acEntropyCodingTable = 1
}
, JpgScanSpecification { componentSelector = 3
, dcEntropyCodingTable = 1
, acEntropyCodingTable = 1
}
]
componentsOfColorSpace _ =
[ JpgComponent { componentIdentifier = 1
, horizontalSamplingFactor = 2
, verticalSamplingFactor = 2
, quantizationTableDest = 0
}
, JpgComponent { componentIdentifier = 2
, horizontalSamplingFactor = 1
, verticalSamplingFactor = 1
, quantizationTableDest = 1
}
, JpgComponent { componentIdentifier = 3
, horizontalSamplingFactor = 1
, verticalSamplingFactor = 1
, quantizationTableDest = 1
}
]
encodingState qual _ = V.fromListN 3 [lumaState, chromaState, chromaState { _encComponentIndex = 2 }]
where
lumaState = EncoderState
{ _encComponentIndex = 0
, _encBlockWidth = 2
, _encBlockHeight = 2
, _encQuantTable = zigZagReorderForwardv $ lumaQuantTableAtQuality qual
, _encDcHuffman = makeInverseTable defaultDcLumaHuffmanTree
, _encAcHuffman = makeInverseTable defaultAcLumaHuffmanTree
}
chromaState = EncoderState
{ _encComponentIndex = 1
, _encBlockWidth = 1
, _encBlockHeight = 1
, _encQuantTable = zigZagReorderForwardv $ chromaQuantTableAtQuality qual
, _encDcHuffman = makeInverseTable defaultDcChromaHuffmanTree
, _encAcHuffman = makeInverseTable defaultAcChromaHuffmanTree
}
instance JpgEncodable PixelRGB8 where
additionalBlocks _ = [] where
_adobe14 = JpgAdobeApp14
{ _adobeDctVersion = 100
, _adobeFlag0 = 0
, _adobeFlag1 = 0
, _adobeTransform = AdobeUnknown
}
imageHuffmanTables _ =
[ prepareHuffmanTable DcComponent 0 defaultDcLumaHuffmanTable
, prepareHuffmanTable AcComponent 0 defaultAcLumaHuffmanTable
]
scanSpecificationOfColorSpace _ = fmap build "RGB" where
build c = JpgScanSpecification
{ componentSelector = fromIntegral $ fromEnum c
, dcEntropyCodingTable = 0
, acEntropyCodingTable = 0
}
componentsOfColorSpace _ = fmap build "RGB" where
build c = JpgComponent
{ componentIdentifier = fromIntegral $ fromEnum c
, horizontalSamplingFactor = 1
, verticalSamplingFactor = 1
, quantizationTableDest = 0
}
encodingState qual _ = V.fromListN 3 $ fmap build [0 .. 2] where
build ix = EncoderState
{ _encComponentIndex = ix
, _encBlockWidth = 1
, _encBlockHeight = 1
, _encQuantTable = zigZagReorderForwardv $ lumaQuantTableAtQuality qual
, _encDcHuffman = makeInverseTable defaultDcLumaHuffmanTree
, _encAcHuffman = makeInverseTable defaultAcLumaHuffmanTree
}
instance JpgEncodable PixelCMYK8 where
additionalBlocks _ = [] where
_adobe14 = JpgAdobeApp14
{ _adobeDctVersion = 100
, _adobeFlag0 = 32768
, _adobeFlag1 = 0
, _adobeTransform = AdobeYCck
}
imageHuffmanTables _ =
[ prepareHuffmanTable DcComponent 0 defaultDcLumaHuffmanTable
, prepareHuffmanTable AcComponent 0 defaultAcLumaHuffmanTable
]
scanSpecificationOfColorSpace _ = fmap build "CMYK" where
build c = JpgScanSpecification
{ componentSelector = fromIntegral $ fromEnum c
, dcEntropyCodingTable = 0
, acEntropyCodingTable = 0
}
componentsOfColorSpace _ = fmap build "CMYK" where
build c = JpgComponent
{ componentIdentifier = fromIntegral $ fromEnum c
, horizontalSamplingFactor = 1
, verticalSamplingFactor = 1
, quantizationTableDest = 0
}
encodingState qual _ = V.fromListN 4 $ fmap build [0 .. 3] where
build ix = EncoderState
{ _encComponentIndex = ix
, _encBlockWidth = 1
, _encBlockHeight = 1
, _encQuantTable = zigZagReorderForwardv $ lumaQuantTableAtQuality qual
, _encDcHuffman = makeInverseTable defaultDcLumaHuffmanTree
, _encAcHuffman = makeInverseTable defaultAcLumaHuffmanTree
}
-- | Equivalent to 'encodeJpegAtQuality', but will store the following
-- metadatas in the file using a JFIF block:
--
-- * 'Codec.Picture.Metadata.DpiX'
-- * 'Codec.Picture.Metadata.DpiY'
--
encodeJpegAtQualityWithMetadata :: Word8 -- ^ Quality factor
-> Metadatas
-> Image PixelYCbCr8 -- ^ Image to encode
-> L.ByteString -- ^ Encoded JPEG
encodeJpegAtQualityWithMetadata = encodeDirectJpegAtQualityWithMetadata
-- | Equivalent to 'encodeJpegAtQuality', but will store the following
-- metadatas in the file using a JFIF block:
--
-- * 'Codec.Picture.Metadata.DpiX'
-- * 'Codec.Picture.Metadata.DpiY'
--
-- This function also allow to create JPEG files with the following color
-- space:
--
-- * Y (Pixel8) for greyscale.
-- * RGB (PixelRGB8) with no color downsampling on any plane
-- * CMYK (PixelCMYK8) with no color downsampling on any plane
--
encodeDirectJpegAtQualityWithMetadata :: forall px. (JpgEncodable px)
=> Word8 -- ^ Quality factor
-> Metadatas
-> Image px -- ^ Image to encode
-> L.ByteString -- ^ Encoded JPEG
encodeDirectJpegAtQualityWithMetadata quality metas img = encode finalImage where
!w = imageWidth img
!h = imageHeight img
finalImage = JpgImage $
encodeMetadatas metas ++
additionalBlocks img ++
[ JpgQuantTable $ quantTableSpec img (fromIntegral quality)
, JpgScans JpgBaselineDCTHuffman hdr
, JpgHuffmanTable $ imageHuffmanTables img
, JpgScanBlob scanHeader encodedImage
]
!outputComponentCount = componentCount (undefined :: px)
scanHeader = scanHeader'{ scanLength = fromIntegral $ calculateSize scanHeader' }
scanHeader' = JpgScanHeader
{ scanLength = 0
, scanComponentCount = fromIntegral outputComponentCount
, scans = scanSpecificationOfColorSpace img
, spectralSelection = (0, 63)
, successiveApproxHigh = 0
, successiveApproxLow = 0
}
hdr = hdr' { jpgFrameHeaderLength = fromIntegral $ calculateSize hdr' }
hdr' = JpgFrameHeader
{ jpgFrameHeaderLength = 0
, jpgSamplePrecision = 8
, jpgHeight = fromIntegral h
, jpgWidth = fromIntegral w
, jpgImageComponentCount = fromIntegral outputComponentCount
, jpgComponents = componentsOfColorSpace img
}
!maxSampling = maximumSubSamplingOf img
!horizontalMetaBlockCount = w `divUpward` (dctBlockSize * maxSampling)
!verticalMetaBlockCount = h `divUpward` (dctBlockSize * maxSampling)
!componentDef = encodingState (fromIntegral quality) img
encodedImage = runST $ do
dc_table <- M.replicate outputComponentCount 0
block <- createEmptyMutableMacroBlock
workData <- createEmptyMutableMacroBlock
zigzaged <- createEmptyMutableMacroBlock
writeState <- newWriteStateRef
rasterMap horizontalMetaBlockCount verticalMetaBlockCount $ \mx my ->
V.forM_ componentDef $ \(EncoderState comp sizeX sizeY table dc ac) ->
let !xSamplingFactor = maxSampling - sizeX + 1
!ySamplingFactor = maxSampling - sizeY + 1
!extractor = extractBlock img block xSamplingFactor ySamplingFactor outputComponentCount
in
rasterMap sizeX sizeY $ \subX subY -> do
let !blockY = my * sizeY + subY
!blockX = mx * sizeX + subX
prev_dc <- dc_table `M.unsafeRead` comp
extracted <- extractor comp blockX blockY
(dc_coeff, neo_block) <- encodeMacroBlock table workData zigzaged prev_dc extracted
(dc_table `M.unsafeWrite` comp) $ fromIntegral dc_coeff
serializeMacroBlock writeState dc ac neo_block
finalizeBoolWriter writeState
| Chobbes/Juicy.Pixels | src/Codec/Picture/Jpg.hs | bsd-3-clause | 45,788 | 0 | 24 | 14,839 | 11,292 | 6,003 | 5,289 | -1 | -1 |
{-# LANGUAGE RankNTypes #-}
module Data.Type.Nat.Util where
import Data.Type.Nat
withNat
:: Integer
-> (forall n. Nat n -> Maybe r)
-> Maybe r
withNat x f = case compare x 0 of
LT -> Nothing
EQ -> f Z_
GT -> withNat (x - 1) (f . S_)
| mstksg/tensor-ops | src/Data/Type/Nat/Util.hs | bsd-3-clause | 270 | 0 | 10 | 85 | 108 | 57 | 51 | 11 | 3 |
import Data.List (sort)
import Graphics.Rendering.Chart.Simple
import Data.Random.Normal
-- | The integral of the probability density from -inf to x for
-- the normal distribution with mean 0 and standard deviation 1.
-- This formula is an approximation taken from Beta.
normalDistribution :: Double -> Double
normalDistribution x = if x >= -100 then 1 / (1 + exp (-p x))
else 0 where p x = x * (1.59145 + 0.01095*x + 0.06651*x^2)
samples = mkNormals 165795 :: [Double]
xs n = sort $ take n samples
ys n = map (/m) [1..m] where m = fromIntegral n :: Double
n1 = 100
n2 = 10000
main = do
plotWindow (xs n1) (ys n1) normalDistribution
plotWindow (xs n2) (ys n2) normalDistribution
| bjornbm/normaldistribution | Test.hs | bsd-3-clause | 707 | 1 | 13 | 149 | 240 | 129 | 111 | 14 | 2 |
module Husky.Network
(
allHostAddrs
)
where
import Network.Info
import Control.Monad
import Data.Bits
import Data.Binary
import Data.Binary.Put
-- | return all IPv4 address of local computer
allHostAddrs :: IO [String]
allHostAddrs = (map show . filter wanted . map ipv4) `liftM` getNetworkInterfaces
where
wanted (IPv4 w) = w /= 0 && w/= loopback
loopback = decode $ runPut $ putWord32host $ shift 127 24 + 1
| abaw/husky | Husky/Network.hs | bsd-3-clause | 479 | 1 | 10 | 134 | 134 | 72 | 62 | 12 | 1 |
---------------------------------------------------------------
-- |
-- Module : Data.Minecraft.Release17.Version
-- Copyright : (c) 2016 Michael Carpenter
-- License : BSD3
-- Maintainer : Michael Carpenter <[email protected]>
-- Stability : experimental
-- Portability : portable
--
---------------------------------------------------------------
module Data.Minecraft.Release17.Version
( version
, minecraftVersion
, majorVersion
) where
version :: Int
version = 5
minecraftVersion :: String
minecraftVersion = "1.7.10"
majorVersion :: String
majorVersion = "1.7" | oldmanmike/hs-minecraft-protocol | src/Data/Minecraft/Release17/Version.hs | bsd-3-clause | 613 | 0 | 4 | 101 | 59 | 41 | 18 | 10 | 1 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Ordinal.KO.Rules
( rules ) where
import Prelude
import Data.String
import Duckling.Dimensions.Types
import Duckling.Ordinal.Helpers
import Duckling.Numeral.Types (NumeralData (..))
import qualified Duckling.Numeral.Types as TNumeral
import Duckling.Types
ruleOrdinals :: Rule
ruleOrdinals = Rule
{ name = "ordinals (첫번째)"
, pattern =
[ dimension Numeral
, regex "번째|째(번)?"
]
, prod = \tokens -> case tokens of
(Token Numeral NumeralData{TNumeral.value = v}:_) ->
Just . ordinal $ floor v
_ -> Nothing
}
rules :: [Rule]
rules =
[ ruleOrdinals
]
| facebookincubator/duckling | Duckling/Ordinal/KO/Rules.hs | bsd-3-clause | 890 | 0 | 16 | 174 | 182 | 112 | 70 | 24 | 2 |
{-# LANGUAGE CPP, TypeFamilies #-}
-- -----------------------------------------------------------------------------
-- | This is the top-level module in the LLVM code generator.
--
module LlvmCodeGen ( llvmCodeGen, llvmFixupAsm ) where
#include "HsVersions.h"
import Llvm
import LlvmCodeGen.Base
import LlvmCodeGen.CodeGen
import LlvmCodeGen.Data
import LlvmCodeGen.Ppr
import LlvmCodeGen.Regs
import LlvmMangler
import BlockId
import CgUtils ( fixStgRegisters )
import Cmm
import CmmUtils
import Hoopl
import PprCmm
import BufWrite
import DynFlags
import ErrUtils
import FastString
import Outputable
import UniqSupply
import SysTools ( figureLlvmVersion )
import qualified Stream
import Control.Monad ( when )
import Data.Maybe ( fromMaybe, catMaybes )
import System.IO
-- -----------------------------------------------------------------------------
-- | Top-level of the LLVM Code generator
--
llvmCodeGen :: DynFlags -> Handle -> UniqSupply
-> Stream.Stream IO RawCmmGroup ()
-> IO ()
llvmCodeGen dflags h us cmm_stream
= do bufh <- newBufHandle h
-- Pass header
showPass dflags "LLVM CodeGen"
-- get llvm version, cache for later use
ver <- (fromMaybe supportedLlvmVersion) `fmap` figureLlvmVersion dflags
-- warn if unsupported
debugTraceMsg dflags 2
(text "Using LLVM version:" <+> text (show ver))
let doWarn = wopt Opt_WarnUnsupportedLlvmVersion dflags
when (ver /= supportedLlvmVersion && doWarn) $
putMsg dflags (text "You are using an unsupported version of LLVM!"
$+$ text ("Currently only " ++
llvmVersionStr supportedLlvmVersion ++
" is supported.")
$+$ text "We will try though...")
-- run code generation
runLlvm dflags ver bufh us $
llvmCodeGen' (liftStream cmm_stream)
bFlush bufh
llvmCodeGen' :: Stream.Stream LlvmM RawCmmGroup () -> LlvmM ()
llvmCodeGen' cmm_stream
= do -- Preamble
renderLlvm pprLlvmHeader
ghcInternalFunctions
cmmMetaLlvmPrelude
-- Procedures
let llvmStream = Stream.mapM llvmGroupLlvmGens cmm_stream
_ <- Stream.collect llvmStream
-- Declare aliases for forward references
renderLlvm . pprLlvmData =<< generateExternDecls
-- Postamble
cmmUsedLlvmGens
llvmGroupLlvmGens :: RawCmmGroup -> LlvmM ()
llvmGroupLlvmGens cmm = do
-- Insert functions into map, collect data
let split (CmmData s d' ) = return $ Just (s, d')
split (CmmProc h l live g) = do
-- Set function type
let l' = case mapLookup (g_entry g) h of
Nothing -> l
Just (Statics info_lbl _) -> info_lbl
lml <- strCLabel_llvm l'
funInsert lml =<< llvmFunTy live
return Nothing
cdata <- fmap catMaybes $ mapM split cmm
{-# SCC "llvm_datas_gen" #-}
cmmDataLlvmGens cdata
{-# SCC "llvm_procs_gen" #-}
mapM_ cmmLlvmGen cmm
-- -----------------------------------------------------------------------------
-- | Do LLVM code generation on all these Cmms data sections.
--
cmmDataLlvmGens :: [(Section,CmmStatics)] -> LlvmM ()
cmmDataLlvmGens statics
= do lmdatas <- mapM genLlvmData statics
let (gss, tss) = unzip lmdatas
let regGlobal (LMGlobal (LMGlobalVar l ty _ _ _ _) _)
= funInsert l ty
regGlobal _ = return ()
mapM_ regGlobal (concat gss)
gss' <- mapM aliasify $ concat gss
renderLlvm $ pprLlvmData (concat gss', concat tss)
-- | LLVM can't handle entry blocks which loop back to themselves (could be
-- seen as an LLVM bug) so we rearrange the code to keep the original entry
-- label which branches to a newly generated second label that branches back
-- to itself. See: Trac #11649
fixBottom :: RawCmmDecl -> LlvmM RawCmmDecl
fixBottom cp@(CmmProc hdr entry_lbl live g) =
maybe (pure cp) fix_block $ mapLookup (g_entry g) blk_map
where
blk_map = toBlockMap g
fix_block :: CmmBlock -> LlvmM RawCmmDecl
fix_block blk
| (CmmEntry e_lbl tickscp, middle, CmmBranch b_lbl) <- blockSplit blk
, isEmptyBlock middle
, e_lbl == b_lbl = do
new_lbl <- mkBlockId <$> getUniqueM
let fst_blk =
BlockCC (CmmEntry e_lbl tickscp) BNil (CmmBranch new_lbl)
snd_blk =
BlockCC (CmmEntry new_lbl tickscp) BNil (CmmBranch new_lbl)
pure . CmmProc hdr entry_lbl live . ofBlockMap (g_entry g)
$ mapFromList [(e_lbl, fst_blk), (new_lbl, snd_blk)]
fix_block _ = pure cp
fixBottom rcd = pure rcd
-- | Complete LLVM code generation phase for a single top-level chunk of Cmm.
cmmLlvmGen ::RawCmmDecl -> LlvmM ()
cmmLlvmGen cmm@CmmProc{} = do
-- rewrite assignments to global regs
dflags <- getDynFlag id
fixed_cmm <- fixBottom $
{-# SCC "llvm_fix_regs" #-}
fixStgRegisters dflags cmm
dumpIfSetLlvm Opt_D_dump_opt_cmm "Optimised Cmm" (pprCmmGroup [fixed_cmm])
-- generate llvm code from cmm
llvmBC <- withClearVars $ genLlvmProc fixed_cmm
-- pretty print
(docs, ivars) <- fmap unzip $ mapM pprLlvmCmmDecl llvmBC
-- Output, note down used variables
renderLlvm (vcat docs)
mapM_ markUsedVar $ concat ivars
cmmLlvmGen _ = return ()
-- -----------------------------------------------------------------------------
-- | Generate meta data nodes
--
cmmMetaLlvmPrelude :: LlvmM ()
cmmMetaLlvmPrelude = do
metas <- flip mapM stgTBAA $ \(uniq, name, parent) -> do
-- Generate / lookup meta data IDs
tbaaId <- getMetaUniqueId
setUniqMeta uniq tbaaId
parentId <- maybe (return Nothing) getUniqMeta parent
-- Build definition
return $ MetaUnamed tbaaId $ MetaStruct
[ MetaStr name
, case parentId of
Just p -> MetaNode p
Nothing -> MetaVar $ LMLitVar $ LMNullLit i8Ptr
]
renderLlvm $ ppLlvmMetas metas
-- -----------------------------------------------------------------------------
-- | Marks variables as used where necessary
--
cmmUsedLlvmGens :: LlvmM ()
cmmUsedLlvmGens = do
-- LLVM would discard variables that are internal and not obviously
-- used if we didn't provide these hints. This will generate a
-- definition of the form
--
-- @llvm.used = appending global [42 x i8*] [i8* bitcast <var> to i8*, ...]
--
-- Which is the LLVM way of protecting them against getting removed.
ivars <- getUsedVars
let cast x = LMBitc (LMStaticPointer (pVarLift x)) i8Ptr
ty = (LMArray (length ivars) i8Ptr)
usedArray = LMStaticArray (map cast ivars) ty
sectName = Just $ fsLit "llvm.metadata"
lmUsedVar = LMGlobalVar (fsLit "llvm.used") ty Appending sectName Nothing Constant
lmUsed = LMGlobal lmUsedVar (Just usedArray)
if null ivars
then return ()
else renderLlvm $ pprLlvmData ([lmUsed], [])
| mcschroeder/ghc | compiler/llvmGen/LlvmCodeGen.hs | bsd-3-clause | 7,212 | 0 | 20 | 1,958 | 1,591 | 792 | 799 | 134 | 3 |
{- |
Module : Glutton.Subscription.Types
Description : data types and instances for @Subscription@ and @ItemState@
-}
{-# LANGUAGE DeriveDataTypeable, TemplateHaskell, TypeFamilies #-}
module Glutton.Subscription.Types where
import Control.Monad.Reader (ask)
import Control.Monad.State (put)
import Data.Acid
import Data.SafeCopy
import Data.Typeable
-- | A Subscription is the state of a Feed as it is stored on our local machine
data Subscription =
Subscription {
feedTitle :: String,
feedAuthor :: Maybe String,
feedHome :: Maybe String,
feedHtml :: Maybe String,
feedDescription :: Maybe String,
feedPubDate :: Maybe String,
feedLastUpdate :: Maybe String,
feedDate :: Maybe String,
feedLogoLink :: Maybe String,
feedLanguage :: Maybe String,
feedCategories :: [(String, Maybe String)],
feedGenerator :: Maybe String,
feedItems :: [ItemState],
feedUrl :: String,
feedLastError :: Maybe String
} deriving (Typeable, Show)
newSubscription :: String -> Subscription
newSubscription url = Subscription {
feedTitle = url,
feedAuthor = Nothing,
feedHome = Nothing,
feedHtml = Nothing,
feedDescription = Nothing,
feedPubDate = Nothing,
feedLastUpdate = Nothing,
feedDate = Nothing,
feedLogoLink = Nothing,
feedLanguage = Nothing,
feedCategories = [],
feedGenerator = Nothing,
feedItems = [],
feedUrl = url,
feedLastError = Nothing
}
data ItemState =
ItemState {
itemTitle :: Maybe String,
itemLink :: Maybe String,
--itemPublishDate :: ParseTime t => Maybe (Maybe t),
itemPublishDateString :: Maybe String,
itemDate :: Maybe String,
itemAuthor :: Maybe String,
itemCommentLink :: Maybe String,
itemEnclosure :: Maybe (String, Maybe String, Maybe Integer),
itemFeedLink :: Maybe String,
itemId :: String,
itemCategories :: [String],
itemRights :: Maybe String,
itemSummary :: Maybe String,
itemDescription :: Maybe String,
itemRead :: Bool
} deriving (Show)
newItemState :: String -> ItemState
newItemState _id =
ItemState {
itemTitle = Nothing,
itemLink = Nothing,
itemPublishDateString = Nothing,
itemDate = Nothing,
itemAuthor = Nothing,
itemCommentLink = Nothing,
itemEnclosure = Nothing,
itemFeedLink = Nothing,
itemId = _id,
itemCategories = [],
itemRights = Nothing,
itemSummary = Nothing,
itemDescription = Nothing,
itemRead = False
}
writeSubscription :: Subscription -> Update Subscription ()
writeSubscription = put
querySubscription :: Query Subscription Subscription
querySubscription = ask
$(deriveSafeCopy 0 'base ''ItemState) --Move these to Subscription.Types to fix orphan instances
$(deriveSafeCopy 0 'base ''Subscription)
$(makeAcidic ''Subscription ['writeSubscription, 'querySubscription])
| alancocanour/glutton | src/Glutton/Subscription/Types.hs | bsd-3-clause | 2,849 | 0 | 11 | 583 | 668 | 396 | 272 | 83 | 1 |
module Parse.PatternTest where
import Test.Tasty
import Test.Tasty.HUnit
import Parse.Pattern
import AST.V0_16
import AST.Pattern
import Parse.TestHelpers
pending = at 0 0 0 0 Anything
example name input expected =
testCase name $
assertParse expr input expected
tests :: TestTree
tests =
testGroup "Parse.Pattern"
[ example "wildcard" "_" $ at 1 1 1 2 Anything
, example "literal" "1" $ at 1 1 1 2 (Literal (IntNum 1 DecimalInt))
, example "variable" "a" $ at 1 1 1 2 (VarPattern (LowercaseIdentifier "a"))
, testGroup "data"
[ example "" "Just x y" $ at 1 1 1 9 (Data [UppercaseIdentifier "Just"] [([],at 1 6 1 7 (VarPattern (LowercaseIdentifier "x"))),([],at 1 8 1 9 (VarPattern (LowercaseIdentifier "y")))])
, example "single parameter" "Just x" $ at 1 1 1 7 (Data [UppercaseIdentifier "Just"] [([],at 1 6 1 7 (VarPattern (LowercaseIdentifier "x")))])
, example "comments" "Just{-A-}x{-B-}y" $ at 1 1 1 17 (Data [UppercaseIdentifier "Just"] [([BlockComment ["A"]],at 1 10 1 11 (VarPattern (LowercaseIdentifier "x"))),([BlockComment ["B"]],at 1 16 1 17 (VarPattern (LowercaseIdentifier "y")))])
, example "newlines" "Just\n x\n y" $ at 1 1 3 3 (Data [UppercaseIdentifier "Just"] [([],at 2 2 2 3 (VarPattern (LowercaseIdentifier "x"))),([],at 3 2 3 3 (VarPattern (LowercaseIdentifier "y")))])
]
, testGroup "unit"
[ example "" "()" $ at 1 1 1 3 (UnitPattern [])
, example "whitespace" "( )" $ at 1 1 1 4 (UnitPattern [])
, example "comments" "({-A-})" $ at 1 1 1 8 (UnitPattern [BlockComment ["A"]])
, example "newlines" "(\n )" $ at 1 1 2 3 (UnitPattern [])
]
, testGroup "parentheses"
[ example "" "(_)" $ at 1 2 1 3 Anything
, example "whitespace" "( _ )" $ at 1 3 1 4 Anything
, example "comments" "({-A-}_{-B-})" $ at 1 1 1 14 (PatternParens (Commented [BlockComment ["A"]] (at 1 7 1 8 Anything) [BlockComment ["B"]]))
, example "newlines" "(\n _\n )" $ at 2 2 2 3 Anything
]
, testGroup "tuple"
[ example "" "(x,y)" $ at 1 1 1 6 (Tuple [Commented [] (at 1 2 1 3 (VarPattern (LowercaseIdentifier "x"))) [],Commented [] (at 1 4 1 5 (VarPattern (LowercaseIdentifier "y"))) []])
, example "whitespace" "( x , y )" $ at 1 1 1 10 (Tuple [Commented [] (at 1 3 1 4 (VarPattern (LowercaseIdentifier "x"))) [],Commented [] (at 1 7 1 8 (VarPattern (LowercaseIdentifier "y"))) []])
, example "comments" "({-A-}x{-B-},{-C-}y{-D-})" $ at 1 1 1 26 (Tuple [Commented [BlockComment ["A"]] (at 1 7 1 8 (VarPattern (LowercaseIdentifier "x"))) [BlockComment ["B"]],Commented [BlockComment ["C"]] (at 1 19 1 20 (VarPattern (LowercaseIdentifier "y"))) [BlockComment ["D"]]])
, example "newlines" "(\n x\n ,\n y\n )" $ at 1 1 5 3 (Tuple [Commented [] (at 2 2 2 3 (VarPattern (LowercaseIdentifier "x"))) [],Commented [] (at 4 2 4 3 (VarPattern (LowercaseIdentifier "y"))) []])
]
, testGroup "empty list pattern"
[ example "" "[]" $ at 1 1 1 3 (EmptyListPattern [])
, example "whitespace" "[ ]" $ at 1 1 1 4 (EmptyListPattern [])
, example "comments" "[{-A-}]" $ at 1 1 1 8 (EmptyListPattern [BlockComment ["A"]])
, example "newlines" "[\n ]" $ at 1 1 2 3 (EmptyListPattern [])
]
, testGroup "list"
[ example "" "[x,y]" $ at 1 1 1 6 (List [Commented [] (at 1 2 1 3 (VarPattern (LowercaseIdentifier "x"))) [],Commented [] (at 1 4 1 5 (VarPattern (LowercaseIdentifier "y"))) []])
, example "single element" "[x]" $ at 1 1 1 4 (List [Commented [] (at 1 2 1 3 (VarPattern (LowercaseIdentifier "x"))) []])
, example "whitespace" "[ x , y ]" $ at 1 1 1 10 (List [Commented [] (at 1 3 1 4 (VarPattern (LowercaseIdentifier "x"))) [],Commented [] (at 1 7 1 8 (VarPattern (LowercaseIdentifier "y"))) []])
, example "comments" "[{-A-}x{-B-},{-C-}y{-D-}]" $ at 1 1 1 26 (List [Commented [BlockComment ["A"]] (at 1 7 1 8 (VarPattern (LowercaseIdentifier "x"))) [BlockComment ["B"]],Commented [BlockComment ["C"]] (at 1 19 1 20 (VarPattern (LowercaseIdentifier "y"))) [BlockComment ["D"]]])
, example "newlines" "[\n x\n ,\n y\n ]" $ at 1 1 5 3 (List [Commented [] (at 2 2 2 3 (VarPattern (LowercaseIdentifier "x"))) [],Commented [] (at 4 2 4 3 (VarPattern (LowercaseIdentifier "y"))) []])
]
, testGroup "record"
[ example "" "{a,b}" $ at 1 1 1 6 (Record [Commented [] (LowercaseIdentifier "a") [],Commented [] (LowercaseIdentifier "b") []])
, example "single element" "{a}" $ at 1 1 1 4 (Record [Commented [] (LowercaseIdentifier "a") []])
, example "whitespace" "{ a , b }" $ at 1 1 1 10 (Record [Commented [] (LowercaseIdentifier "a") [],Commented [] (LowercaseIdentifier "b") []])
, example "comments" "{{-A-}a{-B-},{-C-}b{-D-}}" $ at 1 1 1 26 (Record [Commented [BlockComment ["A"]] (LowercaseIdentifier "a") [BlockComment ["B"]],Commented [BlockComment ["C"]] (LowercaseIdentifier "b") [BlockComment ["D"]]])
, example "newlines" "{\n a\n ,\n b\n }" $ at 1 1 5 3 (Record [Commented [] (LowercaseIdentifier "a") [],Commented [] (LowercaseIdentifier "b") []])
, testCase "must have at least one field" $
assertParseFailure expr "{}"
]
, testGroup "alias"
[ example "" "_ as x" $ at 1 1 1 7 (Alias (at 1 1 1 2 Anything,[]) ([],LowercaseIdentifier "x"))
, example "left side has whitespace" "A b as x" $ at 1 1 1 9 (Alias (at 1 1 1 4 (Data [UppercaseIdentifier "A"] [([], at 1 3 1 4 (VarPattern (LowercaseIdentifier "b")))]),[]) ([],LowercaseIdentifier "x"))
, example "left side ctor without whitespace" "A as x" $ at 1 1 1 7 (Alias (at 1 1 1 2 (Data [UppercaseIdentifier "A"] []),[]) ([],LowercaseIdentifier "x"))
, example "comments" "_{-A-}as{-B-}x" $ at 1 1 1 15 (Alias (at 1 1 1 2 Anything,[BlockComment ["A"]]) ([BlockComment ["B"]],LowercaseIdentifier "x"))
, example "newlines" "_\n as\n x" $ at 1 1 3 3 (Alias (at 1 1 1 2 Anything,[]) ([],LowercaseIdentifier "x"))
, example "nested" "(_ as x)as y" $ at 1 1 1 13 (Alias (at 1 2 1 8 (Alias (at 1 2 1 3 Anything,[]) ([],LowercaseIdentifier "x")),[]) ([],LowercaseIdentifier "y"))
, example "nested (whitespace)" "(_ as x) as y" $ at 1 1 1 14 (Alias (at 1 2 1 8 (Alias (at 1 2 1 3 Anything,[]) ([],LowercaseIdentifier "x")),[]) ([],LowercaseIdentifier "y"))
, testCase "nesting required parentheses" $
assertParseFailure expr "_ as x as y"
]
]
| nukisman/elm-format-short | tests/Parse/PatternTest.hs | bsd-3-clause | 6,554 | 0 | 23 | 1,497 | 3,016 | 1,518 | 1,498 | 66 | 1 |
{-# LANGUAGE TemplateHaskell #-}
module Code.LZ.Data where
import Code.Type ( BitSize (..), bits )
import Autolib.Reader
import Autolib.ToDoc
import Autolib.Size
import Autolib.Set
import Autolib.FiniteMap
import Data.Typeable
data Lempel_Ziv_Welch = Lempel_Ziv_Welch deriving ( Eq, Ord, Typeable )
data Lempel_Ziv_77 = Lempel_Ziv_77 deriving ( Eq, Ord, Typeable )
$(derives [makeReader, makeToDoc] [''Lempel_Ziv_Welch])
$(derives [makeReader, makeToDoc] [''Lempel_Ziv_77])
data Code_Letter a = Letter a
| Entry Int -- ^ num in dict
| Block { width :: Int, dist :: Int }
-- ^ relative position in stream
deriving ( Eq, Ord, Typeable )
$(derives [makeReader, makeToDoc] [''Code_Letter])
instance Size ( Code_Letter a ) where
size _ = 1 -- not used
instance Ord a => BitSize [ Code_Letter a ] where
bitSize xs =
let alpha = mkSet $ do Letter x <- xs ; return x
weight ( Letter _ ) = 1 + bits ( cardinality alpha )
weight ( Entry i ) = 1 + bits i
weight ( Block { dist = d, width = w })
= 1 + bits d + bits w
in sum $ map weight xs
data ( ToDoc [a], Ord a, Reader [a] )
=> Book a = Book
{ short :: Set a
, long :: FiniteMap [a] Int
}
deriving ( Eq, Ord, Typeable )
$(derives [makeReader, makeToDoc] [''Book])
leer :: ( ToDoc [a], Reader [a], Ord a ) => Book a
leer = Book { short = emptySet , long = emptyFM }
data ( ToDoc [a], ToDoc [b], Ord a, Reader [a], Reader [b] )
=> Cache a b = Cache
{ book :: Book a
, output :: [ b ]
}
$(derives [makeReader, makeToDoc] [''Cache])
blank :: ( ToDoc [a], ToDoc [b], Ord a, Reader [a], Reader [b] )
=> Cache a b
blank = Cache { book = leer , output = [] }
-- Local variables:
-- mode: haskell
-- End:
| florianpilz/autotool | src/Code/LZ/Data.hs | gpl-2.0 | 1,906 | 0 | 14 | 584 | 726 | 399 | 327 | -1 | -1 |
{-# LANGUAGE StrictData #-}
{-# LANGUAGE Trustworthy #-}
module Network.Tox.DHT.DhtRequestPacketSpec where
import Test.Hspec
import Data.Proxy (Proxy (..))
import Network.Tox.DHT.DhtRequestPacket (DhtRequestPacket (..))
import Network.Tox.EncodingSpec
spec :: Spec
spec = do
rpcSpec (Proxy :: Proxy DhtRequestPacket)
binarySpec (Proxy :: Proxy DhtRequestPacket)
readShowSpec (Proxy :: Proxy DhtRequestPacket)
| iphydf/hs-toxcore | test/Network/Tox/DHT/DhtRequestPacketSpec.hs | gpl-3.0 | 482 | 0 | 9 | 117 | 106 | 62 | 44 | 12 | 1 |
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE ViewPatterns #-}
module Data.IRC.Znc.Parse where
import Control.Applicative
import qualified Control.Exception as Ex
import Data.Attoparsec (Parser)
import qualified Data.Attoparsec as P
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as B8
import qualified Data.Foldable as F
import Data.IRC.Event
import Data.List
import Data.Maybe
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.Encoding.Error as T
import qualified Data.Time as Time
import Data.Time.Format (ParseTime)
import qualified Data.Time.LocalTime.TimeZone.Olson as Zone
import qualified Data.Time.LocalTime.TimeZone.Series as Zone
import Data.Word
import qualified System.Environment as Env
import qualified System.FilePath as Path
import System.Locale
-- | Configuring the parser.
data Config = Config
{ timeZone :: String -- ^ Timestamp time zone; an Olson time zone name.
, zoneInfo :: FilePath -- ^ Directory for time zone files; @$TZDIR@ overrides.
} deriving (Show)
-- | @'Config'@ value suitable for parsing @#haskell@ logs on Linux.
ircbrowseConfig :: Config
ircbrowseConfig = Config
{ timeZone = "Europe/Berlin"
, zoneInfo = "/usr/share/zoneinfo" }
-- Many text encodings are used on IRC.
-- We decode clog metadata as ASCII.
-- We parse messages as UTF-8 in a lenient mode.
decode :: B.ByteString -> T.Text
decode = T.decodeUtf8With T.lenientDecode
-- Timestamps are in local time and must be converted.
type TimeConv = Time.LocalTime -> Time.UTCTime
getTimeConv :: FilePath -> IO TimeConv
getTimeConv p = Zone.localTimeToUTC' <$> Zone.getTimeZoneSeriesFromOlsonFile p
data TimeAdj = TimeAdj Time.Day TimeConv
-- Parsers.
notNewline :: Word8 -> Bool
notNewline w = w /= 13 && w /= 10
restOfLine :: P.Parser T.Text
restOfLine = decode <$> P.takeWhile notNewline <* P.take 1
nextLine :: P.Parser ()
nextLine = P.skipWhile notNewline <* P.take 1
digits :: Int -> P.Parser Int
digits n = atoi <$> P.count n digit where
atoi = foldl' (\m d -> m*10 + fromIntegral d - 48) 0
digit = P.satisfy isDigit
isDigit w = w >= 48 && w <= 57
time :: TimeAdj -> P.Parser Time.UTCTime
time (TimeAdj day conv) = f <$> d2 <* col <*> d2 <* col <*> d2 where
d2 = digits 2
col = P.word8 58
f h m s = conv . Time.LocalTime day $ Time.TimeOfDay h m (fromIntegral s)
event :: P.Parser Event
event = F.asum
[ str " *** " *> F.asum
[ userAct Join "Joins: "
, userAct Part "Parts: "
, userAct Quit "Quits: "
, ReNick <$> (nick <* str " is now known as ") <*> nick <* nextLine
, Mode <$> nick <*> (str " sets mode: " *> restOfLine)
, (\kicked kicker x ->
Kick kicked
kicker
(fromMaybe x (T.stripSuffix (T.pack ")") x))) <$>
(nick <* str " was kicked by ") <*> (nick <* str " (") <*> restOfLine
, (\x -> Topic (fromMaybe x (T.stripSuffix (T.pack "'") x))) <$>
(nick *> str " changes topic to '" *> restOfLine)
]
, Talk <$ str " <" <*> nick <* str "> " <*> restOfLine
, Notice <$ str " -" <*> nick <*> restOfLine -- FIXME: parse host
, Act <$ str " * " <*> nick <* chr ' ' <*> restOfLine
] where
chr = P.word8 . fromIntegral . fromEnum
nick = (Nick . decode) <$> P.takeWhile (not . P.inClass " \n\r\t\v<>")
userAct f x = f <$ str x <*> nick <* chr ' ' <*> restOfLine
str :: String -> Parser ByteString
str = P.string . B8.pack
line :: TimeAdj -> P.Parser EventAt
line adj =
P.try (EventAt <$> (str "[" *> time adj <* str "]") <*> event)
<|> (NoParse <$> restOfLine)
safeRead :: (Read a) => String -> Maybe a
safeRead x | [(v,"")] <- reads x = Just v
safeRead _ = Nothing
getDay :: ParseTime t => FilePath -> t
getDay fp = case Path.splitFileName fp of
(_,(drop 1 . dropWhile (/='_')) -> date) ->
case Time.parseTime defaultTimeLocale "%Y%m%d.log" date of
Just day -> day
Nothing -> error ("cannot parse date from filename: " ++ date)
-- | Parse a log file.
--
-- The file name (after any directory) is significant.
-- It is used to set the date for timestamps.
-- It should have the form @YY.MM.DD@, as do the files on
-- @tunes.org@.
parseLog :: Config -> FilePath -> IO [EventAt]
parseLog (Config{timeZone=tz, zoneInfo=zi}) p = do
tzdir <- either (const zi :: Ex.IOException -> FilePath) id <$> Ex.try (Env.getEnv "TZDIR")
adj <- TimeAdj (getDay p) <$> getTimeConv (Path.combine tzdir tz)
b <- B.readFile p
let go [email protected]{} = error $ show r
go (P.Partial g) = go $ g B.empty
go (P.Done _ x) = x
let es = go $ P.parse (P.manyTill (line adj) P.endOfInput) b
return es
| plow-technologies/ircbrowse | src/Data/IRC/Znc/Parse.hs | bsd-3-clause | 4,784 | 0 | 22 | 1,085 | 1,548 | 826 | 722 | 101 | 3 |
{-# LANGUAGE CPP #-}
module System.Console.Haskeline.Backend.Win32.Echo (hWithoutInputEcho) where
import Control.Exception (throw)
import Control.Monad (void)
import Control.Monad.Catch (MonadMask, bracket)
import Control.Monad.IO.Class (MonadIO(..))
import System.Exit (ExitCode(..))
import System.IO (Handle, hGetContents, hGetEcho, hSetEcho)
import System.Process (StdStream(..), createProcess, shell,
std_in, std_out, waitForProcess)
#if MIN_VERSION_Win32(2,5,0)
import Control.Concurrent.MVar (readMVar)
import Data.Typeable (cast)
import Foreign.C.Types
import Foreign.StablePtr (StablePtr, freeStablePtr, newStablePtr)
import GHC.IO.FD (FD(..))
#if defined(__IO_MANAGER_WINIO__)
import GHC.IO.Handle.Windows (handleToHANDLE)
import GHC.IO.SubSystem ((<!>))
#endif
import GHC.IO.Handle.Types (Handle(..), Handle__(..))
import System.Win32.Types (HANDLE)
import System.Win32.MinTTY (isMinTTYHandle)
#endif
-- | Return the handle's current input 'EchoState'.
hGetInputEchoState :: Handle -> IO EchoState
hGetInputEchoState input = do
min_tty <- minTTY input
if min_tty
then fmap MinTTY (hGetInputEchoSTTY input)
else fmap DefaultTTY $ hGetEcho input
-- | Return all of @stty@'s current settings in a non-human-readable format.
--
-- This function is not very useful on its own. Its greater purpose is to
-- provide a compact 'STTYSettings' that can be fed back into
-- 'hSetInputEchoState'.
hGetInputEchoSTTY :: Handle -> IO STTYSettings
hGetInputEchoSTTY input = hSttyRaw input "-g"
-- | Set the handle's input 'EchoState'.
hSetInputEchoState :: Handle -> EchoState -> IO ()
hSetInputEchoState input (MinTTY settings) = hSetInputEchoSTTY input settings
hSetInputEchoState input (DefaultTTY echo) = hSetEcho input echo
-- | Create an @stty@ process and wait for it to complete. This is useful for
-- changing @stty@'s settings, after which @stty@ does not output anything.
--
-- @
-- hSetInputEchoSTTY input = 'void' . 'hSttyRaw' input
-- @
hSetInputEchoSTTY :: Handle -> STTYSettings -> IO ()
hSetInputEchoSTTY input = void . hSttyRaw input
-- | Save the handle's current input 'EchoState', perform a computation,
-- restore the saved 'EchoState', and then return the result of the
-- computation.
--
-- @
-- bracketInputEcho input action =
-- 'bracket' ('liftIO' $ 'hGetInputEchoState' input)
-- ('liftIO' . 'hSetInputEchoState' input)
-- (const action)
-- @
hBracketInputEcho :: (MonadIO m, MonadMask m) => Handle -> m a -> m a
hBracketInputEcho input action =
bracket (liftIO $ hGetInputEchoState input)
(liftIO . hSetInputEchoState input)
(const action)
-- | Perform a computation with the handle's input echoing disabled. Before
-- running the computation, the handle's input 'EchoState' is saved, and the
-- saved 'EchoState' is restored after the computation finishes.
hWithoutInputEcho :: (MonadIO m, MonadMask m) => Handle -> m a -> m a
hWithoutInputEcho input action = do
echo_off <- liftIO $ hEchoOff input
hBracketInputEcho input
(liftIO (hSetInputEchoState input echo_off) >> action)
-- | Create an @stty@ process, wait for it to complete, and return its output.
hSttyRaw :: Handle -> String -> IO STTYSettings
hSttyRaw input arg = do
let stty = (shell $ "stty " ++ arg) {
std_in = UseHandle input
, std_out = CreatePipe
}
(_, mbStdout, _, rStty) <- createProcess stty
exStty <- waitForProcess rStty
case exStty of
e@ExitFailure{} -> throw e
ExitSuccess -> maybe (return "") hGetContents mbStdout
-- | A representation of the handle input's current echoing state.
-- See, for instance, 'hEchoOff'.
data EchoState
= MinTTY STTYSettings
-- ^ The argument to (or value returned from) an invocation of the @stty@
-- command-line utility. Most POSIX-like shells have @stty@, including
-- MinTTY on Windows. Since neither 'hGetEcho' nor 'hSetEcho' work on
-- MinTTY, when 'getInputEchoState' runs on MinTTY, it returns a value
-- built with this constructor.
--
-- However, native Windows consoles like @cmd.exe@ or PowerShell do not
-- have @stty@, so if you construct an 'EchoState' with this constructor
-- manually, take care not to use it with a native Windows console.
| DefaultTTY Bool
-- ^ A simple on ('True') or off ('False') toggle. This is returned by
-- 'hGetEcho' and given as an argument to 'hSetEcho', which work on most
-- consoles, with the notable exception of MinTTY on Windows. If you
-- construct an 'EchoState' with this constructor manually, take care not
-- to use it with MinTTY.
deriving (Eq, Ord, Show)
-- | Indicates that the handle's input echoing is (or should be) off.
hEchoOff :: Handle -> IO EchoState
hEchoOff input = do
min_tty <- minTTY input
return $ if min_tty
then MinTTY "-echo"
else DefaultTTY False
-- | Settings used to configure the @stty@ command-line utility.
type STTYSettings = String
-- | Is the current process attached to a MinTTY console (e.g., Cygwin or MSYS)?
minTTY :: Handle -> IO Bool
#if MIN_VERSION_Win32(2,5,0)
minTTY input = withHandleToHANDLE input isMinTTYHandle
#else
-- On older versions of Win32, we simply punt.
minTTY _ = return False
#endif
#if MIN_VERSION_Win32(2,5,0)
foreign import ccall unsafe "_get_osfhandle"
c_get_osfhandle :: CInt -> IO HANDLE
-- | Extract a Windows 'HANDLE' from a Haskell 'Handle' and perform
-- an action on it.
-- Originally authored by Max Bolingbroke in the ansi-terminal library
withHandleToHANDLE :: Handle -> (HANDLE -> IO a) -> IO a
#if defined(__IO_MANAGER_WINIO__)
withHandleToHANDLE = withHandleToHANDLEPosix <!> withHandleToHANDLENative
#else
withHandleToHANDLE = withHandleToHANDLEPosix
#endif
#if defined(__IO_MANAGER_WINIO__)
withHandleToHANDLENative :: Handle -> (HANDLE -> IO a) -> IO a
withHandleToHANDLENative haskell_handle action =
-- Create a stable pointer to the Handle. This prevents the garbage collector
-- getting to it while we are doing horrible manipulations with it, and hence
-- stops it being finalized (and closed).
withStablePtr haskell_handle $ const $ do
windows_handle <- handleToHANDLE haskell_handle
-- Do what the user originally wanted
action windows_handle
#endif
withHandleToHANDLEPosix :: Handle -> (HANDLE -> IO a) -> IO a
withHandleToHANDLEPosix haskell_handle action =
-- Create a stable pointer to the Handle. This prevents the garbage collector
-- getting to it while we are doing horrible manipulations with it, and hence
-- stops it being finalized (and closed).
withStablePtr haskell_handle $ const $ do
-- Grab the write handle variable from the Handle
let write_handle_mvar = case haskell_handle of
FileHandle _ handle_mvar -> handle_mvar
DuplexHandle _ _ handle_mvar -> handle_mvar
-- This is "write" MVar, we could also take the "read" one
-- Get the FD from the algebraic data type
Just fd <- fmap (\(Handle__ { haDevice = dev }) -> fmap fdFD (cast dev))
$ readMVar write_handle_mvar
-- Finally, turn that (C-land) FD into a HANDLE using msvcrt
windows_handle <- c_get_osfhandle fd
-- Do what the user originally wanted
action windows_handle
withStablePtr :: a -> (StablePtr a -> IO b) -> IO b
withStablePtr value = bracket (newStablePtr value) freeStablePtr
#endif
| judah/haskeline | System/Console/Haskeline/Backend/Win32/Echo.hs | bsd-3-clause | 7,499 | 0 | 16 | 1,496 | 1,238 | 684 | 554 | 56 | 2 |
{-# LANGUAGE Haskell2010 #-}
{-# LINE 1 "System/Posix.hs" #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE Safe #-}
-----------------------------------------------------------------------------
-- |
-- Module : System.Posix
-- Copyright : (c) The University of Glasgow 2002
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : non-portable (requires POSIX)
--
-- <http://pubs.opengroup.org/onlinepubs/9699919799/ POSIX.1-2008> support
--
-----------------------------------------------------------------------------
module System.Posix (
module System.Posix.Types,
module System.Posix.Signals,
module System.Posix.Directory,
module System.Posix.Files,
module System.Posix.Unistd,
module System.Posix.IO,
module System.Posix.Env,
module System.Posix.Process,
module System.Posix.Temp,
module System.Posix.Terminal,
module System.Posix.Time,
module System.Posix.User,
module System.Posix.Resource,
module System.Posix.Semaphore,
module System.Posix.SharedMem,
module System.Posix.DynamicLinker,
-- XXX 'Module' type clashes with GHC
-- module System.Posix.DynamicLinker.Module
) where
import System.Posix.Types
import System.Posix.Signals
import System.Posix.Directory
import System.Posix.Files
import System.Posix.Unistd
import System.Posix.Process
import System.Posix.IO
import System.Posix.Env
import System.Posix.Temp
import System.Posix.Terminal
import System.Posix.Time
import System.Posix.User
import System.Posix.Resource
import System.Posix.Semaphore
import System.Posix.SharedMem
-- XXX: bad planning, we have two constructors called "Default"
import System.Posix.DynamicLinker hiding (Default)
--import System.Posix.DynamicLinker.Module
{- TODO
Here we detail our support for the IEEE Std 1003.1-2001 standard. For
each header file defined by the standard, we categorise its
functionality as
- "supported"
Full equivalent functionality is provided by the specified Haskell
module.
- "unsupported" (functionality not provided by a Haskell module)
The functionality is not currently provided.
- "to be supported"
Currently unsupported, but support is planned for the future.
Exceptions are listed where appropriate.
Interfaces supported
--------------------
unix package:
dirent.h System.Posix.Directory
dlfcn.h System.Posix.DynamicLinker
errno.h Foreign.C.Error
fcntl.h System.Posix.IO
signal.h System.Posix.Signals
sys/stat.h System.Posix.Files
sys/times.h System.Posix.Process
sys/types.h System.Posix.Types (with exceptions...)
sys/utsname.h System.Posix.Unistd
sys/wait.h System.Posix.Process
termios.h System.Posix.Terminal (check exceptions)
unistd.h System.Posix.*
utime.h System.Posix.Files
pwd.h System.Posix.User
grp.h System.Posix.User
stdlib.h: System.Posix.Env (getenv()/setenv()/unsetenv())
System.Posix.Temp (mkstemp())
sys/resource.h: System.Posix.Resource (get/setrlimit() only)
regex-posix package:
regex.h Text.Regex.Posix
network package:
arpa/inet.h
net/if.h
netinet/in.h
netinet/tcp.h
sys/socket.h
sys/un.h
To be supported
---------------
limits.h (pathconf()/fpathconf() already done)
poll.h
sys/resource.h (getrusage(): use instead of times() for getProcessTimes?)
sys/select.h
sys/statvfs.h (?)
sys/time.h (but maybe not the itimer?)
time.h (System.Posix.Time)
stdio.h (popen only: System.Posix.IO)
sys/mman.h
Unsupported interfaces
----------------------
aio.h
assert.h
complex.h
cpio.h
ctype.h
fenv.h
float.h
fmtmsg.h
fnmatch.h
ftw.h
glob.h
iconv.h
inttypes.h
iso646.h
langinfo.h
libgen.h
locale.h (see System.Locale)
math.h
monetary.h
mqueue.h
ndbm.h
netdb.h
nl_types.h
pthread.h
sched.h
search.h
semaphore.h
setjmp.h
spawn.h
stdarg.h
stdbool.h
stddef.h
stdint.h
stdio.h except: popen()
stdlib.h except: exit(): System.Posix.Process
free()/malloc(): Foreign.Marshal.Alloc
getenv()/setenv(): ?? System.Environment
rand() etc.: System.Random
string.h
strings.h
stropts.h
sys/ipc.h
sys/msg.h
sys/sem.h
sys/shm.h
sys/timeb.h
sys/uio.h
syslog.h
tar.h
tgmath.h
trace.h
ucontext.h
ulimit.h
utmpx.h
wchar.h
wctype.h
wordexp.h
-}
| phischu/fragnix | tests/packages/scotty/System.Posix.hs | bsd-3-clause | 4,209 | 0 | 5 | 563 | 245 | 176 | 69 | 37 | 0 |
module Graphics.Wayland.Scanner.Names (
ServerClient(..),
registryBindName,
-- apparently we are not allowed to use foreign C names generated by the C scanner
requestInternalCName, eventInternalCName,
-- requestForeignCName, eventForeignCName,
requestHaskName, eventHaskName,
interfaceTypeName, interfaceCInterfaceName,
enumTypeName, enumEntryHaskName,
messageListenerTypeName,
messageListenerMessageName,
messageListenerWrapperName,
interfaceResourceCreator,
capitalize
) where
import Data.Char
import Data.List
import Language.Haskell.TH
import Graphics.Wayland.Scanner.Types
registryBindName :: ProtocolName -> InterfaceName -> String
registryBindName pname iname = "registryBind" ++ (capitalize $ haskifyInterfaceName pname iname)
requestInternalCName :: InterfaceName -> MessageName -> Name
requestInternalCName iface msg = mkName $ iface ++ "_" ++ msg ++ "_request_binding"
eventInternalCName :: InterfaceName -> MessageName -> Name
eventInternalCName iface msg = mkName $ iface ++ "_" ++ msg ++ "_event_binding"
requestHaskName :: ProtocolName -> InterfaceName -> MessageName -> String
requestHaskName pname iname mname = toCamel (haskifyInterfaceName pname iname ++ "_" ++ mname)
eventHaskName :: ProtocolName -> InterfaceName -> MessageName -> String
eventHaskName = requestHaskName
enumEntryHaskName :: ProtocolName -> InterfaceName -> EnumName -> String -> Name
enumEntryHaskName pname iname ename entryName =
mkName $ haskifyInterfaceName pname iname ++ capitalize (toCamel ename) ++ capitalize (toCamel entryName)
interfaceTypeName :: ProtocolName -> InterfaceName -> String
interfaceTypeName pname iname = capitalize $ haskifyInterfaceName pname iname
interfaceCInterfaceName :: ProtocolName -> InterfaceName -> Name
interfaceCInterfaceName _ iname = mkName $ iname ++ "_c_interface"
enumTypeName :: ProtocolName -> InterfaceName -> EnumName -> Name
enumTypeName pname iname ename = mkName $ capitalize $ haskifyInterfaceName pname iname ++ capitalize (toCamel ename)
messageListenerTypeName :: ServerClient -> ProtocolName -> InterfaceName -> Name
messageListenerTypeName Server pname iname = mkName $ capitalize (haskifyInterfaceName pname iname) ++ "Implementation"
messageListenerTypeName Client pname iname = mkName $ capitalize (haskifyInterfaceName pname iname) ++ "Listener"
messageListenerMessageName :: ServerClient -> ProtocolName -> InterfaceName -> MessageName -> String
messageListenerMessageName Server = requestHaskName
messageListenerMessageName Client = eventHaskName
messageListenerWrapperName :: ServerClient -> InterfaceName -> MessageName -> Name
messageListenerWrapperName Client iname mname = mkName $ iname ++ "_" ++ mname ++ "_listener_wrapper"
messageListenerWrapperName Server iname mname = mkName $ iname ++ "_" ++ mname ++ "_implementation_wrapper"
interfaceResourceCreator :: ProtocolName -> InterfaceName -> Name
interfaceResourceCreator pname iname = mkName $ pname ++ "_" ++ iname ++ "_resource_create"
-- | Some interfaces use a naming convention where wl_ or their protocol's name is prepended.
-- We remove both because it doesn't look very Haskelly.
haskifyInterfaceName :: ProtocolName -> InterfaceName -> String
haskifyInterfaceName pname iname =
toCamel $ removeInitial (pname ++ "_") $ removeInitial "wl_" iname
-- stupid utility functions follow
-- | if the second argument starts with the first argument, strip that start
removeInitial :: Eq a => [a] -> [a] -> [a]
removeInitial remove input = if remove `isPrefixOf` input
then drop (length remove) input
else input
-- | convert some_string to someString
toCamel :: String -> String
toCamel (a:'_':c:d) | isAlpha a, isAlpha c = a : toUpper c : toCamel d
toCamel (a:b) = a : toCamel b
toCamel x = x
capitalize :: String -> String
capitalize x = toUpper (head x) : tail x
-- decapitalize :: String -> String
-- decapitalize x = toLower (head x) : tail x
| abooij/haskell-wayland | Graphics/Wayland/Scanner/Names.hs | mit | 3,992 | 0 | 9 | 627 | 929 | 486 | 443 | 59 | 2 |
{-# 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.RDS.DescribeEvents
-- 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.
-- | Returns events related to DB instances, DB security groups, DB snapshots,
-- and DB parameter groups for the past 14 days. Events specific to a particular
-- DB instance, DB security group, database snapshot, or DB parameter group can
-- be obtained by providing the name as a parameter. By default, the past hour
-- of events are returned.
--
-- <http://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_DescribeEvents.html>
module Network.AWS.RDS.DescribeEvents
(
-- * Request
DescribeEvents
-- ** Request constructor
, describeEvents
-- ** Request lenses
, deDuration
, deEndTime
, deEventCategories
, deFilters
, deMarker
, deMaxRecords
, deSourceIdentifier
, deSourceType
, deStartTime
-- * Response
, DescribeEventsResponse
-- ** Response constructor
, describeEventsResponse
-- ** Response lenses
, derEvents
, derMarker
) where
import Network.AWS.Prelude
import Network.AWS.Request.Query
import Network.AWS.RDS.Types
import qualified GHC.Exts
data DescribeEvents = DescribeEvents
{ _deDuration :: Maybe Int
, _deEndTime :: Maybe ISO8601
, _deEventCategories :: List "member" Text
, _deFilters :: List "member" Filter
, _deMarker :: Maybe Text
, _deMaxRecords :: Maybe Int
, _deSourceIdentifier :: Maybe Text
, _deSourceType :: Maybe SourceType
, _deStartTime :: Maybe ISO8601
} deriving (Eq, Read, Show)
-- | 'DescribeEvents' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'deDuration' @::@ 'Maybe' 'Int'
--
-- * 'deEndTime' @::@ 'Maybe' 'UTCTime'
--
-- * 'deEventCategories' @::@ ['Text']
--
-- * 'deFilters' @::@ ['Filter']
--
-- * 'deMarker' @::@ 'Maybe' 'Text'
--
-- * 'deMaxRecords' @::@ 'Maybe' 'Int'
--
-- * 'deSourceIdentifier' @::@ 'Maybe' 'Text'
--
-- * 'deSourceType' @::@ 'Maybe' 'SourceType'
--
-- * 'deStartTime' @::@ 'Maybe' 'UTCTime'
--
describeEvents :: DescribeEvents
describeEvents = DescribeEvents
{ _deSourceIdentifier = Nothing
, _deSourceType = Nothing
, _deStartTime = Nothing
, _deEndTime = Nothing
, _deDuration = Nothing
, _deEventCategories = mempty
, _deFilters = mempty
, _deMaxRecords = Nothing
, _deMarker = Nothing
}
-- | The number of minutes to retrieve events for.
--
-- Default: 60
deDuration :: Lens' DescribeEvents (Maybe Int)
deDuration = lens _deDuration (\s a -> s { _deDuration = a })
-- | The end of the time interval for which to retrieve events, specified in ISO
-- 8601 format. For more information about ISO 8601, go to the <http://en.wikipedia.org/wiki/ISO_8601 ISO8601 Wikipediapage.>
--
-- Example: 2009-07-08T18:00Z
deEndTime :: Lens' DescribeEvents (Maybe UTCTime)
deEndTime = lens _deEndTime (\s a -> s { _deEndTime = a }) . mapping _Time
-- | A list of event categories that trigger notifications for a event
-- notification subscription.
deEventCategories :: Lens' DescribeEvents [Text]
deEventCategories =
lens _deEventCategories (\s a -> s { _deEventCategories = a })
. _List
-- | This parameter is not currently supported.
deFilters :: Lens' DescribeEvents [Filter]
deFilters = lens _deFilters (\s a -> s { _deFilters = a }) . _List
-- | An optional pagination token provided by a previous DescribeEvents request.
-- If this parameter is specified, the response includes only records beyond the
-- marker, up to the value specified by 'MaxRecords'.
deMarker :: Lens' DescribeEvents (Maybe Text)
deMarker = lens _deMarker (\s a -> s { _deMarker = a })
-- | The maximum number of records to include in the response. If more records
-- exist than the specified 'MaxRecords' value, a pagination token called a marker
-- is included in the response so that the remaining results may be retrieved.
--
-- Default: 100
--
-- Constraints: minimum 20, maximum 100
deMaxRecords :: Lens' DescribeEvents (Maybe Int)
deMaxRecords = lens _deMaxRecords (\s a -> s { _deMaxRecords = a })
-- | The identifier of the event source for which events will be returned. If not
-- specified, then all sources are included in the response.
--
-- Constraints:
--
-- If SourceIdentifier is supplied, SourceType must also be provided. If the
-- source type is 'DBInstance', then a 'DBInstanceIdentifier' must be supplied. If
-- the source type is 'DBSecurityGroup', a 'DBSecurityGroupName' must be supplied. If the source type is
-- 'DBParameterGroup', a 'DBParameterGroupName' must be supplied. If the source type
-- is 'DBSnapshot', a 'DBSnapshotIdentifier' must be supplied. Cannot end with a
-- hyphen or contain two consecutive hyphens.
deSourceIdentifier :: Lens' DescribeEvents (Maybe Text)
deSourceIdentifier =
lens _deSourceIdentifier (\s a -> s { _deSourceIdentifier = a })
-- | The event source to retrieve events for. If no value is specified, all
-- events are returned.
deSourceType :: Lens' DescribeEvents (Maybe SourceType)
deSourceType = lens _deSourceType (\s a -> s { _deSourceType = a })
-- | The beginning of the time interval to retrieve events for, specified in ISO
-- 8601 format. For more information about ISO 8601, go to the <http://en.wikipedia.org/wiki/ISO_8601 ISO8601 Wikipediapage.>
--
-- Example: 2009-07-08T18:00Z
deStartTime :: Lens' DescribeEvents (Maybe UTCTime)
deStartTime = lens _deStartTime (\s a -> s { _deStartTime = a }) . mapping _Time
data DescribeEventsResponse = DescribeEventsResponse
{ _derEvents :: List "member" Event
, _derMarker :: Maybe Text
} deriving (Eq, Read, Show)
-- | 'DescribeEventsResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'derEvents' @::@ ['Event']
--
-- * 'derMarker' @::@ 'Maybe' 'Text'
--
describeEventsResponse :: DescribeEventsResponse
describeEventsResponse = DescribeEventsResponse
{ _derMarker = Nothing
, _derEvents = mempty
}
-- | A list of 'Event' instances.
derEvents :: Lens' DescribeEventsResponse [Event]
derEvents = lens _derEvents (\s a -> s { _derEvents = a }) . _List
-- | An optional pagination token provided by a previous Events request. If this
-- parameter is specified, the response includes only records beyond the marker,
-- up to the value specified by 'MaxRecords' .
derMarker :: Lens' DescribeEventsResponse (Maybe Text)
derMarker = lens _derMarker (\s a -> s { _derMarker = a })
instance ToPath DescribeEvents where
toPath = const "/"
instance ToQuery DescribeEvents where
toQuery DescribeEvents{..} = mconcat
[ "Duration" =? _deDuration
, "EndTime" =? _deEndTime
, "EventCategories" =? _deEventCategories
, "Filters" =? _deFilters
, "Marker" =? _deMarker
, "MaxRecords" =? _deMaxRecords
, "SourceIdentifier" =? _deSourceIdentifier
, "SourceType" =? _deSourceType
, "StartTime" =? _deStartTime
]
instance ToHeaders DescribeEvents
instance AWSRequest DescribeEvents where
type Sv DescribeEvents = RDS
type Rs DescribeEvents = DescribeEventsResponse
request = post "DescribeEvents"
response = xmlResponse
instance FromXML DescribeEventsResponse where
parseXML = withElement "DescribeEventsResult" $ \x -> DescribeEventsResponse
<$> x .@? "Events" .!@ mempty
<*> x .@? "Marker"
instance AWSPager DescribeEvents where
page rq rs
| stop (rs ^. derMarker) = Nothing
| otherwise = (\x -> rq & deMarker ?~ x)
<$> (rs ^. derMarker)
| romanb/amazonka | amazonka-rds/gen/Network/AWS/RDS/DescribeEvents.hs | mpl-2.0 | 8,647 | 0 | 12 | 1,914 | 1,195 | 713 | 482 | 114 | 1 |
{-# LANGUAGE CPP #-}
-----------------------------------------------------------------------------
--
-- Code generator utilities; mostly monadic
--
-- (c) The University of Glasgow 2004-2006
--
-----------------------------------------------------------------------------
module StgCmmUtils (
cgLit, mkSimpleLit,
emitDataLits, mkDataLits,
emitRODataLits, mkRODataLits,
emitRtsCall, emitRtsCallWithResult, emitRtsCallGen,
assignTemp, newTemp,
newUnboxedTupleRegs,
emitMultiAssign, emitCmmLitSwitch, emitSwitch,
tagToClosure, mkTaggedObjectLoad,
callerSaves, callerSaveVolatileRegs, get_GlobalReg_addr,
cmmAndWord, cmmOrWord, cmmNegate, cmmEqWord, cmmNeWord,
cmmUGtWord, cmmSubWord, cmmMulWord, cmmAddWord, cmmUShrWord,
cmmOffsetExprW, cmmOffsetExprB,
cmmRegOffW, cmmRegOffB,
cmmLabelOffW, cmmLabelOffB,
cmmOffsetW, cmmOffsetB,
cmmOffsetLitW, cmmOffsetLitB,
cmmLoadIndexW,
cmmConstrTag1,
cmmUntag, cmmIsTagged,
addToMem, addToMemE, addToMemLblE, addToMemLbl,
mkWordCLit,
newStringCLit, newByteStringCLit,
blankWord
) where
#include "HsVersions.h"
import StgCmmMonad
import StgCmmClosure
import Cmm
import BlockId
import MkGraph
import CodeGen.Platform
import CLabel
import CmmUtils
import CmmSwitch
import ForeignCall
import IdInfo
import Type
import TyCon
import SMRep
import Module
import Literal
import Digraph
import Util
import Unique
import DynFlags
import FastString
import Outputable
import qualified Data.ByteString as BS
import qualified Data.Map as M
import Data.Char
import Data.List
import Data.Ord
import Data.Word
-------------------------------------------------------------------------
--
-- Literals
--
-------------------------------------------------------------------------
cgLit :: Literal -> FCode CmmLit
cgLit (MachStr s) = newByteStringCLit (BS.unpack s)
-- not unpackFS; we want the UTF-8 byte stream.
cgLit other_lit = do dflags <- getDynFlags
return (mkSimpleLit dflags other_lit)
mkSimpleLit :: DynFlags -> Literal -> CmmLit
mkSimpleLit dflags (MachChar c) = CmmInt (fromIntegral (ord c)) (wordWidth dflags)
mkSimpleLit dflags MachNullAddr = zeroCLit dflags
mkSimpleLit dflags (MachInt i) = CmmInt i (wordWidth dflags)
mkSimpleLit _ (MachInt64 i) = CmmInt i W64
mkSimpleLit dflags (MachWord i) = CmmInt i (wordWidth dflags)
mkSimpleLit _ (MachWord64 i) = CmmInt i W64
mkSimpleLit _ (MachFloat r) = CmmFloat r W32
mkSimpleLit _ (MachDouble r) = CmmFloat r W64
mkSimpleLit _ (MachLabel fs ms fod)
= CmmLabel (mkForeignLabel fs ms labelSrc fod)
where
-- TODO: Literal labels might not actually be in the current package...
labelSrc = ForeignLabelInThisPackage
mkSimpleLit _ other = pprPanic "mkSimpleLit" (ppr other)
--------------------------------------------------------------------------
--
-- Incrementing a memory location
--
--------------------------------------------------------------------------
addToMemLbl :: CmmType -> CLabel -> Int -> CmmAGraph
addToMemLbl rep lbl n = addToMem rep (CmmLit (CmmLabel lbl)) n
addToMemLblE :: CmmType -> CLabel -> CmmExpr -> CmmAGraph
addToMemLblE rep lbl = addToMemE rep (CmmLit (CmmLabel lbl))
addToMem :: CmmType -- rep of the counter
-> CmmExpr -- Address
-> Int -- What to add (a word)
-> CmmAGraph
addToMem rep ptr n = addToMemE rep ptr (CmmLit (CmmInt (toInteger n) (typeWidth rep)))
addToMemE :: CmmType -- rep of the counter
-> CmmExpr -- Address
-> CmmExpr -- What to add (a word-typed expression)
-> CmmAGraph
addToMemE rep ptr n
= mkStore ptr (CmmMachOp (MO_Add (typeWidth rep)) [CmmLoad ptr rep, n])
-------------------------------------------------------------------------
--
-- Loading a field from an object,
-- where the object pointer is itself tagged
--
-------------------------------------------------------------------------
mkTaggedObjectLoad
:: DynFlags -> LocalReg -> LocalReg -> ByteOff -> DynTag -> CmmAGraph
-- (loadTaggedObjectField reg base off tag) generates assignment
-- reg = bitsK[ base + off - tag ]
-- where K is fixed by 'reg'
mkTaggedObjectLoad dflags reg base offset tag
= mkAssign (CmmLocal reg)
(CmmLoad (cmmOffsetB dflags
(CmmReg (CmmLocal base))
(offset - tag))
(localRegType reg))
-------------------------------------------------------------------------
--
-- Converting a closure tag to a closure for enumeration types
-- (this is the implementation of tagToEnum#).
--
-------------------------------------------------------------------------
tagToClosure :: DynFlags -> TyCon -> CmmExpr -> CmmExpr
tagToClosure dflags tycon tag
= CmmLoad (cmmOffsetExprW dflags closure_tbl tag) (bWord dflags)
where closure_tbl = CmmLit (CmmLabel lbl)
lbl = mkClosureTableLabel (tyConName tycon) NoCafRefs
-------------------------------------------------------------------------
--
-- Conditionals and rts calls
--
-------------------------------------------------------------------------
emitRtsCall :: UnitId -> FastString -> [(CmmExpr,ForeignHint)] -> Bool -> FCode ()
emitRtsCall pkg fun args safe = emitRtsCallGen [] (mkCmmCodeLabel pkg fun) args safe
emitRtsCallWithResult :: LocalReg -> ForeignHint -> UnitId -> FastString
-> [(CmmExpr,ForeignHint)] -> Bool -> FCode ()
emitRtsCallWithResult res hint pkg fun args safe
= emitRtsCallGen [(res,hint)] (mkCmmCodeLabel pkg fun) args safe
-- Make a call to an RTS C procedure
emitRtsCallGen
:: [(LocalReg,ForeignHint)]
-> CLabel
-> [(CmmExpr,ForeignHint)]
-> Bool -- True <=> CmmSafe call
-> FCode ()
emitRtsCallGen res lbl args safe
= do { dflags <- getDynFlags
; updfr_off <- getUpdFrameOff
; let (caller_save, caller_load) = callerSaveVolatileRegs dflags
; emit caller_save
; call updfr_off
; emit caller_load }
where
call updfr_off =
if safe then
emit =<< mkCmmCall fun_expr res' args' updfr_off
else do
let conv = ForeignConvention CCallConv arg_hints res_hints CmmMayReturn
emit $ mkUnsafeCall (ForeignTarget fun_expr conv) res' args'
(args', arg_hints) = unzip args
(res', res_hints) = unzip res
fun_expr = mkLblExpr lbl
-----------------------------------------------------------------------------
--
-- Caller-Save Registers
--
-----------------------------------------------------------------------------
-- Here we generate the sequence of saves/restores required around a
-- foreign call instruction.
-- TODO: reconcile with includes/Regs.h
-- * Regs.h claims that BaseReg should be saved last and loaded first
-- * This might not have been tickled before since BaseReg is callee save
-- * Regs.h saves SparkHd, ParkT1, SparkBase and SparkLim
--
-- This code isn't actually used right now, because callerSaves
-- only ever returns true in the current universe for registers NOT in
-- system_regs (just do a grep for CALLER_SAVES in
-- includes/stg/MachRegs.h). It's all one giant no-op, and for
-- good reason: having to save system registers on every foreign call
-- would be very expensive, so we avoid assigning them to those
-- registers when we add support for an architecture.
--
-- Note that the old code generator actually does more work here: it
-- also saves other global registers. We can't (nor want) to do that
-- here, as we don't have liveness information. And really, we
-- shouldn't be doing the workaround at this point in the pipeline, see
-- Note [Register parameter passing] and the ToDo on CmmCall in
-- cmm/CmmNode.hs. Right now the workaround is to avoid inlining across
-- unsafe foreign calls in rewriteAssignments, but this is strictly
-- temporary.
callerSaveVolatileRegs :: DynFlags -> (CmmAGraph, CmmAGraph)
callerSaveVolatileRegs dflags = (caller_save, caller_load)
where
platform = targetPlatform dflags
caller_save = catAGraphs (map callerSaveGlobalReg regs_to_save)
caller_load = catAGraphs (map callerRestoreGlobalReg regs_to_save)
system_regs = [ Sp,SpLim,Hp,HpLim,CCCS,CurrentTSO,CurrentNursery
{- ,SparkHd,SparkTl,SparkBase,SparkLim -}
, BaseReg ]
regs_to_save = filter (callerSaves platform) system_regs
callerSaveGlobalReg reg
= mkStore (get_GlobalReg_addr dflags reg) (CmmReg (CmmGlobal reg))
callerRestoreGlobalReg reg
= mkAssign (CmmGlobal reg)
(CmmLoad (get_GlobalReg_addr dflags reg) (globalRegType dflags reg))
-- -----------------------------------------------------------------------------
-- Global registers
-- We map STG registers onto appropriate CmmExprs. Either they map
-- to real machine registers or stored as offsets from BaseReg. Given
-- a GlobalReg, get_GlobalReg_addr always produces the
-- register table address for it.
-- (See also get_GlobalReg_reg_or_addr in MachRegs)
get_GlobalReg_addr :: DynFlags -> GlobalReg -> CmmExpr
get_GlobalReg_addr dflags BaseReg = regTableOffset dflags 0
get_GlobalReg_addr dflags mid
= get_Regtable_addr_from_offset dflags
(globalRegType dflags mid) (baseRegOffset dflags mid)
-- Calculate a literal representing an offset into the register table.
-- Used when we don't have an actual BaseReg to offset from.
regTableOffset :: DynFlags -> Int -> CmmExpr
regTableOffset dflags n =
CmmLit (CmmLabelOff mkMainCapabilityLabel (oFFSET_Capability_r dflags + n))
get_Regtable_addr_from_offset :: DynFlags -> CmmType -> Int -> CmmExpr
get_Regtable_addr_from_offset dflags _rep offset =
if haveRegBase (targetPlatform dflags)
then CmmRegOff (CmmGlobal BaseReg) offset
else regTableOffset dflags offset
-- -----------------------------------------------------------------------------
-- Information about global registers
baseRegOffset :: DynFlags -> GlobalReg -> Int
baseRegOffset dflags Sp = oFFSET_StgRegTable_rSp dflags
baseRegOffset dflags SpLim = oFFSET_StgRegTable_rSpLim dflags
baseRegOffset dflags (LongReg 1) = oFFSET_StgRegTable_rL1 dflags
baseRegOffset dflags Hp = oFFSET_StgRegTable_rHp dflags
baseRegOffset dflags HpLim = oFFSET_StgRegTable_rHpLim dflags
baseRegOffset dflags CCCS = oFFSET_StgRegTable_rCCCS dflags
baseRegOffset dflags CurrentTSO = oFFSET_StgRegTable_rCurrentTSO dflags
baseRegOffset dflags CurrentNursery = oFFSET_StgRegTable_rCurrentNursery dflags
baseRegOffset dflags HpAlloc = oFFSET_StgRegTable_rHpAlloc dflags
baseRegOffset dflags GCEnter1 = oFFSET_stgGCEnter1 dflags
baseRegOffset dflags GCFun = oFFSET_stgGCFun dflags
baseRegOffset _ reg = pprPanic "baseRegOffset:" (ppr reg)
-------------------------------------------------------------------------
--
-- Strings generate a top-level data block
--
-------------------------------------------------------------------------
emitDataLits :: CLabel -> [CmmLit] -> FCode ()
-- Emit a data-segment data block
emitDataLits lbl lits = emitDecl (mkDataLits Data lbl lits)
emitRODataLits :: CLabel -> [CmmLit] -> FCode ()
-- Emit a read-only data block
emitRODataLits lbl lits = emitDecl (mkRODataLits lbl lits)
newStringCLit :: String -> FCode CmmLit
-- Make a global definition for the string,
-- and return its label
newStringCLit str = newByteStringCLit (map (fromIntegral . ord) str)
newByteStringCLit :: [Word8] -> FCode CmmLit
newByteStringCLit bytes
= do { uniq <- newUnique
; let (lit, decl) = mkByteStringCLit uniq bytes
; emitDecl decl
; return lit }
-------------------------------------------------------------------------
--
-- Assigning expressions to temporaries
--
-------------------------------------------------------------------------
assignTemp :: CmmExpr -> FCode LocalReg
-- Make sure the argument is in a local register.
-- We don't bother being particularly aggressive with avoiding
-- unnecessary local registers, since we can rely on a later
-- optimization pass to inline as necessary (and skipping out
-- on things like global registers can be a little dangerous
-- due to them being trashed on foreign calls--though it means
-- the optimization pass doesn't have to do as much work)
assignTemp (CmmReg (CmmLocal reg)) = return reg
assignTemp e = do { dflags <- getDynFlags
; uniq <- newUnique
; let reg = LocalReg uniq (cmmExprType dflags e)
; emitAssign (CmmLocal reg) e
; return reg }
newTemp :: CmmType -> FCode LocalReg
newTemp rep = do { uniq <- newUnique
; return (LocalReg uniq rep) }
newUnboxedTupleRegs :: Type -> FCode ([LocalReg], [ForeignHint])
-- Choose suitable local regs to use for the components
-- of an unboxed tuple that we are about to return to
-- the Sequel. If the Sequel is a join point, using the
-- regs it wants will save later assignments.
newUnboxedTupleRegs res_ty
= ASSERT( isUnboxedTupleType res_ty )
do { dflags <- getDynFlags
; sequel <- getSequel
; regs <- choose_regs dflags sequel
; ASSERT( regs `equalLength` reps )
return (regs, map primRepForeignHint reps) }
where
UbxTupleRep ty_args = repType res_ty
reps = [ rep
| ty <- ty_args
, let rep = typePrimRep ty
, not (isVoidRep rep) ]
choose_regs _ (AssignTo regs _) = return regs
choose_regs dflags _ = mapM (newTemp . primRepCmmType dflags) reps
-------------------------------------------------------------------------
-- emitMultiAssign
-------------------------------------------------------------------------
emitMultiAssign :: [LocalReg] -> [CmmExpr] -> FCode ()
-- Emit code to perform the assignments in the
-- input simultaneously, using temporary variables when necessary.
type Key = Int
type Vrtx = (Key, Stmt) -- Give each vertex a unique number,
-- for fast comparison
type Stmt = (LocalReg, CmmExpr) -- r := e
-- We use the strongly-connected component algorithm, in which
-- * the vertices are the statements
-- * an edge goes from s1 to s2 iff
-- s1 assigns to something s2 uses
-- that is, if s1 should *follow* s2 in the final order
emitMultiAssign [] [] = return ()
emitMultiAssign [reg] [rhs] = emitAssign (CmmLocal reg) rhs
emitMultiAssign regs rhss = do
dflags <- getDynFlags
ASSERT( equalLength regs rhss )
unscramble dflags ([1..] `zip` (regs `zip` rhss))
unscramble :: DynFlags -> [Vrtx] -> FCode ()
unscramble dflags vertices = mapM_ do_component components
where
edges :: [ (Vrtx, Key, [Key]) ]
edges = [ (vertex, key1, edges_from stmt1)
| vertex@(key1, stmt1) <- vertices ]
edges_from :: Stmt -> [Key]
edges_from stmt1 = [ key2 | (key2, stmt2) <- vertices,
stmt1 `mustFollow` stmt2 ]
components :: [SCC Vrtx]
components = stronglyConnCompFromEdgedVertices edges
-- do_components deal with one strongly-connected component
-- Not cyclic, or singleton? Just do it
do_component :: SCC Vrtx -> FCode ()
do_component (AcyclicSCC (_,stmt)) = mk_graph stmt
do_component (CyclicSCC []) = panic "do_component"
do_component (CyclicSCC [(_,stmt)]) = mk_graph stmt
-- Cyclic? Then go via temporaries. Pick one to
-- break the loop and try again with the rest.
do_component (CyclicSCC ((_,first_stmt) : rest)) = do
dflags <- getDynFlags
u <- newUnique
let (to_tmp, from_tmp) = split dflags u first_stmt
mk_graph to_tmp
unscramble dflags rest
mk_graph from_tmp
split :: DynFlags -> Unique -> Stmt -> (Stmt, Stmt)
split dflags uniq (reg, rhs)
= ((tmp, rhs), (reg, CmmReg (CmmLocal tmp)))
where
rep = cmmExprType dflags rhs
tmp = LocalReg uniq rep
mk_graph :: Stmt -> FCode ()
mk_graph (reg, rhs) = emitAssign (CmmLocal reg) rhs
mustFollow :: Stmt -> Stmt -> Bool
(reg, _) `mustFollow` (_, rhs) = regUsedIn dflags (CmmLocal reg) rhs
-------------------------------------------------------------------------
-- mkSwitch
-------------------------------------------------------------------------
emitSwitch :: CmmExpr -- Tag to switch on
-> [(ConTagZ, CmmAGraphScoped)] -- Tagged branches
-> Maybe CmmAGraphScoped -- Default branch (if any)
-> ConTagZ -> ConTagZ -- Min and Max possible values;
-- behaviour outside this range is
-- undefined
-> FCode ()
-- First, two rather common cases in which there is no work to do
emitSwitch _ [] (Just code) _ _ = emit (fst code)
emitSwitch _ [(_,code)] Nothing _ _ = emit (fst code)
-- Right, off we go
emitSwitch tag_expr branches mb_deflt lo_tag hi_tag = do
join_lbl <- newLabelC
mb_deflt_lbl <- label_default join_lbl mb_deflt
branches_lbls <- label_branches join_lbl branches
tag_expr' <- assignTemp' tag_expr
-- Sort the branches before calling mk_discrete_switch
let branches_lbls' = [ (fromIntegral i, l) | (i,l) <- sortBy (comparing fst) branches_lbls ]
let range = (fromIntegral lo_tag, fromIntegral hi_tag)
emit $ mk_discrete_switch False tag_expr' branches_lbls' mb_deflt_lbl range
emitLabel join_lbl
mk_discrete_switch :: Bool -- ^ Use signed comparisons
-> CmmExpr
-> [(Integer, BlockId)]
-> Maybe BlockId
-> (Integer, Integer)
-> CmmAGraph
-- SINGLETON TAG RANGE: no case analysis to do
mk_discrete_switch _ _tag_expr [(tag, lbl)] _ (lo_tag, hi_tag)
| lo_tag == hi_tag
= ASSERT( tag == lo_tag )
mkBranch lbl
-- SINGLETON BRANCH, NO DEFAULT: no case analysis to do
mk_discrete_switch _ _tag_expr [(_tag,lbl)] Nothing _
= mkBranch lbl
-- The simplifier might have eliminated a case
-- so we may have e.g. case xs of
-- [] -> e
-- In that situation we can be sure the (:) case
-- can't happen, so no need to test
-- SOMETHING MORE COMPLICATED: defer to CmmImplementSwitchPlans
-- See Note [Cmm Switches, the general plan] in CmmSwitch
mk_discrete_switch signed tag_expr branches mb_deflt range
= mkSwitch tag_expr $ mkSwitchTargets signed range mb_deflt (M.fromList branches)
divideBranches :: Ord a => [(a,b)] -> ([(a,b)], a, [(a,b)])
divideBranches branches = (lo_branches, mid, hi_branches)
where
-- 2 branches => n_branches `div` 2 = 1
-- => branches !! 1 give the *second* tag
-- There are always at least 2 branches here
(mid,_) = branches !! (length branches `div` 2)
(lo_branches, hi_branches) = span is_lo branches
is_lo (t,_) = t < mid
--------------
emitCmmLitSwitch :: CmmExpr -- Tag to switch on
-> [(Literal, CmmAGraphScoped)] -- Tagged branches
-> CmmAGraphScoped -- Default branch (always)
-> FCode () -- Emit the code
emitCmmLitSwitch _scrut [] deflt = emit $ fst deflt
emitCmmLitSwitch scrut branches deflt = do
scrut' <- assignTemp' scrut
join_lbl <- newLabelC
deflt_lbl <- label_code join_lbl deflt
branches_lbls <- label_branches join_lbl branches
dflags <- getDynFlags
let cmm_ty = cmmExprType dflags scrut
rep = typeWidth cmm_ty
-- We find the necessary type information in the literals in the branches
let signed = case head branches of
(MachInt _, _) -> True
(MachInt64 _, _) -> True
_ -> False
let range | signed = (tARGET_MIN_INT dflags, tARGET_MAX_INT dflags)
| otherwise = (0, tARGET_MAX_WORD dflags)
if isFloatType cmm_ty
then emit =<< mk_float_switch rep scrut' deflt_lbl noBound branches_lbls
else emit $ mk_discrete_switch
signed
scrut'
[(litValue lit,l) | (lit,l) <- branches_lbls]
(Just deflt_lbl)
range
emitLabel join_lbl
-- | lower bound (inclusive), upper bound (exclusive)
type LitBound = (Maybe Literal, Maybe Literal)
noBound :: LitBound
noBound = (Nothing, Nothing)
mk_float_switch :: Width -> CmmExpr -> BlockId
-> LitBound
-> [(Literal,BlockId)]
-> FCode CmmAGraph
mk_float_switch rep scrut deflt _bounds [(lit,blk)]
= do dflags <- getDynFlags
return $ mkCbranch (cond dflags) deflt blk Nothing
where
cond dflags = CmmMachOp ne [scrut, CmmLit cmm_lit]
where
cmm_lit = mkSimpleLit dflags lit
ne = MO_F_Ne rep
mk_float_switch rep scrut deflt_blk_id (lo_bound, hi_bound) branches
= do dflags <- getDynFlags
lo_blk <- mk_float_switch rep scrut deflt_blk_id bounds_lo lo_branches
hi_blk <- mk_float_switch rep scrut deflt_blk_id bounds_hi hi_branches
mkCmmIfThenElse (cond dflags) lo_blk hi_blk
where
(lo_branches, mid_lit, hi_branches) = divideBranches branches
bounds_lo = (lo_bound, Just mid_lit)
bounds_hi = (Just mid_lit, hi_bound)
cond dflags = CmmMachOp lt [scrut, CmmLit cmm_lit]
where
cmm_lit = mkSimpleLit dflags mid_lit
lt = MO_F_Lt rep
--------------
label_default :: BlockId -> Maybe CmmAGraphScoped -> FCode (Maybe BlockId)
label_default _ Nothing
= return Nothing
label_default join_lbl (Just code)
= do lbl <- label_code join_lbl code
return (Just lbl)
--------------
label_branches :: BlockId -> [(a,CmmAGraphScoped)] -> FCode [(a,BlockId)]
label_branches _join_lbl []
= return []
label_branches join_lbl ((tag,code):branches)
= do lbl <- label_code join_lbl code
branches' <- label_branches join_lbl branches
return ((tag,lbl):branches')
--------------
label_code :: BlockId -> CmmAGraphScoped -> FCode BlockId
-- label_code J code
-- generates
-- [L: code; goto J]
-- and returns L
label_code join_lbl (code,tsc) = do
lbl <- newLabelC
emitOutOfLine lbl (code MkGraph.<*> mkBranch join_lbl, tsc)
return lbl
--------------
assignTemp' :: CmmExpr -> FCode CmmExpr
assignTemp' e
| isTrivialCmmExpr e = return e
| otherwise = do
dflags <- getDynFlags
lreg <- newTemp (cmmExprType dflags e)
let reg = CmmLocal lreg
emitAssign reg e
return (CmmReg reg)
| AlexanderPankiv/ghc | compiler/codeGen/StgCmmUtils.hs | bsd-3-clause | 22,985 | 0 | 15 | 5,429 | 4,876 | 2,592 | 2,284 | -1 | -1 |
-- -----------------------------------------------------------------------------
-- |
-- Module : Text.IPv6Addr
-- Copyright : Copyright © Michel Boucey 2011-2015
-- License : BSD-Style
-- Maintainer : [email protected]
--
-- Dealing with IPv6 address text representations, canonization and manipulations.
--
-- -----------------------------------------------------------------------------
{-# LANGUAGE OverloadedStrings #-}
module QC.IPv6.Internal where {-
( expandTokens
, macAddr
, maybeIPv6AddrTokens
, ipv4AddrToIPv6AddrTokens
, ipv6TokensToText
, ipv6TokensToIPv6Addr
, isIPv6Addr
, maybeTokIPv6Addr
, maybeTokPureIPv6Addr
, fromDoubleColon
, fromIPv6Addr
, toDoubleColon
) where -}
import Debug.Trace
import Control.Monad (replicateM)
import Data.Attoparsec.Text
import Data.Char (isDigit,isHexDigit,toLower)
import Data.Monoid ((<>))
import Control.Applicative ((<|>),(<*))
import Data.List (group,isSuffixOf,elemIndex,elemIndices,intersperse)
import Data.Word (Word32)
import Numeric (showHex)
import qualified Data.Text as T
import qualified Data.Text.Read as R (decimal)
import Data.Maybe (fromJust)
import QC.IPv6.Types
tok0 = "0"
-- | Returns the 'T.Text' of an IPv6 address.
fromIPv6Addr :: IPv6Addr -> T.Text
fromIPv6Addr (IPv6Addr t) = t
-- | Given an arbitrary list of 'IPv6AddrToken', returns the corresponding 'T.Text'.
ipv6TokensToText :: [IPv6AddrToken] -> T.Text
ipv6TokensToText l = T.concat $ map ipv6TokenToText l
-- | Returns the corresponding 'T.Text' of an IPv6 address token.
ipv6TokenToText :: IPv6AddrToken -> T.Text
ipv6TokenToText (SixteenBit s) = s
ipv6TokenToText Colon = ":"
ipv6TokenToText DoubleColon = "::"
ipv6TokenToText AllZeros = tok0 -- "A single 16-bit 0000 field MUST be represented as 0" (RFC 5952, 4.1)
ipv6TokenToText (IPv4Addr a) = a
-- | Returns 'True' if a list of 'IPv6AddrToken' constitutes a valid IPv6 Address.
isIPv6Addr :: [IPv6AddrToken] -> Bool
isIPv6Addr [] = False
isIPv6Addr [DoubleColon] = True
isIPv6Addr [DoubleColon,SixteenBit tok1] = True
isIPv6Addr tks =
diffNext tks && (do
let cdctks = countDoubleColon tks
let lentks = length tks
let lasttk = last tks
let lenconst = (lentks == 15 && cdctks == 0) || (lentks < 15 && cdctks == 1)
firstValidToken tks &&
(case countIPv4Addr tks of
0 -> case lasttk of
SixteenBit _ -> lenconst
DoubleColon -> lenconst
AllZeros -> lenconst
_ -> False
1 -> case lasttk of
IPv4Addr _ -> (lentks == 13 && cdctks == 0) || (lentks < 12 && cdctks == 1)
_ -> False
otherwise -> False))
where diffNext [] = False
diffNext [_] = True
diffNext (t:ts) = do
let h = head ts
case t of
SixteenBit _ -> case h of
SixteenBit _ -> False
AllZeros -> False
_ -> diffNext ts
AllZeros -> case h of
SixteenBit _ -> False
AllZeros -> False
_ -> diffNext ts
_ -> diffNext ts
firstValidToken l =
case head l of
SixteenBit _ -> True
DoubleColon -> True
AllZeros -> True
_ -> False
countDoubleColon l = length $ elemIndices DoubleColon l
tok1 = "1"
countIPv4Addr = foldr oneMoreIPv4Addr 0
where
oneMoreIPv4Addr t c = case t of
IPv4Addr _ -> c + 1
otherwise -> c
-- | This is the main function which returns 'Just' the list of a tokenized IPv6
-- address text representation validated against RFC 4291 and canonized
-- in conformation with RFC 5952, or 'Nothing'.
maybeTokIPv6Addr :: T.Text -> Maybe [IPv6AddrToken]
maybeTokIPv6Addr t =
case maybeIPv6AddrTokens t of
Just ltks -> if isIPv6Addr ltks
then Just $ (ipv4AddrReplacement . toDoubleColon . fromDoubleColon) ltks
else Nothing
Nothing -> Nothing
where
ipv4AddrReplacement ltks =
if ipv4AddrRewrite ltks
then init ltks ++ ipv4AddrToIPv6AddrTokens (last ltks)
else ltks
-- | Returns 'Just' the list of tokenized pure IPv6 address, always rewriting an
-- embedded IPv4 address if present.
maybeTokPureIPv6Addr :: T.Text -> Maybe [IPv6AddrToken]
maybeTokPureIPv6Addr t = do
ltks <- maybeIPv6AddrTokens t
if isIPv6Addr ltks
then Just $ (toDoubleColon . ipv4AddrReplacement . fromDoubleColon) ltks
else Nothing
where
ipv4AddrReplacement ltks' = init ltks' ++ ipv4AddrToIPv6AddrTokens (last ltks')
-- | Tokenize a 'T.Text' into 'Just' a list of 'IPv6AddrToken', or 'Nothing'.
maybeIPv6AddrTokens :: T.Text -> Maybe [IPv6AddrToken]
maybeIPv6AddrTokens s =
case readText s of
Done r l -> traceShow (r,l) $ if r==T.empty then Just l else Nothing
Fail {} -> Nothing
where
readText s = feed (parse (many1 $ ipv4Addr <|> sixteenBit <|> doubleColon <|> colon) s) T.empty
-- | An embedded IPv4 address have to be rewritten to output a pure IPv6 Address
-- text representation in hexadecimal digits. But some well-known prefixed IPv6
-- addresses have to keep visible in their text representation the fact that
-- they deals with IPv4 to IPv6 transition process (RFC 5952 Section 5):
--
-- IPv4-compatible IPv6 address like "::1.2.3.4"
--
-- IPv4-mapped IPv6 address like "::ffff:1.2.3.4"
--
-- IPv4-translated address like "::ffff:0:1.2.3.4"
--
-- IPv4-translatable address like "64:ff9b::1.2.3.4"
--
-- ISATAP address like "fe80::5efe:1.2.3.4"
--
ipv4AddrRewrite :: [IPv6AddrToken] -> Bool
ipv4AddrRewrite tks =
case last tks of
IPv4Addr _ -> do
let itks = init tks
not (itks == [DoubleColon]
|| itks == [DoubleColon,SixteenBit tokffff,Colon]
|| itks == [DoubleColon,SixteenBit tokffff,Colon,AllZeros,Colon]
|| itks == [SixteenBit "64",Colon,SixteenBit "ff9b",DoubleColon]
|| [SixteenBit "200",Colon,SixteenBit tok5efe,Colon] `isSuffixOf` itks
|| [AllZeros,Colon,SixteenBit tok5efe,Colon] `isSuffixOf` itks
|| [DoubleColon,SixteenBit tok5efe,Colon] `isSuffixOf` itks)
_ -> False
where
tokffff = "ffff"
tok5efe = "5efe"
-- | Rewrites an embedded 'IPv4Addr' into the corresponding list of pure 'IPv6Addr' tokens.
--
-- > ipv4AddrToIPv6AddrTokens (IPv4Addr "127.0.0.1") == [SixteenBits "7f0",Colon,SixteenBits "1"]
--
ipv4AddrToIPv6AddrTokens :: IPv6AddrToken -> [IPv6AddrToken]
ipv4AddrToIPv6AddrTokens t =
case t of
IPv4Addr a -> do
let m = toHex a
[ SixteenBit ((!!) m 0 <> addZero ((!!) m 1))
, Colon
, SixteenBit ((!!) m 2 <> addZero ((!!) m 3)) ]
_ -> [t]
where
toHex a = map (\x -> T.pack $ showHex (read (T.unpack x)::Int) "") $ T.split (=='.') a
addZero d = if T.length d == 1 then tok0 <> d else d
expandTokens :: [IPv6AddrToken] -> [IPv6AddrToken]
expandTokens = map expandToken
where expandToken (SixteenBit s) = SixteenBit $ T.justifyRight 4 '0' s
expandToken AllZeros = SixteenBit "0000"
expandToken t = t
fromDoubleColon :: [IPv6AddrToken] -> [IPv6AddrToken]
fromDoubleColon tks =
if DoubleColon `notElem` tks
then tks
else do let s = splitAt (fromJust $ elemIndex DoubleColon tks) tks
let fsts = fst s
let snds = if not (null (snd s)) then tail(snd s) else []
let fste = if null fsts then [] else fsts ++ [Colon]
let snde = if null snds then [] else Colon : snds
fste ++ allZerosTokensReplacement(quantityOfAllZerosTokenToReplace tks) ++ snde
where
allZerosTokensReplacement x = intersperse Colon (replicate x AllZeros)
quantityOfAllZerosTokenToReplace x =
ntks tks - foldl (\c x -> if (x /= DoubleColon) && (x /= Colon) then c+1 else c) 0 x
where
ntks tks = if countIPv4Addr tks == 1 then 7 else 8
toDoubleColon :: [IPv6AddrToken] -> [IPv6AddrToken]
toDoubleColon tks =
zerosToDoubleColon tks (zerosRunToReplace $ zerosRunsList tks)
where
zerosToDoubleColon :: [IPv6AddrToken] -> (Int,Int) -> [IPv6AddrToken]
-- No all zeros token, so no double colon replacement...
zerosToDoubleColon ls (_,0) = ls
-- "The symbol '::' MUST NOT be used to shorten just one 16-bit 0 field" (RFC 5952 4.2.2)
zerosToDoubleColon ls (_,1) = ls
zerosToDoubleColon ls (i,l) =
let ls' = filter (/= Colon) ls
in intersperse Colon (Prelude.take i ls') ++ [DoubleColon] ++ intersperse Colon (drop (i+l) ls')
zerosRunToReplace t =
let l = longestLengthZerosRun t
in (firstLongestZerosRunIndex t l,l)
where
firstLongestZerosRunIndex x y = sum . snd . unzip $ Prelude.takeWhile (/=(True,y)) x
longestLengthZerosRun x =
maximum $ map longest x
where longest t = case t of
(True,i) -> i
_ -> 0
zerosRunsList x = map helper $ groupZerosRuns x
where
helper h = (head h == AllZeros, lh) where lh = length h
groupZerosRuns = group . filter (/= Colon)
ipv6TokensToIPv6Addr :: [IPv6AddrToken] -> Maybe IPv6Addr
ipv6TokensToIPv6Addr l = Just $ IPv6Addr $ ipv6TokensToText l
fullSixteenBit :: T.Text -> Maybe IPv6AddrToken
fullSixteenBit t =
case parse ipv6AddrFullChunk t of
Done a b -> if a==T.empty then Just $ SixteenBit $ T.pack b else Nothing
_ -> Nothing
macAddr :: Parser (Maybe [IPv6AddrToken])
macAddr = do
n1 <- count 2 hexaChar <* ":"
n2 <- count 2 hexaChar <* ":"
n3 <- count 2 hexaChar <* ":"
n4 <- count 2 hexaChar <* ":"
n5 <- count 2 hexaChar <* ":"
n6 <- count 2 hexaChar
return $ maybeIPv6AddrTokens $ T.pack $ concat [n1,n2,n3,n4,n5,n6]
sixteenBit :: Parser IPv6AddrToken
sixteenBit = do
r <- ipv6AddrFullChunk <|> count 3 hexaChar <|> count 2 hexaChar <|> count 1 hexaChar
-- "Leading zeros MUST be suppressed" (RFC 5952, 4.1)
let r' = T.dropWhile (=='0') $ T.pack r
return $ if T.null r'
then AllZeros
-- Hexadecimal digits MUST be in lowercase (RFC 5952 4.3)
else SixteenBit $ T.toLower r'
ipv4Addr :: Parser IPv6AddrToken
ipv4Addr = do
n1 <- manyDigits <* "."
if n1 /= T.empty
then do n2 <- manyDigits <* "."
if n2 /= T.empty
then do n3 <- manyDigits <* "."
if n3 /= T.empty
then do n4 <- manyDigits
if n4 /= T.empty
then return $ IPv4Addr $ T.intercalate "." [n1,n2,n3,n4]
else parserFailure
else parserFailure
else parserFailure
else parserFailure
where
parserFailure = fail "ipv4Addr parsing failure"
manyDigits = do
ds <- takeWhile1 isDigit
case R.decimal ds of
Right (n,_) -> return (if n < 256 then T.pack $ show n else T.empty)
Left _ -> return T.empty
doubleColon :: Parser IPv6AddrToken
doubleColon = do
string "::"
return DoubleColon
colon :: Parser IPv6AddrToken
colon = do
string ":"
return Colon
ipv6AddrFullChunk :: Parser String
ipv6AddrFullChunk = count 4 hexaChar
hexaChar :: Parser Char
hexaChar = satisfy (inClass "0-9a-fA-F")
| beni55/attoparsec | tests/QC/IPv6/Internal.hs | bsd-3-clause | 12,259 | 0 | 25 | 3,915 | 3,059 | 1,588 | 1,471 | 219 | 18 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -Wincomplete-patterns #-}
module Bug where
import Data.Type.Equality
data G a where
GInt :: G Int
GBool :: G Bool
ex1, ex2, ex3
:: a :~: Int
-> G a
-> ()
ex1 Refl g
| GInt <- id g
= ()
ex2 Refl g
| GInt <- g
= ()
ex3 Refl g
= case id g of
GInt -> ()
| sdiehl/ghc | testsuite/tests/pmcheck/should_compile/T15753a.hs | bsd-3-clause | 354 | 0 | 9 | 105 | 132 | 70 | 62 | 21 | 1 |
module SplitAt2 where
{- splitIt n xs = splitAt (n - 1) xs -}
splitIt n xs = case (n-1, xs) of
(0, xs) -> ("", xs)
(_, "") -> ("","")
(m, (x:xs)) -> (x:xs', xs'')
where (xs', xs'') = splitAt (m-1) xs
{- this time the where is bound to the case alternative
and thus m is in scope... -}
{- splitIt 0 xs = ("", xs)
splitIt _ xs@("") = (xs, xs)
splitIt m (x:xs) = (x:xs', xs'')
where
(xs', xs'') = splitAt (m - 1) xs -} | kmate/HaRe | old/testing/generativeFold/SplitAtIn2.hs | bsd-3-clause | 507 | 0 | 12 | 181 | 122 | 72 | 50 | 6 | 3 |
{-# LANGUAGE PatternSynonyms #-}
module PolyPat where
-- Testing whether type changing updates work correctly.
pattern MyTuple :: a -> b -> (a, b)
pattern MyTuple{mfst, msnd} = (mfst, msnd)
expr1 :: (Int, String) -> (Int, Int)
expr1 a = a { msnd = 2}
expr3 a = a { msnd = 2}
expr2 :: (a, b) -> a
expr2 a = mfst a
| snoyberg/ghc | testsuite/tests/patsyn/should_compile/records-poly.hs | bsd-3-clause | 319 | 0 | 8 | 70 | 129 | 75 | 54 | 9 | 1 |
-- (c) Florian Mayer <[email protected]> under the ISC license.
-- See COPYING for more details.
dividesany ns x = any (\y -> rem x y == 0) ns
main = print (sum (filter (dividesany [3, 5]) [1..999]))
| derdon/euler-solutions | 1/1.hs | isc | 201 | 0 | 12 | 38 | 74 | 39 | 35 | 2 | 1 |
module Extras.Data.Time.Calendar where
import Data.Time.Calendar
dateValid :: Integer -> Int -> Int -> Bool
dateValid y m d = case fromGregorianValid y m d of
Nothing -> False
Just _ -> True
| fredmorcos/attic | projects/pet/archive/pet_haskell_modular_1/Extras/Data/Time/Calendar.hs | isc | 198 | 0 | 8 | 39 | 69 | 37 | 32 | 6 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module Y2020.M12.D10.Solution where
{--
Okay, I have a confession to make.
I cheated.
I said, yesterday, that there were unicode-issues and today we would address
them so we could realign the alliances from the aliased-countries to the
source ones.
Well, the only unicode issue was with one country, and how do we* refer to that
country? As its name in unicode? No. So, I renamed the country, then ran
yesterday's code, and it worked.
The code to fix the problem is as follows:
MATCH (c:Country) WHERE "Sao Tome and Principe" in c.aliases
SET c.aliases = ["São Tomé and Príncipe"], c.name = "Sao Tome and Principe"
RETURN c
Run this fix, then run yesterday's solution.
Up to date now? Great!
Today, we're going to remove the Alliance relations from the aliased countries.
First, we need to get those now-redundant relations. But we already did that:
yesterday.
--}
import Control.Arrow ((&&&))
import qualified Data.Map as Map
import Data.Maybe (mapMaybe)
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Text (Text)
import qualified Data.Text as T
import Data.Relation
import Graph.Query
import Graph.JSON.Cypher
import Graph.JSON.Cypher.Read.Rows (TableRow)
import qualified Graph.JSON.Cypher.Read.Rows as RR
import Y2020.M10.D28.Solution (Name)
import Y2020.M11.D17.Solution (CapAt, CapAt(CAPITAL))
import Y2020.M12.D01.Solution (Country, Country(Country))
import Y2020.M12.D09.Solution (Alias, AliasCountryMap)
import qualified Y2020.M12.D09.Solution as AA -- for aliased alliances
{--
>>> graphEndpoint
...
>>> let url = it
>>> getGraphResponse url [AA.fetchAliasedAlliances]
...
>>> let aaq = it
>>> let aas = AA.aliasedAlliances $ map (AA.toAliasAlliance . RR.row) (RR.justRows aaq)
>>> Map.size aas
29
... and there they are. So we can delete them now, by writing more Haskell?
Well, that was the plan, but, hark! When is writing external functionality
to a database good, and when is it not? There are differing opinions on this,
but mine is that if you needuto do several (serial) things, like: moving
relations from aliases to source countries, THEN deleting those original
relations, then yes, do those multiple steps programatically.
But.
If we're just deleting relations, let's ... just delete the relations.
MATCH (c:Country)<-[r:MEMBER_OF]-(d:Alliance)
WHERE not (c)-[:IN]->(:Continent)
DELETE r
Boom! Done! ... with pics! (see pic; this directory)
Okay, now that we did (didn't) today's Haskell problem (deleting aliased
alliance relations), let's do a new problem for today.
How many aliased alliances have capitals related to them?
--}
capitalQuery :: Cypher
capitalQuery =
T.concat ["MATCH p=(c:Country)-[:CAPITAL]-(c1:Capital) ",
"WHERE not (:Continent)--(c) ",
"RETURN c.name as country, c1.name as capital"]
{--
returns the following:
country capital
-----------------------------------------------------------
"People's Republic of China" "Beijing"
"Saint Helena, Ascension and Tristan da Cunha" "Jamestown"
"Yugoslavia" "Belgrade"
Recall that we're ignoring the two countries of Saint Helena, Ascension and
Tristan da Cunha, and Yugoslavia. (Yes, two countries. One country, the first
one, has three countries in its one country.)
We also see that the country China does not have a capital.* Let's move the
aliased capital to China, using the same approach as to yesterday.
* I say 'China' ... the other countries will fall out of the wash. Whatevs.
--}
data AliasedCapital = AC { alias :: Text, capital :: Text }
deriving (Eq, Ord, Show)
toAliasedCapital :: [Text] -> AliasedCapital
toAliasedCapital = AC . head <*> last
{--
>>> getGraphResponse url [capitalQuery]
...
>>> let cq = it
>>> let ccs = map (toAliasedCapital . RR.row) $ RR.justRows cq
>>> ccs
[AC {alias = "People's Republic of China", capital = "Beijing"},
AC {alias = "Saint Helena, Ascension and Tristan da Cunha", capital = "Jamestown"},
AC {alias = "Yugoslavia", capital = "Belgrade"}]
Now, for these aliased countries, we need the source countries. The query
is different than yesterday's however.
--}
aliasCountryQuery :: Cypher
aliasCountryQuery =
T.concat ["MATCH (c:Country)--(:Capital) ",
"WHERE NOT (c)--(:Continent) ",
"WITH c.name as alias ",
"MATCH (c1:Country) ",
"WHERE alias in c1.aliases ",
"RETURN alias, c1.name as country"]
-- with the above query, we can get to our AliasCountryMap
{--
>>> getGraphResponse url [aliasCountryQuery]
{"results":[{"columns":["alias","country"],"data":[
{"row":["People's Republic of China","China"],"meta":[null,null]}]}],
"errors":[]}
... not much of a map, but hey! Like I said: the other countries dropped out.
>>> let acq = it
>>> let acm = AA.toAliasCountry $ map RR.row (RR.justRows acq)
>>> acm
fromList [("People's Republic of China",Country {country = "China"})]
As was yesterday, so today: we copy the relation of the aliased capital to
the source country. We can leverage the work we did in Y2020.M11.D17.Solution.
--}
data Capital = Capital Name
deriving (Eq, Ord, Show)
instance Node Capital where
asNode (Capital c) = constr "Capital" [("name", c)]
type RelCountryCapital = Relation Country CapAt Capital
relinkCapitals :: AliasCountryMap -> AliasedCapital -> Maybe RelCountryCapital
relinkCapitals acm alicap =
mkRelink (Capital $ capital alicap) <$> Map.lookup (alias alicap) acm
mkRelink :: Capital -> Country -> RelCountryCapital
mkRelink cap country = Rel country CAPITAL cap
{--
>>> let rels = mapMaybe (relinkCapitals acm) ccs
>>> rels
[Rel (Country {country = "China"}) CAPITAL (Capital "Beijing")]
>>> cyphIt url rels
"{\"results\":[{\"columns\":[],\"data\":[]}],\"errors\":[]}"
Yay! Now we can delete this relation from PRC, ...
MATCH p=(c:Country)-[r:CAPITAL]-(d:Capital)
WHERE d.name = "Beijing"
AND NOT ()-->(c)
DELETE r
... and also delete singleton nodes with:
--}
singletonNodesQuery :: Cypher
singletonNodesQuery =
"MATCH (c) WHERE NOT ()-->(c) AND NOT (c)-->() RETURN c.name"
{--
>>> getGraphResponse url [singletonNodesQuery]
>>> let qer = it
>>> let strs = (RR.justRows qer) :: [TableRow [String]]
>>> let singies = Set.fromList (map (head . RR.row) strs)
>>> Set.size singies
30
... (30 country (aliases) returned)
Are all these nodes found somewhere? Let's see:
--}
countriesWithAliasesQuery :: Cypher
countriesWithAliasesQuery =
T.concat ["MATCH (c) ",
"WHERE NOT ()-->(c) ",
"AND NOT (c)-->() ",
"WITH c.name AS alias ",
"MATCH (q:Country) WHERE alias IN q.aliases ",
"RETURN alias, q.name AS country"]
{--
>>> getGraphResponse url [countriesWithAliasesQuery]
...
>>> let mac = it
>>> let macr = (RR.justRows mac) :: [TableRow [String]]
>>> let macm = Map.fromList (map ((head &&& last) . RR.row) macr)
>>> Map.size macm
28
>>> Set.difference singies (Map.keysSet macm)
fromList ["Ansarullah","Hezbollah"]
Which is fine, because those 'countries' are not countries.
So now we can delete the singleton nodes with:
MATCH (c) WHERE NOT ()-->(c) AND NOT (c)-->() DELETE c
When we execute that Cypher against the graph store, our query:
>>> getGraphResponse url [singletonNodesQuery]
"{\"results\":[{\"columns\":[\"c.name\"],\"data\":[]}],\"errors\":[]}"
... now returns the empty set of nodes.
Mission accomplished.
--}
{-- BONUS -------------------------------------------------------
This all begs the question of our graph:
Which countries-in-alliances have capitals? And which ones do not?
With the countries that do not have capitals, can we populate that information?
How?
The query to see which countries-in-alliances that do not have capitals is:
--}
noCAPSquery :: Cypher
noCAPSquery =
T.concat ["MATCH (a:Alliance)--(c:Country) ",
"WHERE not (c)--(:Capital) ",
"RETURN DISTINCT c.name"]
{--
Write a Haskell function that extracts that information from the graph
data-store.
--}
capitalless :: Endpoint -> Cypher -> IO (Set Name)
capitalless url cyph =
getGraphResponse url [cyph] >>= \resp ->
let ncq = (RR.justRows resp) :: [TableRow [Text]] in
return . Set.fromList $ map (head . RR.row) ncq
{--
>>> capitalless url noCAPSquery
{"Albania","Angola","Antigua and Barbuda","Armenia","Austria","Bangladesh",
"Barbados","Belize","Benin","Botswana","Brazil","Brunei","Burkina Faso",
"Burundi","Cambodia","Cameroon","Cape Verde","Central African Republic",
"Colombia","Comoros","Costa Rica","Cuba","Cyprus","Dominica","East Timor",
"Equatorial Guinea","Gabon","Ghana","Grenada","Guatemala","Guine","Guinea",
"Guinea-Bissau","Guyana","Haiti","Iceland","Italy","Jamaica","Japan","Kenya",
"Laos","Lesotho","Liberia","Luxembourg","Malawi","Maldives","Mali","Malta",
"Mauritania","Mauritius","Moldova","Mongolia","Montenegro","Montserrat",
"Morocco","Mozambique","Namibia","Netherlands","Nicaragua","Nigeria",
"Palestine","Paraguay","Republic of Ireland","Republic of the Congo","Rwanda",
"Saint Kitts and Nevis","Saint Lucia","Saint Vincent and the Grenadines",
"Senegal","Seychelles","Sierra Leone","Singapore","Slovenia","Somalia",
"South Sudan","Spain","Suriname","Swaziland (Eswatini)","Tajikistan",
"The Bahamas","The Gambia","Togo","Trinidad and Tobago","Uganda",
"Western Sahara","Yemen","Zambia"]
>>> Set.size it
87
Oh, dear me!
Also. I just realized something that saddened me. Y2020.M11.D17.Solution
had the lat/long data of capitals, but I did not load that information
to the graph store, but, instead, dropped the lat/longs on the floor.
Guess what we're doing tomorrow? le sigh.
--}
| geophf/1HaskellADay | exercises/HAD/Y2020/M12/D10/Solution.hs | mit | 9,671 | 0 | 13 | 1,584 | 651 | 387 | 264 | 67 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
#if __GLASGOW_HASKELL__ < 710
{-# LANGUAGE OverlappingInstances #-}
#endif
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
{-# OPTIONS_HADDOCK show-extensions #-}
{-|
Module : Control.Hspl.Internal.Debugger
Description : An interactive debugger for HSPL programs.
Stability : Internal
This module implements an interactive debugger for HSPL programs. The debugger hooks into the HSPL
prover using the 'MonadSolver' framework, and provides several commands for navigating through an
HSPL program.
-}
module Control.Hspl.Internal.Debugger (
-- * Commands
Command (..)
, debugHelp
, parseCommand
, getCommand
, runCommand
, repl
, prompt
-- * State
, MsgType (..)
, Target (..)
, DebugContext (..)
, TerminalState (..)
-- * Control flow
-- | The complete debugger is composed of two cooperating coroutines. One routine controls the
-- interactive terminal. It prompts the user for commands, processes them, and displays the output
-- to the user. Whenever the user enters a command which should cause exectution to continue (e.g.
-- 'Step' or 'Next') the terminal routine yields control to the second coroutine.
--
-- The second coroutine runs the HSPL solver, attempting to produce a proof of the given goal. At
-- each step of the computation (e.g. calling a subgoal or returning from a proof) the solver
-- yields control back to the terminal coroutine and passes it some context about the current
-- state of the computation. The terminal then decides whether to prompt the user or to continue
-- the solve.
, DebugStateT
, runDebugStateT
, TerminalCoroutine
, terminalCoroutine
, SolverCoroutine
, solverCoroutine
, DebugSolverT
-- * Entry points
, debug
) where
import Control.Applicative hiding ((<|>))
import Control.Monad.Coroutine
import Control.Monad.Coroutine.SuspensionFunctors hiding (yield)
import qualified Control.Monad.Coroutine.SuspensionFunctors as CR
import Control.Monad.Identity
import Control.Monad.State
import Data.Char
import Data.List
import Data.Maybe
import System.Console.ANSI
import System.Console.Haskeline
import Text.Parsec hiding (Error, tokens)
import Control.Hspl.Internal.Ast
import Control.Hspl.Internal.Logic
import Control.Hspl.Internal.Solver
import Control.Hspl.Internal.Tuple
import Control.Hspl.Internal.UI
import Control.Hspl.Internal.Unification (MonadVarGenerator, MonadUnification (..), munify)
import Control.Hspl.Internal.VarMap (for_)
-- | The available debugger commands.
data Command =
-- | Continue execution until the next event (predicate call, failure, or exit).
Step
-- | Continue execution until the next event involving the current goal, skipping past any
-- subgoals.
| Next
-- | Continue execution until the next event in the parent goal.
| Finish
-- | Continue execution until the next breakpoint.
| Continue
-- | Set a breakpoint on a predicate, specified by name.
| SetBreakpoint String
-- | Delete a breakpoint, specified either by name or by the index associated with that
-- breakpoint in 'InfoBreakpoints'.
| DeleteBreakpoint (Either String Int)
-- | Show the currently set breakpoints.
| InfoBreakpoints
-- | Print out the current goal stack.
| InfoStack (Maybe Int)
-- | Print a usage message.
| Help
deriving (Show, Eq)
-- | A usage message describing the various commands offered by the debugger.
debugHelp :: String
debugHelp = intercalate "\n"
["s, step: proceed one predicate call"
,"n, next: proceed to the next call, failure, or exit at this level"
,"f, finish: proceed to the exit or failure of the current goal"
,"c, continue: proceed to the next breakpoint"
,"b, break <predicate>: set a breakpoint to stop execution when calling a predicate with the"
," given name"
,"db, delete-breakpoint <breakpoint>: remove a breakpoint previously created via break. The"
," breakpoint to delete can be specified by the same string passed to break, or by the"
," breakpoint index listed in breakpoints"
,"bs, breakpoints: list currently enabled breakpoints"
,"gs, goals [N]: print the most recent N goals from the goal stack, or all goals if no N is given"
,"g, goal: print the current goal (equivalent to 'goals 1')"
,"?, h, help: show this help"
, "<return>: replay last command"
]
-- | Descriptor of the next event at which to stop execution and prompt the user for a command.
data Target =
-- | Stop at any event with debug hooks
Any
-- | Stop at an event occuring at a depth less than or equal to the specified depth.
| Depth Int
-- | Stop when calling a predicate matching a breakpoint
| Breakpoint
-- | The various events which trigger debug messages.
data MsgType = Call | Redo | Exit | Fail | Error
deriving (Show, Eq)
-- | Mapping from events ('MsgType') to 'SGR' commands which set the console color.
msgColor :: MsgType -> SGR
msgColor Call = SetColor Foreground Vivid Green
msgColor Redo = SetColor Foreground Vivid Yellow
msgColor Exit = SetColor Foreground Vivid Green
msgColor Fail = SetColor Foreground Vivid Red
msgColor Error = SetColor Foreground Vivid Red
setColor :: SGR -> TerminalCoroutine ()
setColor color = do
istty <- liftHL haveTerminalUI
when istty $ liftIO $ setSGR [color]
resetColor :: TerminalCoroutine ()
resetColor = do
istty <- liftHL haveTerminalUI
when istty $ liftIO $ setSGR []
-- | Description of the current status of an HSPL computation.
data DebugContext = DC {
-- | The current 'Goal' stack. During a computation, this stack will always
-- be nonempty. The front of the stack is the 'Goal' currently being worked
-- on; the back of the stack is the top-level 'Goal' specified by the user
-- who invoked the debugger.
stack :: [Goal]
-- | The type of event which triggered this context dump.
, status :: MsgType
-- | Some arbitrary text associated with the event.
, msg :: String
}
-- | State maintained by the debugger during execution.
data TerminalState = Terminal {
-- | Descriptor of the next event at which to stop execution and prompt the
-- user for a command.
currentTarget :: Target
-- | The last command issued by the user.
, lastCommand :: Command
-- | List of predicates which we should stop at when running until a
-- breakpoint.
, breakpoints :: [String]
}
-- | Monad transformer which encapsulates the state required by the interactive terminal.
type DebugStateT = StateT TerminalState
-- | Evaluate a compuation in the 'DebugStateT' monad, returning a computation in the underlying
-- monad.
runDebugStateT :: (MonadException m, MonadIO m) => DebugStateT m a -> m a
runDebugStateT m = evalStateT m Terminal { currentTarget = Any
, lastCommand = Step
, breakpoints = []
}
-- | Monad which runs the interactive debugger terminal. It maintains some state, and performs
-- computations in the 'IO' monad. At certain times, it yields control to the calling routine, which
-- should run one step of the computation and then pass control back to the terminal, along with
-- some context about the current state of the computation or a final result.
type TerminalCoroutine =
Coroutine (Await (Maybe (Either DebugContext ProofResult))) (DebugStateT (InputT IO))
liftHL :: InputT IO a -> TerminalCoroutine a
liftHL = lift.lift
-- | Monad transformer which runs an HSPL program, yielding control and context at each important
-- step of the computation.
type SolverCoroutine m = Coroutine (Yield (Either DebugContext ProofResult)) m
-- | State maintained by the solver coroutine.
data SolverState = Solver {
-- | The current goal stack. @head goalStack@ is the current goal,
-- @goalStack !! 1@ is the parent of that goal, and so on, so that
-- @last goalStack@ is the top-level goal we are ultimately trying to prove.
goalStack :: [Goal]
}
instance SplittableState SolverState where
type BacktrackingState SolverState = [Goal]
type GlobalState SolverState = ()
splitState s = (goalStack s, ())
combineState gs () = Solver { goalStack = gs }
-- | Monad transformer which, when executed using 'observeAllSolverT' or 'observeManySolverT',
-- yields a 'SolverCoroutine'.
newtype DebugSolverT m a = DebugSolverT { unDebugSolverT :: SolverT SolverState (SolverCoroutine m) a }
deriving (Functor, Applicative, Alternative, Monad, MonadPlus, MonadLogic, MonadLogicCut, MonadVarGenerator, MonadUnification)
-- | Same as callWith, but for unitary provers.
callWith :: Monad m => MsgType -> DebugSolverT m Theorem -> DebugSolverT m Theorem
callWith m cont = do
s <- gets goalStack
let dc = DC { stack = s, status = m, msg = formatGoal (head s) }
yield dc
ifte cont
(\thm -> do thm' <- munify thm
yield dc { status = Exit, msg = formatGoal thm' }
return thm)
(yield dc { status = Fail } >> mzero)
-- | Attempt to prove a subgoal and log 'Call', 'Exit', and 'Fail' messages as appropriate.
call :: Monad m => DebugSolverT m Theorem -> DebugSolverT m Theorem
call = callWith Call
-- | Run a 'DebugSolverT' action with the given goal at the top of the goal stack.
goalFrame :: Monad m => Goal -> DebugSolverT m a -> DebugSolverT m a
goalFrame g m = do
s <- get
put $ s { goalStack = g : goalStack s }
r <- m
put s
return r
instance MonadTrans DebugSolverT where
lift = DebugSolverT . lift . lift
instance Monad m => MonadState SolverState (DebugSolverT m) where
state = DebugSolverT . state
instance Monad m => MonadSolver (DebugSolverT m) where
recordThm = DebugSolverT . recordThm
getRecordedThms = DebugSolverT getRecordedThms
tryPredicate p c = goalFrame (PredGoal p []) (call $ provePredicate p c)
retryPredicate p c = goalFrame (PredGoal p []) (callWith Redo $ provePredicate p c)
tryUnifiable t1 t2 = goalFrame (CanUnify t1 t2) (call $ proveUnifiable t1 t2)
tryIdentical t1 t2 = goalFrame (Identical t1 t2) (call $ proveIdentical t1 t2)
tryEqual lhs rhs = goalFrame (Equal lhs rhs) (call $ proveEqual lhs rhs)
tryLessThan lhs rhs = goalFrame (LessThan lhs rhs) (call $ proveLessThan lhs rhs)
tryIsUnified t = goalFrame (IsUnified t) (call $ proveIsUnified t)
tryIsVariable t = goalFrame (IsVariable t) (call $ proveIsVariable t)
tryAnd = proveAnd -- No 'call' here, we don't trace the 'And' itself. To the user, proving a
-- conjunction just looks like proving each subgoal in sequence.
tryOrLeft g1 g2 = goalFrame (Or g1 g2) (call $ proveOrLeft g1 g2)
tryOrRight g1 g2 = goalFrame (Or g1 g2) (callWith Redo $ proveOrRight g1 g2)
tryTop = goalFrame Top (call proveTop)
tryBottom = goalFrame Bottom (call proveBottom)
tryOnce g = goalFrame (Once g) (call $ proveOnce g)
tryIf c t f = goalFrame (If c t f) (call $ proveIf c t f)
tryAlternatives n x g xs = goalFrame (Alternatives n x g xs) (call $ proveAlternatives n x g xs)
tryCut = goalFrame Cut (call proveCut)
tryCutFrame g = goalFrame (CutFrame g) (call $ proveCutFrame g)
tryTrack g = goalFrame (Track g) (call $ proveTrack g)
failUnknownPred p@(Predicate _ _ name _) = do
s <- gets $ (PredGoal p [] :) . goalStack
-- Since there are no clauses, there will be no corresponding 'Call' message, rather we will fail
-- immediately. To make the output a little more intuitive, we explicitly log a 'Call' here.
yield DC { stack = s, status = Call, msg = formatGoal (head s) }
yield DC { stack = s
, status = Error
, msg = "Unknown predicate \"" ++ name ++ " :: " ++ formatType (predType p) ++ "\""
}
mzero
errorUninstantiatedVariables = gets goalStack >>= \s -> error $
"Variables are not sufficiently instantiated.\nGoal stack:\n" ++ showStack Nothing s
-- | Suspend a 'SolverCoroutine' with the given context.
yield :: Monad m => DebugContext -> DebugSolverT m ()
yield dc = DebugSolverT $ lift $ CR.yield $ Left dc
-- | Format a goal stack in a manner suitable for displaying to the user. If a number @n@ is
-- specified, then just the top @n@ goals are shown from the stack. Otherwise, the entire stack is
-- displayed.
showStack :: Maybe Int -> [Goal] -> String
showStack mn s =
let enumeratedStack = zip ([1..] :: [Int]) (reverse s)
truncatedStack = case mn of
Just n -> reverse $ take n $ reverse enumeratedStack
Nothing -> enumeratedStack
in intercalate "\n" ["(" ++ show d ++ ") " ++ formatGoal g | (d, g) <- truncatedStack]
showBreakpoints :: [String] -> String
showBreakpoints bs =
let enumeratedBreakpoints = zip ([1..] :: [Int]) (reverse bs)
in intercalate "\n" ["(" ++ show d ++ ") " ++ b | (d, b) <- enumeratedBreakpoints]
-- | Print a line to the 'output' 'Handle'. The end-of-line character depends on whether we are
-- running in interactive mode (i.e. whether 'tty' is set). In interactive mode, the end of line is
-- a ' ', and the user is prompted for input at the end of the same line. In non-interactive mode,
-- each line of output is terminated by a '\n' character.
printPrompt :: String -> TerminalCoroutine ()
printPrompt s = do
istty <- liftHL haveTerminalUI
let endChar = if istty then " " else "\n"
liftIO $ putStr $ s ++ endChar
printLine :: String -> TerminalCoroutine ()
printLine s = liftIO $ putStrLn s
printStr :: String -> TerminalCoroutine ()
printStr s = liftIO $ putStr s
type TerminalParser = ParsecT String () Identity
class Tokens ps rs | ps -> rs where
trimmedTokens :: ps -> TerminalParser rs
tokens :: ps -> TerminalParser rs
tokens ps = spaces *> trimmedTokens ps <* spaces
instance {-# OVERLAPPING #-} Tokens (TerminalParser a1, TerminalParser a2) (a1, a2) where
trimmedTokens (p1, p2) = do
r1 <- try $ p1 <* space
spaces
r2 <- try p2
return (r1, r2)
instance {-# OVERLAPPABLE #-} ( TupleCons ps, TupleCons rs
, Tokens (Tail ps) (Tail rs)
, Head ps ~ TerminalParser a1
, Head rs ~ a1
) => Tokens ps rs where
trimmedTokens ps = do
r1 <- try $ thead ps <* space
spaces
r2 <- trimmedTokens $ ttail ps
return $ tcons r1 r2
str :: String -> TerminalParser String
str s = try (string s) <?> s
tok :: String -> TerminalParser String
tok t = spaces *> str t <* spaces
integer :: (Read a, Integral a) => TerminalParser a
integer = try (fmap read $ spaces *> raw <* spaces) <?> "integer"
where raw = do sign <- optionMaybe $ oneOf "+-"
num <- many1 digit
case sign of
Just s -> return $ s : num
Nothing -> return num
predicate :: TerminalParser String
predicate = try (many1 $ satisfy $ not . isSpace) <?> "predicate"
step :: TerminalParser Command
step = (tok "step" <|> tok "s") >> return Step
next :: TerminalParser Command
next = (tok "next" <|> tok "n") >> return Next
finish :: TerminalParser Command
finish = (tok "finish" <|> tok "f") >> return Finish
continue :: TerminalParser Command
continue = (tok "continue" <|> tok "c") >> return Continue
setBreak :: TerminalParser Command
setBreak = do (_, p) <- tokens ( str "break" <|> str "b"
, predicate
)
return $ SetBreakpoint p
deleteBreak :: TerminalParser Command
deleteBreak = do (_, b) <- tokens ( str "db" <|> str "delete-breakpoint"
, liftM Right integer <|> liftM Left predicate
)
return $ DeleteBreakpoint b
infoBreakpoints :: TerminalParser Command
infoBreakpoints = (tok "breakpoints" <|> tok "bs") >> return InfoBreakpoints
goals :: TerminalParser Command
goals = do (_, n) <- tokens ( str "goals" <|> str "gs"
, integer
)
return $ InfoStack (Just n)
<|> ((tok "goals" <|> tok "gs") >> return (InfoStack Nothing))
<|> ((tok "goal" <|> tok "g") >> return (InfoStack $ Just 1))
help :: TerminalParser Command
help = (tok "help" <|> tok "h" <|> tok "?") >> return Help
commandParsers :: [TerminalParser Command]
commandParsers = [step, next, finish, continue, setBreak, deleteBreak, infoBreakpoints, goals, help]
-- | Read a 'Command' from a string. This accounts for short aliases of commands. For example,
--
-- >>> parseCommand "step"
-- Just Step
--
-- >>> parseCommand "s"
-- Just Step
parseCommand :: String -> TerminalCoroutine (Either ParseError Command)
parseCommand s = do
st <- lift get
let repeatLast = eof >> return (lastCommand st)
command p = spaces *> p <* spaces <* eof
parser = (foldl1' (<|>) (map command commandParsers) <?> "command") <|> repeatLast
return $ parse parser "" s
-- | Read a 'Command' from the input file handle. If the input is not a valid command, an error
-- message is shown and the user is prompted to re-enter the command. This loop continues until a
-- valid command is entered.
getCommand :: TerminalCoroutine Command
getCommand = do
commStr <- liftHL $ getInputLine ""
when (isNothing commStr) $ error "Unexpected end of input"
comm <- parseCommand $ fromJust commStr
case comm of
Left err -> printLine (show err ++ "\nTry \"?\" for help.") >> getCommand
Right c -> return c
-- | Process a 'Command'. When this function returns, the command will be stored in 'lastCommand',
-- and 'currentTarget' will be set appropriately. The return value indicates whether the processed
-- command should cause the solver to continue executing. For example, if the given command is
-- 'Next', the return value will be 'True', and the caller should thus yield control back to the
-- solver. But if the given command is, say, 'Help', the caller should simply prompt for another
-- command.
runCommand :: DebugContext -> Command -> TerminalCoroutine Bool
runCommand context@DC { stack = s } c = do
st <- lift get
result <- case c of
Step -> lift (put st { currentTarget = Any }) >> return True
Next -> lift (put st { currentTarget = Depth $ length s }) >> return True
Finish -> lift (put st { currentTarget = Depth $ length s - 1 }) >> return True
Continue -> lift (put st { currentTarget = Breakpoint }) >> return True
SetBreakpoint p
| p `elem` breakpoints st ->
printLine ("Breakpoint " ++ p ++ " already exists.") >> return False
| otherwise -> do
lift (put st { breakpoints = p : breakpoints st })
printLine $ "Set breakpoint on " ++ p ++ "."
return False
DeleteBreakpoint (Left p)
| p `elem` breakpoints st -> do
lift (put st { breakpoints = delete p $ breakpoints st})
printLine $ "Deleted breakpoint " ++ p ++ "."
return False
| otherwise -> printLine ("No breakpoint \"" ++ p ++ "\".") >> return False
DeleteBreakpoint (Right i)
| i > 0 && i <= length (breakpoints st) ->
runCommand context (DeleteBreakpoint $ Left $ reverse (breakpoints st) !! (i - 1))
| otherwise -> printLine "Index out of range." >> return False
InfoBreakpoints -> printLine (showBreakpoints $ breakpoints st) >> return False
InfoStack (Just n)
| n > 0 -> printLine (showStack (Just n) s) >> return False
| otherwise -> printLine "Argument must be positive." >> return False
InfoStack Nothing -> printLine (showStack Nothing s) >> return False
Help -> printLine debugHelp >> return False
lift $ modify $ \st' -> st' { lastCommand = c }
return result
-- | Read and evalute commands until a command is entered which causes control to be yielded back to
-- the solver.
repl :: DebugContext -> TerminalCoroutine ()
repl context = do
c <- getCommand
shouldYield <- runCommand context c
unless shouldYield $ prompt context
-- | Entry point when yielding control from the solver to the terminal. This function outputs a
-- message to the user based on the yielded context, and then enters the interactive 'repl'.
prompt :: DebugContext -> TerminalCoroutine ()
prompt context@DC { stack = s, status = mtype, msg = m } = do
st <- lift get
let shouldStop = case currentTarget st of
Any -> True
Depth d -> length s <= d
Breakpoint
| mtype == Call ->
case head s of
PredGoal (Predicate _ _ p _) _ -> p `elem` breakpoints st
_ -> False
| otherwise -> False
when shouldStop $ do
printStr $ "(" ++ show (length s) ++ ") "
setColor $ msgColor mtype
printStr $ show mtype ++ ": "
resetColor
printPrompt m
repl context
showResult :: ProofResult -> TerminalCoroutine ()
showResult ProofResult { unifiedVars = u } =
for_ u $ \x t ->
case (x, t) of
-- Only show user variables bound to a non-variable term
(_, Variable _) -> return ()
(Var v, _) -> liftIO $ putStrLn $ v ++ " = " ++ formatTerm t
_ -> return ()
-- | A coroutine which controls the HSPL solver, yielding control at every important event.
solverCoroutine :: Monad m => Goal -> SolverCoroutine m [ProofResult]
solverCoroutine g =
let solverT = do r <- prove g >>= getResult
DebugSolverT $ lift $ CR.yield $ Right r
return r
in observeAllSolverT (unDebugSolverT solverT) Solver { goalStack = [] }
-- | A coroutine which controls the interactive debugger terminal, periodically yielding control to
-- the solver.
terminalCoroutine :: TerminalCoroutine ()
terminalCoroutine = await >>= \mc -> when (isJust mc) $ do
case fromJust mc of
Left dc -> prompt dc
Right r -> showResult r
terminalCoroutine
-- | Run the debugger with the given goal. The result of this function is a computation in the 'IO'
-- monad which, when executed, will run the debugger.
debug :: Goal -> IO [ProofResult]
debug g =
let cr = weave sequentialBinder weaveAwaitMaybeYield terminalCoroutine (solverCoroutine g)
st = pogoStick runIdentity cr
inputT = snd `fmap` runDebugStateT st -- Keep the solver output, ignore the terminal output
io = runInputT defaultSettings inputT
in io
| jbearer/hspl | src/Control/Hspl/Internal/Debugger.hs | mit | 23,192 | 0 | 20 | 5,906 | 5,203 | 2,676 | 2,527 | 360 | 11 |
-- Graphter.hs
module Graphter where
import Graphter.Convert
import Graphter.Generate
import Graphter.Calculate
import Graphter.Representation
| martinstarman/graphter | src/Graphter.hs | mit | 144 | 0 | 4 | 14 | 25 | 16 | 9 | 5 | 0 |
-- 1. fib n вовзращает n-ое число Фибоначчи.
-- Функция должна работать за линейное вермя и определена для всех целых n.
-- Для отрицательных n значение определяется по формуле fib n = fib (n + 2) - fib (n + 1).
-- (1 балл)
fib :: Integer -> Integer
fib n = let (_, res, _) = fibRec (1, 0, abs n)
in if n > 0 then res else (if abs n `mod` 2 == 1 then 1 else -1) * res
where fibRec (a, b, n) | n > 0 = fibRec (a + b, a, n - 1)
| otherwise = (a, b, n)
-- 2a. Написать функцию, возвращающую количество цифр числа.
-- Для целочисленного деления можете использовать функции div и mod.
-- (0.5 балла)
numberOfDigits :: Integer -> Integer
numberOfDigits i | i < 10 = 1
| otherwise = 1 + numberOfDigits (i `div` 10)
-- 2b. Написать функцию, возвращающую сумму цифр числа.
-- (0.5 балла)
sumOfDigits :: Integer -> Integer
sumOfDigits i | i == 0 = 0
| otherwise = (i `mod` 10) + sumOfDigits (i `div` 10)
-- 3. gcd' возвращает НОД.
-- (1 балл)
gcd' :: Integer -> Integer -> Integer
gcd' a b | b == 0 = a
| otherwise = gcd b (a `mod` b)
-- 4. minp p возвращает минимальное по модулю число x такое, что p x == True. Если такого x не существует, minp не завершается.
-- (1 балл)
minp :: (Integer -> Bool) -> Integer
minp p = minpRec (p, 0)
where minpRec (p, i) | p i = i
| otherwise = minpRec (p, i + 1)
-- 5. integral f a b возвращает значение определенного интеграла функции f на отрезке [a,b].
-- Для реализации можете использовать метод трапеций.
-- (2 балла)
integral :: (Double -> Double) -> Double -> Double -> Double
integral f a b | a >= b = 0
| otherwise = dx * (f a + f (a + dx)) / 2 + integral f (a + dx) b
where dx = 0.05
-- 6. Реализуйте оператор примитивной рекурсии rec, используя функцию (-), укажите тип rec.
-- (1 балл)
rec :: a -> (a -> Integer -> a) -> Integer -> a
rec z s n | n == 0 = z
| otherwise = s (rec z s (n - 1)) n
-- 7. Реализуйте факторил при помощи rec.
-- (1 балл)
facRec :: Integer -> Integer
facRec n = rec 1 (*) n
-- 8. Реализуйте факториал при помощи fix.
-- (1 балл)
facFix :: Integer -> Integer
facFix = fix $ \f n -> if n == 0 then 1 else n * f (n - 1)
where fix f = f (fix f)
| SergeyKrivohatskiy/fp_haskell | hw04.hs | mit | 2,910 | 0 | 13 | 650 | 719 | 382 | 337 | 30 | 3 |
{-# LANGUAGE RankNTypes, GeneralizedNewtypeDeriving, DeriveFunctor, TypeFamilies #-}
{-# LANGUAGE TypeSynonymInstances, NullaryTypeClasses #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE GADTs #-}
module Constraint.Solver where
import Control.Applicative
import Data.Foldable
import Data.IORef
-- data Structure a t = Structure { _structure :: a
-- , _map :: (a -> a) -> t a -> t a
-- , _fold :: (a -> a) -> t a -> }
{-
Syntax of constraints:
======================
C ::=
| true
| C /\ C
| v = v
| exists v.C
| x w [witnesses?]
| def x = v in C
| let [vs?] C [x, v, s?]* in C
-}
-- This class is superfluous, just require that a term variable has
-- an instance of Ord
class TermVar t where
type Var t
compare :: Var t -> Var t -> Int
class Output a t where
type Structure a
type Ty t
variable :: Int -> Ty t
structure :: Structure (Ty t) -> Ty t
mu :: Ty t -> Ty t -> Ty t
-- Foldable s, Functor
-- instance Applicative Constraint where
-- pure c = Constraint (Raw.CTrue, \env -> unConstraint c)
-- a <*> b = undefined
-- | [v ~= w] is an equality constraint on the typevariables v and w.
(~=) :: var -> var -> co ()
(~=) = undefined
-- | [v ~== w ] Analogous to [ v ~= w ], except that the right hand
-- | side is a shallow type instead of a type variable.
(~==) :: var -> str var -> co ()
(~==) = undefined
exist :: (var -> co a) -> co (typ, var)
exist = undefined
construct :: str var -> (var -> co var) -> co (typ, var)
construct = undefined
exist_ :: var -> co var -> co var
exist_ = undefined
construct_ :: str var -> (var -> co var) -> co var
construct_ = undefined
lift :: (a -> var -> co b) -> a -> (str var) -> co b
lift = undefined
isinstance :: tevar -> var -> co [ty]
isinstance = undefined
def :: tevar -> var -> co a -> co a
def = undefined
let1 :: tevar -> (var -> co a) -> co b -> co ([tyvar], a, [scheme], b)
let1 = undefined
let0 :: co a -> co ([tyvar], a)
let0 = undefined
letn :: [tevar] -> ([variable] -> co a) -> co b -> co ([tyvar], a, [scheme], b)
letn = undefined
solve :: Bool -> co a -> a
solve = undefined
data Ref a = Ref
data Constraint v tv s where
CTrue :: Constraint v tv s
CConj :: Constraint v tv s -> Constraint v tv s -> Constraint v tv s
CEq :: v -> v -> Constraint v tv s
CExist :: v -> Constraint v tv s -> Constraint v tv s
CInstance :: tv -> v -> Ref [v] -> Constraint v tv s
CDef :: tv -> v -> Constraint v tv s
CLet :: Ref [v]
-> Constraint v tv s
-> [(tv, v, Ref s)]
-> Constraint v tv s
-> Constraint v tv s
unify = undefined
getState = undefined
register = undefined
solve' env c = case c of
CTrue -> undefined
CConj c1 c2 -> do solve env c1
solve env c2
CEq v w -> unify v w
CExist v c -> do s <- getState
register s v
solve env c
| cpehle/faust | src/Constraint/Solver.hs | mit | 3,162 | 0 | 11 | 1,056 | 930 | 491 | 439 | 67 | 4 |
-- realworldhaskell - WC.hs
-- Counts the number of words in its input.
-- USAGE: runghc WC < sample.txt
main = interact wordCount
where wordCount input = show (length (words input)) ++ "\n" | JoshDev/haskell | chapter1/WC.hs | mit | 192 | 0 | 12 | 34 | 41 | 21 | 20 | 2 | 1 |
module Main
(
main
)
where
import System.Directory ( createDirectoryIfMissing )
import Core ( Ray(..), Point(..), UnitVector
, vector, normal, normalize, translate, to, origin, cross
, (|*|), (|+|) )
import Color ( Color(..), saveRender )
import Light ( PointLightSource(..), Light(..) )
import Material ( Material, diffuseMaterial, flatMaterial )
import Scene ( Scene, mkScene )
import Surface ( Surface(..), mkSphere, mkPlane )
import Render ( renderRay )
main :: IO ()
main = do
putStrLn "Starting render..."
createDirectoryIfMissing True "output"
saveRender "output/experiment02.bmp" 640 480 $ render cam cornellBox
putStrLn "Written output to output/experiment02.bmp"
where cam = Ray { rayOrigin = Point 50.0 52.0 295.6
, rayDirection = normal 0.0 (-0.042612) (-1.0)
}
cornellBox :: Scene
cornellBox = mkScene
[ plane (Point 1.0 40.8 81.6) (normal 1.0 0.0 0.0) $ diffuseMaterial (Color 0.75 0.25 0.25) 0.5
, plane (Point 99.0 40.8 81.6) (normal (-1.0) 0.0 0.0) $ diffuseMaterial (Color 0.25 0.25 0.75) 0.5
, plane (Point 50.0 40.8 0.0) (normal 0.0 0.0 1.0) $ diffuseMaterial (Color 0.75 0.75 0.75) 0.5
, plane (Point 50.0 0.0 81.6) (normal 0.0 1.0 0.0) $ diffuseMaterial (Color 0.75 0.75 0.75) 0.5
, plane (Point 50.0 81.6 81.6) (normal 0.0 (-1.0) 0.0) $ diffuseMaterial (Color 0.75 0.75 0.75) 0.5
, plane (Point 50.0 40.8 170.0) (normal 0.0 0.0 (-1.0)) $ diffuseMaterial (Color 0.00 0.00 0.00) 0.5
, sphere (Point 27.0 16.5 47.0) 16.5 $ diffuseMaterial (Color 0.99 0.99 0.99) 0.5
, sphere (Point 73.0 16.5 78.0) 16.5 $ diffuseMaterial (Color 0.99 0.99 0.99) 0.5
, sphere (Point 50.0 681.33 81.6) 600.0 $ flatMaterial (Color 1.00 1.00 1.00)
]
[ PointLightSource (Point 50.0 79.33 81.6) (Light 100.0 100.0 100.0)
]
sphere :: Point -> Double -> Material -> Surface
sphere center radius mat =
translate (origin `to` center) $ mkSphere radius mat
plane :: Point -> UnitVector -> Material -> Surface
plane =
mkPlane
render :: Ray -> Scene -> Int -> Int -> Int -> Int -> Color
render (Ray camOrigin camDirection) scene !x !y !w !h =
renderRay rr scene
where rr = Ray { rayOrigin = translate (d |*| focal) camOrigin
, rayDirection = normalize d
}
d = (cx |*| ( dx / dw - 0.5)) |+|
(cy |*| (0.5 - dy / dh )) |+|
camDirection
cx = vector (dw * aspect / dh) 0.0 0.0
cy = normalize (cx `cross` camDirection) |*| aspect
aspect = dh / dw / 2.0
focal = 140.0
dw = fromIntegral w
dh = fromIntegral h
dx = fromIntegral x
dy = fromIntegral y
| stu-smith/rendering-in-haskell | src/experiment02/Main.hs | mit | 3,022 | 0 | 13 | 1,009 | 1,020 | 540 | 480 | -1 | -1 |
{-# LANGUAGE NoImplicitPrelude #-}
-- |
-- Module: Main
-- Description: Unit tests executor
-- Copyright: (c) 2015-2016, Ixperta Solutions s.r.o.
-- License: AllRightsReserved
--
-- Stability: stable
-- Portability: portable
--
-- Unit tests executor.
module Main (main)
where
import System.IO (IO)
import Test.Framework (defaultMain)
import TestCase (tests)
main :: IO ()
main = defaultMain tests
| Unoriginal-War/unoriginal-war | test/unit-tests.hs | mit | 424 | 0 | 6 | 83 | 66 | 43 | 23 | 7 | 1 |
{-# LANGUAGE ForeignFunctionInterface, JavaScriptFFI,
MagicHash, UnboxedTuples, UnliftedFFITypes, GHCForeignImportPrim
#-}
{-
Low level bindings for JavaScript strings. These expose the underlying
encoding. Use Data.JSString for
-}
module Data.JSString.Raw ( rawHead
, rawTail
, rawInit
, rawLast
, rawLength
, rawTake
, rawDrop
, rawTakeEnd
, rawDropEnd
, rawChunksOf
, rawChunksOf'
) where
import GHC.Exts
( Int(..), Int#, Char(..)
, negateInt#
, (+#), (-#), (>=#), (<#)
, isTrue#, chr#)
import qualified GHC.Exts as Exts
import GHCJS.Prim (JSVal)
import Unsafe.Coerce
import Data.JSString.Internal.Type
rawLength :: JSString -> Int
rawLength x = I# (js_length x)
{-# INLINE rawLength #-}
rawHead :: JSString -> Char
rawHead x
| js_null x = emptyError "rawHead"
| otherwise = C# (chr# (js_codePointAt 0# x))
{-# INLINE rawHead #-}
unsafeRawHead :: JSString -> Char
unsafeRawHead x = C# (chr# (js_codePointAt 0# x))
{-# INLINE unsafeRawHead #-}
rawLast :: JSString -> Char
rawLast x
| js_null x = emptyError "rawLast"
| otherwise = C# (chr# (js_charCodeAt (js_length x -# 1#) x))
{-# INLINE rawLast #-}
unsafeRawLast :: JSString -> Char
unsafeRawLast x = C# (chr# (js_charCodeAt (js_length x -# 1#) x))
{-# INLINE unsafeRawLast #-}
rawTail :: JSString -> JSString
rawTail x
| js_null x = emptyError "rawTail"
| otherwise = JSString $ js_tail x
{-# INLINE rawTail #-}
unsafeRawTail :: JSString -> JSString
unsafeRawTail x = JSString $ js_tail x
{-# INLINE unsafeRawTail #-}
rawInit :: JSString -> JSString
rawInit x = js_substr 0# (js_length x -# 1#) x
{-# INLINE rawInit #-}
unsafeRawInit :: JSString -> JSString
unsafeRawInit x = js_substr 0# (js_length x -# 1#) x
{-# INLINE unsafeRawInit #-}
unsafeRawIndex :: Int -> JSString -> Char
unsafeRawIndex (I# n) x = C# (chr# (js_charCodeAt n x))
{-# INLINE unsafeRawIndex #-}
rawIndex :: Int -> JSString -> Char
rawIndex (I# n) x
| isTrue# (n <# 0#) || isTrue# (n >=# js_length x) =
overflowError "rawIndex"
| otherwise = C# (chr# (js_charCodeAt n x))
{-# INLINE rawIndex #-}
rawTake :: Int -> JSString -> JSString
rawTake (I# n) x = js_substr 0# n x
{-# INLINE rawTake #-}
rawDrop :: Int -> JSString -> JSString
rawDrop (I# n) x = js_substr1 n x
{-# INLINE rawDrop #-}
rawTakeEnd :: Int -> JSString -> JSString
rawTakeEnd (I# k) x = js_slice1 (negateInt# k) x
{-# INLINE rawTakeEnd #-}
rawDropEnd :: Int -> JSString -> JSString
rawDropEnd (I# k) x = js_substr 0# (js_length x -# k) x
{-# INLINE rawDropEnd #-}
rawChunksOf :: Int -> JSString -> [JSString]
rawChunksOf (I# k) x =
let l = js_length x
go i = case i >=# l of
0# -> js_substr i k x : go (i +# k)
_ -> []
in go 0#
{-# INLINE rawChunksOf #-}
rawChunksOf' :: Int -> JSString -> [JSString]
rawChunksOf' (I# k) x = unsafeCoerce (js_rawChunksOf k x)
{-# INLINE rawChunksOf' #-}
rawSplitAt :: Int -> JSString -> (JSString, JSString)
rawSplitAt (I# k) x = (js_substr 0# k x, js_substr1 k x)
{-# INLINE rawSplitAt #-}
emptyError :: String -> a
emptyError fun = error $ "Data.JSString.Raw." ++ fun ++ ": empty input"
overflowError :: String -> a
overflowError fun = error $ "Data.JSString.Raw." ++ fun ++ ": size overflow"
-- -----------------------------------------------------------------------------
foreign import javascript unsafe
"$1===''" js_null :: JSString -> Bool
foreign import javascript unsafe
"$1.length" js_length :: JSString -> Int#
foreign import javascript unsafe
"$3.substr($1,$2)" js_substr :: Int# -> Int# -> JSString -> JSString
foreign import javascript unsafe
"$2.substr($1)" js_substr1 :: Int# -> JSString -> JSString
foreign import javascript unsafe
"$3.slice($1,$2)" js_slice :: Int# -> Int# -> JSString -> JSString
foreign import javascript unsafe
"$2.slice($1)" js_slice1 :: Int# -> JSString -> JSString
foreign import javascript unsafe
"$3.indexOf($1,$2)" js_indexOf :: JSString -> Int# -> JSString -> Int#
foreign import javascript unsafe
"$2.indexOf($1)" js_indexOf1 :: JSString -> JSString -> Int#
foreign import javascript unsafe
"$2.charCodeAt($1)" js_charCodeAt :: Int# -> JSString -> Int#
foreign import javascript unsafe
"$2.codePointAt($1)" js_codePointAt :: Int# -> JSString -> Int#
foreign import javascript unsafe
"$hsRawChunksOf" js_rawChunksOf :: Int# -> JSString -> Exts.Any -- [JSString]
foreign import javascript unsafe
"h$jsstringTail" js_tail :: JSString -> JSVal -- null for empty string
| ghcjs/ghcjs-base | Data/JSString/Raw.hs | mit | 4,776 | 38 | 16 | 1,116 | 1,344 | 700 | 644 | 118 | 2 |
module Main where
import BFIOlib
import System.IO
import Control.Concurrent
import Control.Monad.State
import Control.Monad.Writer
import BFLib.Brainfuch (Code, emptyStack, Stack)
import BFLib.BrainfuchFollow
main :: IO ()
main = do
code <- readCode
putStr "\nOutput of script:\n"
stacks <- interpret code
putStr "\n\nStack states during interpretation:\n"
mapM_ showWaitDelete (zipWith appendRotateSym (stackStrings stacks) rotatesyms)
putStrLn ""
where stackStrings = map showStack
rotatesyms = concat . repeat $ progressRotateSyms
appendRotateSym stack sym = stack ++ " (" ++ [sym] ++ ")"
sleeptime :: Int
sleeptime = round 1e6
sleep :: IO ()
sleep = threadDelay sleeptime
sleepShort :: IO ()
sleepShort = threadDelay (sleeptime `div` 3)
deleteLine :: String
deleteLine = "\r\ESC[K"
showWaitDelete :: String -> IO ()
showWaitDelete stack = do
putStr deleteLine
hFlush stdout
putStr stack
hFlush stdout
sleep
-- Code
progressRotateSyms :: String
progressRotateSyms = "-\\|/-|/"
interpret :: Code -> IO [StackCode]
interpret c = liftM (snd . fst) $ runStateT (runWriterT (bffTell (emptyStack,' ') >> bfInt c)) emptyStack
| dermesser/Brainfuch | BFdbgIA.hs | mit | 1,328 | 0 | 12 | 363 | 367 | 187 | 180 | 38 | 1 |
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE BangPatterns #-}
module Data.Digest.Pure.MD4 (md4) where
import Control.Applicative
import Control.Monad.State
import Data.Bits
import Data.Binary.Put
import Data.Binary.Get
import qualified Data.ByteString.Lazy as L
import Data.Word
f x y z = x .&. y .|. complement x .&. z
g x y z = x .&. y .|. x .&. z .|. y .&. z
h x y z = x `xor` y `xor` z
abcd f a b c d = f a b c d
dabc f a b c d = f d a b c
cdab f a b c d = f c d a b
bcda f a b c d = f b c d a
data State = Vals !Word32 !Word32 !Word32 !Word32
store1 x (Vals a b c d) = Vals x b c d
store2 x (Vals a b c d) = Vals a x c d
store3 x (Vals a b c d) = Vals a b x d
store4 x (Vals a b c d) = Vals a b c x
get1 (Vals x _ _ _) = x
get2 (Vals _ x _ _) = x
get3 (Vals _ _ x _) = x
get4 (Vals _ _ _ x) = x
op f n k s x a b c d =
rotateL (a + f b c d + (x!!k) + n) s
op1 = op f 0
op2 = op g 0x5a827999
op3 = op h 0x6ed9eba1
params1 = [ 0, 3, 1, 7, 2, 11, 3, 19
, 4, 3, 5, 7, 6, 11, 7, 19
, 8, 3, 9, 7, 10, 11, 11, 19
,12, 3, 13, 7, 14, 11, 15, 19]
params2 = [0, 3, 4, 5, 8, 9, 12, 13
,1, 3, 5, 5, 9, 9, 13, 13
,2, 3, 6, 5, 10, 9, 14, 13
,3, 3, 7, 5, 11, 9, 15, 13]
params3 = [0, 3, 8, 9, 4, 11, 12, 15
,2, 3, 10, 9, 6, 11, 14, 15
,1, 3, 9, 9, 5, 11, 13, 15
,3, 3, 11, 9, 7, 11, 15, 15]
apply x op p k s = p go (gets get1, modify . store1)
(gets get2, modify . store2)
(gets get3, modify . store3)
(gets get4, modify . store4)
where go (a, store) (b,_) (c,_) (d,_) =
store =<< (op k s x <$> a <*> b <*> c <*> d)
on app = go
where go [] = pure ()
go (k1:s1:k2:s2:k3:s3:k4:s4:r)
= app abcd k1 s1
*> app dabc k2 s2
*> app cdab k3 s3
*> app bcda k4 s4
*> go r
proc !x = (modify . add) =<< (get <* go op1 params1
<* go op2 params2
<* go op3 params3)
where add (Vals a b c d) (Vals a' b' c' d') = Vals (a+a') (b+b') (c+c') (d+d')
go op params = apply x op `on` params
md4 s = output $ execState (go (prep s) (return ())) (Vals 0x67452301 0xefcdab89 0x98badcfe 0x10325476)
where go [] m = m
go !s m = go (drop 16 s) $ m >> proc (take 16 s)
prep = getWords . pad
pad bs = runPut $ putAndCountBytes bs >>= \len ->
putWord8 0x80
*> replicateM_ (mod (55 - fromIntegral len) 64) (putWord8 0)
*> putWord64le (len * 8)
putAndCountBytes = go 0
where go !n s = case L.uncons s of
Just (w, s') -> putWord8 w >> go (n+1) s'
Nothing -> return $! n
getWords = runGet words
where words = isEmpty >>= \e -> if e then pure [] else (:) <$> getWord32le <*> words
output (Vals a b c d) = L.toStrict . runPut $ mapM_ putWord32le [a,b,c,d]
| mfeyg/md4 | Data/Digest/Pure/MD4.hs | mit | 3,085 | 0 | 16 | 1,187 | 1,619 | 870 | 749 | 85 | 2 |
module Hickory.Graphics
( module Hickory.Graphics.DrawUtils
, module Hickory.Graphics.Drawing
, module Hickory.Graphics.GLSupport
, module Hickory.Graphics.Shader
, module Hickory.Graphics.StockShaders
, module Hickory.Graphics.Textures
, module Hickory.Graphics.VAO
, module Hickory.Graphics.DrawText
, module Hickory.Graphics.DeferredRendering
, module Hickory.Graphics.DirectXModel
, module Hickory.Graphics.Uniforms
, module Hickory.Graphics.SSAO
, module Hickory.Graphics.Wavefront
, module Hickory.Graphics.MatrixMonad
, module Hickory.Graphics.ShaderMonad
) where
import Hickory.Graphics.DrawUtils
import Hickory.Graphics.DrawText
import Hickory.Graphics.Drawing
import Hickory.Graphics.GLSupport
import Hickory.Graphics.Shader
import Hickory.Graphics.StockShaders
import Hickory.Graphics.Textures
import Hickory.Graphics.VAO
import Hickory.Graphics.DeferredRendering
import Hickory.Graphics.DirectXModel
import Hickory.Graphics.Uniforms
import Hickory.Graphics.SSAO
import Hickory.Graphics.Wavefront
import Hickory.Graphics.MatrixMonad
import Hickory.Graphics.ShaderMonad
| asivitz/Hickory | Hickory/Graphics.hs | mit | 1,113 | 0 | 5 | 112 | 203 | 140 | 63 | 31 | 0 |
{-# LANGUAGE OverloadedStrings #-}
------------------------------------------------------------------------------
-- | This module is where the main blog is defined.
module Blog
( Blog
, blogInit
) where
import Control.Concurrent.MVar (MVar, newMVar, readMVar)
import Control.Monad.IO.Class (liftIO)
import Control.Monad.State.Class (gets)
import Data.Map.Syntax (MapSyntaxM, (##))
import Data.String.Conversions (cs)
import qualified Data.Text as T
import Data.Time.Clock (UTCTime, getCurrentTime)
import Data.Time.Format (formatTime)
import System.Locale (defaultTimeLocale)
import Snap.Snaplet (Handler, SnapletInit, addRoutes, makeSnaplet)
import Snap.Snaplet.Heist (HasHeist, renderWithSplices)
import qualified Heist.Interpreted as I
import qualified Text.XmlHtml as H
data Blog = Blog
{ _blogPosts :: MVar [BlogPost]
}
data BlogPost = BlogPost
{ title :: T.Text
, content :: [H.Node]
, author :: T.Text
, datePublished :: UTCTime
, tags :: [T.Text]
}
blogInit :: HasHeist b => SnapletInit b Blog
blogInit = makeSnaplet "blog" "A blog snaplet" Nothing $ do
addRoutes [("", blogHandler)]
posts <- liftIO $ newMVar =<< testBlogPosts
return $ Blog posts
blogHandler :: HasHeist b => Handler b Blog ()
blogHandler = do
posts <- liftIO . readMVar =<< gets _blogPosts
renderBlogPosts posts
renderBlogPosts :: HasHeist b => [BlogPost] -> Handler b Blog ()
renderBlogPosts =
let render = renderWithSplices "blog"
posts = (##) "blog_posts"
splice = I.mapSplices (I.runChildrenWithTemplates . blogPostMap)
in render . posts . splice
blogPostMap :: BlogPost -> MapSyntaxM T.Text [H.Node] ()
blogPostMap (BlogPost title' content' author' datePublished' tags') = do
"title" ## [H.TextNode title']
"post" ## content'
"author" ## [H.TextNode author']
"date-published" ## [timeNode datePublished']
"tags" ## map tagNode tags'
timeNode :: UTCTime -> H.Node
timeNode = H.TextNode . cs . (formatTime defaultTimeLocale "%e %B %Y")
tagNode :: T.Text -> H.Node
tagNode tag = H.Element "a" [("href", "#"), ("class", "post-category")] [H.TextNode tag]
testBlogPosts :: IO [BlogPost]
testBlogPosts = do
time <- getCurrentTime
return [ BlogPost "Hello, world!" [(H.TextNode "This is a test blog post.")] "Ryan Bye" time ["haskell", "blog"]
, BlogPost "This is a blog post." [(H.TextNode "And another blog post.")] "Ryan Bye" time ["blog", "coding"]
, BlogPost "Welcome to Haskell." [(H.TextNode "Yet one more blog post.")] "Ryan Bye" time ["haskell", "c++", "rust"]
, BlogPost "Would you like a pizza roll?" [(H.TextNode "What's wrong with your face?")] " Ryan Bye" time []
]
| rybye/blog | src/Blog.hs | mit | 2,755 | 0 | 13 | 549 | 807 | 445 | 362 | 58 | 1 |
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
module Kashmir.Github.Types.Hook where
import Cases
import Data.Aeson
import Data.Set as Set
import Data.Text
import GHC.Generics
import Kashmir.Github.Types.Common
asSnakeString :: Show a
=> a -> Value
asSnakeString = String . snakify . pack . show
data ContentType
= Json
| Form
deriving (Show,Eq,Generic)
instance ToJSON ContentType where
toJSON = asSnakeString
newtype WebhookSecret = WebhookSecret {unWebhookSecret :: Text}
deriving (Show,Eq)
instance ToJSON WebhookSecret where
toJSON (WebhookSecret t) = toJSON t
instance FromJSON WebhookSecret where
parseJSON t = WebhookSecret <$> parseJSON t
data HookConfig =
HookConfig {url :: URL
,contentType :: ContentType
,secret :: WebhookSecret
,insecureSsl :: Bool}
deriving (Show,Eq,Generic,ToJSON)
data HookName = Web
deriving (Show,Eq,Generic)
instance ToJSON HookName where
toJSON = asSnakeString
data HookEvent
= Push
| PullRequest
deriving (Show,Eq,Ord,Generic)
instance ToJSON HookEvent where
toJSON = asSnakeString
data Hook =
Hook {name :: HookName
,config :: HookConfig
,events :: Set HookEvent
,active :: Bool}
deriving (Show,Eq,Generic,ToJSON)
| krisajenkins/kashmir | src/Kashmir/Github/Types/Hook.hs | epl-1.0 | 1,450 | 0 | 9 | 400 | 370 | 211 | 159 | 47 | 1 |
-- benchmark/Bench.hs
module Main (main) where
import Criterion.Main (bgroup, defaultMain)
import qualified MataskellBench
main :: IO ()
main = defaultMain
[ bgroup "Mataskell" MataskellBench.benchmarks
]
| tylerjl/mataskell | benchmark/Bench.hs | gpl-2.0 | 219 | 0 | 8 | 39 | 55 | 32 | 23 | 6 | 1 |
{-# LANGUAGE OverloadedStrings #-}
-----------------------------------------------------------------------------
-- |
-- Module : Hoodle.Util
-- Copyright : (c) 2013 Ian-Woo Kim
--
-- License : BSD3
-- Maintainer : Ian-Woo Kim <[email protected]>
-- Stability : experimental
-- Portability : GHC
--
-----------------------------------------------------------------------------
module Hoodle.Util where
import Control.Applicative
import Data.Attoparsec.Char8
import qualified Data.ByteString.Char8 as B
import Data.Maybe
import Data.Time.Clock
import Data.Time.Format
import Data.UUID.V4 (nextRandom)
import Network.URI
import System.Directory
import System.Environment
import System.FilePath
import System.IO
import System.Locale
--
import Data.Hoodle.Simple
--
-- import Debug.Trace
(#) :: a -> (a -> b) -> b
(#) = flip ($)
infixr 0 #
maybeFlip :: Maybe a -> b -> (a->b) -> b
maybeFlip m n j = maybe n j m
uncurry4 :: (a->b->c->d->e)->(a,b,c,d)->e
uncurry4 f (x,y,z,w) = f x y z w
maybeRead :: Read a => String -> Maybe a
maybeRead = fmap fst . listToMaybe . reads
getLargestWidth :: Hoodle -> Double
getLargestWidth hdl =
let ws = map (dim_width . page_dim) (hoodle_pages hdl)
in maximum ws
getLargestHeight :: Hoodle -> Double
getLargestHeight hdl =
let hs = map (dim_height . page_dim) (hoodle_pages hdl)
in maximum hs
waitUntil :: (Monad m) => (a -> Bool) -> m a -> m ()
waitUntil p act = do
a <- act
if p a
then return ()
else waitUntil p act
-- | for debugging
errorlog :: String -> IO ()
errorlog str = do
homepath <- getEnv "HOME"
let dir = homepath </> ".hoodle.d"
createDirectoryIfMissing False dir
outh <- openFile (dir </> "error.log") AppendMode
utctime <- getCurrentTime
let timestr = formatTime defaultTimeLocale "%F %H:%M:%S %Z" utctime
hPutStr outh (timestr ++ " : " )
hPutStrLn outh str
hClose outh
-- |
maybeError' :: String -> Maybe a -> a
maybeError' str = maybe (error str) id
data UrlPath = FileUrl FilePath | HttpUrl String
deriving (Show,Eq)
data T = N | F | H | HS deriving (Show,Eq)
-- |
urlParse :: String -> Maybe UrlPath
urlParse str =
if length str < 7
then Just (FileUrl str)
else
let p = do b <- (try (string "file://" *> return F)
<|> try (string "http://" *> return H)
<|> try (string "https://" *> return HS)
<|> (return N) )
remaining <- manyTill anyChar ((satisfy (inClass "\r\n") *> return ()) <|> endOfInput)
return (b,remaining)
r = parseOnly p (B.pack str)
in case r of
Left _ -> Nothing
Right (b,f) -> case b of
N -> Just (FileUrl f)
F -> Just (FileUrl (unEscapeString f))
H -> Just (HttpUrl ("http://" ++ f))
HS -> Just (HttpUrl ("https://" ++ f))
-- |
mkTmpFile :: String -> IO FilePath
mkTmpFile ext = do
tdir <- getTemporaryDirectory
tuuid <- nextRandom
return $ tdir </> show tuuid <.> ext
| wavewave/hoodle-core | src/Hoodle/Util.hs | gpl-3.0 | 3,162 | 0 | 20 | 870 | 1,056 | 546 | 510 | 78 | 6 |
#!/usr/bin/env stack
{- stack runghc --verbosity info
--package hledger
--package here
--package text
--package time
-}
{-# OPTIONS_GHC -Wno-missing-signatures #-}
{-# LANGUAGE QuasiQuotes #-}
import Data.Maybe
import Data.List
import Data.String.Here
import Data.Time
import qualified Data.Text as T
import Hledger.Cli
------------------------------------------------------------------------------
cmdmode = hledgerCommandMode
[here| prices
Print all market prices from the journal.
|]
[flagNone ["costs"] (setboolopt "costs") "print transaction prices from postings"
,flagNone ["inverted-costs"] (setboolopt "inverted-costs") "print transaction inverted prices from postings also"]
[generalflagsgroup1]
[]
([], Nothing)
------------------------------------------------------------------------------
showPrice :: MarketPrice -> String
showPrice mp = unwords ["P", show $ mpdate mp, T.unpack . quoteCommoditySymbolIfNeeded $ mpcommodity mp, showAmountWithZeroCommodity $ mpamount mp]
divideAmount' :: Amount -> Quantity -> Amount
divideAmount' a d = a' where
a' = (a `divideAmount` d) { astyle = style' }
style' = (astyle a) { asprecision = precision' }
extPrecision = (1+) . floor . logBase 10 $ (realToFrac d :: Double)
precision' = extPrecision + asprecision (astyle a)
invertPrice :: Amount -> Amount
invertPrice a =
case aprice a of
NoPrice -> a
UnitPrice pa -> invertPrice
-- normalize to TotalPrice
a { aprice = TotalPrice pa' } where
pa' = (pa `divideAmount` (1 / aquantity a)) { aprice = NoPrice }
TotalPrice pa ->
a { aquantity = aquantity pa * signum (aquantity a), acommodity = acommodity pa, aprice = TotalPrice pa' } where
pa' = pa { aquantity = abs $ aquantity a, acommodity = acommodity a, aprice = NoPrice, astyle = astyle a }
amountCost :: Day -> Amount -> Maybe MarketPrice
amountCost d a =
case aprice a of
NoPrice -> Nothing
UnitPrice pa -> Just
MarketPrice { mpdate = d, mpcommodity = acommodity a, mpamount = pa }
TotalPrice pa -> Just
MarketPrice { mpdate = d, mpcommodity = acommodity a, mpamount = pa `divideAmount'` abs (aquantity a) }
postingCosts :: Posting -> [MarketPrice]
postingCosts p = mapMaybe (amountCost date) . amounts $ pamount p where
date = fromMaybe (tdate . fromJust $ ptransaction p) $ pdate p
allPostings :: Journal -> [Posting]
allPostings = concatMap tpostings . jtxns
mapAmount :: (Amount -> Amount) -> [Posting] -> [Posting]
mapAmount f = map pf where
pf p = p { pamount = mf (pamount p) }
mf = mixed . map f . amounts
main :: IO ()
main = do
opts <- getHledgerCliOpts cmdmode
withJournalDo opts{ ignore_assertions_ = True } $ \_ j -> do
let cprices = concatMap postingCosts . allPostings $ j
icprices = concatMap postingCosts . mapAmount invertPrice . allPostings $ j
printPrices = mapM_ (putStrLn . showPrice)
forBoolOpt opt | boolopt opt $ rawopts_ opts = id
| otherwise = const []
allPrices = sortOn mpdate . concat $
[ jmarketprices j
, forBoolOpt "costs" cprices
, forBoolOpt "inverted-costs" icprices
]
printPrices allPrices
| mstksg/hledger | bin/hledger-prices.hs | gpl-3.0 | 3,359 | 0 | 18 | 835 | 962 | 507 | 455 | 64 | 3 |
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE PartialTypeSignatures #-}
{-# OPTIONS_GHC -fno-warn-overlapping-patterns #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# OPTIONS_GHC -fno-warn-unused-do-bind #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module Handler.DB.RouteTransferreceipts where
import Handler.DB.Enums
import Handler.DB.Esqueleto
import Handler.DB.Internal
import Handler.DB.Validation
import qualified Handler.DB.FilterSort as FS
import qualified Handler.DB.PathPieces as PP
import Prelude
import Database.Esqueleto
import Database.Esqueleto.Internal.Sql (unsafeSqlBinOp)
import qualified Database.Persist as P
import Database.Persist.TH
import Yesod.Auth (requireAuth, requireAuthId, YesodAuth, AuthId, YesodAuthPersist, AuthEntity)
import Yesod.Core hiding (fileName, fileContentType)
import Yesod.Persist (runDB, YesodPersist, YesodPersistBackend)
import Control.Monad (when)
import Data.Aeson ((.:), (.:?), (.!=), FromJSON, parseJSON, decode)
import Data.Aeson.TH
import Data.Int
import Data.Word
import Data.Time
import Data.Text.Encoding (encodeUtf8)
import Data.Typeable (Typeable)
import qualified Data.Attoparsec as AP
import qualified Data.Aeson as A
import qualified Data.Aeson.Types as AT
import qualified Data.ByteString.Lazy as LBS
import Data.Maybe
import qualified Data.Text.Read
import qualified Data.Text as T
import Data.Text (Text)
import qualified Data.List as DL
import Control.Monad (mzero, forM_)
import Control.Monad.Trans.Resource (runResourceT)
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as L
import qualified Network.HTTP.Conduit as C
import qualified Network.Wai as W
import Data.Conduit.Lazy (lazyConsume)
import Network.HTTP.Types (status200, status400, status403, status404)
import Blaze.ByteString.Builder.ByteString (fromByteString)
import Control.Applicative ((<$>), (<*>))
import qualified Data.HashMap.Lazy as HML
import qualified Data.HashMap.Strict as HMS
import Handler.Utils (nonEmpty)
import Handler.Utils (prepareNewUser,hasWritePerm,hasReadPermMaybe,hasReadPerm)
postTransferreceiptsR :: forall master. (
YesodAuthPersist master,
AuthEntity master ~ User,
AuthId master ~ Key User,
YesodPersistBackend master ~ SqlBackend)
=> HandlerT DB (HandlerT master IO) A.Value
postTransferreceiptsR = lift $ runDB $ do
authId <- lift $ requireAuthId
jsonResult <- parseJsonBody
jsonBody <- case jsonResult of
A.Error err -> sendResponseStatus status400 $ A.object [ "message" .= ( "Could not decode JSON object from request body : " ++ err) ]
A.Success o -> return o
jsonBodyObj <- case jsonBody of
A.Object o -> return o
v -> sendResponseStatus status400 $ A.object [ "message" .= ("Expected JSON object in the request body, got: " ++ show v) ]
attr_receiptIdList <- case HML.lookup "receiptIdList" jsonBodyObj of
Just v -> case A.fromJSON v of
A.Success v' -> return v'
A.Error err -> sendResponseStatus status400 $ A.object [
"message" .= ("Could not parse value from attribute receiptIdList in the JSON object in request body" :: Text),
"error" .= err
]
Nothing -> sendResponseStatus status400 $ A.object [
"message" .= ("Expected attribute receiptIdList in the JSON object in request body" :: Text)
]
attr_processPeriodId <- case HML.lookup "processPeriodId" jsonBodyObj of
Just v -> case A.fromJSON v of
A.Success v' -> return v'
A.Error err -> sendResponseStatus status400 $ A.object [
"message" .= ("Could not parse value from attribute processPeriodId in the JSON object in request body" :: Text),
"error" .= err
]
Nothing -> sendResponseStatus status400 $ A.object [
"message" .= ("Expected attribute processPeriodId in the JSON object in request body" :: Text)
]
runDB_result <- do
forM_ (attr_receiptIdList :: [_]) $ \result_rId -> do
e1 <- do
es <- select $ from $ \o -> do
where_ (o ^. ReceiptId ==. (val result_rId))
limit 1
return o
e <- case es of
[(Entity _ e')] -> return e'
_ -> sendResponseStatus status404 $ A.object [
"message" .= ("Could not update a non-existing Receipt" :: Text)
]
return $ e {
receiptProcessPeriodId = attr_processPeriodId
}
vErrors <- lift $ validate e1
case vErrors of
xs@(_:_) -> sendResponseStatus status400 (A.object [
"message" .= ("Entity validation failed" :: Text),
"errors" .= toJSON xs
])
_ -> P.repsert result_rId (e1 :: Receipt)
return AT.emptyObject
return $ runDB_result
| tlaitinen/receipts | backend/Handler/DB/RouteTransferreceipts.hs | gpl-3.0 | 5,687 | 0 | 27 | 1,570 | 1,227 | 694 | 533 | 116 | 9 |
module SIR.Model where
data SIRState
= Susceptible
| Infected
| Recovered
deriving (Show, Eq)
aggregateSIRStates :: [SIRState] -> (Int, Int, Int)
aggregateSIRStates as = (sus, inf, recs)
where
sus = length $ filter (==Susceptible) as
inf = length $ filter (==Infected) as
recs = length $ filter (==Recovered) as
int3ToDbl3 :: (Int, Int, Int) -> (Double, Double, Double)
int3ToDbl3 (x,y,z) = (fromIntegral x, fromIntegral y, fromIntegral z) | thalerjonathan/phd | thesis/code/sir/src/SIR/Model.hs | gpl-3.0 | 467 | 0 | 9 | 94 | 186 | 108 | 78 | 13 | 1 |
module Scyther.Theory.Parser (
-- * Lexing
Token
, Keyword(..)
, scanString
, scanFile
-- * Parsing
, Parser
, parseFile
-- ** Additional combinators
, liftMaybe
, liftMaybe'
, token
-- ** Keyword combinations
, kw
, betweenKWs
, commaSep
, commaSep1
, list
, braced
, parens
, brackets
, singleQuoted
, doubleQuoted
, identifier
, string
, strings
, integer
, genFunOpen
, genFunApp
, funOpen
, funApp
-- ** Security protocol theorys for the free-algebra
, protocol
, claims
, theory
, formalComment
, parseTheory
-- * Extended patterns
, mkLTSPat
, mkMultIdentityPat
, mkExpPat
, mkMultPat
, destLTSPat
, destMultIdentityPat
, destExpPat
, destMultPat
) where
import Data.Char
import Data.List
import Data.Either
import qualified Data.Set as S
import qualified Data.Map as M
import Data.DAG.Simple
import Data.Foldable (asum)
import Control.Arrow ( (***), first )
import Control.Monad hiding (sequence)
import Control.Applicative hiding (empty, many, optional)
import Text.Parsec hiding (token, (<|>), string )
import qualified Text.Parsec as P
import Text.Parsec.Pos
import qualified Scyther.Equalities as E
import Scyther.Facts as F hiding (variable, protocol)
import Scyther.Sequent
import Scyther.Proof
import Scyther.Theory
import Scyther.Theory.Lexer (Keyword(..), TextType(..), runAlex, AlexPosn(..), alexGetPos, alexMonadScan)
------------------------------------------------------------------------------
-- Specializing Parsec to our needs
------------------------------------------------------------------------------
-- Scanner
----------
-- | The tokens delivered by our Alex based scanner
type Token = (SourcePos, Keyword)
-- | Scan a string using the given filename in the error messages.
--
-- NOTE: Lexical errors are thrown using 'error'.
scanString :: FilePath -> String -> [Token]
scanString filename s =
case runAlex s gatherUntilEOF of
Left err -> error err
Right kws -> kws
where
gatherUntilEOF = do
AlexPn _ line col <- alexGetPos
let pos = newPos filename line col
k <- alexMonadScan
case k of
EOF -> return [(pos,EOF)]
_ -> do kws <- gatherUntilEOF
return $ (pos,k) : kws
-- Parser
---------
-- | A parser with an arbitrary user state for a stream of tokens.
type Parser s a = Parsec [Token] s a
-- | Lift a maybe to a monad plus action.
liftMaybe :: MonadPlus m => Maybe a -> m a
liftMaybe = maybe mzero return
-- | Lift a maybe to a monad action with the given failure message.
liftMaybe' :: Monad m => String -> Maybe a -> m a
liftMaybe' msg = maybe (fail msg) return
-- | Parse a token based on the acceptance condition
token :: (Keyword -> Maybe a) -> Parser s a
token p = P.token (show . snd) fst (p . snd)
-- | Parse a term.
kw :: Keyword -> Parser s ()
kw t = token check
where
check t' | t == t' = Just () | otherwise = Nothing
-- | Parse content between keywords.
betweenKWs :: Keyword -> Keyword -> Parser s a -> Parser s a
betweenKWs l r = between (kw l) (kw r)
-- | Between braces.
braced :: Parser s a -> Parser s a
braced = betweenKWs LBRACE RBRACE
-- | Between parentheses.
parens :: Parser s a -> Parser s a
parens = betweenKWs LPAREN RPAREN
-- | Between parentheses.
brackets :: Parser s a -> Parser s a
brackets = betweenKWs LBRACKET RBRACKET
-- | Between single quotes.
singleQuoted :: Parser s a -> Parser s a
singleQuoted = betweenKWs SQUOTE SQUOTE
-- | Between double quotes.
doubleQuoted :: Parser s a -> Parser s a
doubleQuoted = betweenKWs DQUOTE DQUOTE
-- | Parse an identifier as a string
identifier :: Parser s String
identifier = token extract
where extract (IDENT name) = Just $ name
extract _ = Nothing
-- | Parse a fixed string which could be an identifier.
string :: String -> Parser s ()
string cs = (try $ do { i <- identifier; guard (i == cs) }) <?> ('`' : cs ++ "'")
-- | Parse a sequence of fixed strings.
strings :: [String] -> Parser s ()
strings = mapM_ string
-- | Parse an integer.
integer :: Parser s Int
integer = do i <- identifier
guard (all isDigit i)
return (read i)
-- | A comma separated list of elements.
commaSep :: Parser s a -> Parser s [a]
commaSep = (`sepBy` kw COMMA)
-- | A comma separated non-empty list of elements.
commaSep1 :: Parser s a -> Parser s [a]
commaSep1 = (`sepBy1` kw COMMA)
-- | Parse a list of items '[' item ',' ... ',' item ']'
list :: Parser s a -> Parser s [a]
list p = kw LBRACKET *> commaSep p <* kw RBRACKET
------------------------------------------------------------------------------
-- Lexing, parsing and proving theory files
------------------------------------------------------------------------------
-- Lexing
---------
-- | Scan a file
scanFile :: FilePath -> IO [Token]
scanFile f = do
s <- readFile f
return $ scanString f s
-- Parsing
----------
-- | Parser s a theory file.
parseFile :: Parser s a -> s -> FilePath -> IO a
parseFile parser state f = do
s <- readFile f
case runParser parser state f (scanString f s) of
Right p -> return p
Left err -> error $ show err
-- | Parse a security protocol theory given as a string using the given
-- filename for the error messages
parseTheory :: FilePath -> IO Theory
parseTheory = parseFile theory ()
------------------------------------------------------------------------------
-- Parsing Patterns and Messages
------------------------------------------------------------------------------
-- | An identifier.
ident :: Parser s Id
ident = Id <$> identifier
-- | Left-hand-side of a function application written with the given delimiter.
genFunOpen :: Parser s a -> Parser s b -> Parser s a
genFunOpen ldelim f = try $ f *> ldelim
-- | Left-hand-side of a function application.
genFunApp :: Parser s a -> Parser s b -> Parser s d -> Parser s c -> Parser s c
genFunApp ldelim rdelim f arg = genFunOpen ldelim f *> arg <* rdelim
-- | Left-hand-side of a function application.
funOpen :: String -> Parser s ()
funOpen = genFunOpen (kw LPAREN) . string
-- | A function application.
funApp :: String -> Parser s a -> Parser s a
funApp = genFunApp (kw LPAREN) (kw RPAREN) . string
-- Extended patterns supported by the parser but not by the underlying free
-- term algebra. They are used in the 'scyther-ac-proof' application.
---------------------------------------------------------------------------
mkLTSPat :: Pattern -> Pattern
mkLTSPat x = PHash (PTup (PConst (Id "PARSE_LTS")) x)
mkMultIdentityPat :: Pattern
mkMultIdentityPat = PHash (PConst (Id "PARSE_MULT_IDENTITY"))
mkExpPat :: Pattern -> Pattern -> Pattern
mkExpPat x y = PHash (PTup (PConst (Id "PARSE_EXP")) (PTup x y))
mkMultPat :: Pattern -> Pattern -> Pattern
mkMultPat x y = PHash (PTup (PConst (Id "PARSE_MULT")) (PTup x y))
destLTSPat :: Pattern -> Maybe Pattern
destLTSPat (PHash (PTup (PConst (Id "PARSE_LTS")) x)) = return x
destLTSPat _ = mzero
destMultIdentityPat :: Pattern -> Maybe ()
destMultIdentityPat (PHash (PConst (Id "PARSE_MULT_IDENTITY"))) = return ()
destMultIdentityPat _ = mzero
destExpPat :: Pattern -> Maybe (Pattern, Pattern)
destExpPat (PHash (PTup (PConst (Id "PARSE_EXP")) (PTup x y))) = return (x,y)
destExpPat _ = mzero
destMultPat :: Pattern -> Maybe (Pattern, Pattern)
destMultPat (PHash (PTup (PConst (Id "PARSE_MULT")) (PTup x y))) = return (x,y)
destMultPat _ = mzero
-- Patterns
-----------
-- | Parse a pattern.
-- NOTE: All local atoms (MFresh, MMVar, MAVar) are set to MMVar with a space
-- preceding the identifier to mark it for later resolution.
--
-- TODO: Remove this ugly string hack.
pattern :: Parser s Pattern
pattern = asum
[ string "1" *> pure mkMultIdentityPat
, kw UNDERSCORE *> pure PAny
, PConst <$> singleQuoted ident
, PMVar <$> (kw QUESTIONMARK *> ident)
, PAVar <$> (kw DOLLAR *> ident)
, PFresh <$> (kw TILDE *> ident)
, parens tuplepattern
, PHash <$> funApp "h" tuplepattern
, mkLTSPat <$> funApp "lts" tuplepattern
, PSymK <$> (try (funOpen "k") *> multpattern <* kw COMMA) <*> (multpattern <* kw RPAREN)
, PShrK <$> (try (string "k" *> kw LBRACKET) *> multpattern <* kw COMMA)
<*> (multpattern <* kw RBRACKET)
, PAsymPK <$> funApp "pk" tuplepattern
, PAsymSK <$> funApp "sk" tuplepattern
, PEnc <$> braced tuplepattern <*> pattern
, PSign <$> genFunApp (kw LBRACE) (kw RBRACE) (string "sign") tuplepattern <*> pattern
, PMVar <$> tempIdentifier
]
-- | Parse a specification variable. Untyped identifiers are handled as in
-- 'pattern'.
specVariable :: Parser s VarId
specVariable = asum
[ SMVar <$> (kw QUESTIONMARK *> ident)
, SAVar <$> (kw DOLLAR *> ident)
, SMVar <$> tempIdentifier
]
-- | Parse multiple ^ applications as a left-associative list of exponentations
-- hackily marked using hashes and constant identifiers.
exppattern :: Parser s Pattern
exppattern = chainl1 pattern (mkExpPat <$ kw HAT)
-- | Parse multiple ^ applications as a left-associative list of
-- multiplications hackily marked using hashes and constant identifiers.
multpattern :: Parser s Pattern
multpattern = chainl1 exppattern (mkMultPat <$ kw STAR)
-- | Parse a comma separated list of patterns as a sequence of
-- right-associative tuples.
tuplepattern :: Parser s Pattern
tuplepattern = chainr1 multpattern (PTup <$ kw COMMA)
-- | Parse a local identifier which is yet unresolved. The identifier is
-- prefixed by a space to mark it for later resolution.
tempIdentifier :: Parser s Id
tempIdentifier = do i <- identifier
if isLetter (head i)
then return (Id (' ':i))
else fail $ "invalid variable name '" ++ i ++
"': variable names must start with a letter"
-- | Drops the space prefix used for identifying identifiers that need to be
-- resolved later.
dropSpacePrefix :: Id -> Id
dropSpacePrefix (Id (' ':i)) = Id i
dropSpacePrefix i = i
-- | Resolve the type of a local identifier according to the sets of agent
-- variables and the set of message variables. Fresh messages are the ones
-- which are in none these sets.
resolveId :: S.Set Id -> S.Set Id -> Id -> Pattern
resolveId avars mvars i
| i `S.member` avars = PAVar i
| i `S.member` mvars = PMVar i
| otherwise = PFresh i
-- | Resolve all identifiers in the pattern.
resolveIds :: S.Set Id -> S.Set Id -> Pattern -> Pattern
resolveIds avars mvars = patMapFMV resolve
where
resolve i = case getId i of
' ':i' -> resolveId avars mvars (Id i')
_ -> PMVar i
-- | Resolve identifiers as identifiers of the given role.
-- PRE: The role must use disjoint identifiers for fresh messages, agent
-- variables, and message variables.
resolveIdsLocalToRole :: Role -> Pattern -> Pattern
resolveIdsLocalToRole role = resolveIds (roleFAV role) (roleFMV role)
-- | Resolve the type of a specification variable according to the set of
-- agent and message variables.
--
-- TODO: Better error handling.
resolveVarId :: S.Set Id -> S.Set Id -> VarId -> VarId
resolveVarId avars mvars (SMVar i) = case getId i of
' ':i'
| Id i' `S.member` avars -> SAVar (Id i')
| Id i' `S.member` mvars -> SMVar (Id i')
| otherwise -> error $ "resolveVarId: '" ++ i' ++
"' resolves to neither agent nor message variable"
_ -> SMVar i
resolveVarId _ _ v = v
-- Messages
-----------
-- | Parse a thread identifier.
threadId :: Parser s TID
threadId = TID <$> (kw SHARP *> integer)
-- | Parse a local identifier.
localIdentifier :: Parser s LocalId
localIdentifier = LocalId <$> ((,) <$> ident <*> threadId)
-- | Resolve a thread identifier
resolveTID :: MonadPlus m => E.Mapping -> TID -> m Role
resolveTID mapping tid =
liftMaybe' ("resolveTID: no role assigned to thread "++show tid)
(E.threadRole tid (E.getMappingEqs mapping))
-- | Resolve a local identifier.
-- PRE: Thread id must be in the role equalities.
resolveLocalId :: MonadPlus m => E.Mapping -> LocalId -> m Message
resolveLocalId mapping (LocalId (i, tid)) =
do role <- resolveTID mapping tid
return $ inst tid (resolveId (roleFAV role) (roleFMV role) i)
`mplus`
(fail $ "resolveLocalId: no role defined for thread " ++ show tid)
-- | Resolve an executed step.
resolveStep :: MonadPlus m => E.Mapping -> TID -> String -> m RoleStep
resolveStep mapping tid stepId = do
role <- resolveTID mapping tid
let roleId = roleName role
if isPrefixOf roleId stepId
then liftMaybe' ("resolveStep: step '"++stepId++"' not part of role '"++roleName role++"'")
(lookupRoleStep (drop (length roleId + 1) stepId) role)
else fail ("resolveStep: role of step '"++stepId++"' does not agree to role '"
++roleName role++"' of thread "++show tid)
-- | Parse an instantiation of a pattern.
instantiation :: MonadPlus m => Parser s (E.Mapping -> m Message)
instantiation = do
tid <- TID <$> (funOpen "inst" *> integer <* kw COMMA)
m <- (do i <- identifier
let (stepId, iTyp) = splitAt (length i - 3) i
when (iTyp /= "_pt") (fail $ "inst: could not resolve pattern '"++i++"'")
return $ \mapping -> do
step <- resolveStep mapping tid stepId
return (inst tid $ stepPat step)
`mplus`
do pt <- pattern
return $ \mapping -> do
role <- resolveTID mapping tid
return (inst tid $ resolveIds (roleFAV role) (roleFMV role) pt)
)
kw RPAREN
return m
-- Parse a message.
message :: MonadPlus m => Parser s (E.Mapping -> m Message)
message = asum
[ instantiation
, (pure . return . MConst) <$> betweenKWs SQUOTE SQUOTE ident
, parens tuplemessage
, (liftA $ liftM MHash) <$> funApp "h" tuplemessage
, (liftA2 $ liftM2 MSymK) <$> (funOpen "k" *> message) <*> (kw COMMA *> message <* kw RPAREN)
, (liftA $ liftM MAsymPK) <$> funApp "pk" message
, (liftA $ liftM MAsymSK) <$> funApp "sk" message
, (liftA2 $ liftM2 MEnc) <$> braced tuplemessage <*> message
, (liftA $ liftM MInvKey) <$> funApp "inv" tuplemessage
, (flip resolveLocalId) <$> localIdentifier
]
-- | Parse a comma separated list of patterns as a sequence of
-- right-associative tuples.
tuplemessage :: MonadPlus m => Parser s (E.Mapping -> m Message)
tuplemessage = chainr1 message ((liftA2 $ liftM2 MTup) <$ kw COMMA)
------------------------------------------------------------------------------
-- Parsing Alice and Bob Protocol Specifications
------------------------------------------------------------------------------
{- EBNF for the Alice and Bob protocol language
TODO: Update to new syntax
Protocol := "protocol" Identifier "{" Transfer+ "}"
Transfer := Identifier "->" Identifier ":" Term
| Identifier "->" ":" Term "<-" Identifier ":" Term
| Identifier "<-" ":" Term "->" Identifier ":" Term
Term := "{" Term "}" Key
| Term "," Term
| Identifier
Key := "sk(" Identifier ")"
| "pk(" Identifier ")"
| "k(" Identifier, Identifier ")"
| Term
Identifier := [A..Za..z-_]
-}
-- | Parse a single transfer with the given label.
transfer :: Label -> Parser s [(Id, RoleStep)]
transfer lbl =
do right <- kw RIGHTARROW *> ident <* kw COLON
pt <- tuplepattern
return [(right, Recv lbl pt)]
<|>
do right <- kw LEFTARROW *> ident <* kw COLON
ptr <- tuplepattern
(do left <- try $ ident <* kw LEFTARROW <* kw COLON
ptl <- tuplepattern
return [(left, Recv lbl ptl),(right, Send lbl ptr)]
<|>
return [(right, Send lbl ptr)]
)
<|>
do left <- ident
(do kw RIGHTARROW
(do right <- ident <* kw COLON
pt <- tuplepattern
return [(left,Send lbl pt), (right, Recv lbl pt)]
<|>
do ptl <- kw COLON *> tuplepattern
(do right <- kw RIGHTARROW *> ident <* kw COLON
ptr <- tuplepattern
return [(left,Send lbl ptl), (right, Recv lbl ptr)]
<|>
do return [(left, Send lbl ptl)]
)
)
<|>
do kw LEFTARROW
(do pt <- kw COLON *> tuplepattern
return [(left, Recv lbl pt)]
<|>
do right <- ident <* kw COLON
pt <- tuplepattern
return [(left, Recv lbl pt), (right, Send lbl pt)]
)
)
-- | Try to parse a local computation with the given label.
compute :: Label -> Parser s [(Id, RoleStep)]
compute lbl = do
actor <- try $ ident <* kw COLON
v <- specVariable
eq <- (kw RIGHTARROW *> pure True) <|> (kw SHARP *> pure False)
ptr <- tuplepattern
return [(actor, Match lbl eq v ptr)]
-- | Parse a labeled part of a protocol specification, i.e., either a transfer
-- or a computation.
labeledSteps :: Parser s [(Id, RoleStep)]
labeledSteps = do
lbl <- Label <$> identifier <* kw DOT
compute lbl <|> transfer lbl
-- | Parse a protocol.
protocol :: Parser s Protocol
protocol = do
name <- string "protocol" *> identifier
allSteps <- concat <$> braced (many1 labeledSteps)
-- convert parsed steps into role scripts
let roleIds = S.fromList $ map fst allSteps
roles = do
actor <- S.toList roleIds
let steps = [ step | (i, step) <- allSteps, i == actor ]
return $ Role (getId actor)
(ensureFreshSteps actor (S.map addSpacePrefix roleIds) steps)
return $ Protocol name roles
where
addSpacePrefix = Id . (' ':) . getId
dropSpacePrefixes = S.map dropSpacePrefix
-- | Ensure message variables are received before they are sent.
ensureFreshSteps actor possibleAvars =
go (S.singleton (addSpacePrefix actor)) S.empty S.empty
where
-- TODO: Make sure that this does what one expects.
go _ _ _ [] = []
go avars mvars fresh (step : rs) = step' : go avars' mvars' fresh' rs
where
avars' = avars `S.union` (((stepUsedMV step `S.intersection` possibleAvars)
`S.difference` mvars) `S.difference` fresh)
mvars' = mvars `S.union` ((stepBoundMV step `S.difference` avars')
`S.difference` fresh)
fresh' = fresh `S.union` ((stepUsedMV step `S.difference` avars')
`S.difference` mvars')
pt' = resolveIds (dropSpacePrefixes avars') (dropSpacePrefixes mvars')
(stepPat step)
step' = case step of
Send l _ -> Send l pt'
Recv l _ -> Recv l pt'
Match l eq v _ -> Match l eq (resolveVarId (dropSpacePrefixes avars')
(dropSpacePrefixes mvars') v) pt'
------------------------------------------------------------------------------
-- Parse Claims
------------------------------------------------------------------------------
-- | Parse a claim.
claims :: (String -> Maybe Protocol) -> Parser s [ThyItem]
claims protoMap = do
let mkAxiom (name, se) = ThyTheorem (name, Axiom se)
(multiplicity, mkThyItem) <-
(string "property" *> pure (id, ThySequent)) <|>
(string "properties" *> pure ((concat <$>) . many1, ThySequent)) <|>
(string "axiom" *> pure (id, mkAxiom ))
protoId <- kw LPAREN *> string "of" *> identifier
proto <- liftMaybe' ("unknown protocol '"++protoId++"'") $ protoMap protoId
kw RPAREN
multiplicity $ do
claimId <- try $ identifier <* kw COLON
when ('-' `elem` claimId) (fail $ "hyphen '-' not allowed in property name '"++claimId++"'")
let mkThySequent (mkClaimId, se) = mkThyItem (mkClaimId claimId, se)
singleSequents = map (liftM (return . (,) id) . ($ proto))
[ agreeSequent, secrecySequent, implicationSequent, parseTypingSequent ]
multiSequents = map ($ proto)
[ parseNonceSecrecy, parseFirstSends
, parseTransferTyping, parseAutoProps ]
sequents <- asum $ multiSequents ++ singleSequents
return $ map mkThySequent sequents
-- | Auto-generated simple properties: first-sends, ltk-secrecy, nonce-secrecy,
-- msc-typing
parseAutoProps :: Protocol -> Parser s [(String -> String,Sequent)]
parseAutoProps proto =
string "auto" *> kw MINUS *> string "properties" *>
pure (concat
[ transferTyping proto, firstSendSequents proto, nonceSecrecySequents proto ])
-- | Create secrecy claims for nonces and variables.
parseNonceSecrecy :: Protocol -> Parser s [(String -> String,Sequent)]
parseNonceSecrecy proto =
string "nonce" *> kw MINUS *> string "secrecy" *> pure (nonceSecrecySequents proto)
-- | Create secrecy claims for nonces and variables.
nonceSecrecySequents :: Protocol -> [(String -> String,Sequent)]
nonceSecrecySequents proto =
concatMap mkSequent . toposort $ protoOrd proto
where
mkSequent (step, role) = case step of
Send _ pt -> do
n@(PFresh i) <- S.toList $ subpatterns pt
guard (not (plainUse pt n) && firstUse n)
return $ secrecySe (MFresh . Fresh) i
Recv _ pt -> varSequents pt
Match _ True _ pt -> varSequents pt
Match _ False _ _ -> mzero
where
(tid, prem0) = freshTID (empty proto)
(prefix, _) = break (step ==) $ roleSteps role
firstUse = (`S.notMember` (S.unions $ map (subpatterns . stepPat) prefix))
plainUse pt = (`S.member` splitpatterns pt)
avars = [ MAVar (AVar (LocalId (v,tid)))
| (PAVar v) <- S.toList . S.unions . map (subpatterns.stepPat) $ roleSteps role ]
varSequents pt = do
v@(PMVar i) <- S.toList $ subpatterns pt
guard (not (plainUse pt v) && firstUse v)
return $ secrecySe (MMVar . MVar) i
secrecySe constr i =
( (++("_"++roleName role++"_sec_"++getId i))
, Sequent prem (FAtom (ABool False)) Standard
)
-- flip (Sequent proto) FFalse $ FFacts $
-- insertEv (Learn (constr (LocalId (i,tid)))) $
-- insertEv (Step tid step) $
-- foldr uncompromise (insertRole tid role emptyFacts) avars
where
-- here we know that conjunction will work, as we build it by ourselves
Just (Just prem) = conjoinAtoms atoms prem0
atoms = [ AEq (E.TIDRoleEq (tid, role))
, AEv (Step tid step)
, AEv (Learn (constr (LocalId (i, tid))))
] ++ map AUncompr avars
parseFirstSends :: Protocol -> Parser s [(String -> String,Sequent)]
parseFirstSends proto =
string "first" *> kw MINUS *> string "sends" *> pure (firstSendSequents proto)
firstSendSequents :: Protocol -> [(String -> String,Sequent)]
firstSendSequents proto =
concatMap mkRoleSequents $ protoRoles proto
where
mkRoleSequents role =
concatMap mkStepSequents $ zip (inits steps) steps
where
steps = roleSteps role
(tid, prem0) = freshTID (empty proto)
mkStepSequents (_, Recv _ _) = []
mkStepSequents (_, Match _ _ _ _) = []
mkStepSequents (prefix, step@(Send _ pt)) = do
n@(PFresh i) <- S.toList $ splitpatterns pt
guard (n `S.notMember` S.unions (map (subpatterns.stepPat) prefix))
let learn = (Learn (MFresh (Fresh (LocalId (i, tid)))))
atoms = [ AEq (E.TIDRoleEq (tid, role)), AEv learn ]
Just (Just prem) = conjoinAtoms atoms prem0
concl = FAtom (AEvOrd (Step tid step, learn))
return ( (++("_" ++ getId i)), Sequent prem concl Standard)
parseTransferTyping :: Protocol -> Parser s [(String -> String, Sequent)]
parseTransferTyping proto =
string "msc" *> kw MINUS *> string "typing" *> pure (transferTyping proto)
transferTyping :: Protocol -> [(String -> String, Sequent)]
transferTyping proto = case mscTyping proto of
Just typing -> pure
((++"_msc_typing"), Sequent (empty proto) (FAtom (ATyping typing)) Standard)
Nothing -> fail "transferTyping: failed to construct typing"
-- | Parse secrecy formula.
secrecySequent :: Protocol -> Parser s Sequent
secrecySequent proto = do
let (tid, prem0) = freshTID (empty proto)
roleId <- funOpen "secret" *> identifier
role <- liftMaybe' ("could not find role '"++roleId++"'") $ lookupRole roleId proto
lbl <- kw COMMA *> (identifier <|> kw MINUS *> pure "-")
stepAtoms <-
(do step <- liftMaybe $ lookupRoleStep lbl role
return $ [AEv (Step tid step)]
`mplus` return [])
kw COMMA
(msgMod, pt) <- asum
[ ((,) MInvKey) <$> funApp "inv" tuplepattern
, ((,) id) <$> pattern ]
let m = msgMod . inst tid . resolveIdsLocalToRole role $ pt
kw COMMA
uncompromised <- map (inst tid . resolveIdsLocalToRole role) <$> msgSet
kw RPAREN
-- construct secrecy claim
let atoms = [ AEq (E.TIDRoleEq (tid, role)), AEv (Learn m) ] ++ stepAtoms ++
map AUncompr uncompromised
prem = case conjoinAtoms atoms prem0 of
Just (Just prem1) -> prem1
Just Nothing -> error "secrecySequent: secrecy claim is trivially true"
Nothing -> error "secrecySequent: failed to construct secrecy claim"
return $ Sequent prem (FAtom (ABool False)) Standard
where
msgSet = braced $ sepBy pattern (kw COMMA)
-- | Parse (non-)injective agreement claim.
agreeSequent :: Protocol -> Parser s Sequent
agreeSequent proto = do
qualifier <- (funOpen "niagree" *> pure Standard) <|>
(funOpen "iagree" *> pure Injective)
(roleCom, stepCom, patCom) <- roleStepPattern
kw RIGHTARROW
(roleRun, stepRun, patRun) <- roleStepPattern
kw COMMA
uncompromised <- map (AUncompr . instPat tidCom roleCom) <$> patSet
kw RPAREN
let premAtoms = [ AEq (E.TIDRoleEq (tidCom, roleCom))
, AEv (Step tidCom stepCom)
] ++
uncompromised
conclAtoms = [ AEq (E.TIDRoleEq (tidRun, roleRun))
, AEv (Step tidRun stepRun)
, AEq (E.MsgEq ( instPat tidRun roleRun patRun
, instPat tidCom roleCom patCom ))
]
concl = FExists (Left tidRun) (foldr1 FConj $ map FAtom conclAtoms)
prem = case conjoinAtoms premAtoms prem0 of
Just (Just prem1) -> prem1
Just Nothing -> error "niagreeSequent: claim is trivially true"
Nothing -> error "niagreeSequent: failed to construct claim"
return (Sequent prem concl qualifier)
where
(tidCom, prem0) = freshTID (empty proto)
tidRun = succ tidCom
patSet = braced $ sepBy pattern (kw COMMA)
instPat tid role = inst tid . resolveIdsLocalToRole role
-- parse a step and a local pattern; e.g., 'B_1[A,B,TNA,Text1]'
roleStepPattern = do
(role, step) <- roleStepById proto
pat <- kw LBRACKET *> tuplepattern <* kw RBRACKET
return (role, step, pat)
-- | Parse an explicit list of typing assertions.
parseTypingSequent :: Protocol -> Parser s Sequent
parseTypingSequent proto = do
typ <- M.fromList <$> doubleQuoted (many1 typeAssertion)
return $ Sequent (empty proto) (FAtom (ATyping typ)) Standard
where
variable = (,) <$> (Id <$> identifier) <*> (kw AT *> roleById proto)
typeAssertion = (,) <$> (variable <* kw COLON <* kw COLON)
<*> (normType <$> msgTypeDisj)
msgTypeTup = foldr1 TupT <$> sepBy1 msgTypeDisj (kw COMMA)
msgTypeDisj = foldr1 SumT <$> sepBy1 msgType (kw MID)
msgType = asum
[ pure AgentT <* string "Agent"
, (ConstT . Id) <$> singleQuoted identifier
, HashT <$> funApp "h" msgTypeTup
, EncT <$> braced msgTypeTup <*> msgType
, SymKT <$> (funOpen "k" *> msgTypeDisj) <*> (kw COMMA *> msgTypeDisj <* kw RPAREN)
, AsymPKT <$> funApp "pk" msgTypeTup
, AsymSKT <$> funApp "pk" msgTypeTup
, KnownT <$> funApp "Known" (snd <$> roleStepById proto)
, flip NonceT <$> (Id <$> identifier) <*> (kw AT *> roleById proto)
, parens msgTypeTup
]
-- | Parser a role given only by its identifier.
roleById :: Protocol -> Parser s Role
roleById proto = do
roleId <- identifier
case lookupRole roleId proto of
Just role -> return role
Nothing -> fail $ "role '"++roleId++"' does not occur in protocol '"
++protoName proto++"'"
-- parse a role step given by its identifier 'B_1'.
roleStepById :: Protocol -> Parser s (Role, RoleStep)
roleStepById proto = do
stepId <- identifier
let (lbl, roleId) = (reverse *** (init . reverse)) (break ('_' ==) $ reverse stepId)
role <- liftMaybe' ("could not find role '" ++ roleId ++
"' in protocol '" ++ protoName proto ++ "'")
(lookupRole roleId proto)
step <- liftMaybe' ("unknown label '" ++ lbl ++ "' in role '" ++ roleId ++ "'")
(lookupRoleStep lbl role)
return (role, step)
-- General premises parsing
---------------------------
-- | A raw fact: Either a premise modifier parametrized over a set of role
-- equalities or a single role equality. We'll use these facts to allow for
-- late binding of thread ids to roles.
data RawFact m =
RawAtom (E.Mapping -> m Atom)
| RawTIDRoleEq TID String
-- | Extract the role equalities from a list of raw facts.
extractRoleEqs :: MonadPlus m => Protocol -> [RawFact m] -> m [(TID, Role)]
extractRoleEqs proto facts =
mapM mkEq [(tid, roleId) | RawTIDRoleEq tid roleId <- facts]
where
mkEq (tid, roleId) = case lookupRole roleId proto of
Just role -> return (tid, role)
Nothing -> fail $ "mkRoleEqs: role '"++roleId++"' does not occur in protocol '"
++protoName proto++"'"
-- | Parse a role equality.
roleEqFact :: MonadPlus m => Parser s (RawFact m)
roleEqFact = RawTIDRoleEq <$> (TID <$> (string "role" *> parens integer))
<*> (kw EQUAL *> identifier)
-- | Parse a knowledge fact.
knowsFact :: MonadPlus m => Parser s (RawFact m)
knowsFact = do
m <- funApp "knows" message
return $ RawAtom (liftM (AEv . Learn) <$> m)
-- | Parsing an executed role step.
rawStep :: MonadPlus m => Parser s (E.Mapping -> m Event)
rawStep = parens $ do
tid <- TID <$> integer
stepId <- kw COMMA *> identifier
let step = resolveStep <*> pure tid <*> pure stepId
return $ (liftM (Step tid) <$> step)
-- | Parse a step fact.
stepFact :: MonadPlus m => Parser s (RawFact m)
stepFact = do
step <- string "step" *> rawStep
return $ RawAtom (liftM AEv <$> step)
-- | Parse an honesty assumption.
honestFact :: MonadPlus m => Parser s [RawFact m]
honestFact = do
string "uncompromised"
msgs <- parens (sepBy1 message (kw COMMA))
-- let mod prems = foldr uncompromise prems lids
return $ [RawAtom (liftM AUncompr <$> m) | m <- msgs]
-- | Parses a learn or a step event.
event :: MonadPlus m => Parser s (E.Mapping -> m Event)
event = asum [ string "St" *> rawStep
, (liftM Learn <$>) <$> (string "Ln" *> message)
, (liftM Learn <$>) <$> instantiation ]
-- | Parse a series of ordering facts.
orderFacts :: MonadPlus m => Parser s [RawFact m]
orderFacts = do
ev <- event <* kw LESS
evs <- sepBy1 event (kw LESS)
let mkAtom e1 e2 = RawAtom $ \mapping -> do
e1' <- e1 mapping
e2' <- e2 mapping
return $ AEvOrd (e1', e2')
return $ zipWith mkAtom (ev:evs) evs
-- | Parse an equality fact.
eqFact :: MonadPlus m => Parser s (RawFact m)
eqFact = do
m1 <- message <* kw EQUAL
m2 <- message
return $ RawAtom (liftM2 (\x y -> AEq (E.MsgEq (x , y))) <$> m1 <*> m2)
-- | Parse a raw fact.
rawFacts :: MonadPlus m => Parser s [RawFact m]
rawFacts = foldl1 (<|>)
( [try orderFacts, honestFact] ++
map (liftM return) [roleEqFact, knowsFact, stepFact, eqFact] )
-- | Parse the conclusion "False".
falseConcl :: Parser s Formula
falseConcl = doubleQuoted (string "False" *> pure (FAtom (ABool False)))
-- | Parse a conclusion formula consisting of raw facts.
--
-- TODO: Handling of role equalities is incomplete.
factsFormula :: Protocol -> E.Mapping -> Parser s Formula
factsFormula proto mapping = doubleQuoted formula
where
formula = foldr1 FDisj `liftM` sepBy1 term (kw MID)
term = do
conjuncts <- sepBy1 factOrFormula (kw AND)
let (facts, subformulas) = first concat $ partitionEithers conjuncts
roleeqs <- extractRoleEqs proto facts
let mapping' = foldr (uncurry E.addTIDRoleMapping) mapping roleeqs
atoms <- (map (AEq . E.TIDRoleEq) roleeqs ++) `liftM`
sequence [ mkAtom mapping' | RawAtom mkAtom <- facts ]
return $ foldr1 FConj (map FAtom atoms ++ subformulas)
factOrFormula = (Left <$> try rawFacts) <|> (Right <$> parens formula)
-- | Parse a conclusion stating existence of some threads of a specific
-- structure.
existenceConcl :: Protocol -> E.Mapping -> Parser s Formula
existenceConcl proto mapping = do
tids <- map (Left . TID) <$> (threads <|> pure [])
inner <- factsFormula proto mapping
return $ foldr FExists inner tids
where
singleThread = pure <$> (strings ["a", "thread"] *> integer)
multiThreads = strings ["threads"] *> sepBy1 integer (kw COMMA)
threads = (singleThread <|> multiThreads) <* strings ["such","that"]
-- | Parse a conclusion.
-- currently only contradiction supported
conclusion :: Protocol -> E.Mapping -> Parser s Formula
conclusion proto mapping = asum
[try falseConcl, existenceConcl proto mapping]
-- | Parse a general implication claim.
implicationSequent :: Protocol -> Parser s Sequent
implicationSequent proto = do
facts <- concat <$> (string "premises" *> many (doubleQuoted rawFacts))
roleeqs <- extractRoleEqs proto facts
let mapping = foldr (uncurry E.addTIDRoleMapping) (E.Mapping E.empty) roleeqs
quantifiers = map fst roleeqs
atoms <- (map (AEq . E.TIDRoleEq) roleeqs ++) `liftM`
sequence [ mkAtom mapping | RawAtom mkAtom <- facts ]
prems0 <- foldM (flip quantifyTID) (F.empty proto) quantifiers
optPrems <- conjoinAtoms atoms prems0
prems <- maybe (fail "contradictory premises") return optPrems
qualifier <- option Standard (string "injectively" *> pure Injective)
string "imply"
concl <- conclusion proto mapping
return $ Sequent prems concl qualifier
{-
-- | Construct the premise modifier. The given set of role equalities is used
-- for thread identfier lookup.
mkPremiseMod :: MonadPlus m => E.Mapping -> [RawFact m] -> Facts -> m Facts
mkPremiseMod mapping rawfacts facts = do
atoms <- sequence [ mkAtom mapping | RawAtom mkAtom <- rawfacts ]
optFacts <- conjoinAtoms atoms facts
maybe (error "mkPremiseMod: contradictory facts") return $ optFacts
-}
-- | A formal comment; i.e., (header, body)
formalComment :: Parser s (String, String)
formalComment =
(,) <$> text begin
<*> (concat <$> many (text content) <* text end)
where
text f = token (\t -> case t of TEXT ty -> f ty; _ -> mzero)
begin (TextBegin str) = return str
begin _ = mzero
content (TextContent str) = return str
content _ = mzero
end (TextEnd) = return ()
end _ = mzero
------------------------------------------------------------------------------
-- Parse a theory
------------------------------------------------------------------------------
-- | Parse a theory.
theory :: Parser s Theory
theory = do
string "theory"
thyId <- identifier
string "begin" *> addItems (Theory thyId []) <* string "end"
where
addItems :: Theory -> Parser s (Theory)
addItems thy =
do p <- protocol
case lookupProtocol (protoName p) thy of
Just _ -> fail $ "duplicate protocol '" ++ protoName p ++ "'"
Nothing -> addItems (insertItem (ThyProtocol p) thy)
<|>
do item <- uncurry ThyText <$> formalComment
addItems (insertItem item thy)
<|>
do cs <- claims (flip lookupProtocol thy)
addItems (foldl' (flip insertItem) thy cs)
<|>
do return thy
| meiersi/scyther-proof | src/Scyther/Theory/Parser.hs | gpl-3.0 | 36,410 | 33 | 28 | 9,167 | 10,878 | 5,490 | 5,388 | 649 | 5 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TypeFamilies #-}
module Object.Account where
import Data.Serialize
import GHC.Generics
import Servant.Server.Experimental.Auth.Cookie
data Account = Account { uid :: Integer, username :: String } deriving Generic
instance Serialize Account
type instance AuthCookieData = Account | Ferdinand-vW/collab | server/src/Object/Account.hs | gpl-3.0 | 325 | 0 | 8 | 41 | 65 | 41 | 24 | 9 | 0 |
{-# OPTIONS_GHC -fno-warn-incomplete-patterns #-}
module QHaskell.Expression.Conversions.Evaluation.ADTUntypedNamed () where
import QHaskell.MyPrelude
import QHaskell.Expression.ADTUntypedNamed
import qualified QHaskell.Expression.ADTValue as FAV
import QHaskell.Environment.Map
import QHaskell.Conversion
instance (Show x , Eq x) => Cnv (Exp x , (Env x FAV.Exp , Env x FAV.Exp)) FAV.Exp where
cnv (ee , r@(s , g)) = join (case ee of
Var x -> FAV.var <$> get x g
Prm x es -> FAV.prm <$> get x s <*> mapM (\ e -> cnv (e,r)) es
_ -> $(biGenOverloadedML 'ee ''Exp "FAV" ['Prm,'Var]
(\ tt -> if
| matchQ tt [t| Exp x |] ->
[| \ e -> cnv (e , r) |]
| matchQ tt [t| (x , Exp x) |] ->
[| \ (x , e) ->
pure (\ v -> frmRgtZro (cnv (e , (s , (x,v) : g)))) |]
| otherwise ->
[| pure |])))
| shayan-najd/QHaskell | QHaskell/Expression/Conversions/Evaluation/ADTUntypedNamed.hs | gpl-3.0 | 906 | 0 | 20 | 269 | 295 | 168 | 127 | -1 | -1 |
-- Copyright (c) 2010 John Millikin
--
-- Permission is hereby granted, free of charge, to any person
-- obtaining a copy of this software and associated documentation
-- files (the "Software"), to deal in the Software without
-- restriction, including without limitation the rights to use,
-- copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the
-- Software is furnished to do so, subject to the following
-- conditions:
--
-- The above copyright notice and this permission notice shall be
-- included in all copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
-- OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
-- HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
-- WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-- FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
-- OTHER DEALINGS IN THE SOFTWARE.
{-# LANGUAGE OverloadedStrings #-}
module Main where
-- XMPP imports
import Network
import Network.Protocol.XMPP
import Data.XML.Types
-- other imports
import Control.Concurrent
import Control.Monad
import Control.Monad.IO.Class
import qualified Data.Text as T
import System.Environment
runEcho :: String -> T.Text -> T.Text -> IO ()
runEcho hostname user password = do
-- Verify that the user provided a valid JID, and that it contains a username
-- (AKA a "node").
jid <- case parseJID user of
Just x -> return x
Nothing -> error $ "Invalid JID: " ++ show user
username <- case strNode `fmap` jidNode jid of
Just x -> return x
Nothing -> error $ "JID must include a username"
-- 'Server' values record what host the connection will be opened to. Normally
-- the hostname and JID will be the same; however, in some cases the hostname is
-- something special (like "jabber.domain.com" or "localhost").
--
-- The port number is hardcoded to 5222 in this example, but in the wild there
-- might be servers with a jabberd running on alternative ports.
let server = Server
{ serverHostname = hostname
, serverJID = JID Nothing (jidDomain jid) Nothing
, serverPort = PortNumber 5222
}
-- 'runClient' and 'runComponent' open a connection to the remote server and
-- establish an XMPP session.
--
-- It is possible to run an XMPP session over multiple IO chunks using the
-- 'getSession' computation. The returned session value can be used to run
-- 'runXMPP'.
--
-- Unusual conditions like socket errors or async exceptions might cause this
-- computation to raise an exception, but in normal operation all XMPP errors
-- are returned via a 'Left' value.
--
-- 'XMPP' is an instance of 'MonadError', so you can use the standard
-- 'throwError' and 'catchError' computations to handle errors within an XMPP
-- session.
res <- runClient server jid username password $ do
-- When running a client session, most servers require the user to
-- "bind" their JID before sending any stanzas.
boundJID <- bindJID jid
-- Some servers will close the XMPP connection after some period
-- of inactivity. For this example, we'll simply send a "ping" every
-- 60 seconds
getSession >>= liftIO . forkIO . sendPings 60
-- 'XMPP' is an instance of 'MonadIO', so any IO may be performed
-- within.
liftIO $ putStrLn $ "Server bound our session to: " ++ show boundJID
-- This is a simple loop which will echo received messages back to the
-- sender; additionally, it prints *all* received stanzas to the console.
forever $ do
stanza <- getStanza
liftIO $ putStr "\n" >> print stanza >> putStrLn "\n"
case stanza of
ReceivedMessage msg -> if messageType msg == MessageError
then return ()
else putStanza $ echo msg
ReceivedPresence msg -> if presenceType msg == PresenceSubscribe
then putStanza (subscribe msg)
else return ()
_ -> return ()
-- If 'runClient' terminated due to an XMPP error, propagate it as an exception.
-- In non-example code, you might want to show this error to the user.
case res of
Left err -> error $ show err
Right _ -> return ()
-- Copy a 'Message' into another message, setting the 'messageTo' field to the
-- original sender's address.
echo :: Message -> Message
echo msg = Message
{ messageType = MessageNormal
, messageTo = messageFrom msg
-- Note: Conforming XMPP servers populate the "from" attribute on
-- stanzas, to prevent clients from spoofing it. Therefore, the
-- 'messageFrom' field's value is irrelevant when sending stanzas.
, messageFrom = Nothing
, messageID = Nothing
, messageLang = Nothing
, messagePayloads = messagePayloads msg
}
subscribe :: Presence -> Presence
subscribe p = Presence
{ presenceType = PresenceSubscribed
, presenceTo = presenceFrom p
, presenceFrom = Nothing
, presenceID = Nothing
, presenceLang = Nothing
, presencePayloads = []
}
-- Send a "ping" occasionally, to prevent server timeouts from
-- closing the connection.
sendPings :: Integer -> Session -> IO ()
sendPings seconds s = forever send where
send = do
-- Ignore errors
runXMPP s $ putStanza ping
threadDelay $ fromInteger $ 1000000 * seconds
ping = (emptyIQ IQGet)
{ iqPayload = Just (Element pingName [] [])
}
pingName :: Name
pingName = Name "ping" (Just "urn:xmpp:ping") Nothing
main :: IO ()
main = do
args <- getArgs
case args of
(server:user:pass:_) -> runEcho server (T.pack user) (T.pack pass)
_ -> do
name <- getProgName
error $ "Use: " ++ name ++ " <server> <username> <password>"
| jmillikin/haskell-xmpp | examples/echo.hs | gpl-3.0 | 5,704 | 29 | 18 | 1,123 | 867 | 472 | 395 | 73 | 8 |
{-# LANGUAGE TemplateHaskell, FlexibleInstances, IncoherentInstances, ScopedTypeVariables, MultiParamTypeClasses, ConstraintKinds #-}
module Sh where
import Test.QuickCheck
import DeriveArbitrary
import Language.Bash.Pretty
import Language.Bash.Syntax
import Text.PrettyPrint
import Language.Bash.Word
import qualified Data.ByteString.Lazy as LS
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BC8
import DeriveFixable
import Data.List
import Control.Monad.Trans
import Control.Monad.Trans.State
import Debug.Trace
import qualified Data.ByteString.ShellEscape as SE
import Data.Word(Word8, Word16, Word32)
import Strings
type Sh = Command
instance Arbitrary String where
arbitrary = genName
instance Arbitrary SE.Bash where
arbitrary = do
--l <- listOf (arbitrary :: Gen Word8)
return $ SE.escape $ BS.pack []
instance Arbitrary Parameter where
arbitrary = Parameter <$> arbitrary <*> (return Nothing)
getVId (ParamSubst (Bare p)) = p
getVId _ = (Parameter "" Nothing)
getAId (Assign p _ _) = p
initV :: StV (Parameter)
initV = StV []
printSt (StV v) = "\nstate: " ++ (concat $ map (\(Parameter i _) -> show i) v) ++ "\n"
popId :: Parameter -> VState Parameter ()
popId i = do st <- get
put $ st {vars = delete i (vars st)}
pushId :: Parameter -> VState Parameter ()
pushId i = do st <- get
put $ st {vars = i:(vars st)}
genCons :: Gen Span
genCons = resize 1 arbitrary{-do i <- arbitrary
a <- arbitrary
return (IntLit a i)-}
genVar :: [Parameter] -> Gen Span
genVar xs = do n <- elements xs
return (ParamSubst (Bare n))
$(devFixLang ''Parameter ['ParamSubst] ['Assign] ''Command)
instance (Arbitrary a, Eq a, Show a) => Fixable Parameter a where
fix = return
instance Arbitrary Sh where
arbitrary
= do a <- sized go
evalStateT (fix a) initV
where go n = Command <$> resize (max 0 (n - 1)) arbitrary
<*> (listOf $ (resize (n `div` 10) arbitrary))
$(devArbitrary ''Sh)
mencode :: Sh -> LS.ByteString
mencode x = LS.fromStrict $ BC8.pack $ render $ pretty x
| fcostantini/QuickFuzz | src/Sh.hs | gpl-3.0 | 2,191 | 0 | 14 | 506 | 722 | 386 | 336 | 56 | 1 |
module S03 where
{-
Module : S03
Description : Series 03 of the Functionnal and Logic Programming course at UniFR
Author : Sylvain Julmy
Email : sylvain.julmy(at)unifr.ch
-}
import Data.Char
-- Import for the test
import Test.QuickCheck
import Control.Monad
import qualified Data.List as L
import qualified Data.Set as S
-- Ex1.a
flatten :: [[a]] -> [a]
flatten [] = []
flatten (x:xs) = x ++ (flatten xs)
-- Ex1.b
partitions :: [a] -> [[a]]
partitions [] = [[]]
partitions (x:xs) = [x:parts | parts <- partitions xs] ++ -- first case, x belongs to the set
[parts | parts <- partitions xs] -- second case, x does not belongs to the set
-- Ex1.c
permutations :: Eq a => [a] -> [[a]]
permutations [] = [[]]
-- the permutations of xs are all the of x with all the permutations of xs \ x
permutations xs = [x:ys | x <- xs, ys <- permutations (delete' x xs)] where
delete' :: Eq a => a -> [a] -> [a]
delete' _ [] = []
delete' (e) (x:xs) = if e == x then xs else x:(delete' e xs)
find' :: Eq a => a -> [a] -> a
find' e xs = undefined
-- Ex2.a
-- why using a comprehension ?
length' :: [a] -> Int
length' l = sum [1 | _ <- l]
-- Ex2.b
deleteAll' :: Eq a => a -> [a] -> [a]
deleteAll' e l = [x | x <- l, x /= e]
-- Ex2.c
toUpperString :: String -> String
toUpperString s = [toUpper c | c <- s]
-- Tests
-- toUpperString
prop_toUpperString :: [Char] -> Bool
prop_toUpperString xs = (toUpperString xs) == (map toUpper xs)
-- flatten
prop_flatten :: Eq a => [[a]] -> Bool
prop_flatten xss = (flatten xss) == (join xss)
-- permutations
prop_permutations :: (Eq a, Ord a) => [[a]] -> Bool
prop_permutations xss = (S.fromList (permutations xss)) == (S.fromList (L.permutations xss))
-- length
prop_length :: [a] -> Bool
prop_length xs = (length' xs) == (length xs)
-- deleteAll
prop_deleteAll' :: Eq a => a -> [a] -> Bool
prop_deleteAll' e l = (deleteAll' e l) == (filter (\x -> x /= e) l)
-- Running the tests with the main programm
main = do
quickCheck prop_toUpperString
quickCheck (prop_flatten :: [[Int]] -> Bool)
quickCheck (prop_permutations :: [[Int]] -> Bool)
quickCheck (prop_length :: [Int] -> Bool)
quickCheck (prop_deleteAll' :: Int -> [Int] -> Bool)
| SnipyJulmy/mcs_notes_and_resume | fun-and-log-prog/exercices/s03/s03.hs | lgpl-3.0 | 2,207 | 0 | 11 | 462 | 868 | 473 | 395 | 43 | 3 |
module Main where
data Mood = Blah | Woot deriving Show
-- 1. Mood
-- 2. Blah or Woot
-- 3.
changeMood :: Mood -> Mood
changeMood Blah = Woot
changeMood _ = Blah
instance Eq Mood where
(==) Woot Woot = True
(==) Blah Blah = True
(==) _ _ = False
awesome = ["Papuchon", "curry", ":)"]
alsoAwesome = ["Quake", "The Simons"]
allAwesome = [awesome, alsoAwesome]
ex1 = not True && True
ex2 x = not (x == 6)
ex3 = (1 * 2) > 5
ex4 = ["Merry"] > ["Happy"]
ex5 = ['1', '2', '3'] ++ "look at me!"
len :: [a] -> Integer
len [] = 0
len (x : xs) = 1 + len xs
main :: IO ()
main = do
putStrLn "hello world"
isPalindrome :: (Eq a) => [a] -> Bool
isPalindrome x = x == reverse x
myAbs :: Integer -> Integer
myAbs n = if n > 0 then n else (-1) * n
f :: (a, b) -> (c, d) -> ((b, d), (a, c))
f t1 t2 = ((snd t1, snd t2), (fst t1, fst t2))
fun xs = x w 1
where w = length xs
x = (+)
id' x = x
head' = \(x : xs) -> x
fst' (a, b) = a
-- *Main> 6/3
-- 2.0
-- *Main> 6/ length [1,2,3]
-- <interactive>:9:1: error:
-- • No instance for (Fractional Int) arising from a use of ‘/’
-- • In the expression: 6 / length [1, 2, 3]
-- In an equation for ‘it’: it = 6 / length [1, 2, 3]
-- *Main> 6/ len [1,2,3]
-- <interactive>:10:1: error:
-- • No instance for (Fractional Integer) arising from a use of ‘/’
-- • In the expression: 6 / len [1, 2, 3]
-- In an equation for ‘it’: it = 6 / len [1, 2, 3
-- Main> fromIntegral 6 / (fromIntegral $ len [1,2,3])
-- 2.0
-- *Main> 2 + 3 == 5
-- True
-- *Main> let x = 5
-- *Main> x + 3 == 5
-- False
| prt2121/haskell-practice | hb-chap04/src/Main.hs | apache-2.0 | 1,609 | 0 | 8 | 424 | 514 | 297 | 217 | 35 | 2 |
{-# LANGUAGE TemplateHaskell, QuasiQuotes, OverloadedStrings #-}
module Handler.Profile where
import Import
type UserFormResult = Maybe Text
profileEditForm :: User -> Form UserFormResult
profileEditForm u = renderTable $ aopt textField "Användarnamn"
{ fsTooltip = Just "Visas t.ex. vid nyhetsinlägg"
} (Just $ userNick u)
getProfileR :: Handler Html
getProfileR = do
u <- fmap entityVal requireAuth
((_, form), enctype) <- runFormPost $ profileEditForm u
defaultLayout $ do
[whamlet|
<h1>Redigera
<article .fullpage .profile>
<form enctype="#{enctype}" method="post">
<table>
^{form}
<tr>
<td>
<td .buttons>
<input type="submit" value="Spara">
|]
setDtekTitle "Redigera profil"
postProfileR :: Handler Html
postProfileR = do
Entity uid u <- requireAuth
((res, _ ), _ ) <- runFormPost $ profileEditForm u
case res of
FormSuccess ef -> saveChanges uid ef
_ -> return ()
getProfileR
where
saveChanges :: UserId -> UserFormResult -> Handler ()
saveChanges uid ef = do
runDB $ update uid
[ UserNick =. ef
]
setSuccessMessage "Profil sparad"
| dtekcth/DtekPortalen | src/Handler/Profile.hs | bsd-2-clause | 1,414 | 0 | 12 | 517 | 283 | 141 | 142 | 28 | 2 |
{-# LANGUAGE DeriveDataTypeable #-}
module Application.WebLogger.Client.ProgType where
import System.FilePath
import System.Console.CmdArgs hiding (name)
data WebLogger_client =
Create { config :: FilePath, modulename :: String }
| GetList { config :: FilePath }
deriving (Show,Data,Typeable)
create :: WebLogger_client
create = Create { config = "test.conf"
, modulename = "" &= typ "MODULENAME" &= argPos 0
}
{-
| Get { config :: FilePath, name :: String }
| Put { config :: FilePath, name :: FilePath, modulename :: String }
| Delete { config :: FilePath, name :: String }
get :: WebLogger_client
get = Get { config = "test.conf"
, name = "" &= typ "NAME" &= argPos 0
}
put :: WebLogger_client
put = Put { config = "test.conf"
, name = "" &= typ "NAME" &= argPos 0
, modulename = "" &= typ "NAME" &= argPos 1
}
delete :: WebLogger_client
delete = Delete { config = "test.conf"
, name = "" &= typ "NAME" &= argPos 0
}
-}
getlist :: WebLogger_client
getlist = GetList { config = "test.conf" }
mode = modes [ create, getlist ]
| wavewave/weblogger-client | lib/Application/WebLogger/Client/ProgType.hs | bsd-2-clause | 1,227 | 0 | 9 | 381 | 144 | 87 | 57 | 14 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Application.HXournal.Coroutine.EventConnect
-- Copyright : (c) 2011, 2012 Ian-Woo Kim
--
-- License : BSD3
-- Maintainer : Ian-Woo Kim <[email protected]>
-- Stability : experimental
-- Portability : GHC
--
-----------------------------------------------------------------------------
module Application.HXournal.Coroutine.EventConnect where
import Graphics.UI.Gtk hiding (get,set,disconnect)
import Application.HXournal.Type.Event
import Application.HXournal.Type.Canvas
import Application.HXournal.Type.XournalState
import Application.HXournal.Device
import Application.HXournal.Type.Coroutine
import Application.HXournal.Accessor
-- import qualified Control.Monad.State as St
import Control.Applicative
import Control.Monad.Trans
import Control.Category
import Data.Label
import Prelude hiding ((.), id)
-- |
disconnect :: (WidgetClass w) => ConnectId w -> MainCoroutine ()
disconnect = liftIO . signalDisconnect
-- |
connectPenUp :: CanvasInfo a -> MainCoroutine (ConnectId DrawingArea)
connectPenUp cinfo = do
let cid = get canvasId cinfo
canvas = get drawArea cinfo
connPenUp canvas cid
-- |
connectPenMove :: CanvasInfo a -> MainCoroutine (ConnectId DrawingArea)
connectPenMove cinfo = do
let cid = get canvasId cinfo
canvas = get drawArea cinfo
connPenMove canvas cid
-- |
connPenMove :: (WidgetClass w) => w -> CanvasId -> MainCoroutine (ConnectId w)
connPenMove c cid = do
callbk <- get callBack <$> getSt
dev <- get deviceList <$> getSt
liftIO (c `on` motionNotifyEvent $ tryEvent $ do
(_,p) <- getPointer dev
liftIO (callbk (PenMove cid p)))
-- |
connPenUp :: (WidgetClass w) => w -> CanvasId -> MainCoroutine (ConnectId w)
connPenUp c cid = do
callbk <- get callBack <$> getSt
dev <- get deviceList <$> getSt
liftIO (c `on` buttonReleaseEvent $ tryEvent $ do
(_,p) <- getPointer dev
liftIO (callbk (PenMove cid p)))
| wavewave/hxournal | lib/Application/HXournal/Coroutine/EventConnect.hs | bsd-2-clause | 2,057 | 0 | 16 | 374 | 531 | 284 | 247 | 39 | 1 |
{-# LANGUAGE ForeignFunctionInterface, CPP #-}
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.Raw.ARB.GetProgramBinary
-- Copyright : (c) Sven Panne 2013
-- License : BSD3
--
-- Maintainer : Sven Panne <[email protected]>
-- Stability : stable
-- Portability : portable
--
-- All raw functions and tokens from the ARB_get_program_binary extension, see
-- <http://www.opengl.org/registry/specs/ARB/get_program_binary.txt>.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.Raw.ARB.GetProgramBinary (
-- * Functions
glGetProgramBinary, glProgramBinary, glProgramParameteri,
-- * Tokens
gl_PROGRAM_BINARY_RETRIEVABLE_HINT,
gl_PROGRAM_BINARY_LENGTH,
gl_NUM_PROGRAM_BINARY_FORMATS,
gl_PROGRAM_BINARY_FORMATS
) where
import Foreign.C.Types
import Foreign.Ptr
import Graphics.Rendering.OpenGL.Raw.ARB.GeometryShader4
import Graphics.Rendering.OpenGL.Raw.Core31.Types
import Graphics.Rendering.OpenGL.Raw.Extensions
#include "HsOpenGLRaw.h"
extensionNameString :: String
extensionNameString = "GL_ARB_get_program_binary"
EXTENSION_ENTRY(dyn_glGetProgramBinary,ptr_glGetProgramBinary,"glGetProgramBinary",glGetProgramBinary,GLuint -> GLsizei -> Ptr GLsizei -> Ptr GLenum -> Ptr a -> IO ())
EXTENSION_ENTRY(dyn_glProgramBinary,ptr_glProgramBinary,"glProgramBinary",glProgramBinary,GLuint -> GLenum -> Ptr a -> GLsizei -> IO ())
gl_PROGRAM_BINARY_RETRIEVABLE_HINT :: GLenum
gl_PROGRAM_BINARY_RETRIEVABLE_HINT = 0x8257
gl_PROGRAM_BINARY_LENGTH :: GLenum
gl_PROGRAM_BINARY_LENGTH = 0x8741
gl_NUM_PROGRAM_BINARY_FORMATS :: GLenum
gl_NUM_PROGRAM_BINARY_FORMATS = 0x87FE
gl_PROGRAM_BINARY_FORMATS :: GLenum
gl_PROGRAM_BINARY_FORMATS = 0x87FF
| mfpi/OpenGLRaw | src/Graphics/Rendering/OpenGL/Raw/ARB/GetProgramBinary.hs | bsd-3-clause | 1,824 | 0 | 14 | 192 | 238 | 148 | 90 | -1 | -1 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
--
-- Copyright (c) 2009-2011, ERICSSON AB
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
--
-- * Redistributions of source code must retain the above copyright notice,
-- this list of conditions and the following disclaimer.
-- * Redistributions in binary form must reproduce the above copyright
-- notice, this list of conditions and the following disclaimer in the
-- documentation and/or other materials provided with the distribution.
-- * Neither the name of the ERICSSON AB nor the names of its contributors
-- may be used to endorse or promote products derived from this software
-- without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 Feldspar.Vector.Internal where
import qualified Prelude
import Control.Applicative
import Test.QuickCheck
import QuickAnnotate
import Language.Syntactic hiding (fold)
import Feldspar.Range (rangeSubSat)
import qualified Feldspar
import Feldspar hiding (sugar,desugar,resugar)
import Data.Tuple.Curry
import Data.Tuple.Select
--------------------------------------------------------------------------------
-- * Types
--------------------------------------------------------------------------------
-- | Symbolic vector
data Vector a
= Empty
| Indexed
{ segmentLength :: Data Length
, segmentIndex :: Data Index -> a
, continuation :: Vector a
}
type instance Elem (Vector a) = a
type instance CollIndex (Vector a) = Data Index
type instance CollSize (Vector a) = Data Length
-- | Non-nested vector
type Vector1 a = Vector (Data a)
-- | Two-level nested vector
type Vector2 a = Vector (Vector (Data a))
instance Syntax a => Syntactic (Vector a)
where
type Domain (Vector a) = FeldDomain
type Internal (Vector a) = [Internal a]
desugar = desugar . freezeVector . map resugar
sugar = map resugar . thawVector . sugar
instance (Syntax a, Show (Internal a)) => Show (Vector a)
where
show = show . eval
--------------------------------------------------------------------------------
-- * Construction/conversion
--------------------------------------------------------------------------------
indexed :: Data Length -> (Data Index -> a) -> Vector a
indexed 0 _ = Empty
indexed l idxFun = Indexed l idxFun Empty
-- | Breaks up a segmented vector into a list of single-segment vectors.
segments :: Vector a -> [Vector a]
segments Empty = []
segments (Indexed l ixf cont) = Indexed l ixf Empty : segments cont
-- Note: Important to use `Indexed` instead of `indexed` since we need to
-- guarantee that each vector has a single segment.
length :: Vector a -> Data Length
length Empty = 0
length vec = Prelude.sum $ Prelude.map segmentLength $ segments vec
-- | Converts a segmented vector to a vector with a single segment.
mergeSegments :: Syntax a => Vector a -> Vector a
mergeSegments Empty = Empty
mergeSegments vec = Indexed (length vec) (ixFun (segments vec)) Empty
-- Note: Important to use `Indexed` instead of `indexed` since we need to
-- guarantee that the result has a single segment.
where
ixFun [] = const $ err "indexing in empty vector"
ixFun (Empty : vs) = ixFun vs
ixFun (Indexed l ixf _ : vs) = case vs of
[] -> ixf
_ -> \i -> (i<l) ? ixf i $ ixFun vs (i-l)
-- | Converts a non-nested vector to a core vector.
freezeVector :: Type a => Vector (Data a) -> Data [a]
freezeVector Empty = value []
freezeVector (Indexed l ixf cont) = parallel l ixf `append` freezeVector cont
-- | Converts a non-nested core array to a vector.
thawVector :: Type a => Data [a] -> Vector (Data a)
thawVector arr = indexed (getLength arr) (getIx arr)
thawVector' :: Type a => Length -> Data [a] -> Vector (Data a)
thawVector' len arr = thawVector $ setLength (value len) arr
--------------------------------------------------------------------------------
-- * Operations
--------------------------------------------------------------------------------
instance Syntax a => Indexed (Vector a)
where
(!) = segmentIndex . mergeSegments
instance Syntax a => Sized (Vector a)
where
collSize = length
setCollSize = newLen
instance CollMap (Vector a) (Vector b)
where
collMap = map
-- | Change the length of the vector to the supplied value. If the supplied
-- length is greater than the old length, the new elements will have undefined
-- value. The resulting vector has only one segment.
newLen :: Syntax a => Data Length -> Vector a -> Vector a
newLen l vec = (mergeSegments vec) {segmentLength = l}
(++) :: Vector a -> Vector a -> Vector a
Empty ++ v = v
v ++ Empty = v
Indexed l ixf cont ++ v = Indexed l ixf (cont ++ v)
infixr 5 ++
take :: Data Length -> Vector a -> Vector a
take _ Empty = Empty
take n (Indexed l ixf cont) = indexed nHead ixf ++ take nCont cont
where
nHead = min l n
nCont = sizeProp (uncurry rangeSubSat) (n,l) $ n - min l n
drop :: Data Length -> Vector a -> Vector a
drop _ Empty = Empty
drop n (Indexed l ixf cont) = indexed nHead (ixf . (+n)) ++ drop nCont cont
where
nHead = sizeProp (uncurry rangeSubSat) (l,n) $ l - min l n
nCont = sizeProp (uncurry rangeSubSat) (n,l) $ n - min l n
splitAt :: Data Index -> Vector a -> (Vector a, Vector a)
splitAt n vec = (take n vec, drop n vec)
head :: Syntax a => Vector a -> a
head = (!0)
last :: Syntax a => Vector a -> a
last vec = vec ! (length vec - 1)
tail :: Vector a -> Vector a
tail = drop 1
init :: Vector a -> Vector a
init vec = take (length vec - 1) vec
tails :: Vector a -> Vector (Vector a)
tails vec = indexed (length vec + 1) (`drop` vec)
inits :: Vector a -> Vector (Vector a)
inits vec = indexed (length vec + 1) (`take` vec)
inits1 :: Vector a -> Vector (Vector a)
inits1 = tail . inits
-- | Permute a single-segment vector
permute' :: (Data Length -> Data Index -> Data Index) -> (Vector a -> Vector a)
permute' _ Empty = Empty
permute' perm (Indexed l ixf Empty) = indexed l (ixf . perm l)
-- | Permute a vector
permute :: Syntax a =>
(Data Length -> Data Index -> Data Index) -> (Vector a -> Vector a)
permute perm = permute' perm . mergeSegments
reverse :: Syntax a => Vector a -> Vector a
reverse = permute $ \l i -> l-1-i
-- TODO Can be optimized (reversing each segment separately, and then
-- reversing the segment order)
rotateVecL :: Syntax a => Data Index -> Vector a -> Vector a
rotateVecL ix = permute $ \l i -> (i + ix) `rem` l
rotateVecR :: Syntax a => Data Index -> Vector a -> Vector a
rotateVecR ix = reverse . rotateVecL ix . reverse
replicate :: Data Length -> a -> Vector a
replicate n a = Indexed n (const a) Empty
-- | @enumFromTo m n@: Enumerate the integers from @m@ to @n@
--
enumFromTo :: forall a. (Integral a)
=> Data a -> Data a -> Vector (Data a)
enumFromTo 1 n
| IntType U _ <- typeRep :: TypeRep a
= indexed (i2n n) ((+1) . i2n)
enumFromTo m n = indexed (i2n l) ((+m) . i2n)
where
l = (n<m) ? 0 $ (n-m+1)
-- TODO The first case avoids the comparison when `m` is 1. However, it
-- cover the case when `m` is a complicated expression that is later
-- optimized to the literal 1. The same holds for other such
-- optimizations in this module.
--
-- Perhaps we need a language construct that lets the user supply a
-- custom optimization rule (similar to `sizeProp`)? `sizeProp` could
-- probably be expressed in terms of this more general construct.
-- | @enumFrom m@: Enumerate the indexes from @m@ to 'maxBound'
enumFrom :: (Integral a) => Data a -> Vector (Data a)
enumFrom = flip enumFromTo (value maxBound)
-- | See 'enumFromTo'
(...) :: (Integral a) => Data a -> Data a -> Vector (Data a)
(...) = enumFromTo
-- | 'map' @f v@ is the 'Vector' obtained by applying f to each element of
-- @f@.
map :: (a -> b) -> Vector a -> Vector b
map _ Empty = Empty
map f (Indexed l ixf cont) = Indexed l (f . ixf) $ map f cont
-- | Zipping two 'Vector's
zip :: (Syntax a, Syntax b) => Vector a -> Vector b -> Vector (a,b)
zip v1 v2 = go (mergeSegments v1) (mergeSegments v2)
where
go Empty _ = Empty
go _ Empty = Empty
go (Indexed l1 ixf1 Empty) (Indexed l2 ixf2 Empty) =
indexed (min l1 l2) ((,) <$> ixf1 <*> ixf2)
-- | Zipping three 'Vector's
zip3 :: (Syntax a, Syntax b, Syntax c)
=> Vector a -> Vector b -> Vector c -> Vector (a,b,c)
zip3 v1 v2 v3 = go (mergeSegments v1) (mergeSegments v2) (mergeSegments v3)
where
go Empty _ _ = Empty
go _ Empty _ = Empty
go _ _ Empty = Empty
go (Indexed l1 ixf1 Empty) (Indexed l2 ixf2 Empty) (Indexed l3 ixf3 Empty) =
indexed (Prelude.foldr1 min [l1,l2,l3]) ((,,) <$> ixf1 <*> ixf2 <*> ixf3)
-- | Zipping four 'Vector's
zip4 :: (Syntax a, Syntax b, Syntax c, Syntax d)
=> Vector a -> Vector b -> Vector c -> Vector d -> Vector (a,b,c,d)
zip4 v1 v2 v3 v4 = go (mergeSegments v1) (mergeSegments v2) (mergeSegments v3) (mergeSegments v4)
where
go Empty _ _ _ = Empty
go _ Empty _ _ = Empty
go _ _ Empty _ = Empty
go _ _ _ Empty = Empty
go (Indexed l1 ixf1 Empty) (Indexed l2 ixf2 Empty) (Indexed l3 ixf3 Empty) (Indexed l4 ixf4 Empty) =
indexed (Prelude.foldr1 min [l1,l2,l3,l4]) ((,,,) <$> ixf1 <*> ixf2 <*> ixf3 <*> ixf4)
-- | Zipping five 'Vector's
zip5 :: (Syntax a, Syntax b, Syntax c, Syntax d, Syntax e)
=> Vector a -> Vector b -> Vector c -> Vector d -> Vector e -> Vector (a,b,c,d,e)
zip5 v1 v2 v3 v4 v5 = go (mergeSegments v1) (mergeSegments v2) (mergeSegments v3) (mergeSegments v4) (mergeSegments v5)
where
go Empty _ _ _ _ = Empty
go _ Empty _ _ _ = Empty
go _ _ Empty _ _ = Empty
go _ _ _ Empty _ = Empty
go _ _ _ _ Empty = Empty
go (Indexed l1 ixf1 Empty) (Indexed l2 ixf2 Empty) (Indexed l3 ixf3 Empty) (Indexed l4 ixf4 Empty) (Indexed l5 ixf5 Empty) =
indexed (Prelude.foldr1 min [l1,l2,l3,l4,l5]) ((,,,,) <$> ixf1 <*> ixf2 <*> ixf3 <*> ixf4 <*> ixf5)
-- | Unzip to two 'Vector's
unzip :: Vector (a,b) -> (Vector a, Vector b)
unzip v = (map sel1 v, map sel2 v)
-- | Unzip to three 'Vector's
unzip3 :: Vector (a,b,c) -> (Vector a, Vector b, Vector c)
unzip3 v = (map sel1 v, map sel2 v, map sel3 v)
-- | Unzip to four 'Vector's
unzip4 :: Vector (a,b,c,d) -> (Vector a, Vector b, Vector c, Vector d)
unzip4 v = (map sel1 v, map sel2 v, map sel3 v, map sel4 v)
-- | Unzip to five 'Vector's
unzip5 :: Vector (a,b,c,d,e) -> (Vector a, Vector b, Vector c, Vector d, Vector e)
unzip5 v = (map sel1 v, map sel2 v, map sel3 v, map sel4 v, map sel5 v)
-- | Generalization of 'zip' using the supplied function instead of tupling
-- to combine the elements
zipWith :: (Syntax a, Syntax b) =>
(a -> b -> c) -> Vector a -> Vector b -> Vector c
zipWith f a b = map (uncurryN f) $ zip a b
-- | Generalization of 'zip3' using the supplied function instead of tupling
-- to combine the elements
zipWith3 :: (Syntax a, Syntax b, Syntax c) =>
(a -> b -> c -> d) -> Vector a -> Vector b -> Vector c -> Vector d
zipWith3 f a b c = map (uncurryN f) $ zip3 a b c
-- | Generalization of 'zip4' using the supplied function instead of tupling
-- to combine the elements
zipWith4 :: (Syntax a, Syntax b, Syntax c, Syntax d) =>
(a -> b -> c -> d -> e) -> Vector a -> Vector b -> Vector c -> Vector d -> Vector e
zipWith4 f a b c d = map (uncurryN f) $ zip4 a b c d
-- | Generalization of 'zip5' using the supplied function instead of tupling
-- to combine the elements
zipWith5 :: (Syntax a, Syntax b, Syntax c, Syntax d, Syntax e) =>
(a -> b -> c -> d -> e -> f) -> Vector a -> Vector b -> Vector c -> Vector d -> Vector e -> Vector f
zipWith5 f a b c d e = map (uncurryN f) $ zip5 a b c d e
-- | Corresponds to the standard 'foldl'.
fold :: (Syntax a) => (a -> b -> a) -> a -> Vector b -> a
fold _ x Empty = x
fold f x (Indexed l ixf cont) =
fold f (forLoop l x $ \ix s -> f s (ixf ix)) cont
-- | Corresponds to the standard 'foldl1'.
fold1 :: Syntax a => (a -> a -> a) -> Vector a -> a
fold1 f a = fold f (head a) (tail a)
sum :: (Syntax a, Num a) => Vector a -> a
sum = fold (+) 0
maximum :: Ord a => Vector (Data a) -> Data a
maximum = fold1 max
minimum :: Ord a => Vector (Data a) -> Data a
minimum = fold1 min
or :: Vector (Data Bool) -> Data Bool
or = fold (||) false
-- TODO Should be lazy
and :: Vector (Data Bool) -> Data Bool
and = fold (&&) true
-- TODO Should be lazy
any :: (a -> Data Bool) -> Vector a -> Data Bool
any p = or . map p
all :: (a -> Data Bool) -> Vector a -> Data Bool
all p = and . map p
eqVector :: Eq a => Vector (Data a) -> Vector (Data a) -> Data Bool
eqVector a b = (length a == length b) && and (zipWith (==) a b)
-- | Scalar product of two vectors
scalarProd :: (Syntax a, Num a) => Vector a -> Vector a -> a
scalarProd a b = sum (zipWith (*) a b)
scan :: (Syntax a, Syntax b) => (a -> b -> a) -> a -> Vector b -> Vector a
scan f init bs = Feldspar.sugar $ sequential (length bs) (Feldspar.desugar init) $ \i s ->
let s' = Feldspar.desugar $ f (Feldspar.sugar s) (bs!i)
in (s',s')
-- Note: This function should not be exported by the `Vector` module, since it doesn't fuse with
-- other operations.
-- TODO Ideally, the `Stream` library should make this function superfluous.
--------------------------------------------------------------------------------
-- Misc.
--------------------------------------------------------------------------------
tVec :: Patch a a -> Patch (Vector a) (Vector a)
tVec _ = id
tVec1 :: Patch a a -> Patch (Vector (Data a)) (Vector (Data a))
tVec1 _ = id
tVec2 :: Patch a a -> Patch (Vector (Vector (Data a))) (Vector (Vector (Data a)))
tVec2 _ = id
instance (Arbitrary (Internal a), Syntax a) => Arbitrary (Vector a)
where
arbitrary = fmap value arbitrary
instance Annotatable a => Annotatable (Vector a)
where
annotate _ Empty = Empty
annotate info (Indexed len ixf cont) = Indexed
(annotate (info Prelude.++ " (vector length)") len)
(annotate (info Prelude.++ " (vector element)") . ixf)
(annotate info cont)
| rCEx/feldspar-lang-small | src/Feldspar/Vector/Internal.hs | bsd-3-clause | 15,315 | 1 | 15 | 3,483 | 5,258 | 2,698 | 2,560 | -1 | -1 |
module Abstract.GroupTag(avarGroupTag) where
import Abstract.Predicate
import Frontend.Inline
avarGroupTag :: AbsVar -> Maybe String
avarGroupTag (AVarBool t) | (isFairVarName $ show t) = Just "$fair"
avarGroupTag (AVarPred (PAtom _ (PTInt t1) (PTInt t2))) | isSimpleTerm t1 && isConstTerm t2 = fmap show $ simpleTermAtom t1
avarGroupTag (AVarPred (PAtom _ (PTInt t1) (PTInt t2))) | isConstTerm t1 && isSimpleTerm t2 = fmap show $ simpleTermAtom t2
avarGroupTag _ = Nothing
-- A simple term depends on at most one scalar variable
-- x[const] - yes
-- x[y] - no
-- x + const - yes
-- x+y - no
isSimpleTerm :: Term -> Bool
isSimpleTerm (TVar _) = True
isSimpleTerm (TSInt _ _) = True
isSimpleTerm (TUInt _ _) = True
isSimpleTerm (TEnum _) = True
isSimpleTerm TTrue = True
isSimpleTerm (TAddr t) = isSimpleTerm t
isSimpleTerm (TField t _) = isSimpleTerm t
isSimpleTerm (TIndex t i) = isSimpleTerm t && isConstTerm i
isSimpleTerm (TUnOp _ t) = isSimpleTerm t
isSimpleTerm (TBinOp _ t1 t2) = (isSimpleTerm t1 && isConstTerm t1) || (isConstTerm t1 && isSimpleTerm t2)
isSimpleTerm (TSlice t _) = isSimpleTerm t
simpleTermAtom :: Term -> Maybe Term
simpleTermAtom t@(TVar _) = Just t
simpleTermAtom (TSInt _ _) = Nothing
simpleTermAtom (TUInt _ _) = Nothing
simpleTermAtom (TEnum _) = Nothing
simpleTermAtom TTrue = Nothing
simpleTermAtom (TAddr _) = Nothing
simpleTermAtom t@(TField _ _) = Just t
simpleTermAtom t@(TIndex _ _) = Just t
simpleTermAtom (TUnOp _ t) = Just t
simpleTermAtom (TBinOp _ t1 t2) | isConstTerm t1 = simpleTermAtom t2
| isConstTerm t2 = simpleTermAtom t1
simpleTermAtom (TSlice t _) = simpleTermAtom t
| termite2/tsl | Abstract/GroupTag.hs | bsd-3-clause | 1,924 | 0 | 11 | 570 | 655 | 317 | 338 | 33 | 1 |
-- conll2counts.hs
-- (c) 2015 Jan Snajder
--
-- Word counts mapper/reducer for Hadoop streams for CONLL parsed file
-- Counts word forms
-- -w wordforms
-- -l lemmas
-- -L lemmas, with fallback to wordforms in case of '<unknown>'
-- -p concatenates pos tags
--
-------------------------------------------------------------------------------
{-# LANGUAGE OverloadedStrings #-}
import Control.Applicative
import Control.Monad
import ConllReader
import qualified Data.Counts as C
import Data.Either
import Data.Maybe
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import System.Console.ParseArgs
import System.Environment
import System.IO
type WordCounts = C.Counts Text
count :: (Token -> [String]) -> String -> WordCounts
count f =
C.fromList . concatMap (map T.pack . f) . mapMaybe parseLine . lines
mrMap :: (Token -> [String]) -> String -> String
mrMap f = unlines . concatMap f . mapMaybe parseLine . lines
mrReduce :: Text -> Text
mrReduce = showCounts . C.fromList . T.lines
showCounts :: WordCounts -> Text
showCounts =
T.unlines . map (\(w,c) -> T.concat [w,"\t",T.pack $ show c]) . C.counts
arg =
[ Arg 0 (Just 'm') (Just "map") Nothing
"run as hadoop mapper (reads from stdin)"
, Arg 1 (Just 'r') (Just "reduce") Nothing
"run as hadoop reducer (reads from stdin)"
, Arg 2 (Just 'w') (Just "wordforms") Nothing
"count wordforms"
, Arg 3 (Just 'l') (Just "lemmas") Nothing
"count lemmas (default)"
, Arg 4 (Just 'L') (Just "lemmas-backoff") Nothing
"count lemmas with backoff to wordforms for <unknown> lemmas"
, Arg 5 (Just 'p') (Just "pos") Nothing
"append coarse-grained part-of-speech tag (CPOSTAG) to wordform/lemma"
, Arg 6 Nothing Nothing (argDataOptional "filename" ArgtypeString)
"corpus in CoNLL format" ]
main :: IO ()
main = do
args <- parseArgsIO ArgsComplete arg
let wordform = gotArg args 2
lemmabackoff = gotArg args 4
pos = gotArg args 5
f = getArg args 6
hSetEncoding stdin utf8
hSetEncoding stdout utf8
let g = case (wordform,lemmabackoff,pos) of
(True, _ , True) -> (:[]) . formPos
(True, _ , False) -> (:[]) . form
(_ , True, True) -> lemmaPos'
(_ , True, False) -> lemma'
(_ , _ , True) -> lemmaPos
_ -> lemma
if gotArg args 0 then interact $ mrMap g
else if gotArg args 1 then T.interact mrReduce
else if gotArg args 6 then
readFile (fromJust f) >>= T.putStr . showCounts . count g
else usageError args "Missing input file."
hFlush stdout
| jsnajder/conll-corpus | src/conll2counts.hs | bsd-3-clause | 2,665 | 0 | 15 | 639 | 786 | 421 | 365 | 61 | 9 |
module CIS194.HW10.ApplicativeSpec where
import CIS194.HW10.AParser
import CIS194.HW10.Applicative
import Test.Hspec
import Test.QuickCheck
spec :: Spec
spec = do
describe "abParser" $ do
it "abcdef" $
runParser abParser "abcdef" `shouldBe` Just (('a', 'b'), "cdef")
it "aebcdf" $
runParser abParser "aebcd" `shouldBe` Nothing
describe "abParser_" $ do
it "abcdef" $
runParser abParser_ "abcdef" `shouldBe` Just ((), "cdef")
it "aebcdf" $
runParser abParser_ "aebcd" `shouldBe` Nothing
describe "intPair" $
it "12 34" $
runParser intPair "12 34" `shouldBe` Just ([12, 34], "")
describe "intOrUppercase" $ do
it "342abcd" $
runParser intOrUppercase "342abcd" `shouldBe` Just ((), "abcd")
it "XYZ" $
runParser intOrUppercase "XYZ" `shouldBe` Just ((), "YZ")
it "foo" $
runParser intOrUppercase "foo" `shouldBe` Nothing
| sestrella/cis194 | test/CIS194/HW10/ApplicativeSpec.hs | bsd-3-clause | 954 | 0 | 13 | 247 | 307 | 156 | 151 | 27 | 1 |
module Cloud.AWS.EC2.Types.Route
( CreateRouteRequest(..)
) where
import Data.IP (AddrRange, IPv4)
import Data.Text (Text)
data CreateRouteRequest
= CreateRouteToGateway
{ createRouteTableId :: Text
, createRouteDestinationCidrBlock :: AddrRange IPv4
, createRouteGatewayId :: Text
}
| CreateRouteToInstance
{ createRouteTableId :: Text
, createRouteDestinationCidrBlock :: AddrRange IPv4
, createRouteInstanceId :: Text
}
| CreateRouteToNetworkInterface
{ createRouteTableId :: Text
, createRouteDestinationCidrBlock :: AddrRange IPv4
, createRouteNetworkInterfaceId :: Text
}
deriving (Show, Read, Eq)
| worksap-ate/aws-sdk | Cloud/AWS/EC2/Types/Route.hs | bsd-3-clause | 724 | 0 | 9 | 187 | 138 | 85 | 53 | 18 | 0 |
{-# LANGUAGE CPP #-}
-- |This module contains all the code that depends on a specific
-- version of GHC, and should be the only one requiring CPP
module Language.Haskell.Refact.Utils.GhcVersionSpecific
(
prettyprint
, prettyprint2
, ppType
-- , lexStringToRichTokens
-- , getDataConstructors
, setGhcContext
, showGhcQual
)
where
import qualified DynFlags as GHC
import qualified GHC as GHC
-- import qualified GHC.Paths as GHC
-- import qualified Lexer as GHC
import qualified Outputable as GHC
-- import qualified StringBuffer as GHC
-- import Language.Haskell.Refact.Utils.TypeSyn
-- ---------------------------------------------------------------------
prettyprint :: (GHC.Outputable a) => a -> String
#if __GLASGOW_HASKELL__ > 706
prettyprint x = GHC.renderWithStyle GHC.unsafeGlobalDynFlags (GHC.ppr x) (GHC.mkUserStyle GHC.neverQualify GHC.AllTheWay)
#elif __GLASGOW_HASKELL__ > 704
prettyprint x = GHC.renderWithStyle GHC.tracingDynFlags (GHC.ppr x) (GHC.mkUserStyle GHC.neverQualify GHC.AllTheWay)
#else
prettyprint x = GHC.renderWithStyle (GHC.ppr x) (GHC.mkUserStyle GHC.neverQualify GHC.AllTheWay)
#endif
-- ---------------------------------------------------------------------
prettyprint2 :: (GHC.Outputable a) => a -> String
#if __GLASGOW_HASKELL__ > 706
prettyprint2 x = GHC.renderWithStyle GHC.unsafeGlobalDynFlags (GHC.ppr x) (GHC.cmdlineParserStyle)
#elif __GLASGOW_HASKELL__ > 704
prettyprint2 x = GHC.renderWithStyle GHC.tracingDynFlags (GHC.ppr x) (GHC.cmdlineParserStyle)
#else
prettyprint2 x = GHC.renderWithStyle (GHC.ppr x) (GHC.cmdlineParserStyle)
#endif
-- ---------------------------------------------------------------------
ppType :: GHC.Type -> String
#if __GLASGOW_HASKELL__ > 706
ppType x = GHC.renderWithStyle GHC.unsafeGlobalDynFlags (GHC.pprParendType x) (GHC.mkUserStyle GHC.neverQualify GHC.AllTheWay)
#elif __GLASGOW_HASKELL__ > 704
ppType x = GHC.renderWithStyle GHC.tracingDynFlags (GHC.pprParendType x) (GHC.mkUserStyle GHC.neverQualify GHC.AllTheWay)
#else
ppType x = GHC.renderWithStyle (GHC.pprParendType x) (GHC.mkUserStyle GHC.neverQualify GHC.AllTheWay)
#endif
-- ---------------------------------------------------------------------
{-
getDataConstructors :: GHC.LHsDecl n -> [GHC.LConDecl n]
#if __GLASGOW_HASKELL__ > 704
getDataConstructors (GHC.L _ (GHC.TyClD (GHC.TyDecl _ _ (GHC.TyData _ _ _ _ cons _) _))) = cons
#else
getDataConstructors (GHC.L _ (GHC.TyClD (GHC.TyData _ _ _ _ _ _ cons _))) = cons
-- TyClD - Type definitions
-- GHC7.4.2: defines' decl@(GHC.L l (GHC.TyClD (GHC.TyData _ _ name _ _ _ cons _)))
-- GHC7.6.3: defines' decl@(GHC.L l (GHC.TyClD (GHC.TyDecl _name _vars (GHC.TyData _ _ _ _ cons _) _fvs)))
#endif
getDataConstructors _ = []
-}
-- ---------------------------------------------------------------------
setGhcContext :: GHC.GhcMonad m => GHC.ModSummary -> m ()
#if __GLASGOW_HASKELL__ > 704
setGhcContext modSum = GHC.setContext [GHC.IIModule (GHC.moduleName $ GHC.ms_mod modSum)]
#else
setGhcContext modSum = GHC.setContext [GHC.IIModule ( GHC.ms_mod modSum)]
#endif
-- ---------------------------------------------------------------------
showGhcQual :: (GHC.Outputable a) => a -> String
showGhcQual x = GHC.showSDocForUser GHC.unsafeGlobalDynFlags GHC.alwaysQualify $ GHC.ppr x
| mpickering/HaRe | src/Language/Haskell/Refact/Utils/GhcVersionSpecific.hs | bsd-3-clause | 3,428 | 0 | 11 | 530 | 345 | 198 | 147 | 21 | 1 |
{-# LANGUAGE OverloadedStrings #-}
-- | This module provides a native Haskell representation for the JSON Resume
-- scheme, as defined at
-- <https://github.com/jsonresume/resume-schema/blob/master/schema.json>, as well
-- as instances for Aeson's FromJSON/ToJSON classes to make parsing the files
-- easy.
--
-- Note that nearly all the fields are wrapped in a Maybe type. This is because
-- the JSON scheme on which this is based doesn't specify one way or the other
-- whether a field is required, and in JSON essentially all the fields are
-- optional.
module Data.JSONResume
( Resume (..)
, URL
, EmailAddress
, Address (..)
, Profile (..)
, Basics (..)
, Organization (..)
, Work (..)
, Volunteer (..)
, Education (..)
, Award (..)
, Publication (..)
, Skill (..)
, Language (..)
, Interest (..)
, Reference (..)
) where
import qualified Data.Text as T
import qualified Data.HashMap.Strict as H
import System.Locale (defaultTimeLocale)
import Data.Time (UTCTime)
import Data.Time.Format (formatTime, parseTime)
import Data.Aeson (ToJSON (..), FromJSON (..), Value (..),
object, (.:?), (.!=), (.=), withText)
import Data.Aeson.Types (Parser)
import Control.Applicative (Applicative (..), (<$>), (<*>), pure)
import Control.Monad (mzero)
-- | This is the main datatype, representing the overall structure of the JSON
-- Resume specification.
data Resume = Resume
{ basics :: Maybe Basics
, work :: [Work]
, volunteer :: [Volunteer]
, education :: [Education]
, awards :: [Award]
, publications :: [Publication]
, skills :: [Skill]
, languages :: [Language]
, interests :: [Interest]
, references :: [Reference]
} deriving (Read, Show)
instance FromJSON Resume where
parseJSON (Object v) =
Resume <$> v .:? "basics"
<*> v .:? "work" .!= []
<*> v .:? "volunteer" .!= []
<*> v .:? "education" .!= []
<*> v .:? "awards" .!= []
<*> v .:? "publications" .!= []
<*> v .:? "skills" .!= []
<*> v .:? "languages" .!= []
<*> v .:? "interests" .!= []
<*> v .:? "references" .!= []
parseJSON _ = mzero
instance ToJSON Resume where
toJSON (Resume b w v e a p s l i r) = object
[ "basics" .= b
, "work" .= w
, "volunteer" .= v
, "education" .= e
, "awards" .= a
, "publications" .= p
, "skills" .= s
, "languages" .= l
, "interests" .= i
, "references" .= r
]
-- | Simple representation for URLs
type URL = T.Text
-- | Simple representation for email addresses
type EmailAddress = T.Text
-- | Represents a physical address
data Address = Address
{ address :: Maybe T.Text -- ^ To add multiple address lines, use \n. For example, 1234 Glücklichkeit Straße\nHinterhaus 5. Etage li.
, postalCode :: Maybe T.Text
, city :: Maybe T.Text
, countryCode :: Maybe T.Text -- ^ Code as per ISO-3166-1 ALPHA-2, e.g. US, AU, IN
, region :: Maybe T.Text -- ^ The general region where you live. Can be a US state, or a province, for instance.
} deriving (Read, Show)
instance FromJSON Address where
parseJSON (Object v) =
Address <$> v .:? "address"
<*> v .:? "postalCode"
<*> v .:? "city"
<*> v .:? "countryCode"
<*> v .:? "region"
parseJSON _ = mzero
instance ToJSON Address where
toJSON (Address a p c cc r) = object
[ "address" .= a
, "postalCode" .= p
, "city" .= c
, "countryCode" .= cc
, "region" .= r
]
-- | Specify any number of social networks that you participate in
data Profile = Profile
{ network :: Maybe T.Text -- ^ e.g. Facebook or Twitter
, username :: Maybe T.Text -- ^ e.g. neutralthoughts
, url :: Maybe URL -- ^ e.g. http://twitter.com/neutralthoughts
} deriving (Read, Show)
instance FromJSON Profile where
parseJSON (Object v) =
Profile <$> v .:? "network"
<*> v .:? "username"
<*> v .:? "url"
parseJSON _ = mzero
instance ToJSON Profile where
toJSON (Profile n u web) = object
[ "network" .= n
, "username" .= u
, "url" .= web
]
-- | Basic information
data Basics = Basics
{ name :: Maybe T.Text
, label :: Maybe T.Text -- ^ e.g. Web Developer
, picture :: Maybe URL -- ^ URL (as per RFC 3986) to a picture in JPEG or PNG format
, email :: Maybe EmailAddress -- ^ e.g. [email protected]
, phone :: Maybe T.Text -- ^ Phone numbers are stored as strings so use any format you like, e.g. 712-117-2923
, website :: Maybe URL -- ^ URL (as per RFC 3986) to your website, e.g. personal homepage
, summary :: Maybe T.Text -- ^ Write a short 2-3 sentence biography about yourself
, location :: Maybe Address
, profiles :: [Profile]
} deriving (Read, Show)
instance FromJSON Basics where
parseJSON (Object v) =
Basics <$> v .:? "name"
<*> v .:? "label"
<*> v .:? "picture"
<*> v .:? "email"
<*> v .:? "phone"
<*> v .:? "website"
<*> v .:? "summary"
<*> v .:? "location"
<*> v .:? "profiles" .!= []
parseJSON _ = mzero
instance ToJSON Basics where
toJSON (Basics n l pic e phn w s loc ps) = object
[ "name" .= n
, "label" .= l
, "picture" .= pic
, "email" .= e
, "phone" .= phn
, "website" .= w
, "summary" .= s
, "location" .= loc
, "profiles" .= ps
]
-- | Information about a particular organization that you've worked or
-- volunteered at
data Organization = Organization
{ orgName :: Maybe T.Text -- ^ e.g. Facebook
, orgPosition :: Maybe T.Text -- ^ e.g. Software Engineer
, orgSite :: Maybe URL -- ^ e.g. http://facebook.com
, orgStartDate :: Maybe UTCTime -- ^ resume.json uses the ISO 8601 date standard e.g. 2014-06-29
, orgEndDate :: Maybe UTCTime -- ^ e.g. 2012-06-29
, orgSummary :: Maybe T.Text -- ^ Give an overview of your responsibilities at the company
, orgHighlights :: [T.Text] -- ^ Specify multiple accomplishments, e.g. Increased profits by 20% from 2011-2012 through viral advertising
} deriving (Read, Show)
-- | Specify that you worked at a particular @Organization@ (as opposed to
-- volunteering there)
newtype Work = Work Organization deriving (Read, Show)
instance FromJSON Work where
parseJSON (Object v) = fmap Work $
Organization <$> v .:? "company"
<*> v .:? "position"
<*> v .:? "website"
<*> potentially dateFromJSON v "startDate"
<*> potentially dateFromJSON v "endDate"
<*> v .:? "summary"
<*> v .:? "highlights" .!= []
parseJSON _ = mzero
instance ToJSON Work where
toJSON (Work (Organization n p web start end smry hl)) = object
[ "company" .= n
, "position" .= p
, "website" .= web
, ("startDate", toJSON $ dateToJSON <$> start)
, ("endDate", toJSON $ dateToJSON <$> end)
, "summary" .= smry
, "highlights" .= hl
]
-- | Specify that you volunteered at a particular @Organization@ (as opposed to
-- working there)
newtype Volunteer = Volunteer Organization deriving (Read, Show)
instance FromJSON Volunteer where
parseJSON (Object v) = fmap Volunteer $
Organization <$> v .:? "organization"
<*> v .:? "position"
<*> v .:? "website"
<*> potentially dateFromJSON v "startDate"
<*> potentially dateFromJSON v "endDate"
<*> v .:? "summary"
<*> v .:? "highlights" .!= []
parseJSON _ = mzero
instance ToJSON Volunteer where
toJSON (Volunteer (Organization n p web start end smry hl)) = object
[ "organization" .= n
, "position" .= p
, "website" .= web
, ("startDate", toJSON $ dateToJSON <$> start)
, ("endDate", toJSON $ dateToJSON <$> end)
, "summary" .= smry
, "highlights" .= hl
]
-- | Educational history
data Education = Education
{ institution :: Maybe T.Text -- ^ e.g. Massachusetts Institute of Technology
, area :: Maybe T.Text -- ^ e.g. Arts
, studyType :: Maybe T.Text -- ^ e.g. Bachelor
, startDate :: Maybe UTCTime -- ^ e.g. 2012-06-29
, endDate :: Maybe UTCTime -- ^ e.g. 2014-06-29
, gpa :: Maybe T.Text -- ^ grade point average, e.g. 3.67/4.0
, courses :: [T.Text] -- ^ List notable courses/subjects, e.g. H1302 - Introduction to American history
} deriving (Read, Show)
instance FromJSON Education where
parseJSON (Object v) =
Education <$> v .:? "institution"
<*> v .:? "area"
<*> v .:? "studyType"
<*> potentially dateFromJSON v "startDate"
<*> potentially dateFromJSON v "endDate"
<*> v .:? "gpa"
<*> v .:? "courses" .!= []
parseJSON _ = mzero
instance ToJSON Education where
toJSON (Education i a t start end g cs) = object
[ "institution" .= i
, "area" .= a
, "studyType" .= t
, ("startDate", toJSON $ dateToJSON <$> start)
, ("endDate", toJSON $ dateToJSON <$> end)
, "gpa" .= g
, "courses" .= cs
]
-- | Specify any awards you have received throughout your professional career
data Award = Award
{ title :: Maybe T.Text -- ^ e.g. One of the 100 greatest minds of the century
, date :: Maybe UTCTime -- ^ e.g. 1989-06-12
, awarder :: Maybe T.Text -- ^ e.g. Time Magazine
, awardSummary :: Maybe T.Text -- ^ e.g. Received for my work with Quantum Physics
} deriving (Read, Show)
instance FromJSON Award where
parseJSON (Object v) =
Award <$> v .:? "title"
<*> potentially dateFromJSON v "date"
<*> v .:? "awarder"
<*> v .:? "summary"
parseJSON _ = mzero
instance ToJSON Award where
toJSON (Award t d a s) = object
[ "title" .= t
, ("date", toJSON $ dateToJSON <$> d)
, "awarder" .= a
, "summary" .= s
]
-- | Specify your publications through your career
data Publication = Publication
{ pubName :: Maybe T.Text -- ^ e.g. The World Wide Web
, publisher :: Maybe T.Text -- ^ e.g. IEEE, Computer Magazine
, pubReleaseDate :: Maybe UTCTime -- ^ e.g. 1990-08-01
, pubSite :: Maybe URL -- ^ e.g. http://www.computer.org/csdl/mags/co/1996/10/rx069-abs.html
, pubSummary :: Maybe T.Text -- ^ Short summary of publication. e.g. Discussion of the World Wide Web, HTTP, HTML.
} deriving (Read, Show)
instance FromJSON Publication where
parseJSON (Object v) =
Publication <$> v .:? "name"
<*> v .:? "publisher"
<*> potentially dateFromJSON v "releaseDate"
<*> v .:? "website"
<*> v .:? "summary"
parseJSON _ = mzero
instance ToJSON Publication where
toJSON (Publication n p d web s) = object
[ "name" .= n
, "publisher" .= p
, ("releaseDate", toJSON $ dateToJSON <$> d)
, "website" .= web
, "summary" .= s
]
-- | List out your professional skill-set
data Skill = Skill
{ skillName :: Maybe T.Text -- ^ e.g. Web Development
, skillLevel :: Maybe T.Text -- ^ e.g. Master
, skillKeywords :: [T.Text] -- ^ List some keywords pertaining to this skill, e.g. HTML
} deriving (Read, Show)
instance FromJSON Skill where
parseJSON (Object v) =
Skill <$> v .:? "name"
<*> v .:? "level"
<*> v .:? "keywords" .!= []
parseJSON _ = mzero
instance ToJSON Skill where
toJSON (Skill n l ks) = object
[ "name" .= n
, "level" .= l
, "keywords" .= ks
]
-- | List any other languages you speak
data Language = Language
{ language :: Maybe T.Text -- ^ e.g. English, Spanish
, fluency :: Maybe T.Text -- ^ e.g. Fluent, Beginner
} deriving (Read, Show)
instance FromJSON Language where
parseJSON (Object v) =
Language <$> v .:? "language"
<*> v .:? "fluency"
parseJSON _ = mzero
instance ToJSON Language where
toJSON (Language l f) = object
[ "language" .= l
, "fluency" .= f
]
data Interest = Interest
{ interestName :: Maybe T.Text -- ^ e.g. Philosophy
, interestKeywords :: [T.Text] -- ^ e.g. Friedrich Nietzsche
} deriving (Read, Show)
instance FromJSON Interest where
parseJSON (Object v) =
Interest <$> v .:? "name"
<*> v .:? "keywords" .!= []
parseJSON _ = mzero
instance ToJSON Interest where
toJSON (Interest n ks) = object
[ "name" .= n
, "keywords" .= ks
]
-- | List any references you have received
data Reference = Reference
{ refName :: Maybe T.Text -- ^ e.g. Timothy Cook
, reference :: Maybe T.Text -- ^ e.g. Joe blogs was a great employee, who turned up to work at least once a week. He exceeded my expectations when it came to doing nothing.
} deriving (Read, Show)
instance FromJSON Reference where
parseJSON (Object v) =
Reference <$> v .:? "name"
<*> v .:? "reference"
parseJSON _ = mzero
instance ToJSON Reference where
toJSON (Reference n r) = object
[ "name" .= n
, "reference" .= r
]
-- A couple of utility functions to help with parsing --
-- Write out a date using JSON Resume's preferred date format (YYYY-mm-dd)
dateToJSON :: UTCTime -> Value
dateToJSON t = String $ T.pack $ formatTime defaultTimeLocale "%F" t
-- Read in a date using JSON Resume's preferred date format (YYYY-mm-dd)
dateFromJSON :: Value -> Parser UTCTime
dateFromJSON = withText "UTCTime" $ \t ->
case parseTime defaultTimeLocale "%F" (T.unpack t) of
Just d -> pure d
_ -> fail "could not parse ISO-8601 date"
-- A version of (.:?) which is parameterised on the parsing function to use
potentially :: (Value -> Parser a) -> H.HashMap T.Text Value -> T.Text -> Parser (Maybe a)
potentially f obj key = case H.lookup key obj of
Nothing -> pure Nothing
Just v -> Just <$> f v
| dpwright/jsonresume.hs | src/Data/JSONResume.hs | bsd-3-clause | 15,092 | 0 | 34 | 4,988 | 3,462 | 1,906 | 1,556 | 323 | 2 |
module Language.Iso.Prelude where
import Language.Iso.App
import Language.Iso.Lam
import Language.Iso.Var
idiot :: (Var repr, Lam repr) => repr
idiot = lam "x" (var "x")
kestrel :: (Var repr, Lam repr) => repr
kestrel = lam "x" (lam "y" (var "x"))
starling :: (Var repr, Lam repr, App repr) => repr
starling = lam "x" (lam "y" (lam "z" (app (app (var "x") (var "z")) (app (var "y") (var "z")))))
| joneshf/iso | src/Language/Iso/Prelude.hs | bsd-3-clause | 416 | 0 | 15 | 88 | 205 | 110 | 95 | 10 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.