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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
circle(2)
| three/codeworld | codeworld-compiler/test/testcase/test_nakedExpression/source.hs | apache-2.0 | 10 | 0 | 5 | 1 | 10 | 4 | 6 | -1 | -1 |
-- |
-- Module : Criterion.IO.Printf
-- Copyright : (c) 2009-2014 Bryan O'Sullivan
--
-- License : BSD-style
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : GHC
--
-- Input and output actions.
{-# LANGUAGE FlexibleInstances, Rank2Types, TypeSynonymInstances #-}
module Criterion.IO.Printf
(
CritHPrintfType
, note
, printError
, prolix
, writeCsv
) where
import Control.Monad (when)
import Control.Monad.Reader (ask, asks)
import Control.Monad.Trans (liftIO)
import Criterion.Monad (Criterion)
import Criterion.Types (Config(csvFile, verbosity), Verbosity(..))
import Data.Foldable (forM_)
import System.IO (Handle, stderr, stdout)
import Text.Printf (PrintfArg)
import qualified Data.ByteString.Lazy as B
import qualified Data.Csv as Csv
import qualified Text.Printf (HPrintfType, hPrintf)
-- First item is the action to print now, given all the arguments
-- gathered together so far. The second item is the function that
-- will take a further argument and give back a new PrintfCont.
data PrintfCont = PrintfCont (IO ()) (PrintfArg a => a -> PrintfCont)
-- | An internal class that acts like Printf/HPrintf.
--
-- The implementation is visible to the rest of the program, but the
-- details of the class are not.
class CritHPrintfType a where
chPrintfImpl :: (Config -> Bool) -> PrintfCont -> a
instance CritHPrintfType (Criterion a) where
chPrintfImpl check (PrintfCont final _)
= do x <- ask
when (check x) (liftIO final)
return undefined
instance CritHPrintfType (IO a) where
chPrintfImpl _ (PrintfCont final _)
= final >> return undefined
instance (CritHPrintfType r, PrintfArg a) => CritHPrintfType (a -> r) where
chPrintfImpl check (PrintfCont _ anotherArg) x
= chPrintfImpl check (anotherArg x)
chPrintf :: CritHPrintfType r => (Config -> Bool) -> Handle -> String -> r
chPrintf shouldPrint h s
= chPrintfImpl shouldPrint (make (Text.Printf.hPrintf h s)
(Text.Printf.hPrintf h s))
where
make :: IO () -> (forall a r. (PrintfArg a, Text.Printf.HPrintfType r) =>
a -> r) -> PrintfCont
make curCall curCall' = PrintfCont curCall (\x -> make (curCall' x)
(curCall' x))
{- A demonstration of how to write printf in this style, in case it is
ever needed
in fututre:
cPrintf :: CritHPrintfType r => (Config -> Bool) -> String -> r
cPrintf shouldPrint s
= chPrintfImpl shouldPrint (make (Text.Printf.printf s)
(Text.Printf.printf s))
where
make :: IO () -> (forall a r. (PrintfArg a, Text.Printf.PrintfType r) => a -> r) -> PrintfCont
make curCall curCall' = PrintfCont curCall (\x -> make (curCall' x) (curCall' x))
-}
-- | Print a \"normal\" note.
note :: (CritHPrintfType r) => String -> r
note = chPrintf ((> Quiet) . verbosity) stdout
-- | Print verbose output.
prolix :: (CritHPrintfType r) => String -> r
prolix = chPrintf ((== Verbose) . verbosity) stdout
-- | Print an error message.
printError :: (CritHPrintfType r) => String -> r
printError = chPrintf (const True) stderr
-- | Write a record to a CSV file.
writeCsv :: Csv.ToRecord a => a -> Criterion ()
writeCsv val = do
csv <- asks csvFile
forM_ csv $ \fn ->
liftIO . B.appendFile fn . Csv.encode $ [val]
| paulolieuthier/criterion | Criterion/IO/Printf.hs | bsd-2-clause | 3,349 | 0 | 13 | 733 | 768 | 426 | 342 | 52 | 1 |
undefined = undefined
filter :: (a -> Bool) -> [a] -> [a]
filter p [] = []
filter p (x:xs) = if p x then filter p xs else x:filter p xs
map :: (a -> b) -> [a] -> [b]
map f [] = []
map f (x:xs) = f x : map f xs
not :: Bool -> Bool
not = undefined
toUpper :: Char -> Char
toUpper = undefined
test xs = let xform f = map f xs
in (xform not, xform toUpper)
| themattchan/tandoori | input/let-poly-restrict2.hs | bsd-3-clause | 368 | 2 | 9 | 102 | 256 | 120 | 136 | 13 | 2 |
import Data.Char (ord, chr, isUpper, isAlpha)
caesar, uncaesar :: Int -> String -> String
caesar = (<$>) . tr
uncaesar = caesar . negate
tr :: Int -> Char -> Char
tr offset c
| isAlpha c = chr $ intAlpha + mod ((ord c - intAlpha) + offset) 26
| otherwise = c
where
intAlpha =
ord
(if isUpper c
then 'A'
else 'a')
main :: IO ()
main = mapM_ print [encoded, decoded]
where
encoded = caesar (-114) "Veni, vidi, vici"
decoded = uncaesar (-114) encoded | OpenGenus/cosmos | code/cryptography/src/caesar_cipher/caesar_cipher.hs | gpl-3.0 | 511 | 5 | 12 | 151 | 226 | 112 | 114 | 17 | 2 |
{-# OPTIONS_JHC -fno-prelude -fm4 -funboxed-values -funboxed-tuples -fffi #-}
module Foreign.Storable(Storable(..)) where
import Jhc.Addr
import Jhc.Basics
import Jhc.IO
import Jhc.Int
m4_include(Foreign/Storable.m4)
class Storable a where
sizeOf :: a -> Int
alignment :: a -> Int
peekElemOff :: Ptr a -> Int -> IO a
pokeElemOff :: Ptr a -> Int -> a -> IO ()
peekByteOff :: Ptr b -> Int -> IO a
pokeByteOff :: Ptr b -> Int -> a -> IO ()
peek :: Ptr a -> IO a
poke :: Ptr a -> a -> IO ()
alignment x = sizeOf x
peekElemOff addr idx = fromUIO $ \w -> unIO (peek $! (addr `plusPtr` (idx `times` sizeOf (_f addr)))) w
pokeElemOff addr idx x = fromUIO $ \w -> unIO (let adr = (addr `plusPtr` (idx `times` sizeOf x)) in adr `seq` poke adr x) w
peekByteOff addr off = fromUIO $ \w -> unIO (peek $! (castPtr $ addr `plusPtr` off)) w
pokeByteOff addr off x = fromUIO $ \w -> unIO (let adr = castPtr (addr `plusPtr` off) in adr `seq` poke adr x) w
_f :: Ptr a -> a
_f _ = undefined
INST_STORABLE_X((Ptr a),Ptr,Addr_,bits<ptr>)
INST_STORABLE_X((FunPtr a),FunPtr,FunAddr_,bits<ptr>)
-- foreign import "Add" plusBitsPtr_ :: BitsPtr_ -> Int -> BitsPtr_
| hvr/jhc | lib/jhc/Foreign/Storable.hs | mit | 1,198 | 3 | 20 | 265 | 529 | 279 | 250 | -1 | -1 |
{-# LANGUAGE PolyKinds, TypeFamilies, TypeFamilyDependencies,
ScopedTypeVariables, TypeOperators, GADTs,
DataKinds #-}
module T15141 where
import Data.Type.Equality
import Data.Proxy
type family F a = r | r -> a where
F () = Bool
data Wumpus where
Unify :: k1 ~ F k2 => k1 -> k2 -> Wumpus
f :: forall k (a :: k). k :~: Bool -> ()
f Refl = let x :: Proxy ('Unify a b)
x = undefined
in ()
{-
We want this situation:
forall[1] k[1].
[G] k ~ Bool
forall [2] ... . [W] k ~ F kappa[2]
where the inner wanted can be solved only by taking the outer
given into account. This means that the wanted needs to be floated out.
More germane to this bug, we need *not* to generalize over kappa.
The code above builds this scenario fairly exactly, and indeed fails
without the logic in kindGeneralize that excludes constrained variables
from generalization.
-}
| sdiehl/ghc | testsuite/tests/typecheck/should_compile/T15141.hs | bsd-3-clause | 909 | 0 | 12 | 219 | 137 | 78 | 59 | 14 | 1 |
module Foreign (x) where
x = "test"
| urbanslug/ghc | testsuite/tests/cabal/pkg02/Foreign.hs | bsd-3-clause | 36 | 0 | 4 | 7 | 14 | 9 | 5 | 2 | 1 |
{-# LANGUAGE ForeignFunctionInterface #-}
{-# LANGUAGE CPP #-}
module Text.XML.Pugi.Foreign.XPath.Node where
#if !MIN_VERSION_base(4,8,0)
import Control.Applicative
#endif
import Control.Exception
import Foreign.ForeignPtr
import Foreign.Ptr
import Foreign.C
import Foreign.Marshal
import Text.XML.Pugi.Foreign.Types
import Text.XML.Pugi.Foreign.Node
import Data.IORef
foreign import ccall xpath_node_set_empty :: Ptr (NodeSet m) -> IO CInt
foreign import ccall xpath_node_set_index :: Ptr (NodeSet m) -> CSize -> IO (Ptr XNode)
foreign import ccall "wrapper" wrap_xpath_node_mapper :: (Ptr XNode -> IO ()) -> IO (FunPtr (Ptr XNode -> IO ()))
foreign import ccall xpath_node_set_map :: Ptr (NodeSet m) -> FunPtr (Ptr XNode -> IO ()) -> IO ()
nodeSetSize :: NodeSet m -> Int
nodeSetSize (NodeSet l _) = l
nodeSetEmpty :: NodeSet m -> IO Bool
nodeSetEmpty (NodeSet _ fp) = toBool <$>
withForeignPtr fp xpath_node_set_empty
nodeSetIndex :: NodeSet m -> Int -> IO (XPathNode m)
nodeSetIndex (NodeSet l fp) i
| l > i = withForeignPtr fp $ \p ->
bracket (xpath_node_set_index p (fromIntegral i))
delete_xpath_node peekXNode
| otherwise = fail "out of range"
nodeSetMapM_ :: (XPathNode m -> IO ()) -> NodeSet m -> IO ()
nodeSetMapM_ f (NodeSet _ fp) = withForeignPtr fp $ \p -> do
let func x = peekXNode x >>= f
bracket (wrap_xpath_node_mapper func) freeHaskellFunPtr $ \fn ->
xpath_node_set_map p fn
nodeSetMapM :: (XPathNode m -> IO a) -> NodeSet m -> IO [a]
nodeSetMapM f n = do
ref <- newIORef id
nodeSetMapM_ (\x -> f x >>= \a -> modifyIORef ref (\rf -> rf . (a:))) n
readIORef ref >>= \l -> return (l [])
| philopon/pugixml-hs | Text/XML/Pugi/Foreign/XPath/Node.hs | mit | 1,672 | 0 | 16 | 319 | 641 | 323 | 318 | 37 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
import Control.Monad.IO.Class ( liftIO )
import Data.Aeson ( Object )
import Data.Monoid
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as C8
import Servant
import Servant.GitHub.Webhook
import Network.Wai ( Application )
import Network.Wai.Handler.Warp ( run )
import qualified Data.Text.Encoding as T
main :: IO ()
main = pure ()
realMain :: IO ()
realMain = do
[key, _] <- C8.lines <$> BS.readFile "test/test-keys"
run 8080 (app (repositoryKey $ \user -> pure $ Just (T.encodeUtf8 user <> key)))
app :: GitHubKey Object -> Application
app key
= serveWithContext
(Proxy :: Proxy API)
(key :. EmptyContext)
server
server :: Server API
server = anyEvent
anyEvent :: RepoWebhookEvent -> ((), Object) -> Handler ()
anyEvent e _
= liftIO $ putStrLn $ "got event: " ++ show e
type API
= "repo1"
:> GitHubEvent '[ 'WebhookPushEvent ]
:> GitHubSignedReqBody '[JSON] Object
:> Post '[JSON] ()
| tsani/servant-github-webhook | test/dynamickey/Main.hs | mit | 1,046 | 0 | 18 | 195 | 349 | 193 | 156 | 35 | 1 |
import qualified System.Random as R
main = do
putStrLn "Hola Cuarenta"
| stackbuilders/cuarenta | Main.hs | mit | 74 | 0 | 7 | 14 | 20 | 11 | 9 | 3 | 1 |
module Main where
import Data.Numbers.Primes (isPrime, primes)
sumPrimesMod :: Int -> Bool
sumPrimesMod n = isPrime (sum (take n primes) `mod` n)
main :: IO ()
main = do
let ns = filter sumPrimesMod [1 .. 367]
print ns
print $ length ns
| genos/online_problems | prog_praxis/day280/src/Main.hs | mit | 246 | 0 | 11 | 52 | 109 | 57 | 52 | 9 | 1 |
module JSParser
( jsProgramParser
, jsValueParser
, jsExpressionParser
, jsStatementParser
, parseMaybe
, parseTest
, parseString
) where
import Control.Monad (void)
import Data.List (splitAt)
import Debug.Trace
import JSEntity
import JSError (JSError (ParserError), ThrowsError,
throwError)
import Text.Megaparsec
import Text.Megaparsec.Char
import Text.Megaparsec.Combinator
import qualified Text.Megaparsec.Expr as E
import qualified Text.Megaparsec.Lexer as L
import Text.Megaparsec.Pos
import Text.Megaparsec.String
-- | words that can't be used as identifiers
reservedWords = ["break", "do", "instanceof", "typeof", "case", "else", "new",
"var", "catch", "finally", "return", "void", "continue", "for", "switch",
"while", "debugger", "function", "this", "with", "default", "if", "throw",
"delete", "in", "try", "class", "enum", "extends", "super", "const", "export",
"import", "implements", "let", "private", "public", "yield", "interface",
"package", "protected", "static"
]
-- | parse a JS integer represent by decimal or hexadecimal
--
-- Examples:
-- >>> parseMaybe pJSInt "123"
-- Just 123
-- >>> parseMaybe pJSInt "0xf"
-- Just 15
-- >>> parseMaybe pJSInt "0123"
-- Just 123
-- >>> parseMaybe pJSInt "123a"
-- Nothing
-- >>> parseMaybe pJSInt "0xfg"
-- Nothing
pJSInt :: Parser JSVal
pJSInt = JSInt <$> (try hexadecimal <|> L.decimal)
where
hexadecimal = char '0' >> char' 'x' >> L.hexadecimal
-- | parse a JS floating point number
--
-- Examples:
-- >>> parseMaybe pJSFloat "1.2"
-- Just 1.2
-- >>> parseMaybe pJSFloat "0.12"
-- Just 0.12
-- >>> parseMaybe pJSFloat "12"
-- Nothing
pJSFloat :: Parser JSVal
pJSFloat = JSFloat <$> L.float
-- | parse a JS string, a JS string can be quoted by " or '
--
-- Examples:
-- >>> parseMaybe pJSString "\" abc''\""
-- Just abc''
-- >>> parseMaybe pJSString "' abc '"
-- Just abc
-- >>> parseMaybe pJSString "' abc \"\\\\'"
-- Just abc "\
-- >>> parseMaybe pJSString "'\\n'"
-- Just
-- <BLANKLINE>
-- >>> parseMaybe pJSString "''"
-- Just
pJSString :: Parser JSVal
pJSString = JSString <$> (try doubleQuoteString <|> singleQuoteString)
where
doubleEscapeChar :: Parser Char
doubleEscapeChar = pEscapeChar "nbfrtv\\\""
singleEscapeChar :: Parser Char
singleEscapeChar = pEscapeChar "nbfrtv\\'"
doubleNormalChar :: Parser Char
doubleNormalChar = noneOf "\r\n\\\""
singleNormalChar :: Parser Char
singleNormalChar = noneOf "\r\n\\'"
quoted :: String -> Parser a -> Parser a
quoted q = between (string q) (string q)
doubleQuoteString :: Parser String
doubleQuoteString = quoted "\""
(many (doubleEscapeChar <|> doubleNormalChar))
singleQuoteString :: Parser String
singleQuoteString = quoted "'"
(many (singleEscapeChar <|> singleNormalChar))
-- | parse a escape char which is a char after '\', for 'n' 'b' 'f' 'r' 't' 'v',
-- it will convert it to '\n' '\b' '\f' '\r' '\t' '\v', for other chars, it will
-- leave it as it is, all chars need to be parsed should be declared in the
-- input string
--
-- Examples:
-- >>> parseMaybe (pEscapeChar "n") "\\n"
-- Just '\n'
-- >>> parseMaybe (pEscapeChar "r") "\\n"
-- Nothing
-- >>> parseMaybe (pEscapeChar "xyz") "\\x"
-- Just 'x'
pEscapeChar :: String -> Parser Char
pEscapeChar chars = do c <- char '\\' >> oneOf chars
return $ case c of
'n' -> '\n'
'b' -> '\b'
'f' -> '\f'
'r' -> '\r'
't' -> '\t'
'v' -> '\v'
_ -> c
-- | parse a JS boolean value, representing True as true, False as false
--
-- Examples:
-- >>> parseTest pJSBool "true "
-- true
-- >>> parseTest pJSBool "false "
-- false
-- >>> parseMaybe pJSBool "true "
-- Nothing
pJSBool :: Parser JSVal
pJSBool = JSBool <$>
((string "true" >> return True) <|> (string "false" >> return False))
-- | parse JS null value, representing as null
--
-- Examples:
-- >>> parseMaybe pJSNull "null"
-- Just null
-- >>> parseMaybe pJSNull "null "
-- Nothing
pJSNull :: Parser JSVal
pJSNull = string "null" >> return JSNull
-- | parse JS undefined value, representing as undefined
--
-- Examples:
-- >>> parseMaybe pJSUndefined "undefined"
-- Just undefined
-- >>> parseMaybe pJSUndefined "undefined "
-- Nothing
pJSUndefined :: Parser JSVal
pJSUndefined = string "undefined" >> return JSUndefined
-- | parse JS this object, representing as this
--
-- Examples:
-- >>> parseMaybe pJSThis "this"
-- Just this
-- >>> parseMaybe pJSThis "this "
-- Nothing
pJSThis :: Parser JSVal
pJSThis = string "this" >> return JSThis
-- | parse JS NaN literial
--
-- Examples:
-- >>> parseMaybe pJSNaN "NaN"
-- Just NaN
-- >>> parseMaybe pJSNaN "NaN "
-- Nothing
pJSNaN :: Parser JSVal
pJSNaN = string "NaN" >> return JSNaN
-- | parse JS identifier for variable names.
-- it should start with letter or '$' or '_', and follow by zero or more
-- letters or digits or '$' or '_'
-- and it can't be any of the reserved words
--
-- Examples:
-- >>> parseMaybe pIdentifier "while"
-- Nothing
-- >>> parseMaybe pIdentifier "0abc"
-- Nothing
-- >>> parseMaybe pIdentifier "a123()"
-- Nothing
-- >>> parseMaybe pIdentifier "a123 "
-- Nothing
-- >>> parseMaybe pIdentifier "_xyz"
-- Just "_xyz"
-- >>> parseMaybe pIdentifier "a123"
-- Just "a123"
pIdentifier :: Parser String
pIdentifier = do name <- identifierName
if name `elem` reservedWords
then failure [Unexpected name]
else return name
where
identifierName = do h <- identifierHead
t <- identifierTail
return (h : t)
identifierHead = letterChar <|> oneOf "$_"
identifierTail = many $ identifierHead <|> digitChar
-- | parse JS identifier for variable names.
-- then encapsulate it into a JSAtom
--
-- Examples:
-- >>> parseMaybe pJSAtom "while"
-- Nothing
-- >>> parseMaybe pJSAtom "0abc"
-- Nothing
-- >>> parseMaybe pJSAtom "_xyz"
-- Just _xyz
-- >>> parseMaybe pJSAtom "a123"
-- Just a123
pJSAtom :: Parser JSVal
pJSAtom = JSAtom <$> try pIdentifier
-- | parse parameters in function declaration
--
-- Examples:
-- >>> parseMaybe pFunctionParams "( x , y ) "
-- Just ["x","y"]
-- >>> parseMaybe pFunctionParams "( )"
-- Just []
-- >>> parseMaybe pFunctionParams "(x,y)"
-- Just ["x","y"]
-- >>> parseMaybe pFunctionParams "(this)"
-- Nothing
-- >>> parseMaybe pFunctionPrincipalPart "( x , y ) { return x ; }"
-- Just (["x","y"],[return x])
pFunctionParams :: Parser [String]
pFunctionParams = parentheses (sepBy (pIdentifier <* spaceConsumer) comma)
pFunctionBody :: Parser [JSStatement]
pFunctionBody = braces (many pStatement)
pFunctionPrincipalPart :: Parser ([String], [JSStatement])
pFunctionPrincipalPart = do params <- pFunctionParams
body <- pFunctionBody
return (params, body)
-- | parser of js anonymous function
--
-- Examples:
-- >>> parseMaybe pJSFunction "function (x, y) { return x + y; }"
-- Just function(x,y){return (x+y);}
pJSFunction :: Parser JSVal
pJSFunction =
do begin <- getPosition
_ <- symbol "function"
(params, body) <- pFunctionPrincipalPart
end <- getPosition
return (JSFunction params body (convertPos begin) (convertPos end))
-- | parse a js value, it can be one of:
-- atom: an identifier for variable
-- boolean: true or false
-- null: representing null value
-- undefined: representing undefined value
-- int or float: both of them are js number
-- string: many chars surrounded by quotations
-- function: a js function object
--
-- Examples:
-- >>> parseMaybe pJSVal "true"
-- Just true
-- >>> parseMaybe pJSVal "truea"
-- Just truea
-- >>> parseMaybe pJSVal "null"
-- Just null
-- >>> parseMaybe pJSVal "undefined"
-- Just undefined
-- >>> parseMaybe pJSVal "1.3"
-- Just 1.3
-- >>> parseMaybe pJSVal "5"
-- Just 5
-- >>> parseMaybe pJSVal "'abc'"
-- Just abc
-- >>> parseMaybe pJSVal "x12"
-- Just x12
-- >>> parseMaybe pJSVal "function (x, y) {}"
-- Just function(x,y){}
pJSVal :: Parser JSVal
pJSVal = try pJSAtom
<|> try pJSBool
<|> try pJSNaN
<|> try pJSNull
<|> try pJSUndefined
<|> try pJSString
<|> try pJSFloat
<|> try pJSInt
<|> pJSFunction
-- | skip all spaces and comments, including line comment started with // ,
-- and block comment surrounded by /* and */
--
-- Examples:
-- >>> parseMaybe spaceConsumer " \n"
-- Just ()
-- >>> parseMaybe spaceConsumer " // abc\n \n/*xyz*/ "
-- Just ()
-- >>> parseMaybe spaceConsumer "a "
-- Nothing
-- >>> parseMaybe spaceConsumer " /**/ a"
-- Nothing
spaceConsumer :: Parser ()
spaceConsumer = L.space (void spaceChar) lineCmnt blockCmnt
where lineCmnt = L.skipLineComment "//"
blockCmnt = L.skipBlockComment "/*" "*/"
-- | space consumer for between function that skip many space chars
--
-- Examples:
-- >>> parseMaybe (symbol "#") " #"
-- Nothing
-- >>> parseMaybe (symbol "#") "#"
-- Just "#"
-- >>> parseMaybe (symbol "#") "# "
-- Just "#"
symbol :: String -> Parser String
symbol = L.symbol spaceConsumer
-- | convert a expression to surrounded by parentheses
--
-- Examples:
-- >>> parseTest (parentheses pJSVal) "(abc)"
-- abc
-- >>> parseMaybe (parentheses pJSVal) "( abc) "
-- Just abc
-- >>> parseMaybe (parentheses pJSVal) "(abc )"
-- Nothing
parentheses :: Parser a -> Parser a
parentheses = between (symbol "(") (symbol ")")
-- | convert a expression to surrounded by braces
braces :: Parser a -> Parser a
braces = between (symbol "{") (symbol "}")
-- | convert a expression to surrounded by brackets
brackets :: Parser a -> Parser a
brackets = between (symbol "[") (symbol "]")
-- | parse a semicolon symbol
--
-- Examples:
-- >>> parseMaybe semicolon "; "
-- Just ";"
-- >>> parseMaybe semicolon " ;"
-- Nothing
semicolon :: Parser String
semicolon = symbol ";"
-- | parse a comma symbol
comma :: Parser String
comma = symbol ","
-- | parse a colon symbol
colon :: Parser String
colon = symbol ":"
-- | parse a dot symbol
dot :: Parser String
dot = symbol "."
-- | parse a semicolon symbol or nothing
--
-- Examples:
-- >>> parseMaybe maybeSemicolon "; "
-- Just (Just ";")
-- >>> parseMaybe maybeSemicolon ""
-- Just Nothing
-- >>> parseMaybe maybeSemicolon " ;"
-- Nothing
maybeSemicolon :: Parser (Maybe String)
maybeSemicolon = (do s <- semicolon
return (Just s)) <|> return Nothing
-- | parse a js expression
--
-- Examples:
-- >>> parseMaybe pExpression "x "
-- Just x
-- >>> parseMaybe pExpression "( x ) "
-- Just x
-- >>> parseMaybe pExpression "f (x) "
-- Just f(x)
-- >>> parseMaybe pExpression "f(x)(y, z)"
-- Just f(x)(y,z)
-- >>> parseMaybe pExpression "f(x)['abc']"
-- Just f(x)[abc]
-- >>> parseMaybe pExpression "x = f(a)"
-- Just x = f(a)
-- >>> parseMaybe pExpression "x = f(a) + 3 "
-- Just x = (f(a)+3)
-- >>> parseMaybe pExpression "x + 5 + f(3) "
-- Just ((x+5)+f(3))
-- >>> parseMaybe pExpression "[ 1 , 2, 3 ] [ 2 ] "
-- Just [1,2,3][2]
pExpression :: Parser JSExpression
pExpression = try pAssignmentExpression
<|> pOperateExpression
-- | row value expression
--
-- Examples:
-- >>> parseMaybe pRowValExpression "x "
-- Just x
-- >>> parseMaybe pRowValExpression "'abc' "
-- Just abc
pRowValExpression :: Parser JSExpression
pRowValExpression = (JSRowVal <$> pJSVal) <* spaceConsumer
-- | parse a expression that can occur on the left side of a assignment
--
-- Examples:
-- >>> parseMaybe pLeftSideExpression "x "
-- Just x
-- >>> parseMaybe pLeftSideExpression "( x ) "
-- Just x
-- >>> parseMaybe pLeftSideExpression "f (x) "
-- Just f(x)
-- >>> parseMaybe pLeftSideExpression "f(x)(y, z)"
-- Just f(x)(y,z)
-- >>> parseMaybe pLeftSideExpression "f(x)['abc']"
-- Just f(x)[abc]
pLeftSideExpression :: Parser JSExpression
pLeftSideExpression = do expr <- try (parentheses pLeftSideExpression)
<|> pRowValExpression
furtherExpression expr
-- | terms for expression with operator
--
-- Examples:
-- >>> parseMaybe pOperateTerm "x "
-- Just x
-- >>> parseMaybe pOperateTerm "( x ) "
-- Just x
-- >>> parseMaybe pOperateTerm "f (x) "
-- Just f(x)
-- >>> parseMaybe pOperateTerm "f(x)(y, z)"
-- Just f(x)(y,z)
-- >>> parseMaybe pOperateTerm "f(x)['abc']"
-- Just f(x)[abc]
-- >>> parseMaybe pOperateTerm "[ 1 , 2 , 3 ]"
-- Just [1,2,3]
pOperateTerm :: Parser JSExpression
pOperateTerm = do expr <- try (parentheses pExpression)
<|> try pObjectLiterialExpression
<|> try pArrayLiterialExpression
<|> pRowValExpression
furtherExpression expr
-- | look ahead to find if there is further expression can be parsed,
-- if there is anything can be parsed, then it will parse the further
-- expression, such as function call, field get(including dot or brackets),
-- then it will build a new expression with the input expression and the
-- parsing result, after that, it will look ahead by calling itself.
-- otherwise, it will just return the input expression
--
-- Examples:
-- >>> let parser = furtherExpression (JSRowVal (JSAtom "f"))
-- >>> parseMaybe parser "(a, 1, 2 + 3)"
-- Just f(a,1,(2+3))
-- >>> let parser = furtherExpression (JSRowVal (JSAtom "f"))
-- >>> parseMaybe parser "(a)(2)['xyz']"
-- Just f(a)(2)[xyz]
-- >>> let parser = furtherExpression (JSRowVal (JSAtom "f"))
-- >>> parseMaybe parser "a)"
-- Nothing
furtherExpression :: JSExpression -> Parser JSExpression
furtherExpression expr = lookAheadExpression <|> return expr
where
lookAheadExpression :: Parser JSExpression
lookAheadExpression =
do c <- lookAhead (oneOf "[(.")
case c of
'[' -> brcketField
'(' -> funcCall
'.' -> dotField
where
brcketField = do inside <- brackets pExpression
furtherExpression (JSBracketFieldGet expr inside)
funcCall = do inside <- parentheses (sepBy pExpression comma)
furtherExpression (JSFunctionCall expr inside)
dotField = do after <- pRowValExpression
furtherExpression (JSDotFieldGet expr after)
-- | operators allowed in operator expression
operators :: [[E.Operator Parser JSExpression]]
operators =
[ [ E.Postfix (symbol "++" *> pure (JSSuffixUnaryOperate JSIncrement))
, E.Postfix (symbol "--" *> pure (JSSuffixUnaryOperate JSDecrement))
]
, [ E.Prefix (symbol "++" *> pure (JSPrefixUnaryOperate JSIncrement))
, E.Prefix (symbol "--" *> pure (JSPrefixUnaryOperate JSDecrement))
]
, [ E.InfixL (symbol "*" *> pure (JSInfixOperate JSMultiplication))
, E.InfixL (symbol "/" *> pure (JSInfixOperate JSDivision))
, E.InfixL (symbol "%" *> pure (JSInfixOperate JSModulus))
]
, [ E.InfixL (symbol "+" *> pure (JSInfixOperate JSAddition))
, E.InfixL (symbol "-" *> pure (JSInfixOperate JSSubtraction))
]
, [ E.InfixL (symbol "<=" *> pure (JSInfixOperate JSLessOrEqual))
, E.InfixL (symbol "<" *> pure (JSInfixOperate JSLessThan))
, E.InfixL (symbol ">=" *> pure (JSInfixOperate JSGreaterOrEqual))
, E.InfixL (symbol ">" *> pure (JSInfixOperate JSGreaterThan))
]
, [ E.InfixL (symbol "==" *> pure (JSInfixOperate JSEqualTo))
, E.InfixL (symbol "!=" *> pure (JSInfixOperate JSNotEqual))
, E.InfixL (symbol "===" *> pure (JSInfixOperate JSEqualValAndType))
, E.InfixL (symbol "!==" *> pure (JSInfixOperate JSNotEqualValOrType))
]
, [ E.Prefix (symbol "!" *> pure (JSPrefixUnaryOperate JSLogicNot))]
, [ E.InfixL (symbol "&&" *> pure (JSInfixOperate JSLogicAnd))
, E.InfixL (symbol "||" *> pure (JSInfixOperate JSLogicOr))
]
]
-- | parse js expression with operators
--
-- Examples:
-- >>> parseTest pOperateExpression "3 + 5"
-- (3+5)
-- >>> parseTest pOperateExpression "1 + 3 * 5"
-- (1+(3*5))
-- >>> parseTest pOperateExpression "true && 3"
-- (true&&3)
-- >>> parseMaybe pOperateExpression "5 == false "
-- Just (5==false)
-- >>> parseMaybe pOperateExpression "5 ++"
-- Just 5++
-- >>> parseMaybe pOperateExpression "++x + 3"
-- Just (++x+3)
pOperateExpression :: Parser JSExpression
pOperateExpression = E.makeExprParser pOperateTerm operators
-- | parse a assignment expression
--
-- Examples:
-- >>> parseMaybe pAssignmentExpression "x = 5"
-- Just x = 5
-- >>> parseMaybe pAssignmentExpression "x = f(a)"
-- Just x = f(a)
pAssignmentExpression :: Parser JSExpression
pAssignmentExpression = do name <- pLeftSideExpression
_ <- spaceConsumer >> symbol "="
value <- pExpression
return (JSAssignment name value)
-- | parse a js object written in json literial
--
-- Examples:
-- >>> parseMaybe pObjectLiterialExpression "{ x : 5, y: 'abc' } "
-- Just {x,y}
-- >>> parseMaybe pObjectLiterialExpression "{ } "
-- Just {}
-- >>> parseMaybe pObjectLiterialExpression "{ x } "
-- Nothing
pObjectLiterialExpression :: Parser JSExpression
pObjectLiterialExpression =
JSObjectLiteral <$> (braces (sepBy pEntry comma) <* spaceConsumer)
where
pEntry :: Parser (String, JSExpression)
pEntry = do name <- pIdentifier
_ <- spaceConsumer >> colon
content <- pExpression
return (name, content)
-- | parse a js array written in array literial
--
-- Examples:
-- >>> parseMaybe pArrayLiterialExpression "[ x , 10 ] "
-- Just [x,10]
-- >>> parseMaybe pArrayLiterialExpression "[ ] "
-- Just []
pArrayLiterialExpression :: Parser JSExpression
pArrayLiterialExpression =
JSArrayLiteral <$> (brackets (sepBy pExpression comma) <* spaceConsumer)
-- | convert a pos to a (Int, Int) representing (line, column)
convertPos :: SourcePos -> (Int, Int)
convertPos p = (sourceLine p, sourceColumn p)
-- | add position information to js statement content parser
-- convert the parser to a js statement parser
--
-- Examples:
-- >>> let s = "if ( x < 5 ) { x ; } else { y ; } "
-- >>> parseMaybe pIfStatement s
-- Just if((x<5)){x;}else{y;}
-- >>> let s = "for(var x = 3; x < 5; x = x+1) { f(x); }"
-- >>> parseMaybe pForStatement s
-- Just for(var x=3;(x<5);x = (x+1)){f(x);}
positionStatement :: Parser JSStatementContent -> Parser JSStatement
positionStatement pc = do begin <- getPosition
content <- pc
end <- getPosition
return JSStatement
{ statementContnet = content
, statementPosBegin = convertPos begin
, statementPosEnd = convertPos end
}
-- | parse a statement
--
-- Examples:
-- >>> let parse = parseString pStatement
-- >>> parse "for (var x = 5; x <= 3; x ++) { var y = 5; }"
-- Right for(var x=5;(x<=3);x++){var y=5;}
pStatement :: Parser JSStatement
pStatement = try pEmptyStatement
<|> try pDeclarationStatement
<|> try pIfStatement
<|> try pForStatement
<|> try pBlockStatement
<|> try pBreakStatement
<|> try pContinueStatement
<|> try pReturnStatement
<|> pRowExprStatement
-- | parse a statement which is a row expression
--
-- Examples:
-- >>> parseMaybe pRowExprStatementContent "x "
-- Just x
-- >>> parseMaybe pRowExprStatementContent "x ; "
-- Just x
pRowExprStatementContent :: Parser JSStatementContent
pRowExprStatementContent = JSRowExpression <$> (pExpression <* maybeSemicolon)
pRowExprStatement :: Parser JSStatement
pRowExprStatement = positionStatement pRowExprStatementContent
-- | parse js if-else statement content
--
-- Examples:
-- >>> parseMaybe pIfStatementContent "if ( x < 5 ) { x ; } else { y ; } "
-- Just if((x<5)){x;}else{y;}
-- >>> parseMaybe pIfStatementContent "if ( x < 5 ) { x ; } "
-- Just if((x<5)){x;}
-- >>> parseMaybe pIfStatementContent "if ( x < 5 ) { } "
-- Just if((x<5)){}
pIfStatementContent :: Parser JSStatementContent
pIfStatementContent = do _ <- symbol "if"
expr <- parentheses pExpression
ifStmts <- pStatement
maybeElse <- pElse
return (JSIf expr ifStmts maybeElse)
where
pNoElse :: Parser (Maybe JSStatement)
pNoElse = return Nothing
pHasElse :: Parser (Maybe JSStatement)
pHasElse = Just <$> (symbol "else" >> pStatement)
pElse = try pHasElse <|> pNoElse
pIfStatement :: Parser JSStatement
pIfStatement = positionStatement pIfStatementContent
-- | parse a js for loop statement content
--
-- Examples:
-- >>> let s = "for(var x = 3; x < 5; x = x+1) { f(x); }"
-- >>> parseMaybe pForStatementContent s
-- Just for(var x=3;(x<5);x = (x+1)){f(x);}
-- >>> let s = "for ( var x=3; x < 5; x=x+1 ) { f(x); } "
-- >>> parseMaybe pForStatementContent s
-- Just for(var x=3;(x<5);x = (x+1)){f(x);}
-- >>> let s = "for ( ; ; ) { f(x); } "
-- >>> parseMaybe pForStatementContent s
-- Just for(;;){f(x);}
pForStatementContent :: Parser JSStatementContent
pForStatementContent =
do _ <- symbol "for" >> symbol "("
begin <- sepBy pStatement comma
cond <- sepBy pStatement comma
after <- sepBy pStatement comma <* symbol ")"
body <- pStatement
return JSForLoop { beginLoop = begin
, condition = cond
, afterEachTime = after
, forLoopBody = body
}
pForStatement :: Parser JSStatement
pForStatement = positionStatement pForStatementContent
-- | parse a js block, it is many statements surrounded by braces
--
-- Examples:
-- >>> parseMaybe pBlockStatementContent "{ y = 5\nx + 3; return 5; } "
-- Just {y = 5;(x+3);return 5;}
-- >>> parseMaybe pBlockStatementContent "{}"
-- Just {}
-- >>> parseMaybe pBlockStatementContent "{ {} x-5; }"
-- Just {{};(x-5);}
pBlockStatementContent :: Parser JSStatementContent
pBlockStatementContent = JSBlock <$> braces (many pStatement)
pBlockStatement :: Parser JSStatement
pBlockStatement = positionStatement pBlockStatementContent
-- | parse a js empty statement which is only a semicolon
pEmptyStatementContent :: Parser JSStatementContent
pEmptyStatementContent = const JSEmptyStatement <$> semicolon
pEmptyStatement :: Parser JSStatement
pEmptyStatement = positionStatement pEmptyStatementContent
-- | parse a js break statement which is represented by "break"
pBreakStatementContent :: Parser JSStatementContent
pBreakStatementContent =
const JSBreak <$> (symbol "break" <* maybeSemicolon)
pBreakStatement :: Parser JSStatement
pBreakStatement = positionStatement pBreakStatementContent
-- | parse a js continue statement which is represented by "continue"
pContinueStatementContent :: Parser JSStatementContent
pContinueStatementContent =
const JSContinue <$> (symbol "continue" <* maybeSemicolon)
pContinueStatement :: Parser JSStatement
pContinueStatement = positionStatement pContinueStatementContent
-- | parse js return statement, it may return nothing or just a expression
--
-- Examples:
-- >>> parseMaybe pReturnStatementContent "return "
-- Just return
-- >>> parseMaybe pReturnStatementContent "return;"
-- Just return
-- >>> parseMaybe pReturnStatementContent "return x+3 "
-- Just return (x+3)
-- >>> parseMaybe pReturnStatementContent "return x+3 ;"
-- Just return (x+3)
pReturnStatementContent :: Parser JSStatementContent
pReturnStatementContent =
JSReturn <$> ((symbol "return" >> returnContent) <* maybeSemicolon)
where
noContent :: Parser (Maybe JSExpression)
noContent = return Nothing
hasContent :: Parser (Maybe JSExpression)
hasContent = Just <$> pExpression
returnContent :: Parser (Maybe JSExpression)
returnContent = try hasContent <|> noContent
pReturnStatement :: Parser JSStatement
pReturnStatement = positionStatement pReturnStatementContent
-- | parse a named function declaration
--
-- Examples:
-- >>> let s = "function f ( x , y ) { x = 3 ; return x + y ; }"
-- >>> parseMaybe pFuncDeclStatementContent s
-- Just function f(x,y){x = 3;return (x+y);}
pFuncDeclStatementContent :: Parser JSStatementContent
pFuncDeclStatementContent =
do begin <- getPosition
_ <- symbol "function"
name <- pIdentifier
_ <- spaceConsumer
(params, body) <- pFunctionPrincipalPart
end <- getPosition
return $ JSFuncDeclaration name
(JSFunction params body (convertPos begin) (convertPos end))
-- | parse a variables declaration, it may has a initial value
--
-- Examples:
-- >>> let s = "var x = 5 + f (3) ; "
-- >>> parseMaybe pVarDeclStatementContent s
-- Just var x=(5+f(3))
-- >>> let s = "var x = 5 + f (3) "
-- >>> parseMaybe pVarDeclStatementContent s
-- Just var x=(5+f(3))
-- >>> let s = "var x"
-- >>> parseMaybe pVarDeclStatementContent s
-- Just var x
-- >>> let s = "var x ; "
-- >>> parseMaybe pVarDeclStatementContent s
-- Just var x
pVarDeclStatementContent :: Parser JSStatementContent
pVarDeclStatementContent = try hasInit <|> noInit
where
hasInit = do _ <- symbol "var"
name <- pIdentifier
_ <- spaceConsumer >> symbol "="
expr <- pExpression <* maybeSemicolon
return (JSDeclaration name (Just expr))
noInit = do _ <- symbol "var"
name <- pIdentifier
_ <- spaceConsumer >> maybeSemicolon
return (JSDeclaration name Nothing)
-- | parse a declaration statement, it can be either a variable declaration
-- or a function declaration
--
-- Examples:
-- >>> let s = "function f ( x , y ) { x = 3 ; return x + y ; }"
-- >>> parseMaybe pDeclarationStatementContent s
-- Just function f(x,y){x = 3;return (x+y);}
-- >>> let s = "var x = 5 + f (3) "
-- >>> parseMaybe pDeclarationStatementContent s
-- Just var x=(5+f(3))
-- >>> let s = "var x"
-- >>> parseMaybe pDeclarationStatementContent s
-- Just var x
pDeclarationStatementContent :: Parser JSStatementContent
pDeclarationStatementContent = try pFuncDeclStatementContent
<|> pVarDeclStatementContent
pDeclarationStatement :: Parser JSStatement
pDeclarationStatement = positionStatement pDeclarationStatementContent
-- | parse a js program source code
--
-- Examples:
-- >>> parseMaybe jsProgramParser "var x = 3\nfunction x(y, z) { return y+z; } "
-- Just [var x=3,function x(y,z){return (y+z);}]
jsProgramParser :: Parser [JSStatement]
jsProgramParser = spaceConsumer >> many pStatement
-- | parse a js expression
jsExpressionParser :: Parser JSExpression
jsExpressionParser = pExpression
-- | parse a js value
jsValueParser :: Parser JSVal
jsValueParser = pJSVal
-- | parse a js statement
jsStatementParser :: Parser JSStatement
jsStatementParser = pStatement
-- | parse a string
--
-- Examples:
-- >>> parseString jsProgramParser "var x = 3\nfunction x(y, z) { return y+z; } "
-- Right [var x=3,function x(y,z){return (y+z);}]
-- >>> parseString jsProgramParser "var x = 3\nfunction x(y, ) { return y+z; } "
-- Left Parse error at JavaScript:2:15:
-- unexpected ')'
-- expecting letter
-- >>> parseString jsStatementParser "[x, 3, function(){}]"
-- Right [x,3,function(){}]
parseString :: Parser a -> String -> ThrowsError a
parseString parser input = case parse parser "JavaScript" input of
Left err -> throwError $ ParserError err
Right val -> return val
| li-zhirui/JSAnalyzer | JSParser.hs | mit | 28,004 | 0 | 14 | 6,538 | 4,179 | 2,316 | 1,863 | 318 | 7 |
module PlayerSpec (spec) where
import Player
import Game
import Board
import Test.Hspec
main :: IO ()
main = hspec spec
players = ( Player {playerType="human", playerSymbol=x}
, Player {playerType="computer", playerSymbol=o}
)
spec :: Spec
spec = do
describe "Player Tests" $ do
it "Should return playerType of player" $ do
let newPlayer = Player {playerType="human", playerSymbol=x}
playerType newPlayer `shouldBe` "human"
it "Should return symbol of player" $ do
let newPlayer = Player {playerType="human", playerSymbol=x}
playerSymbol newPlayer `shouldBe` x
it "Should return type of current player" $ do
currentPlayerType players `shouldBe` "human"
it "Should return symbol of current player" $ do
currentPlayerSymbol players `shouldBe` x
it "Should return a tuple with two new players" $ do
let newPlayers = createPlayers "human" x "computer" o
playerSymbol (fst newPlayers) `shouldBe` x
playerType (fst newPlayers) `shouldBe` "human"
playerSymbol (snd newPlayers) `shouldBe` o
playerType (snd newPlayers) `shouldBe` "computer"
it "Should return a tuple with two humans" $ do
let newPlayers = humanVsHuman
playerSymbol (fst newPlayers) `shouldBe` x
playerType (fst newPlayers) `shouldBe` "human"
playerSymbol (snd newPlayers) `shouldBe` o
playerType (snd newPlayers) `shouldBe` "human"
it "Should return a tuple with human and computer" $ do
let newPlayers = humanVsComputer
playerSymbol (fst newPlayers) `shouldBe` x
playerType (fst newPlayers) `shouldBe` "human"
playerSymbol (snd newPlayers) `shouldBe` o
playerType (snd newPlayers) `shouldBe` "computer"
it "Should return a tuple with two computers" $ do
let newPlayers = computerVsComputer
playerSymbol (fst newPlayers) `shouldBe` x
playerType (fst newPlayers) `shouldBe` "computer"
playerSymbol (snd newPlayers) `shouldBe` o
playerType (snd newPlayers) `shouldBe` "computer"
| basilpocklington/haskell-TTT | test/PlayerSpec.hs | mit | 2,058 | 0 | 17 | 468 | 607 | 305 | 302 | 46 | 1 |
module GameCom where
import Base
import Memory
import ROM
import qualified CPU
import qualified PPU
import qualified APU
step :: MachineState -> (Bool, MachineState)
step s0 = do
let s1 = CPU.step s0
let (r, s2) = PPU.step s1
let s3
| PPU.vBlankResult r = CPU.nmi s2
| PPU.scanlineIrqResult r = CPU.irq s2
| otherwise = s2
(PPU.newFrameResult r, s3)
| rkoeninger/GameCom | src/lib/GameCom.hs | mit | 417 | 0 | 14 | 127 | 150 | 76 | 74 | 16 | 1 |
module Language.HLisp.Prelude (hlispPrelude) where
import Data.Either
import qualified Data.Map.Strict as M
import Language.HLisp.Expr
import Language.HLisp.Parse
import Language.HLisp.Eval
import Language.HLisp.Prim
hlispPrelude :: LispEnv a
hlispPrelude =
let pstr = [("random", "[fun [lo hi] [__PRIM__random lo hi]]")
, ("+", "[fun [x y] [__PRIM__+ x y]]")
, ("-", "[fun [x y] [__PRIM__- x y]]")
, ("*", "[fun [x y] [__PRIM__* x y]]")
, ("/", "[fun [x y] [__PRIM__/ x y]]")
, ("<", "[fun [x y] [__PRIM__< x y]]")
, (">", "[fun [x y] [__PRIM__> x y]]")
, ("==", "[fun [x y] [__PRIM__== x y]]")
, ("head", "[fun [x] [__PRIM__head x]]")
, ("tail", "[fun [x] [__PRIM__tail x]]")
, ("nil?", "[fun [x] [__PRIM__nil? x]]")
, ("cons", "[fun [h t] [__PRIM__cons h t]]")
, ("!", "[fun [l n] [__PRIM__! l n]]")
, ("and", "[fun [x y] [if x [if y true false] false]]")
, ("or", "[fun [x y] [if x true [if y true false]]]")
, ("not", "[fun [x] [if x false true]]")
, ("any", "[fun [f lst] [foldl [fun [x acc] [or [f x] acc]] false lst]]")
, ("all", "[fun [f lst] [foldl [fun [x acc] [and [f x] acc]] true lst]]")
, (">=", "[fun [x y] [or [> x y] [== x y]]]")
, ("<", "[fun [x y] [or [< x y] [== x y]]]")
, ("map", "[fun [f lst] [if [nil? lst] ~[] [cons [f [head lst]] [map f [tail lst]]]]]")
, ("filter", "[fun [f lst] [if [nil? lst] ~[] [let [hd [head lst]] [tl [tail lst]] [if [f hd] [cons hd [filter f tl]] [filter f tl]]]]]")
, ("foldr", "[fun [f acc lst] [if [nil? lst] acc [f [head lst] [foldr f acc [tail lst]]]]]")
, ("foldl", "[fun [f acc lst] [if [nil? lst] acc [foldl f [f acc [head lst]] [tail lst]]]]")
, ("length", "[fun [lst] [foldl [fun [acc x] [+ 1 acc]] 0 lst]]")
, ("range", "[fun [lo hi] [if [== lo hi] ~[] [cons lo [range [+ lo 1] hi]]]]")
, ("append", "[fun [x y] [if [nil? x] y [cons [head x] [append [tail x] y]]]]")
, ("cycle", "[fun [n i lst] [[if [< n 1] ~[] [if [< i [length lst]] [cons [! lst i] [cycle [- n 1] [+ i 1] lst]] [cons [! lst 0] [cycle [- n 1] 1 lst]]]]]]")
, ("do-while", "[lfun [body pred] [[eval body] [if [eval pred] [do-while body pred] [nothing]]]]")] in
let msg = "parse error in prelude!" in
let processMapping = fmap (either (const $ error msg) id . parseLisp) in
let pexprs = map processMapping pstr in
let env = foldr (uncurry M.insert) M.empty pexprs in
registerPrimitives env hlispPrimitives
| rolph-recto/HLisp | src/Language/HLisp/Prelude.hs | mit | 2,743 | 0 | 20 | 838 | 431 | 264 | 167 | 43 | 1 |
{-# LANGUAGE TemplateHaskell #-}
import Test.Tasty.TH
{-
prop_foo
-}
main = $(defaultMainGenerator)
| expipiplus1/tasty-bug | Main.hs | mit | 102 | 0 | 6 | 14 | 18 | 11 | 7 | 3 | 1 |
module Test.Metamorph
( morphing
, morphingPure
, morphingGen
, morphingIO
, Metamorph
, Newtype(..)
, module Test.Metamorph.Pretty
, GenIO
, runGenIO
-- * Generics
, TraceOf
, Traceable(..)
, GTraceOf
, genericTrace
, weights
, weights'
, uniform
, genericPrettyWith
, (:%:)
) where
import Test.Metamorph.Generic
import Test.Metamorph.Internal
import Test.Metamorph.IO
import Test.Metamorph.Pretty
| Lysxia/metamorph | src/Test/Metamorph.hs | mit | 440 | 0 | 5 | 93 | 101 | 69 | 32 | 23 | 0 |
{- CIS 194 HW 10
due Monday, 1 April
-}
module AParser where
import Control.Applicative
import Data.Char
-- A parser for a value of type a is a function which takes a String
-- represnting the input to be parsed, and succeeds or fails; if it
-- succeeds, it returns the parsed value along with the remainder of
-- the input.
newtype Parser a = Parser { runParser :: String -> Maybe (a, String) }
-- For example, 'satisfy' takes a predicate on Char, and constructs a
-- parser which succeeds only if it sees a Char that satisfies the
-- predicate (which it then returns). If it encounters a Char that
-- does not satisfy the predicate (or an empty input), it fails.
satisfy :: (Char -> Bool) -> Parser Char
satisfy p = Parser f
where
f [] = Nothing -- fail on the empty input
f (x:xs) -- check if x satisfies the predicate
-- if so, return x along with the remainder
-- of the input (that is, xs)
| p x = Just (x, xs)
| otherwise = Nothing -- otherwise, fail
-- Using satisfy, we can define the parser 'char c' which expects to
-- see exactly the character c, and fails otherwise.
char :: Char -> Parser Char
char c = satisfy (== c)
{- For example:
*Parser> runParser (satisfy isUpper) "ABC"
Just ('A',"BC")
*Parser> runParser (satisfy isUpper) "abc"
Nothing
*Parser> runParser (char 'x') "xyz"
Just ('x',"yz")
-}
-- For convenience, we've also provided a parser for positive
-- integers.
posInt :: Parser Integer
posInt = Parser f
where
f xs
| null ns = Nothing
| otherwise = Just (read ns, rest)
where (ns, rest) = span isDigit xs
------------------------------------------------------------
-- Your code goes below here
------------------------------------------------------------
first :: (a -> b) -> (a,c) -> (b,c)
first f (x,y) = (f x, y)
instance Functor Parser where
fmap f p = Parser (fmap (first f) . (runParser p))
instance Applicative Parser where
pure x = Parser (\s -> Just (x,s) )
p1 <*> p2 = Parser (helper . (runParser p1))
where helper Nothing = Nothing
helper (Just (f,s)) = runParser (fmap f p2) s
-- helper (Just (f,s)) = fmap (first f) (runParser p2 s)
-- p1 <*> p2 -> Parser (a->b) -> Parser a -> Parser b
-- Exercise 3
abParser :: Parser (Char, Char)
abParser = (\x y -> (x,y)) <$> char 'a' <*> char 'b'
abParser_ :: Parser ()
abParser_ = (\x y -> ()) <$> char 'a' <*> char 'b'
intPair :: Parser [Integer]
intPair = (\x _ y -> [x,y]) <$> posInt <*> char ' ' <*> posInt
-- Exercise 4
instance Alternative Parser where
empty = Parser (\s -> Nothing)
p1 <|> p2 = Parser (\s -> ((runParser p1 s) <|> (runParser p2 s)))
-- Exercise 5
mtchOnly :: Parser a -> Parser ()
mtchOnly = fmap (\x -> ())
intOrUppercase :: Parser ()
intOrUppercase = (mtchOnly posInt) <|> (mtchOnly (satisfy isUpper))
| bachase/cis194 | hw10/AParser.hs | mit | 2,952 | 0 | 12 | 739 | 740 | 400 | 340 | 40 | 2 |
{-# htermination (lexDigits :: (List Char) -> (List (Tup2 (List Char) (List Char)))) #-}
import qualified Prelude
data MyBool = MyTrue | MyFalse
data List a = Cons a (List a) | Nil
data Tup2 a b = Tup2 a b ;
data Char = Char MyInt ;
data MyInt = Pos Nat | Neg Nat ;
data Nat = Succ Nat | Zero ;
data Ordering = LT | EQ | GT ;
asAs :: MyBool -> MyBool -> MyBool;
asAs MyFalse x = MyFalse;
asAs MyTrue x = x;
primCmpNat :: Nat -> Nat -> Ordering;
primCmpNat Zero Zero = EQ;
primCmpNat Zero (Succ y) = LT;
primCmpNat (Succ x) Zero = GT;
primCmpNat (Succ x) (Succ y) = primCmpNat x y;
primCmpInt :: MyInt -> MyInt -> Ordering;
primCmpInt (Pos Zero) (Pos Zero) = EQ;
primCmpInt (Pos Zero) (Neg Zero) = EQ;
primCmpInt (Neg Zero) (Pos Zero) = EQ;
primCmpInt (Neg Zero) (Neg Zero) = EQ;
primCmpInt (Pos x) (Pos y) = primCmpNat x y;
primCmpInt (Pos x) (Neg y) = GT;
primCmpInt (Neg x) (Pos y) = LT;
primCmpInt (Neg x) (Neg y) = primCmpNat y x;
primCmpChar :: Char -> Char -> Ordering;
primCmpChar (Char x) (Char y) = primCmpInt x y;
compareChar :: Char -> Char -> Ordering
compareChar = primCmpChar;
esEsOrdering :: Ordering -> Ordering -> MyBool
esEsOrdering LT LT = MyTrue;
esEsOrdering LT EQ = MyFalse;
esEsOrdering LT GT = MyFalse;
esEsOrdering EQ LT = MyFalse;
esEsOrdering EQ EQ = MyTrue;
esEsOrdering EQ GT = MyFalse;
esEsOrdering GT LT = MyFalse;
esEsOrdering GT EQ = MyFalse;
esEsOrdering GT GT = MyTrue;
not :: MyBool -> MyBool;
not MyTrue = MyFalse;
not MyFalse = MyTrue;
fsEsOrdering :: Ordering -> Ordering -> MyBool
fsEsOrdering x y = not (esEsOrdering x y);
gtEsChar :: Char -> Char -> MyBool
gtEsChar x y = fsEsOrdering (compareChar x y) LT;
ltEsChar :: Char -> Char -> MyBool
ltEsChar x y = fsEsOrdering (compareChar x y) GT;
isDigit :: Char -> MyBool;
isDigit c = asAs (gtEsChar c (Char (Pos (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ Zero))))))))))))))))))))))))))))))))))))))))))))))))))) (ltEsChar c (Char (Pos (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ Zero))))))))))))))))))))))))))))))))))))))))))))))))))))))))))));
foldr :: (a -> b -> b) -> b -> (List a) -> b;
foldr f z Nil = z;
foldr f z (Cons x xs) = f x (foldr f z xs);
psPs :: (List a) -> (List a) -> (List a);
psPs Nil ys = ys;
psPs (Cons x xs) ys = Cons x (psPs xs ys);
concat :: (List (List a)) -> (List a);
concat = foldr psPs Nil;
map :: (a -> b) -> (List a) -> (List b);
map f Nil = Nil;
map f (Cons x xs) = Cons (f x) (map f xs);
pt :: (c -> a) -> (b -> c) -> b -> a;
pt f g x = f (g x);
concatMap :: (b -> (List a)) -> (List b) -> (List a);
concatMap f = pt concat (map f);
nonnull00 (Tup2 (Cons vx vy) t) = Cons (Tup2 (Cons vx vy) t) Nil;
nonnull00 vz = Nil;
nonnull0 vu68 = nonnull00 vu68;
otherwise :: MyBool;
otherwise = MyTrue;
span2Span0 xw xx p wu wv MyTrue = Tup2 Nil (Cons wu wv);
span2Vu43 xw xx = span xw xx;
span2Ys0 xw xx (Tup2 ys ww) = ys;
span2Ys xw xx = span2Ys0 xw xx (span2Vu43 xw xx);
span2Zs0 xw xx (Tup2 wx zs) = zs;
span2Zs xw xx = span2Zs0 xw xx (span2Vu43 xw xx);
span2Span1 xw xx p wu wv MyTrue = Tup2 (Cons wu (span2Ys xw xx)) (span2Zs xw xx);
span2Span1 xw xx p wu wv MyFalse = span2Span0 xw xx p wu wv otherwise;
span2 p (Cons wu wv) = span2Span1 p wv p wu wv (p wu);
span3 p Nil = Tup2 Nil Nil;
span3 xu xv = span2 xu xv;
span :: (a -> MyBool) -> (List a) -> Tup2 (List a) (List a);
span p Nil = span3 p Nil;
span p (Cons wu wv) = span2 p (Cons wu wv);
nonnull :: (Char -> MyBool) -> (List Char) -> (List (Tup2 (List Char) (List Char)));
nonnull p s = concatMap nonnull0 (Cons (span p s) Nil);
lexDigits :: (List Char) -> (List (Tup2 (List Char) (List Char)));
lexDigits = nonnull isDigit;
| ComputationWithBoundedResources/ara-inference | doc/tpdb_trs/Haskell/basic_haskell/lexDigits_1.hs | mit | 4,282 | 0 | 125 | 950 | 2,430 | 1,265 | 1,165 | 88 | 1 |
module Main where
import System.ReadEditor
main :: IO ()
main = do
putStrLn ">>> Opening editor for you to write me some content"
content <- readEditor
putStrLn ">>> You wrote:"
putStr content
| yamadapc/haskell-read-editor | examples/Example.hs | mit | 221 | 0 | 7 | 60 | 49 | 23 | 26 | 8 | 1 |
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE RecordWildCards #-}
module Tutte
(
ForceAlgo(..)
, tutte
, Tutte
) where
import Control.Arrow ((***))
import qualified Data.Set as S
import qualified Data.Map.Strict as M
import Graph (vertices, Graph, Vertex, findBestCycle, neighbors)
type Set = S.Set
type Map = M.Map
type Vector2 = (Float, Float)
class ForceAlgo a where
positions :: a -> Map Vertex (Float, Float)
advance :: a -> a
data Tutte =
Tutte
{ graph :: Graph
, vertPositions :: Map Vertex Vector2
, fixedVerts :: Set Vertex
}
instance ForceAlgo Tutte where
positions = vertPositions
advance = advancer 10
tutte :: Graph -> Tutte
tutte graph =
let vertPositions = makeRing cycleVerts
`M.union`
(M.fromList $ zip nonCycleVerts $ repeat (0.0, 0.0))
in Tutte{graph, vertPositions, fixedVerts}
where cycleVerts = findBestCycle graph
fixedVerts = S.fromList cycleVerts
nonCycleVerts = filter (\v -> not $ S.member v fixedVerts) $ vertices graph
makeRing :: [Vertex] -> Map Vertex Vector2
makeRing vs = let numVs = fromIntegral $ length vs
dtheta = (2 * 3.14159265358) / numVs
in M.fromList $ map (id *** circle dtheta) $ zip vs [0.0..]
where circle :: Float -> Float -> Vector2
circle dtheta i = let i' = i * dtheta
in (cos i', sin i')
advancer :: Int -> Tutte -> Tutte
advancer i t@Tutte{..} =
let newPos = M.mapWithKey findNewPosition vertPositions
in t{vertPositions = newPos}
where findNewPosition v oldPos|S.member v fixedVerts = oldPos
|otherwise = baryCenter $ replicate i oldPos ++ neighborPos v
neighborPos v = map (vertPositions M.!) $ neighbors graph v
baryCenter :: [Vector2] -> Vector2
baryCenter vecs = go vecs (0.0,0.0) 0.0
where go [] (x, y) l = let minL = max 1.0 l in (x / minL, y / minL)
go ((vx, vy):vs) (x, y) l = go vs (x+vx,y+vy) (l+1.0)
| j-rock/tutte-your-stuff | src/Tutte.hs | mit | 2,061 | 0 | 13 | 596 | 741 | 399 | 342 | 52 | 2 |
--
-- Copyright (c) 2013 Bonelli Nicola <[email protected]>
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
--
module CGrep.Lang (Lang(..), langMap, getLang, splitLangList,
dumpLangMap, dumpLangRevMap) where
import qualified Data.Map as Map
import System.FilePath(takeExtension, takeFileName)
import Control.Monad
import Control.Applicative
import Data.Maybe
import Options
import Util
data Lang = Awk | C | Cpp | Cabal | Csharp | Chapel | Coffee | Conf | Css | CMake | D | Erlang | Fsharp | Go | Haskell |
Html | Java | Javascript | Latex | Lua | Make | OCaml | ObjectiveC |
Perl | PHP | Python | Ruby | Scala | Tcl | Text | Shell | Verilog | VHDL | Vim
deriving (Read, Show, Eq, Ord, Bounded)
data FileType = Name String | Ext String
deriving (Eq, Ord)
instance Show FileType where
show (Name x) = x
show (Ext e) = "*." ++ e
type LangMapType = Map.Map Lang [FileType]
type LangRevMapType = Map.Map FileType Lang
langMap :: LangMapType
langMap = Map.fromList [
(Awk, [Ext "awk", Ext "mawk", Ext "gawk"]),
(C, [Ext "c", Ext "C"]),
(Cpp, [Ext "cpp", Ext "CPP", Ext "cxx", Ext "cc", Ext "cp", Ext "tcc", Ext "h", Ext "H", Ext "hpp", Ext "ipp", Ext "HPP", Ext "hxx", Ext "hh", Ext "hp"]),
(Cabal, [Ext "cabal"]),
(Csharp, [Ext "cs", Ext "CS"]),
(Coffee, [Ext "coffee"]),
(Conf, [Ext "conf", Ext "cfg", Ext "doxy"]),
(Chapel, [Ext "chpl"]),
(Css, [Ext "css"]),
(CMake, [Name "CMakeLists.txt", Ext "cmake"]),
(D, [Ext "d", Ext "D"]),
(Erlang, [Ext "erl", Ext "ERL",Ext "hrl", Ext "HRL"]),
(Fsharp, [Ext "fs", Ext "fsx", Ext "fsi"]),
(Go, [Ext "go"]),
(Haskell, [Ext "hs", Ext "lhs", Ext "hsc"]),
(Html, [Ext "htm", Ext "html"]),
(Java, [Ext "java"]),
(Javascript,[Ext "js"]),
(Latex, [Ext "latex", Ext "tex"]),
(Lua, [Ext "lua"]),
(Make, [Name "Makefile", Name "makefile", Name "GNUmakefile", Ext "mk", Ext "mak"]),
(OCaml , [Ext "ml", Ext "mli"]),
(ObjectiveC,[Ext "m", Ext "mi"]),
(Perl, [Ext "pl", Ext "pm", Ext "pm6", Ext "plx", Ext "perl"]),
(PHP, [Ext "php", Ext "php3", Ext "php4", Ext "php5",Ext "phtml"]),
(Python, [Ext "py", Ext "pyx", Ext "pxd", Ext "pxi", Ext "scons"]),
(Ruby, [Ext "rb", Ext "ruby"]),
(Scala, [Ext "scala"]),
(Tcl, [Ext "tcl", Ext "tk"]),
(Text, [Ext "txt", Ext "md", Name "README", Name "INSTALL"]),
(Shell, [Ext "sh", Ext "bash", Ext "csh", Ext "tcsh", Ext "ksh", Ext "zsh"]),
(Verilog, [Ext "v", Ext "vh", Ext "sv"]),
(VHDL, [Ext "vhd", Ext "vhdl"]),
(Vim, [Ext "vim"])
]
langRevMap :: LangRevMapType
langRevMap = Map.fromList $ concatMap (\(l, xs) -> map (\x -> (x,l)) xs ) $ Map.toList langMap
-- utility functions
lookupLang :: FilePath -> Maybe Lang
lookupLang f = Map.lookup (Name $ takeFileName f) langRevMap <|> Map.lookup (Ext (let name = takeExtension f in case name of ('.':xs) -> xs; _ -> name )) langRevMap
forcedLang :: Options -> Maybe Lang
forcedLang Options{ force_language = l }
| Nothing <- l = Nothing
| otherwise = Map.lookup (Ext $ fromJust l) langRevMap <|> Map.lookup (Name $ fromJust l) langRevMap
getLang :: Options -> FilePath -> Maybe Lang
getLang opts f = forcedLang opts <|> lookupLang f
dumpLangMap :: LangMapType -> IO ()
dumpLangMap m = forM_ (Map.toList m) $ \(l, ex) ->
putStrLn $ show l ++ [ ' ' | _ <- [length (show l)..12]] ++ "-> " ++ show ex
dumpLangRevMap :: LangRevMapType -> IO ()
dumpLangRevMap m = forM_ (Map.toList m) $ \(ext, l) ->
putStrLn $ show ext ++ [ ' ' | _ <- [length (show ext)..12 ]] ++ "-> " ++ show l
splitLangList :: [String] -> ([Lang], [Lang], [Lang])
splitLangList = foldl run ([],[],[])
where run :: ([Lang], [Lang], [Lang]) -> String -> ([Lang], [Lang], [Lang])
run (l1, l2, l3) l
| '+':xs <- l = (l1, prettyRead xs "Lang" : l2, l3)
| '-':xs <- l = (l1, l2, prettyRead xs "Lang" : l3)
| otherwise = (prettyRead l "Lang" : l1, l2, l3)
| YelaSeamless/cgrep | src/CGrep/Lang.hs | gpl-2.0 | 5,198 | 0 | 16 | 1,554 | 1,891 | 1,053 | 838 | 79 | 2 |
{-# LANGUAGE TypeFamilies, OverloadedStrings #-}
import Data.Word (Word8)
import qualified Data.ByteString as S
import Data.ByteString.Char8 () -- get an orphan IsString instance?? wth does that mean?
class SafeHead a where
type Content a
safeHead :: a -> Maybe (Content a)
instance SafeHead [a] where
type Content [a] = a
safeHead [] = Nothing
safeHead (x:_) = Just x
instance SafeHead S.ByteString where
type Content S.ByteString = Word8
safeHead bs
| S.null bs = Nothing
| otherwise = Just $ S.head bs
main :: IO ()
main = do
print $ safeHead ("" :: String)
print $ safeHead ("hello" :: String)
print $ safeHead ("" :: S.ByteString)
print $ safeHead ("hello" :: S.ByteString)
| softwaremechanic/Miscellaneous | Haskell/yesod_book/type_family.hs | gpl-2.0 | 721 | 0 | 10 | 154 | 253 | 132 | 121 | 22 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE BangPatterns #-}
import Control.Monad
import Control.Concurrent
import qualified Data.ByteString.Char8 as BS
import qualified Sound.OSC as OSC
import qualified Sound.OSC.Transport.FD
import System.Random
import Control.Monad (replicateM)
import GHC.Int
kOSCDest = ("127.0.0.1", 15144)
data Action
= SendOSC
String [OSC.Datum] -- address port pattern args (i.e. "/fluent/play" ["n1","1"])
sendMoreOSC :: Action -> IO ()
sendMoreOSC (SendOSC patt args) = forever $ do
putStrLn "Sending some OSC"
threadDelay 5000
--rand <- randomRIO (0::Int, 7::Int)
g <- newStdGen
let (rx) = fst $ randomR (0::Int, 7::Int) g
g <- newStdGen
let (ry) = fst $ randomR (0::Int, 7::Int) g
g <- newStdGen
let (rs) = fst $ randomR (0::Int, 1::Int) g
--let msg = OSC.Message patt [OSC.Int32 $ fromIntegral (rx :: Int), OSC.Int32 2, OSC.Int32 1]
let msg = OSC.Message patt (fmap (\x -> OSC.Int32 $ fromIntegral (x :: Int)) [rx, ry, rs])
oscOut <- let (addr, port) = kOSCDest in OSC.openUDP addr port
Sound.OSC.Transport.FD.sendMessage oscOut $ msg
main :: IO ()
main = sendMoreOSC $ SendOSC "/monome/grid/led/set" [OSC.Int32 1, OSC.Int32 1, OSC.Int32 1] | kejace/comonome | sender.hs | gpl-2.0 | 1,384 | 0 | 18 | 321 | 410 | 221 | 189 | 31 | 1 |
-- Copyright (c) 2011, Diego Souza
-- 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 <ORGANIZATION> 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 TikTok.Plugins.Invite
( new
) where
import Control.Monad.Reader
import qualified Data.ByteString as B
import Network.SimpleIRC.Messages
import TikTok.Bot
import TikTok.Plugins.ByteStringHelpers
type Whitelist = [String]
new :: Whitelist -> Plugin
new w = Plugin (eventHandler w) "invite"
eventHandler :: Whitelist -> Event -> Bot ()
eventHandler w (EvtInvite m) = let channel = mMsg m
in do { sayf <- asks say
; when (whitelisted w channel) (sayf $ MJoin channel Nothing)
}
eventHandler _ _ = return ()
whitelisted :: Whitelist -> B.ByteString -> Bool
whitelisted ws chan = (frombs chan) `elem` ws
| dgvncsz0f/tiktok | src/main/TikTok/Plugins/Invite.hs | gpl-3.0 | 2,320 | 0 | 12 | 508 | 246 | 144 | 102 | 17 | 1 |
{-
This source file is a part of the noisefunge programming environment.
Copyright (C) 2015 Rev. Johnny Healey <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
-}
{-# LANGUAGE TemplateHaskell #-}
module Language.NoiseFunge.Server (runServer, ServerConfig(..)) where
import Network.Socket hiding (sendTo, recvFrom)
import Network.Socket.ByteString
import Control.Applicative
import Control.Concurrent
import Control.Concurrent.STM
import Control.Monad
import qualified Control.Monad.State as ST
import Control.Monad.Writer
import Control.Lens
import Data.Binary
import Data.Int
import qualified Data.Map as M
import qualified Data.Set as S
import Data.ByteString.Lazy as BSL hiding (readFile)
import qualified Data.ByteString as BS
import System.IO
import Language.NoiseFunge.ALSA
import Language.NoiseFunge.Beat
import Language.NoiseFunge.Befunge
import Language.NoiseFunge.Befunge.VM
import Language.NoiseFunge.Befunge.Process
import Language.NoiseFunge.Engine
import Language.NoiseFunge.Server.Comm
data ServerConfig = ServerConfig {
_serverHosts :: [(Family, SockAddr)],
_serverALSAConfig :: ALSAThreadConfig,
_serverVMOptions :: OperatorParams,
_serverPreload :: [(FilePath, String, String)],
_serverPacketSize :: Word16
} deriving (Show, Eq, Ord)
$(makeLenses ''ServerConfig)
type Subscriptions = M.Map Beat (S.Set SockAddr)
data BinBuffer = BB {
_currBuff :: (Int64, ByteString),
_buffered :: [BS.ByteString] -> [BS.ByteString]
}
$(makeLenses ''BinBuffer)
bufferBinary :: Binary b => Word16 -> [b] -> [BS.ByteString]
bufferBinary ms xs = bufs $ ST.execState (buffer >> flush) initial where
initial = BB blank id
ms' = fromIntegral ms
blank = (0, mempty)
buffer = forM_ xs $ \x -> do
let enc = encode x
len = BSL.length enc
bl <- use (currBuff._1)
when (bl > 0 && (bl + len) > ms') $ flush
zoom currBuff $ do
_1 += len
_2 %= (`mappend` enc)
flush = do
curr <- use currBuff
case curr of
(0, _) -> return ()
(_, bs) -> do
buffered %= (. (toStrict bs:))
currBuff .= blank
bufs bb = (bb^.buffered) []
requestHandler :: Socket -> NoiseFungeEngine -> TVar Bool ->
TVar Subscriptions -> TVar Subscriptions -> IO ()
requestHandler s nfe rstv stats delts = forever $ do
(bs, addr) <- recvFrom s 32768
case decodeOrFail (fromChunks [bs]) of
(Left (_,_,str)) -> hPutStrLn stderr ("Bad request: " ++ str)
(Right (_,_, Subscribe sub b)) -> atomically $ do
bt <- case b of
Just b' -> return b'
Nothing -> readTVar (nfe^.beatVar)
let subs = case sub of
Stats -> stats
Deltas -> delts
altfn = (Just . maybe (S.singleton addr) (S.insert addr))
modifyTVar subs (M.alter altfn bt)
(Right (_,_, StartProgram n ib ob a)) -> do
pid <- startProgram nfe a n ib ob
hPutStrLn stderr ("Starting program: " ++ show pid)
let res = toStrict $ encode $ NewProcess pid
void $ sendTo s res addr
(Right (_,_, StopProgram pf nf r)) -> do
stopProgram nfe pf nf r
hPutStrLn stderr ("Stopping Program(s): " ++ show (pf, nf, r))
(Right (_,_, SendReset)) -> do
atomically $ writeTVar rstv True
runServer :: ServerConfig -> IO ()
runServer conf = do
hSetBuffering stderr LineBuffering
let nextB = ((aconf^.alsaTempo) ##)
bufferB = bufferBinary (conf^.serverPacketSize)
aconf = conf^.serverALSAConfig
nfe <- initNF aconf (conf^.serverVMOptions)
rstv <- newTVarIO True
servs <- forM (conf^.serverHosts) $ \(fam, addr) -> do
s <- socket fam Datagram defaultProtocol
bindSocket s addr
stats <- newTVarIO M.empty
delts <- newTVarIO M.empty
void . forkIO $ requestHandler s nfe rstv stats delts
return (s, stats, delts)
forM_ (conf^.serverPreload) $ \(f, ib, ob) -> do
pa <- (makeProgArray . lines) <$> (liftIO $ readFile f)
startProgram nfe pa f ib ob
hPutStrLn stderr ("Server is running.")
beatEvents nfe $ \bt delts deads _ stats -> do
rst <- atomically $ do
v <- readTVar rstv
when v $ writeTVar rstv False
return v
let nb = toStrict $ encode $ NextBeat (nextB bt)
forM_ servs $ \(s, ssubs, dsubs) -> do
when rst $ do
let rstm = toStrict $ encode Reset
addrs <- atomically $ do
daddrs <- M.elems <$> readTVar dsubs
saddrs <- M.elems <$> readTVar ssubs
return $ mconcat daddrs <> mconcat saddrs
mapM_ (sendTo s rstm) (S.toList addrs)
void $ forkIO $ do
(outd, waiting) <- atomically $ do
subs <- readTVar dsubs
let (outd, waiting, rest) = M.splitLookup bt subs
writeTVar dsubs rest
return (mconcat (M.elems outd), waiting)
let waiting' = maybe [] S.toList waiting
outd' = S.toList outd
forM_ waiting' $ \client -> do
sendTo s nb client
forM_ outd' $ \client -> do
sendTo s nb client
let changes = bufferB $ do
(pid, _, d) <- delts
return $ Change bt pid d
catchus = bufferB $ do
(pid, ps, d) <- delts
return $ Catchup bt pid (ps^.mem) d
forM_ changes $ \ch -> do
forM_ waiting' $ \client -> do
sendTo s ch client
forM_ catchus $ \ch -> do
forM_ outd' $ \client -> do
sendTo s ch client
let deads' = bufferB $ do
(pid, r) <- deads
return $ Dead bt pid r
forM_ deads' $ \dead -> do
forM_ waiting' $ \client -> do
sendTo s dead client
forM_ outd' $ \client -> do
sendTo s dead client
void $ forkIO $ do
waiting <- atomically $ do
subs <- readTVar ssubs
let (outd, waiting, rest) = M.splitLookup bt subs
writeTVar ssubs rest
let waiting' = maybe S.empty id waiting
return (S.toList $ mconcat (M.elems outd) <> waiting')
forM_ waiting $ \client -> do
sendTo s nb client
let stats' = bufferB $ do
stat <- stats
return $ ProcessStats bt stat
forM_ stats' $ \stat -> do
forM_ waiting $ \client -> do
sendTo s stat client
let agg = toStrict $ encode $ TickStats bt run' rbl' wbl' ded'
run' = getSum run
rbl' = getSum rbl
wbl' = getSum wbl
ded' = getSum ded
(run, rbl, wbl, ded) = execWriter $ do
mapM_ (tell . addStat . (^.vmExec)) stats
addStat ERunning = (Sum 1, mempty, mempty, mempty)
addStat (EHalted _) = (mempty, mempty, mempty, Sum 1)
addStat (ERBlock _) = (mempty, Sum 1, mempty, mempty)
addStat (EWBlock _) = (mempty, mempty, Sum 1, mempty)
forM_ waiting $ \client -> do
sendTo s agg client
| wolfspyre/noisefunge | src/Language/NoiseFunge/Server.hs | gpl-3.0 | 8,501 | 0 | 29 | 3,123 | 2,543 | 1,281 | 1,262 | 177 | 7 |
{-# 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.CloudPrivateCatalogProducer.Operations.Cancel
-- 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)
--
-- Starts asynchronous cancellation on a long-running operation. The server
-- makes a best effort to cancel the operation, but success is not
-- guaranteed. If the server doesn\'t support this method, it returns
-- \`google.rpc.Code.UNIMPLEMENTED\`. Clients can use
-- Operations.GetOperation or other methods to check whether the
-- cancellation succeeded or whether the operation completed despite
-- cancellation. On successful cancellation, the operation is not deleted;
-- instead, it becomes an operation with an Operation.error value with a
-- google.rpc.Status.code of 1, corresponding to \`Code.CANCELLED\`.
--
-- /See:/ <https://cloud.google.com/private-catalog/ Cloud Private Catalog Producer API Reference> for @cloudprivatecatalogproducer.operations.cancel@.
module Network.Google.Resource.CloudPrivateCatalogProducer.Operations.Cancel
(
-- * REST Resource
OperationsCancelResource
-- * Creating a Request
, operationsCancel
, OperationsCancel
-- * Request Lenses
, ocXgafv
, ocUploadProtocol
, ocAccessToken
, ocUploadType
, ocPayload
, ocName
, ocCallback
) where
import Network.Google.CloudPrivateCatalogProducer.Types
import Network.Google.Prelude
-- | A resource alias for @cloudprivatecatalogproducer.operations.cancel@ method which the
-- 'OperationsCancel' request conforms to.
type OperationsCancelResource =
"v1beta1" :>
CaptureMode "name" "cancel" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON]
GoogleLongrunningCancelOperationRequest
:> Post '[JSON] GoogleProtobufEmpty
-- | Starts asynchronous cancellation on a long-running operation. The server
-- makes a best effort to cancel the operation, but success is not
-- guaranteed. If the server doesn\'t support this method, it returns
-- \`google.rpc.Code.UNIMPLEMENTED\`. Clients can use
-- Operations.GetOperation or other methods to check whether the
-- cancellation succeeded or whether the operation completed despite
-- cancellation. On successful cancellation, the operation is not deleted;
-- instead, it becomes an operation with an Operation.error value with a
-- google.rpc.Status.code of 1, corresponding to \`Code.CANCELLED\`.
--
-- /See:/ 'operationsCancel' smart constructor.
data OperationsCancel =
OperationsCancel'
{ _ocXgafv :: !(Maybe Xgafv)
, _ocUploadProtocol :: !(Maybe Text)
, _ocAccessToken :: !(Maybe Text)
, _ocUploadType :: !(Maybe Text)
, _ocPayload :: !GoogleLongrunningCancelOperationRequest
, _ocName :: !Text
, _ocCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'OperationsCancel' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ocXgafv'
--
-- * 'ocUploadProtocol'
--
-- * 'ocAccessToken'
--
-- * 'ocUploadType'
--
-- * 'ocPayload'
--
-- * 'ocName'
--
-- * 'ocCallback'
operationsCancel
:: GoogleLongrunningCancelOperationRequest -- ^ 'ocPayload'
-> Text -- ^ 'ocName'
-> OperationsCancel
operationsCancel pOcPayload_ pOcName_ =
OperationsCancel'
{ _ocXgafv = Nothing
, _ocUploadProtocol = Nothing
, _ocAccessToken = Nothing
, _ocUploadType = Nothing
, _ocPayload = pOcPayload_
, _ocName = pOcName_
, _ocCallback = Nothing
}
-- | V1 error format.
ocXgafv :: Lens' OperationsCancel (Maybe Xgafv)
ocXgafv = lens _ocXgafv (\ s a -> s{_ocXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
ocUploadProtocol :: Lens' OperationsCancel (Maybe Text)
ocUploadProtocol
= lens _ocUploadProtocol
(\ s a -> s{_ocUploadProtocol = a})
-- | OAuth access token.
ocAccessToken :: Lens' OperationsCancel (Maybe Text)
ocAccessToken
= lens _ocAccessToken
(\ s a -> s{_ocAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
ocUploadType :: Lens' OperationsCancel (Maybe Text)
ocUploadType
= lens _ocUploadType (\ s a -> s{_ocUploadType = a})
-- | Multipart request metadata.
ocPayload :: Lens' OperationsCancel GoogleLongrunningCancelOperationRequest
ocPayload
= lens _ocPayload (\ s a -> s{_ocPayload = a})
-- | The name of the operation resource to be cancelled.
ocName :: Lens' OperationsCancel Text
ocName = lens _ocName (\ s a -> s{_ocName = a})
-- | JSONP
ocCallback :: Lens' OperationsCancel (Maybe Text)
ocCallback
= lens _ocCallback (\ s a -> s{_ocCallback = a})
instance GoogleRequest OperationsCancel where
type Rs OperationsCancel = GoogleProtobufEmpty
type Scopes OperationsCancel =
'["https://www.googleapis.com/auth/cloud-platform"]
requestClient OperationsCancel'{..}
= go _ocName _ocXgafv _ocUploadProtocol
_ocAccessToken
_ocUploadType
_ocCallback
(Just AltJSON)
_ocPayload
cloudPrivateCatalogProducerService
where go
= buildClient
(Proxy :: Proxy OperationsCancelResource)
mempty
| brendanhay/gogol | gogol-cloudprivatecatalogproducer/gen/Network/Google/Resource/CloudPrivateCatalogProducer/Operations/Cancel.hs | mpl-2.0 | 6,185 | 0 | 16 | 1,328 | 792 | 468 | 324 | 112 | 1 |
-- This Source Code Form is subject to the terms of the Mozilla Public
-- License, v. 2.0. If a copy of the MPL was not distributed with this
-- file, You can obtain one at http://mozilla.org/MPL/2.0/.
module Database.CQL.IO.Timeouts
( TimeoutManager
, create
, destroy
, Action
, Milliseconds (..)
, add
, cancel
, withTimeout
) where
import Control.Applicative
import Control.Concurrent.STM
import Control.Exception (mask_, bracket)
import Control.Reaper
import Control.Monad
import Database.CQL.IO.Types (Milliseconds (..), ignore)
import Prelude
data TimeoutManager = TimeoutManager
{ roundtrip :: !Int
, reaper :: !(Reaper [Action] Action)
}
data Action = Action
{ action :: !(IO ())
, state :: !(TVar State)
}
data State = Running !Int | Canceled
create :: Milliseconds -> IO TimeoutManager
create (Ms n) = TimeoutManager n <$> mkReaper defaultReaperSettings
{ reaperAction = mkListAction prune
, reaperDelay = n * 1000
}
where
prune a = do
s <- atomically $ do
x <- readTVar (state a)
writeTVar (state a) (newState x)
return x
case s of
Running 0 -> do
ignore (action a)
return Nothing
Canceled -> return Nothing
_ -> return $ Just a
newState (Running k) = Running (k - 1)
newState s = s
destroy :: TimeoutManager -> Bool -> IO ()
destroy tm exec = mask_ $ do
a <- reaperStop (reaper tm)
when exec $ mapM_ f a
where
f e = readTVarIO (state e) >>= \s -> case s of
Running _ -> ignore (action e)
Canceled -> return ()
add :: TimeoutManager -> Milliseconds -> IO () -> IO Action
add tm (Ms n) a = do
r <- Action a <$> newTVarIO (Running $ n `div` roundtrip tm)
reaperAdd (reaper tm) r
return r
cancel :: Action -> IO ()
cancel a = atomically $ writeTVar (state a) Canceled
withTimeout :: TimeoutManager -> Milliseconds -> IO () -> IO a -> IO a
withTimeout tm m x a = bracket (add tm m x) cancel $ const a
| twittner/cql-io | src/Database/CQL/IO/Timeouts.hs | mpl-2.0 | 2,091 | 0 | 16 | 608 | 714 | 361 | 353 | 66 | 4 |
{-# 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.Compute.PacketMirrorings.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Retrieves a list of PacketMirroring resources available to the specified
-- project and region.
--
-- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.packetMirrorings.list@.
module Network.Google.Resource.Compute.PacketMirrorings.List
(
-- * REST Resource
PacketMirroringsListResource
-- * Creating a Request
, packetMirroringsList
, PacketMirroringsList
-- * Request Lenses
, pmlReturnPartialSuccess
, pmlOrderBy
, pmlProject
, pmlFilter
, pmlRegion
, pmlPageToken
, pmlMaxResults
) where
import Network.Google.Compute.Types
import Network.Google.Prelude
-- | A resource alias for @compute.packetMirrorings.list@ method which the
-- 'PacketMirroringsList' request conforms to.
type PacketMirroringsListResource =
"compute" :>
"v1" :>
"projects" :>
Capture "project" Text :>
"regions" :>
Capture "region" Text :>
"packetMirrorings" :>
QueryParam "returnPartialSuccess" Bool :>
QueryParam "orderBy" Text :>
QueryParam "filter" Text :>
QueryParam "pageToken" Text :>
QueryParam "maxResults" (Textual Word32) :>
QueryParam "alt" AltJSON :>
Get '[JSON] PacketMirroringList
-- | Retrieves a list of PacketMirroring resources available to the specified
-- project and region.
--
-- /See:/ 'packetMirroringsList' smart constructor.
data PacketMirroringsList =
PacketMirroringsList'
{ _pmlReturnPartialSuccess :: !(Maybe Bool)
, _pmlOrderBy :: !(Maybe Text)
, _pmlProject :: !Text
, _pmlFilter :: !(Maybe Text)
, _pmlRegion :: !Text
, _pmlPageToken :: !(Maybe Text)
, _pmlMaxResults :: !(Textual Word32)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'PacketMirroringsList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pmlReturnPartialSuccess'
--
-- * 'pmlOrderBy'
--
-- * 'pmlProject'
--
-- * 'pmlFilter'
--
-- * 'pmlRegion'
--
-- * 'pmlPageToken'
--
-- * 'pmlMaxResults'
packetMirroringsList
:: Text -- ^ 'pmlProject'
-> Text -- ^ 'pmlRegion'
-> PacketMirroringsList
packetMirroringsList pPmlProject_ pPmlRegion_ =
PacketMirroringsList'
{ _pmlReturnPartialSuccess = Nothing
, _pmlOrderBy = Nothing
, _pmlProject = pPmlProject_
, _pmlFilter = Nothing
, _pmlRegion = pPmlRegion_
, _pmlPageToken = Nothing
, _pmlMaxResults = 500
}
-- | Opt-in for partial success behavior which provides partial results in
-- case of failure. The default value is false.
pmlReturnPartialSuccess :: Lens' PacketMirroringsList (Maybe Bool)
pmlReturnPartialSuccess
= lens _pmlReturnPartialSuccess
(\ s a -> s{_pmlReturnPartialSuccess = a})
-- | Sorts list results by a certain order. By default, results are returned
-- in alphanumerical order based on the resource name. You can also sort
-- results in descending order based on the creation timestamp using
-- \`orderBy=\"creationTimestamp desc\"\`. This sorts results based on the
-- \`creationTimestamp\` field in reverse chronological order (newest
-- result first). Use this to sort resources like operations so that the
-- newest operation is returned first. Currently, only sorting by \`name\`
-- or \`creationTimestamp desc\` is supported.
pmlOrderBy :: Lens' PacketMirroringsList (Maybe Text)
pmlOrderBy
= lens _pmlOrderBy (\ s a -> s{_pmlOrderBy = a})
-- | Project ID for this request.
pmlProject :: Lens' PacketMirroringsList Text
pmlProject
= lens _pmlProject (\ s a -> s{_pmlProject = a})
-- | A filter expression that filters resources listed in the response. The
-- expression must specify the field name, a comparison operator, and the
-- value that you want to use for filtering. The value must be a string, a
-- number, or a boolean. The comparison operator must be either \`=\`,
-- \`!=\`, \`>\`, or \`\<\`. For example, if you are filtering Compute
-- Engine instances, you can exclude instances named \`example-instance\`
-- by specifying \`name != example-instance\`. You can also filter nested
-- fields. For example, you could specify \`scheduling.automaticRestart =
-- false\` to include instances only if they are not scheduled for
-- automatic restarts. You can use filtering on nested fields to filter
-- based on resource labels. To filter on multiple expressions, provide
-- each separate expression within parentheses. For example: \`\`\`
-- (scheduling.automaticRestart = true) (cpuPlatform = \"Intel Skylake\")
-- \`\`\` By default, each expression is an \`AND\` expression. However,
-- you can include \`AND\` and \`OR\` expressions explicitly. For example:
-- \`\`\` (cpuPlatform = \"Intel Skylake\") OR (cpuPlatform = \"Intel
-- Broadwell\") AND (scheduling.automaticRestart = true) \`\`\`
pmlFilter :: Lens' PacketMirroringsList (Maybe Text)
pmlFilter
= lens _pmlFilter (\ s a -> s{_pmlFilter = a})
-- | Name of the region for this request.
pmlRegion :: Lens' PacketMirroringsList Text
pmlRegion
= lens _pmlRegion (\ s a -> s{_pmlRegion = a})
-- | Specifies a page token to use. Set \`pageToken\` to the
-- \`nextPageToken\` returned by a previous list request to get the next
-- page of results.
pmlPageToken :: Lens' PacketMirroringsList (Maybe Text)
pmlPageToken
= lens _pmlPageToken (\ s a -> s{_pmlPageToken = a})
-- | The maximum number of results per page that should be returned. If the
-- number of available results is larger than \`maxResults\`, Compute
-- Engine returns a \`nextPageToken\` that can be used to get the next page
-- of results in subsequent list requests. Acceptable values are \`0\` to
-- \`500\`, inclusive. (Default: \`500\`)
pmlMaxResults :: Lens' PacketMirroringsList Word32
pmlMaxResults
= lens _pmlMaxResults
(\ s a -> s{_pmlMaxResults = a})
. _Coerce
instance GoogleRequest PacketMirroringsList where
type Rs PacketMirroringsList = PacketMirroringList
type Scopes PacketMirroringsList =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/compute",
"https://www.googleapis.com/auth/compute.readonly"]
requestClient PacketMirroringsList'{..}
= go _pmlProject _pmlRegion _pmlReturnPartialSuccess
_pmlOrderBy
_pmlFilter
_pmlPageToken
(Just _pmlMaxResults)
(Just AltJSON)
computeService
where go
= buildClient
(Proxy :: Proxy PacketMirroringsListResource)
mempty
| brendanhay/gogol | gogol-compute/gen/Network/Google/Resource/Compute/PacketMirrorings/List.hs | mpl-2.0 | 7,619 | 0 | 20 | 1,668 | 833 | 497 | 336 | 120 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedStrings #-}
--------------------------------------------------------------------------------
-- See end of this file for licence information.
--------------------------------------------------------------------------------
-- |
-- Module : RDFRulesetTest
-- Copyright : (c) 2003, Graham Klyne, 2009 Vasili I Galchin, 2011, 2012, 2013, 2014 Douglas Burke
-- License : GPL V2
--
-- Maintainer : Douglas Burke
-- Stability : experimental
-- Portability : CPP, OverloadedStrings
--
-- This module contains test cases for ruleset data.
--
-- Note that the proof-related methods defined in RDFRuleset are tested
-- by RDFProofTest and/or RDFProofCheck.
--
module Main where
import qualified Data.Set as S
import qualified Data.Text.Lazy.Builder as B
import qualified Test.Framework as TF
import qualified TestHelpers as TH
import Swish.Namespace (Namespace, makeNamespace, getNamespaceTuple, getNamespaceURI, ScopedName, makeScopedName, makeNSScopedName, namespaceToBuilder)
import Swish.QName (LName)
import Swish.Rule (Formula(..), Rule(..), fwdCheckInference )
import Swish.Ruleset (makeRuleset, getRulesetNamespace, getRulesetAxioms)
import Swish.Ruleset (getRulesetRules, getRulesetAxiom, getRulesetRule)
import Swish.VarBinding (makeVarBinding, vbmCompose, makeVarFilterModify)
import Swish.RDF.Ruleset
( RDFFormula, RDFRule, RDFClosure, RDFRuleset
, GraphClosure(..)
, makeRDFGraphFromN3Builder
, makeRDFFormula
, makeN3ClosureSimpleRule
, makeNodeAllocTo
, graphClosureFwdApply, graphClosureBwdApply
)
import Swish.RDF.Query (rdfQueryBack, rdfQueryBackModify)
import Swish.RDF.VarBinding
( RDFVarBinding
, RDFVarBindingModify
, RDFVarBindingFilter
, rdfVarBindingXMLLiteral
)
import Swish.RDF.Graph
( Label (..), RDFLabel(..), RDFGraph
, RDFArcSet
, getArcs
, allLabels
, toRDFGraph
)
import Swish.RDF.Vocabulary (namespaceRDF, namespaceRDFS, namespaceOWL, scopeRDF)
#if (!defined(__GLASGOW_HASKELL__)) || (__GLASGOW_HASKELL__ < 710)
import Data.Monoid (Monoid(..))
#endif
import Data.List (sort)
import Data.Maybe (isJust, fromJust)
import Data.Text (Text)
import Test.HUnit
( Test(TestCase,TestList)
, assertBool
)
import Network.URI (URI, parseURI)
import TestHelpers ( conv, test
, testLe
, testCompare
, testCompareEq
, testMaker
)
------------------------------------------------------------
-- Test case helpers
------------------------------------------------------------
testVal :: (Eq a, Show a) => String -> a -> a -> Test
testVal = testCompare "testVal:"
testEq :: (Eq a, Show a) => String -> Bool -> a -> a -> Test
testEq = testCompareEq "testIsEq:"
testEqual :: (Eq a, Show a) => String -> a -> a -> Test
testEqual = TH.testEq
testStringEq :: String -> String -> String -> Test
testStringEq = testCompare "testStringEq:"
testSameNamespace :: String -> Namespace -> Namespace -> Test
testSameNamespace = testMaker getNamespaceTuple "testSameNamespace:"
testScopedNameEq :: String -> Bool -> ScopedName -> ScopedName -> Test
testScopedNameEq = testCompareEq "testScopedNameEq:"
testSameAs :: (Ord a) => String -> String -> [a] -> [a] -> Test
testSameAs l1 l2 x y =
let z = sort x == sort y
in TestCase (assertBool ("testSameAs:" ++ l1 ++ ":" ++ l2) z)
testSameAxioms :: String -> [RDFFormula] -> [RDFFormula] -> Test
testSameAxioms = testSameAs "Axioms"
testSameRules :: String -> [RDFRule] -> [RDFRule] -> Test
testSameRules = testSameAs "Rules"
------------------------------------------------------------
-- Common values
------------------------------------------------------------
pref_rdf, pref_owl :: URI
pref_rdf = getNamespaceURI namespaceRDF
pref_owl = getNamespaceURI namespaceOWL
toURI :: String -> URI
toURI = fromJust . parseURI
toNS :: Maybe Text -> String -> Namespace
toNS p = makeNamespace p . toURI
------------------------------------------------------------
-- Define and manipulate rulesets
------------------------------------------------------------
--
-- A ruleset is essentially a collection of axioms and rules
-- associated with a namespace.
--
-- Rulesets for RDF, RDFS and basic datatyping are predefined:
-- see RDFRuleset, RDFSRuleset and RDFDRuleset.
-- Additional rulesets may be defined for specific datatypes.
--
-- A proof context is a list of rulesets,
-- which may be cited by a proof.
rn1 :: Namespace
rn1 = toNS (Just "r1") "http://id.ninebynine.org/wip/2003/rulesettest/r1"
-- Common prefix declarations for graph expressions
mkPrefix :: Namespace -> B.Builder
mkPrefix = namespaceToBuilder
prefix :: B.Builder
prefix =
mconcat
[ mkPrefix namespaceRDF
, mkPrefix namespaceRDFS
, mkPrefix (toNS (Just "ex") "http://example.org/")
]
a11, a12 :: RDFFormula
a11 = makeRDFFormula rn1 "a11" $ prefix `mappend` "ex:R1 rdf:type ex:C1 ."
a12 = makeRDFFormula rn1 "a12" $ prefix `mappend` "ex:R2 rdf:type ex:C2 ."
r11, r12 :: RDFRule
r11 = makeN3ClosureSimpleRule rn1 "r11"
( prefix `mappend` "?r1 rdf:type ex:C1 . ?r2 rdf:type ex:C2 ." )
( prefix `mappend` "?r1 ex:P1 ?r2 ." )
r12 = makeN3ClosureSimpleRule rn1 "r12"
( prefix `mappend` "?r1 rdf:type ex:C1 . ?r2 rdf:type ex:C2 ." )
( prefix `mappend` "?r2 ex:P2 ?r1 ." )
-- Basic formula and rule comparison tests
-- (tests support code added in module Proof.hs)
testFormulaSuite :: Test
testFormulaSuite =
TestList
[ testEq "testCmpAX01" True a11 a11
, testEq "testCmpAX02" False a11 a12
, testLe "testCmpAX03" True a11 a11
, testLe "testCmpAX04" True a11 a12
, testLe "testCmpAX05" False a12 a11
]
testRuleSuite :: Test
testRuleSuite =
TestList
[ testEq "testCmpRU01" True r11 r11
, testEq "testCmpRU02" False r11 r12
, testLe "testCmpRU03" True r11 r11
, testLe "testCmpRU04" True r11 r12
, testLe "testCmpRU05" False r12 r11
]
-- Test simple ruleset construction and access
a1s :: [RDFFormula]
a1s = [ a11, a12 ]
r1s :: [RDFRule]
r1s = [ r11, r12 ]
r1 :: RDFRuleset
r1 = makeRuleset rn1 a1s r1s
testRulesetSuite :: Test
testRulesetSuite =
TestList
[ testSameNamespace "testNS01" rn1 (getRulesetNamespace r1)
, testSameAxioms "testAX01" a1s (getRulesetAxioms r1)
, testSameRules "testRU01" r1s (getRulesetRules r1)
, testEqual "testGeta11" (Just a11) $
getRulesetAxiom (makeNSScopedName rn1 "a11") r1
, testEqual "testGeta11" (Just a12) $
getRulesetAxiom (makeNSScopedName rn1 "a12") r1
, testEqual "testGetr11" (Just r11) $
getRulesetRule (makeNSScopedName rn1 "r11") r1
, testEqual "testGetr12" (Just r12) $
getRulesetRule (makeNSScopedName rn1 "r12") r1
, testEqual "testGetnone" Nothing $
getRulesetRule (makeNSScopedName rn1 "none") r1
]
------------------------------------------------------------
-- Component tests for RDF proof context
------------------------------------------------------------
scopeex :: Namespace
scopeex = toNS (Just "ex") "http://id.ninebynine.org/wip/2003/RDFProofCheck#"
makeFormula :: Namespace -> LName -> B.Builder -> RDFFormula
makeFormula scope local gr =
makeRDFFormula scope local $ prefix `mappend` gr
allocateTo :: String -> String -> [RDFLabel] -> RDFVarBindingModify
allocateTo bv av = makeNodeAllocTo (Var bv) (Var av)
isXMLLit :: String -> RDFVarBindingFilter
isXMLLit = rdfVarBindingXMLLiteral . Var
queryBack :: RDFArcSet -> RDFGraph -> [[RDFVarBinding]]
queryBack qas = rdfQueryBack (toRDFGraph qas)
-- Backward chaining rdf:r2
rdfr2ant, rdfr2con :: RDFGraph
rdfr2ant = makeRDFGraphFromN3Builder "?x ?a ?l . "
rdfr2con = makeRDFGraphFromN3Builder "?x ?a ?b . ?b rdf:type rdf:XMLLiteral ."
rdfr2modv :: RDFVarBindingModify
rdfr2modv = allocateTo "b" "l" $ S.toList $ allLabels labelIsVar rdfr2ant
rdfr2modc :: Maybe RDFVarBindingModify
rdfr2modc = vbmCompose (makeVarFilterModify $ isXMLLit "l") rdfr2modv
rdfr2grc :: RDFClosure
rdfr2grc = GraphClosure
{ nameGraphRule = makeNSScopedName scopeRDF "r2"
, ruleAnt = getArcs rdfr2ant
, ruleCon = getArcs rdfr2con
, ruleModify = fromJust rdfr2modc
}
rdfr2rul :: RDFRule
rdfr2rul = Rule
{ ruleName = nameGraphRule rdfr2grc
, fwdApply = graphClosureFwdApply rdfr2grc
, bwdApply = graphClosureBwdApply rdfr2grc
, checkInference = fwdCheckInference rdfr2rul
}
con03 :: RDFGraph
con03 = formExpr $ makeFormula scopeex "con03" $
"ex:s ex:p1 _:l1 ; ex:p2a _:l2; ex:p2b _:l2 ." `mappend`
"_:l1 rdf:type rdf:XMLLiteral ." `mappend`
"_:l2 rdf:type rdf:XMLLiteral ."
v_a, v_b, v_x :: RDFLabel
v_a = Var "a"
v_b = Var "b"
v_x = Var "x"
exURI :: URI
exURI = toURI "http://example.org/"
u_s, u_p1, u_p2a, u_p2b, u_rt, u_rx :: RDFLabel
u_s = Res $ makeScopedName Nothing exURI "s"
u_p1 = Res $ makeScopedName Nothing exURI "p1"
u_p2a = Res $ makeScopedName Nothing exURI "p2a"
u_p2b = Res $ makeScopedName Nothing exURI "p2b"
u_rt = Res $ makeScopedName Nothing pref_rdf "type"
u_rx = Res $ makeScopedName Nothing pref_rdf "XMLLiteral"
b_l1, b_l2 :: RDFLabel
b_l1 = Blank "l1"
b_l2 = Blank "l2"
-- could look at S.Set (S.Set RDFVarBinding) which would make
-- comparison easier to write
--
rdfr2v1, rdfr2b1, rdfr2v2 :: [[RDFVarBinding]]
rdfr2v1 = queryBack (ruleCon rdfr2grc) con03
rdfr2b1 = [ [ makeVarBinding [ (v_b,b_l2) ]
, makeVarBinding [ (v_b,b_l1) ]
, makeVarBinding [ (v_x,u_s), (v_a,u_p2b), (v_b,b_l2) ]
, makeVarBinding [ (v_x,u_s), (v_a,u_p2a), (v_b,b_l2) ]
, makeVarBinding [ (v_x,u_s), (v_a,u_p1), (v_b,b_l1) ]
]
, [ makeVarBinding [ (v_x,b_l2), (v_a,u_rt), (v_b,u_rx) ]
, makeVarBinding [ (v_b,b_l1) ]
, makeVarBinding [ (v_x,u_s), (v_a,u_p2b), (v_b,b_l2) ]
, makeVarBinding [ (v_x,u_s), (v_a,u_p2a), (v_b,b_l2) ]
, makeVarBinding [ (v_x,u_s), (v_a,u_p1), (v_b,b_l1) ]
]
, [ makeVarBinding [ (v_b,b_l2) ]
, makeVarBinding [ (v_x,b_l1), (v_a,u_rt), (v_b,u_rx) ]
, makeVarBinding [ (v_x,u_s), (v_a,u_p2b), (v_b,b_l2) ]
, makeVarBinding [ (v_x,u_s), (v_a,u_p2a), (v_b,b_l2) ]
, makeVarBinding [ (v_x,u_s), (v_a,u_p1), (v_b,b_l1) ]
]
, [ makeVarBinding [ (v_x,b_l2), (v_a,u_rt), (v_b,u_rx) ]
, makeVarBinding [ (v_x,b_l1), (v_a,u_rt), (v_b,u_rx) ]
, makeVarBinding [ (v_x,u_s), (v_a,u_p2b), (v_b,b_l2) ]
, makeVarBinding [ (v_x,u_s), (v_a,u_p2a), (v_b,b_l2) ]
, makeVarBinding [ (v_x,u_s), (v_a,u_p1), (v_b,b_l1) ]
]
]
rdfr2v2 = rdfQueryBackModify (ruleModify rdfr2grc) rdfr2v1
-- as rdfr2v2 is empty no point in the following
-- rdfr2v3 :: [[RDFVarBinding]]
-- rdfr2v3 = map nub rdfr2v2
testRDFSuite :: Test
testRDFSuite =
TestList
[ test "testRDF01" (isJust rdfr2modc)
, testVal "testRDF02" rdfr2b1 rdfr2v1
, test "testRDF03" $ null rdfr2v2
-- , test "testRDF04" $ null rdfr2v3
, testEq "testRDF09" True [] $ bwdApply rdfr2rul con03
]
------------------------------------------------------------
-- All tests
------------------------------------------------------------
allTests :: [TF.Test]
allTests =
[ conv "Formula" testFormulaSuite
, conv "Rule" testRuleSuite
, conv "Ruleset" testRulesetSuite
, conv "RDF" testRDFSuite
]
main :: IO ()
main = TF.defaultMain allTests
--------------------------------------------------------------------------------
--
-- Copyright (c) 2003, Graham Klyne, 2009 Vasili I Galchin,
-- 2011, 2012, 2013 Douglas Burke
-- All rights reserved.
--
-- This file is part of Swish.
--
-- Swish is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2 of the License, or
-- (at your option) any later version.
--
-- Swish is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with Swish; if not, write to:
-- The Free Software Foundation, Inc.,
-- 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
--
--------------------------------------------------------------------------------
| DougBurke/swish | tests/RDFRulesetTest.hs | lgpl-2.1 | 12,733 | 0 | 13 | 2,600 | 2,869 | 1,674 | 1,195 | 221 | 1 |
import Test.QuickCheck
examples = [('@', "[email protected]"), ("/", "/usr/include")]
| seckcoder/lang-learn | haskell/quickcheck.hs | unlicense | 94 | 0 | 6 | 14 | 29 | 18 | 11 | 2 | 1 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE EmptyDataDecls #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE FlexibleInstances #-}
module Generics.MultiRec.GHC.GHCTHUseAlt where
import Generics.MultiRec.Base
-- import Generics.MultiRec.TH.Alt
import Generics.MultiRec.TH
-- GHC stuff
import Bag
import BasicTypes
import CoreSyn
import CostCentre
import DynFlags
import FastString
import GHC
import HsExpr
import HsPat
import HsSyn
import Name
import Outputable
import TcEvidence
import TypeRep
import UniqFM
import Var
import SrcLoc
-- * Instantiating the library for AST using TH
-- ** Index type
data AST :: * -> * -> * where
-- ABExport :: AST a (ABExport Name)
{-
ArithSeqInfoIt :: AST a (ArithSeqInfo Name)
BoxityIt :: AST a (Boxity)
FixityDirectionIt :: AST a (FixityDirection)
FixityIt :: AST a (HsSyn.Fixity)
FractionalLitIt :: AST a (FractionalLit)
GRHSsIt :: AST a (GRHSs Name)
GRHSIt :: AST a (GRHS Name)
HsArrAppTypeIt :: AST a (HsArrAppType)
HsBindLRIt :: AST a (HsBindLR Name Name)
HsBracketIt :: AST a (HsBracket Name)
HsGroupIt :: AST a (HsGroup Name)
HsIPBindsIt :: AST a (HsIPBinds Name)
HsIPNameIt :: AST a (HsIPName)
-}
-- HsLit :: AST a (HsSyn.HsLit)
{-
HsLocalBindsIt :: AST a (HsLocalBinds Name)
HsMatchContextIt :: AST a (HsMatchContext Name)
HsOverLitIt :: AST a (HsOverLit Name)
HsQuasiQuoteIt :: AST a (HsQuasiQuote Name)
HsRecordBindsIt :: AST a (HsRecordBinds Name)
HsSpliceIt :: AST a (HsSplice Name)
HsStmtContextIt :: AST a (HsStmtContext Name)
HsValBindsLRIt :: AST a (HsValBindsLR Name Name)
IEIt :: AST a (IE Name)
ImportDeclIt :: AST a (ImportDecl Name)
LGRHSIt :: AST a (LGRHS Name)
LHsBindLRIt :: AST a (LHsBindLR Name Name)
LHsBindsIt :: AST a (LHsBinds Name)
LHsCmdTopIt :: AST a (LHsCmdTop Name)
LHsDeclIt :: AST a (LHsDecl Name)
LHsExprIt :: AST a (LHsExpr Name)
LHsTypeIt :: AST a (LHsType Name)
-}
LIEIt :: AST a (LIE Name)
{-
LIPBindIt :: AST a (LIPBind Name)
LImportDeclIt :: AST a (LImportDecl Name)
LInstDeclIt :: AST a ( LInstDecl Name)
LMatchIt :: AST a (LMatch Name)
LPatIt :: AST a (LPat Name)
LSigIt :: AST a (LSig Name)
LStmtLRIt :: AST a (LStmtLR Name Name)
LFixitySigIt :: AST a (LFixitySig Name)
LAnnDeclIt :: AST a (LAnnDecl Name)
LDefaultDeclIt :: AST a (LDefaultDecl Name)
LDerivDeclIt :: AST a (LDerivDecl Name)
LForeignDeclIt :: AST a (LForeignDecl Name)
LRuleDeclIt :: AST a (LRuleDecl Name)
LTyClDeclIt :: AST a (LTyClDecl Name)
LVectDeclIt :: AST a (LVectDecl Name)
LWarnDeclIt :: AST a (LWarnDecl Name)
LDocDecl :: AST a LDocDecl
LocatedIt :: AST a (Located Name)
MatchGroupIt :: AST a (MatchGroup Name)
MatchIt :: AST a (Match Name)
NameIt :: AST a (Name)
OverLitValIt :: AST a (OverLitVal)
PatIt :: AST a (Pat Name)
PostTcExprIt :: AST a PostTcExpr
-- PostTcTypeIt :: AST PostTcType
RenamedSourceIt :: AST a RenamedSource
StmtLRIt :: AST a (StmtLR Name Name)
SyntaxExprIt :: AST a (SyntaxExpr Name)
TcEvBindsIt :: AST a (TcEvBinds)
TickishIt :: AST a (Tickish Name)
-- Maybe elements
MaybeBoolLIENamesIt :: AST a (Maybe ((Bool, [LIE Name])))
-- List elements
ABExportListIt :: AST a [ABExport Name]
LGRHSListIt :: AST a [LGRHS Name]
LHsBindLRListIt :: AST a [LHsBindLR Name Name]
LHsCmdTopListIt :: AST a [LHsCmdTop Name]
LHsDeclListIt :: AST a [LHsDecl Name]
LHsExprListIt :: AST a [LHsExpr Name]
LIEListIt :: AST a [LIE Name]
LIPBindListIt :: AST a [LIPBind Name]
LImportDeclListIt :: AST a [LImportDecl Name]
LInstDeclListIt :: AST a [LInstDecl Name]
LMatchListIt :: AST a [LMatch Name]
LPatListIt :: AST a [LPat Name]
LSigListIt :: AST a [LSig Name]
LStmtListIt :: AST a [LStmt Name]
LTyClDeclListIt :: AST a [LTyClDecl Name]
-- RecBindsListIt :: AST [HsRecField Name (GenLocated SrcSpan (HsExpr Name))]
RecBindsListIt :: AST a [HsRecField Name (LHsExpr Name)]
ValBindsOutListIt :: AST a [(RecFlag, LHsBinds Name)]
LTyClDeclLitListIt :: AST a [[LTyClDecl Name]]
LDerivDeclListIt :: AST a [LDerivDecl Name]
LFixitySigLitsIt :: AST a [LFixitySig Name]
LDefaultDeclListIt :: AST a [LDefaultDecl Name]
LForeignDeclListIt :: AST a [LForeignDecl Name]
LWarnDeclListIt :: AST a [LWarnDecl Name]
LAnnDeclListIt :: AST a [LAnnDecl Name]
LRuleDeclListIt :: AST a [LRuleDecl Name]
LVectDeclListIt :: AST a [LVectDecl Name]
LDocDeclListIt :: AST a [LDocDecl]
-- Tuple elements
TupRecFlagLHsBindsIt :: AST a (RecFlag, LHsBinds Name)
-}
$(deriveAll ''AST)
{-
$(deriveEverything
(DerivOptions {
familyTypes =
[ ( [t| ABExport Name |], "ABExportIt" )
, ( [t| ArithSeqInfo Name |], "ArithSeqInfoIt" )
, ( [t| Boxity |], "BoxityIt" )
, ( [t| FixityDirection |], "FixityDirectionIt" )
, ( [t| FractionalLit |], "FractionalLitIt" )
, ( [t| GRHS Name |], "GRHSIt" )
, ( [t| GRHSs Name |], "GRHSsIt" )
, ( [t| HsArrAppType |], "HsArrAppTypeIt" )
, ( [t| HsBindLR Name Name |], "HsBindLRIt" )
, ( [t| HsBracket Name |], "HsBracketIt" )
, ( [t| HsGroup Name |], "HsGroupIt" )
, ( [t| HsIPBinds Name |], "HsIPBindsIt" )
, ( [t| HsIPName |], "HsIPNameIt" )
, ( [t| HsLit |], "HsLitIt" )
, ( [t| HsLocalBinds Name |], "HsLocalBindsIt" )
, ( [t| HsMatchContext Name |], "HsMatchContextIt" )
, ( [t| HsOverLit Name |], "HsOverLitIt" )
, ( [t| HsQuasiQuote Name |], "HsQuasiQuoteIt" )
, ( [t| HsRecordBinds Name |], "HsRecordBindsIt" )
, ( [t| HsSplice Name |], "HsSpliceIt" )
, ( [t| HsStmtContext Name |], "HsStmtContextIt" )
, ( [t| HsSyn.Fixity |], "FixityIt" )
, ( [t| HsValBindsLR Name Name |], "HsValBindsLRIt" )
, ( [t| IE Name |], "IEIt" )
, ( [t| ImportDecl Name |], "ImportDeclIt" )
, ( [t| LAnnDecl Name |], "LAnnDeclIt" )
, ( [t| LDefaultDecl Name |], "LDefaultDeclIt" )
, ( [t| LDerivDecl Name |], "LDerivDeclIt" )
, ( [t| LDocDecl |], "LDocDecl" )
, ( [t| LFixitySig Name |], "LFixitySigIt" )
, ( [t| LForeignDecl Name |], "LForeignDeclIt" )
, ( [t| LGRHS Name |], "LGRHSIt" )
, ( [t| LHsBindLR Name Name |], "LHsBindLRIt" )
, ( [t| LHsBinds Name |], "LHsBindsIt" )
, ( [t| LHsCmdTop Name |], "LHsCmdTopIt" )
, ( [t| LHsDecl Name |], "LHsDeclIt" )
, ( [t| LHsExpr Name |], "LHsExprIt" )
, ( [t| LHsType Name |], "LHsTypeIt" )
, ( [t| LIE Name |], "LIEIt" )
, ( [t| LIPBind Name |], "LIPBindIt" )
, ( [t| LImportDecl Name |], "LImportDeclIt" )
, ( [t| LInstDecl Name |], "LInstDeclIt" )
, ( [t| LMatch Name |], "LMatchIt" )
, ( [t| LPat Name |], "LPatIt" )
, ( [t| LRuleDecl Name |], "LRuleDeclIt" )
, ( [t| LSig Name |], "LSigIt" )
, ( [t| LStmtLR Name Name |], "LStmtLRIt" )
, ( [t| LTyClDecl Name |], "LTyClDeclIt" )
, ( [t| LVectDecl Name |], "LVectDeclIt" )
, ( [t| LWarnDecl Name |], "LWarnDeclIt" )
, ( [t| Located Name |], "LocatedIt" )
, ( [t| Match Name |], "MatchIt" )
, ( [t| MatchGroup Name |], "MatchGroupIt" )
, ( [t| OverLitVal |], "OverLitValIt" )
, ( [t| Pat Name |], "PatIt" )
, ( [t| PostTcExpr |], "PostTcExprIt" )
, ( [t| RenamedSource |], "RenamedSourceIt" )
, ( [t| StmtLR Name Name |], "StmtLRIt" )
, ( [t| SyntaxExpr Name |], "SyntaxExprIt" )
, ( [t| TcEvBinds |], "TcEvBindsIt" )
, ( [t| Tickish Name |], "TickishIt" )
-- List elements
, ( [t| [(RecFlag, LHsBinds Name)] |], "ValBindsOutListIt" )
, ( [t| [ABExport Name] |], "ABExportListIt" )
, ( [t| [LGRHS Name] |], "LGRHSListIt" )
, ( [t| [LHsDecl Name] |], "LHsDeclListIt" )
, ( [t| [LHsExpr Name] |], "LHsExprListIt" )
, ( [t| [LIPBind Name] |], "LIPBindListIt" )
, ( [t| [LInstDecl Name] |], "LInstDeclListIt" )
, ( [t| [LSig Name] |], "LSigListIt" )
, ( [t| [LStmt Name] |], "LStmtListIt" )
, ( [t| [LTyClDecl Name] |], "LTyClDeclListIt" )
, ( [t| [LPat Name] |], "LPatListIt" )
-- , ( [t| [HsRecField Name (GenLocated SrcSpan (HsExpr Name))] |], "RecBindsListIt" )
, ( [t| [HsRecField Name (LHsExpr Name)] |], "RecBindsListIt" )
, ( [t| [LMatch Name] |], "LMatchListIt" )
, ( [t| [LHsCmdTop Name] |], "LHsCmdTopListIt" )
, ( [t| [LHsBindLR Name Name] |], "LHsBindLRListIt" )
, ( [t| [LImportDecl Name] |], "LImportDeclListIt" )
, ( [t| [LIE Name] |], "LIEListIt" )
, ( [t| [[LTyClDecl Name]] |], "LTyClDeclLitListIt" )
, ( [t| [LDerivDecl Name] |], "LDerivDeclListIt" )
, ( [t| [LFixitySig Name] |], "LFixitySigLitsIt" )
, ( [t| [LDefaultDecl Name] |], "LDefaultDeclListIt" )
, ( [t| [LForeignDecl Name] |], "LForeignDeclListIt" )
, ( [t| [LWarnDecl Name] |], "LWarnDeclListIt" )
, ( [t| [LAnnDecl Name] |], "LAnnDeclListIt" )
, ( [t| [LRuleDecl Name] |], "LRuleDeclListIt" )
, ( [t| [LVectDecl Name] |], "LVectDeclListIt" )
, ( [t| [LDocDecl] |], "LDocDeclListIt" )
-- Maybe elements
, ( [t| Maybe ((Bool, [LIE Name])) |], "MaybeBoolLIENamesIt" )
-- Tuple elements
, ( [t| (RecFlag, LHsBinds Name) |], "TupRecFlagLHsBindsIt" )
],
indexGadtName = "AST",
constructorNameModifier = defaultConstructorNameModifier,
patternFunctorName = "ThePF",
verbose = True,
-- verbose = False,
sumMode = Balanced
}
))
type instance PF (AST a) = ThePF
-}
-- ---------------------------------------------------------------------
| alanz/ghc-multirec | src/Generics/MultiRec/GHC/GHCTHUseAlt2.hs | unlicense | 11,204 | 0 | 8 | 3,752 | 134 | 90 | 44 | 32 | 0 |
module GreetIfCool1 where
greetIfCool :: String -> IO ()
greetIfCool coolness =
if cool then putStrLn "Cool" else putStrLn "not cool"
where cool = coolness == "downright frosty yo"
| thewoolleyman/haskellbook | 04/09/maor/greetIfCool1.hs | unlicense | 192 | 0 | 7 | 40 | 51 | 27 | 24 | 5 | 2 |
{-# LANGUAGE CPP #-}
-- | A representation of Haskell source code.
--
-- Unlike haskell-src-exts, our goal is not to reconstruct detailed semantics,
-- but to preserve original line numbers (if applicable).
module Data.HaskellSource where
import Prelude hiding (fail)
#if MIN_VERSION_base(4,12,0)
import Control.Monad.Fail (fail)
#else
import Prelude (fail)
#endif
import Control.Monad.Trans.Class
import Data.ByteString.Char8 as B
import System.Directory
import System.Exit
import System.Process
import Text.Printf
import Control.Monad.Trans.Uncertain
-- | The ByteStrings are original lines, which we never delete in order to
-- infer line numbers, while the Strings were inserted into the original.
type HaskellSource = [Either B.ByteString String]
parseSource :: B.ByteString -> HaskellSource
parseSource = fmap Left . B.lines
-- | A string representation containing line pragmas so that compiler errors
-- are reported about the original file instead of the modified one.
--
-- >>> let (x:xs) = parseSource $ B.pack "import Data.ByteString\nmain = print 42\n"
-- >>> B.putStr $ showSource "orig.hs" (x:xs)
-- import Data.ByteString
-- main = print 42
--
-- >>> B.putStr $ showSource "orig.hs" (x:Right "import Prelude":xs)
-- import Data.ByteString
-- import Prelude
-- {-# LINE 2 "orig.hs" #-}
-- main = print 42
showSource :: FilePath -- ^ the original's filename,
-- used for fixing up line numbers
-> HaskellSource -> B.ByteString
showSource orig = B.unlines . go True 1
where
go :: Bool -- ^ are line numbers already ok?
-> Int -- ^ the original number of the next original line
-> HaskellSource
-> [B.ByteString]
go _ _ [] = []
go True i (Left x:xs) = x
: go True (i + 1) xs
go False i (Left x:xs) = B.pack (line_marker i)
: x
: go True (i + 1) xs
go _ i (Right x:xs) = B.pack x
: go False i xs
line_marker :: Int -> String
line_marker i = printf "{-# LINE %s %s #-}" (show i) (show orig)
readSource :: FilePath -> IO HaskellSource
readSource = fmap parseSource . B.readFile
writeSource :: FilePath -- ^ the original's filename,
-- used for fixing up line numbers
-> FilePath
-> HaskellSource
-> IO ()
writeSource orig f = B.writeFile f . showSource orig
compileSource :: FilePath -- ^ the original's filename,
-- used for fixing up line numbers
-> FilePath -- ^ new filename, because ghc compiles from disk.
-- the compiled output will be in the same folder.
-> HaskellSource
-> UncertainT IO ()
compileSource = compileSourceWithArgs []
compileSourceWithArgs :: [String] -- ^ extra ghc args
-> FilePath -- ^ the original's filename,
-- used for fixing up line numbers
-> FilePath -- ^ new filename, because ghc compiles from disk.
-- the compiled output will be in the same folder.
-> HaskellSource
-> UncertainT IO ()
compileSourceWithArgs args orig f s = do
lift $ writeSource orig f s
compileFileWithArgs args f
compileFile :: FilePath -> UncertainT IO ()
compileFile = compileFileWithArgs []
compileFileWithArgs :: [String] -> FilePath -> UncertainT IO ()
compileFileWithArgs args f = do
absFilePath <- lift $ canonicalizePath f
let args' = absFilePath : "-v0" : args
(exitCode, out, err) <- lift $ readProcessWithExitCode "ghc" args' ""
case (exitCode, out ++ err) of
(ExitSuccess, []) -> return ()
(ExitSuccess, _msg) -> return () -- TODO: output warnings via 'multilineWarn msg'?
(_ , []) -> fail $ printf "could not compile %s" (show f)
(_ , msg) -> multilineFail msg
| gelisam/hawk | src/Data/HaskellSource.hs | apache-2.0 | 4,027 | 0 | 13 | 1,196 | 776 | 419 | 357 | 63 | 4 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="ru-RU">
<title>Front-End Scanner | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | secdec/zap-extensions | addOns/frontendscanner/src/main/javahelp/org/zaproxy/zap/extension/frontendscanner/resources/help_ru_RU/helpset_ru_RU.hs | apache-2.0 | 978 | 78 | 67 | 159 | 417 | 211 | 206 | -1 | -1 |
{-# LANGUAGE DeriveDataTypeable, ExistentialQuantification, GeneralizedNewtypeDeriving #-}
{-# LANGUAGE BangPatterns #-}
-- Internal file. Lots of types. Lots of coupling.
module Database.VCache.Types
( Address, isVRefAddr, isPVarAddr
, VRef(..), Cache(..), CacheMode(..)
, VREph(..), VREphMap, addVREph, takeVREph
, PVar(..), RDV(..)
, PVEph(..), PVEphMap, addPVEph
, VCache(..), VSpace(..)
, VPut(..), VPutS(..), VPutR(..)
, VGet(..), VGetS(..), VGetR(..)
, VCacheable(..)
, Allocator(..), AllocFrame(..)
, GC(..), GCFrame(..)
, Memory(..)
, VTx(..), VTxState(..), TxW(..), VTxBatch(..)
, Writes(..), WriteLog, WriteCt(..)
, CacheSizeEst(..)
-- misc. utilities
, allocFrameSearch
, recentGC
, withRdOnlyTxn
, withStoreableVal
, withByteStringVal
, getVTxSpace, markForWrite, liftSTM
, mkVRefCache, cacheModeBits, touchCache
) where
import Data.Bits
import Data.Word
import Data.Function (on)
import Data.Typeable
import Data.IORef
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.ByteString (ByteString)
import qualified Data.ByteString.Internal as BSI
import Control.Monad
import Control.Monad.Trans.Class (lift)
import Control.Monad.STM (STM)
import Control.Applicative
import Control.Concurrent.MVar
import Control.Concurrent.STM.TVar
import Control.Monad.Trans.State.Strict
import Control.Exception (bracket)
import System.Mem.Weak (Weak)
import System.FileLock (FileLock)
import Database.LMDB.Raw
import Foreign.Ptr
import Foreign.ForeignPtr (withForeignPtr)
import Foreign.Marshal
import Foreign.Storable
import Database.VCache.RWLock
-- | An address in the VCache address space
type Address = Word64 -- with '0' as special case
-- | VRefs and PVars are divided among odds and evens.
isVRefAddr, isPVarAddr :: Address -> Bool
isVRefAddr addr = 0 == (1 .&. addr)
isPVarAddr = not . isVRefAddr
{-# INLINE isVRefAddr #-}
{-# INLINE isPVarAddr #-}
-- | A VRef is an opaque reference to an immutable value backed by a
-- file, specifically via LMDB. The primary motivation for VRefs is
-- to support memory-cached values, i.e. very large data structures
-- that should not be stored in all at once in RAM.
--
-- The API involving VRefs is conceptually pure.
--
-- > vref :: (VCacheable a) => VSpace -> a -> VRef a
-- > deref :: VRef a -> a
--
-- Under the hood, each VRef has a 64-bit address and a local cache.
-- When dereferenced, the cache is checked or the value is read from
-- the database then cached. Variants of vref and deref control cache
-- behavior.
--
-- VCacheable values may themselves contain VRefs and PVars, storing
-- just the address. Very large structured data is readily modeled
-- by using VRefs to load just the pieces you need. However, there is
-- one major constraint:
--
-- VRefs may only represent acyclic structures.
--
-- If developers want cyclic structure, they need a PVar in the chain.
-- Alternatively, cycles may be modeled indirectly using explicit IDs.
--
-- Besides memory caching, VRefs also utilize structure sharing: all
-- VRefs sharing the same serialized representation will share the
-- same address. Structure sharing enables VRefs to be compared for
-- equality without violating conceptual purity. It also simplifies
-- reasoning about idempotence, storage costs, memoization, etc..
--
data VRef a = VRef
{ vref_addr :: {-# UNPACK #-} !Address -- ^ address within the cache
, vref_cache :: {-# UNPACK #-} !(IORef (Cache a)) -- ^ cached value & weak refs
, vref_space :: !VSpace -- ^ virtual address space for VRef
, vref_type :: !TypeRep -- ^ type of value held by VRef
, vref_parse :: !(VGet a) -- ^ parser for this VRef
} deriving (Typeable)
instance Eq (VRef a) where (==) = (==) `on` vref_cache
instance Show (VRef a) where
showsPrec _ v = showString "VRef#" . shows (vref_addr v)
. showString "::" . shows (vref_type v)
-- For every VRef we have in memory, we need an ephemeron in a table.
-- This ephemeron table supports structure sharing, caching, and GC.
-- I model this ephemeron by use of `mkWeakMVar`.
data VREph = forall a . VREph
{ vreph_addr :: {-# UNPACK #-} !Address
, vreph_type :: !TypeRep
, vreph_cache :: {-# UNPACK #-} !(Weak (IORef (Cache a)))
}
type VREphMap = Map Address (Map TypeRep VREph)
-- Address is at the top layer of the map mostly to simplify GC.
addVREph :: VREph -> VREphMap -> VREphMap
addVREph e = Map.alter (Just . maybe i0 ins) (vreph_addr e) where
ty = vreph_type e
i0 = Map.singleton ty e
ins = Map.insert ty e
{-# INLINABLE addVREph #-}
takeVREph :: Address -> TypeRep -> VREphMap -> Maybe (VREph, VREphMap)
takeVREph !addr !ty !em =
case Map.lookup addr em of
Nothing -> Nothing
Just tym -> case Map.lookup ty tym of
Nothing -> Nothing
Just e ->
let em' = if 1 == Map.size tym
then Map.delete addr em
else Map.insert addr (Map.delete ty tym) em
in
Just (e, em')
{-# INLINABLE takeVREph #-}
-- TODO: I may need a way to "reserve" VRef addresses for destruction,
-- i.e. such that I can guard against
-- Every VRef contains its own cache. Thus, there is no extra lookup
-- overhead to test the cache. The cache includes an integer as a
-- bitfield to describe mode.
data Cache a
= NotCached
| Cached a {-# UNPACK #-} !Word16
--
-- cache bitfield for mode:
-- bit 0..4: weight, log scale
-- log scale: 2^(N+6), max N=31
-- bits 5..6: cache mode 0..3
-- bit 7: toggle; set 1 by manager, 0 by derefc
--
-- Weight is used to guide aggressiveness of the cache manager.
-- Currently, it just records the size of the encoded value, and
-- does not account for expansion of values after parse.
-- | Cache modes are used when deciding, heuristically, whether to
-- clear a value from cache. These modes don't have precise meaning,
-- but there is a general intention: higher numbered modes indicate
-- that VCache should hold onto a value for longer or with greater
-- priority. In the current implementation, CacheMode is used as a
-- pool of 'hitpoints' in a gaming metaphor: if an entry would be
-- removed, but its mode is greater than zero, the mode is reduced
-- instead.
--
-- The default for vref and deref is CacheMode1. Use of vrefc or
-- derefc may specify other modes. Cache mode is monotonic: if
-- the same VRef is deref'd with two different modes, the higher
-- mode will be favored.
--
-- Note: Regardless of mode, a VRef that is fully GC'd from the
-- Haskell layer will ensure any cached content is also GC'd.
--
data CacheMode
= CacheMode0
| CacheMode1
| CacheMode2
| CacheMode3
deriving (Eq, Ord, Show)
cacheModeBits :: CacheMode -> Word16
cacheModeBits CacheMode0 = 0
cacheModeBits CacheMode1 = 1 `shiftL` 5
cacheModeBits CacheMode2 = 2 `shiftL` 5
cacheModeBits CacheMode3 = 3 `shiftL` 5
-- | clear bit 7; adjust cache mode monotonically.
touchCache :: CacheMode -> Word16 -> Word16
touchCache !cm !w =
let cb' = (w .&. 0x60) `max` cacheModeBits cm in
(w .&. 0xff1f) .|. cb'
{-# INLINE touchCache #-}
mkVRefCache :: a -> Int -> CacheMode -> Cache a
mkVRefCache val !w !cm = Cached val cw where
cw = m .|. cs 0 64
cs r k = if (k > w) || (r == 0x1f) then r else cs (r+1) (k*2)
m = cacheModeBits cm
-- | A PVar is a mutable variable backed by VCache. PVars can be read
-- or updated transactionally (see VTx), and may store by reference
-- as part of domain data (see VCacheable).
--
-- A PVar is not cached. If you want memory cached contents, you'll
-- need a PVar that contains one or more VRefs. However, the first
-- read from a PVar is lazy, so merely referencing a PVar does not
-- require loading its contents into memory.
--
-- Due to how updates are batched, high frequency or bursty updates
-- on a PVar should perform acceptably. Not every intermediate value
-- is written to disk.
--
-- Anonymous PVars will be garbage collected if not in use. Persistence
-- requires ultimately tying contents to named roots (cf. loadRootPVar).
-- Garbage collection is based on reference counting, so developers must
-- be cautious when working with cyclic data, i.e. break cycles before
-- disconnecting them from root.
--
-- Note: PVars must never contain undefined or error values, nor any
-- value that cannot be serialized by a VCacheable instance.
--
data PVar a = PVar
{ pvar_addr :: {-# UNPACK #-} !Address
, pvar_data :: {-# UNPACK #-} !(TVar (RDV a))
, pvar_space :: !VSpace -- ^ virtual address space for PVar
, pvar_type :: !TypeRep
, pvar_write :: !(Writer a)
} deriving (Typeable)
type Writer a = (a -> VPut ())
instance Eq (PVar a) where (==) = (==) `on` pvar_data
instance Show (PVar a) where
showsPrec _ pv = showString "PVar#" . shows (pvar_addr pv)
. showString "::" . shows (pvar_type pv)
-- ephemeron table for PVars.
data PVEph = forall a . PVEph
{ pveph_addr :: {-# UNPACK #-} !Address
, pveph_type :: !TypeRep
, pveph_data :: {-# UNPACK #-} !(Weak (TVar (RDV a)))
}
type PVEphMap = Map Address PVEph
addPVEph :: PVEph -> PVEphMap -> PVEphMap
addPVEph pve = Map.insert (pveph_addr pve) pve
{-# INLINE addPVEph #-}
-- I need some way to force an evaluation when a PVar is first
-- read, i.e. in order to load the initial value, without forcing
-- on every read. For the moment, I'm using a simple type wrapper.
newtype RDV a = RDV a
-- | VCache supports a filesystem-backed address space plus a set of
-- persistent, named root variables that can be loaded from one run
-- of the application to another. VCache supports a simple filesystem
-- like model to resist namespace collisions between named roots.
--
-- > openVCache :: Int -> FilePath -> IO VCache
-- > vcacheSubdir :: ByteString -> VCache -> VCache
-- > loadRootPVar :: (VCacheable a) => VCache -> ByteString -> a -> PVar a
--
-- The normal use of VCache is to open VCache in the main function,
-- use vcacheSubdir for each major framework, plugin, or independent
-- component that might need persistent storage, then load at most a
-- few root PVars per component. Most domain modeling should be at
-- the data layer, i.e. the type held by the PVar.
--
-- See VSpace, VRef, and PVar for more information.
data VCache = VCache
{ vcache_space :: !VSpace -- ^ virtual address space for VCache
, vcache_path :: !ByteString
} deriving (Eq)
-- | VSpace represents the virtual address space used by VCache. Except
-- for loadRootPVar, most operations use VSpace rather than the VCache.
-- VSpace is accessed by vcache_space, vref_space, or pvar_space.
--
-- Addresses from this space are allocated incrementally, odds to PVars
-- and evens to VRefs, independent of object size. The space is elastic:
-- it isn't a problem to change the size of PVars (even drastically) from
-- one update to another.
--
-- In theory, VSpace could run out of 64-bit addresses. In practice, this
-- isn't a real concern - a quarter million years at a sustained million
-- allocations per second.
--
data VSpace = VSpace
{ vcache_lockfile :: !FileLock -- block concurrent use of VCache file
-- LMDB contents.
, vcache_db_env :: !MDB_env
, vcache_db_memory :: {-# UNPACK #-} !MDB_dbi' -- address → value
, vcache_db_vroots :: {-# UNPACK #-} !MDB_dbi' -- path → address
, vcache_db_caddrs :: {-# UNPACK #-} !MDB_dbi' -- hashval → [address]
, vcache_db_refcts :: {-# UNPACK #-} !MDB_dbi' -- address → Word64
, vcache_db_refct0 :: {-# UNPACK #-} !MDB_dbi' -- address → ()
, vcache_memory :: !(MVar Memory) -- Haskell-layer memory management
, vcache_signal :: !(MVar ()) -- signal writer that work is available
, vcache_writes :: !(TVar Writes) -- STM-layer PVar writes
, vcache_rwlock :: !RWLock -- replace gap left by MDB_NOLOCK
, vcache_alloc_init :: {-# UNPACK #-} !Address -- (for stats) initial allocator on open
, vcache_gc_start :: !(IORef (Maybe Address)) -- supports incremental GC
, vcache_gc_count :: !(IORef Int) -- (stat) number of addresses GC'd
, vcache_climit :: !(IORef Int) -- targeted max cache size in bytes
, vcache_csize :: !(IORef CacheSizeEst) -- estimated cache sizes
, vcache_cvrefs :: !(MVar VREphMap) -- track just the cached VRefs
-- share persistent variables for safe STM
-- Further, I need...
-- log or queue of 'new' vrefs and pvars,
-- including those still being written
-- a thread performing writes and incremental GC
-- a channel to talk to that thread
-- queue of MVars waiting on synchronization/flush.
} deriving (Typeable)
instance Eq VSpace where (==) = (==) `on` vcache_signal
-- needed: a transactional queue of updates to PVars
-- | The Allocator both tracks the 'bump-pointer' address for the
-- next allocation, plus in-memory logs for recent and near future
-- allocations.
--
-- The log has three frames, based on the following observations:
--
-- * frames are rotated when the writer lock is held
-- * when the writer lock is held, readers exist for two prior frames
-- * readers from two frames earlier use log to find allocations from:
-- * the previous write frame
-- * the current write frame
-- * the next write frame (allocated during write)
--
-- Each write frame includes content for both the primary (db_memory)
-- and secondary (db_caddrs or db_vroots) indices.
--
-- Normal Data.Map is favored because I want the keys in sorted order
-- when writing into the LMDB layer anyway.
--
data Allocator = Allocator
{ alloc_new_addr :: {-# UNPACK #-} !Address -- next address
, alloc_frm_next :: !AllocFrame -- frame N+1 (next step)
, alloc_frm_curr :: !AllocFrame -- frame N (curr step)
, alloc_frm_prev :: !AllocFrame -- frame N-1 (prev step)
}
-- a single allocation frame corresponds to new content written
-- while the writer is busy in the background.
data AllocFrame = AllocFrame
{ alloc_list :: !(Map Address ByteString) -- recent allocations
, alloc_seek :: !(Map Int [Address]) -- vref content addressing
, alloc_root :: ![(Address, ByteString)] -- root PVars with path names
, alloc_init :: {-# UNPACK #-} !Address -- next address at frame start.
}
allocFrameSearch :: (AllocFrame -> Maybe a) -> Allocator -> Maybe a
allocFrameSearch f a = f n <|> f c <|> f p where
n = alloc_frm_next a
c = alloc_frm_curr a
p = alloc_frm_prev a
-- | In addition to recent allocations, we track garbage collection.
-- The goal here is to prevent revival of VRefs after we decide to
-- delete them. So, when we try to allocate a VRef, we'll check to
-- see whether its address has been targeted for deletion.
--
-- To keep this simple, GC is performed by the writer thread. Other
-- threads must worry about reading outdated reference counts. This
-- also means we only need the two frames: a reader of frame N-2
-- only needs to prevent revival of VRefs GC'd at N-1 or N.
--
-- ASIDE: a nursery GC pass eliminates transient VRefs that needn't
-- be recorded in the database, e.g. for a short-lived trie node. In
-- this case, we may simply remove the reference from the allocator.
--
data GC = GC
{ gc_frm_curr :: !GCFrame
, gc_frm_prev :: !GCFrame
}
data GCFrame = forall a . GCFrame !(Map Address a)
-- The concrete map type depends on the writer
recentGC :: GC -> Address -> Bool
recentGC gc addr = ff c || ff p where
ff (GCFrame m) = Map.member addr m
c = gc_frm_curr gc
p = gc_frm_prev gc
{-# INLINE recentGC #-}
-- | The Memory datatype tracks allocations, GC, and ephemeron
-- tables for tracking both PVars and VRefs in Haskell memory.
-- These are combined into one type mostly because typical
-- operations on them are atomic... and STM isn't permitted
-- because vref constructors are used with unsafePerformIO.
data Memory = Memory
{ mem_vrefs :: !VREphMap -- ^ In-memory VRefs
, mem_pvars :: !PVEphMap -- ^ In-memory PVars
, mem_gc :: !GC -- ^ recently GC'd addresses (two frames)
, mem_alloc :: !Allocator -- ^ recent or pending allocations (three frames)
}
-- simple read-only operations
-- LMDB transaction is aborted when finished, so cannot open DBIs
withRdOnlyTxn :: VSpace -> (MDB_txn -> IO a) -> IO a
withRdOnlyTxn vc = withLock . bracket newTX endTX where
withLock = withRdOnlyLock (vcache_rwlock vc)
newTX = mdb_txn_begin (vcache_db_env vc) Nothing True
endTX = mdb_txn_abort
{-# INLINE withRdOnlyTxn #-}
withStoreableVal :: Storable a => a -> (MDB_val -> IO b) -> IO b
withStoreableVal val action = with val $ \p -> action $ MDB_val
{ mv_size = fromIntegral $ sizeOf val
, mv_data = p `plusPtr` alignment val
}
{-# INLINE withStoreableVal #-}
withByteStringVal :: ByteString -> (MDB_val -> IO a) -> IO a
withByteStringVal (BSI.PS fp off len) action = withForeignPtr fp $ \ p ->
action $ MDB_val { mv_size = fromIntegral len, mv_data = p `plusPtr` off }
{-# INLINE withByteStringVal #-}
-- | The VTx transactions allow developers to atomically manipulate
-- PVars and STM resources (TVars, TArrays, etc..). VTx is a thin
-- layer above STM, additionally tracking which PVars are written so
-- it can push the batch to a background writer thread upon commit.
--
-- VTx supports full ACID semantics (atomic, consistent, isolated,
-- durable), but durability is optional (see markDurable).
--
newtype VTx a = VTx { _vtx :: StateT VTxState STM a }
deriving (Monad, Functor, Applicative, Alternative, MonadPlus)
-- | In addition to the STM transaction, I need to track whether
-- the transaction is durable (such that developers may choose
-- based on internal domain-model concerns) and which variables
-- have been read or written. All PVars involved must be part of
-- the same VSpace.
data VTxState = VTxState
{ vtx_space :: !VSpace
, vtx_writes :: !WriteLog
, vtx_durable :: !Bool
}
-- | run an arbitrary STM operation as part of a VTx transaction.
liftSTM :: STM a -> VTx a
liftSTM = VTx . lift
{-# INLINE liftSTM #-}
getVTxSpace :: VTx VSpace
getVTxSpace = VTx (gets vtx_space)
{-# INLINE getVTxSpace #-}
-- | add a PVar write to the VTxState. This should be combined with
-- a function that modifies the underlying TVar.
markForWrite :: PVar a -> a -> VTx ()
markForWrite pv a = VTx $ modify $ \ vtx ->
let txw = TxW (pvar_write pv) a in
let addr = pvar_addr pv in
let writes' = Map.insert addr txw (vtx_writes vtx) in
vtx { vtx_writes = writes' }
{-# INLINE markForWrite #-}
-- | Estimate for cache size is based on random samples with an
-- exponential moving average. It isn't very precise, but it is
-- good enough for the purpose of guiding aggressiveness of the
-- exponential decay model.
data CacheSizeEst = CacheSizeEst
{ csze_addr_size :: {-# UNPACK #-} !Double -- average of sizes
, csze_addr_sqsz :: {-# UNPACK #-} !Double -- average of squares
}
type WriteLog = Map Address TxW
data TxW = forall a . TxW !(Writer a) a
-- Note: I can either record just the PVar, or the PVar and its value.
-- The latter is favorable because it avoids risk of creating very large
-- transactions in the writer thread (i.e. to read the updated PVars).
-- | Collection of writes
data Writes = Writes
{ write_data :: !WriteLog
, write_sync :: ![MVar ()]
}
-- Design Thoughts: It might be worthwhile to separate the writelog
-- and synchronization, i.e. to potentially reduce conflicts between
-- transactions. But I'll leave this to later.
data WriteCt = WriteCt
{ wct_frames :: {-# UNPACK #-} !Int -- how many write frames
, wct_pvars :: {-# UNPACK #-} !Int -- how many PVars written
, wct_sync :: {-# UNPACK #-} !Int -- how many sync requests
}
data VTxBatch = VTxBatch SyncOp WriteLog
type SyncOp = IO () -- called after write is synchronized.
type Ptr8 = Ptr Word8
type PtrIni = Ptr8
type PtrEnd = Ptr8
type PtrLoc = Ptr8
-- | VPut is a serialization monad akin to Data.Binary or Data.Cereal.
-- However, VPut is not restricted to pure binaries: developers may
-- include VRefs and PVars in the output.
--
-- Content emitted by VPut will generally be read only by VCache. So
-- it may be worth optimizing some cases, such as lists are written
-- in reverse such that readers won't need to reverse the list.
newtype VPut a = VPut { _vput :: VPutS -> IO (VPutR a) }
data VPutS = VPutS
{ vput_space :: !VSpace -- ^ destination space
, vput_children :: ![Address] -- ^ addresses written (addends buffer)
, vput_buffer :: !(IORef PtrIni) -- ^ buffer for easy free, realloc
, vput_target :: {-# UNPACK #-} !PtrLoc -- ^ location within buffer
, vput_limit :: {-# UNPACK #-} !PtrEnd -- ^ current limit for input
}
data VPutR r = VPutR
{ vput_result :: r
, vput_state :: !VPutS
}
instance Functor VPut where
fmap f m = VPut $ _vput m >=> \ (VPutR r s') ->
return (VPutR (f r) s')
{-# INLINE fmap #-}
instance Applicative VPut where
pure = return
(<*>) = ap
{-# INLINE pure #-}
{-# INLINE (<*>) #-}
instance Monad VPut where
fail msg = VPut (\ _ -> fail ("VCache.VPut.fail " ++ msg))
return r = VPut (return . VPutR r)
m >>= k = VPut $ _vput m >=> \ (VPutR r s') ->
_vput (k r) s'
m >> k = VPut $ _vput m >=> \ (VPutR _ s') ->
_vput k s'
{-# INLINE return #-}
{-# INLINE (>>=) #-}
{-# INLINE (>>) #-}
-- | VGet is a parser combinator monad for VCache. Unlike pure binary
-- parsers, VGet supports reads from a stack of VRefs and PVars to
-- directly model structured data.
--
newtype VGet a = VGet { _vget :: VGetS -> IO (VGetR a) }
data VGetS = VGetS
{ vget_children :: ![Address]
, vget_target :: {-# UNPACK #-} !PtrLoc
, vget_limit :: {-# UNPACK #-} !PtrEnd
, vget_space :: !VSpace
}
data VGetR r
= VGetR r !VGetS
| VGetE String
instance Functor VGet where
fmap f m = VGet $ _vget m >=> \ c ->
return $ case c of
VGetR r s' -> VGetR (f r) s'
VGetE msg -> VGetE msg
{-# INLINE fmap #-}
instance Applicative VGet where
pure = return
(<*>) = ap
{-# INLINE pure #-}
{-# INLINE (<*>) #-}
instance Monad VGet where
fail msg = VGet (\ _ -> return (VGetE msg))
return r = VGet (return . VGetR r)
m >>= k = VGet $ _vget m >=> \case
VGetE msg -> return (VGetE msg)
VGetR r s' -> _vget (k r) s'
m >> k = VGet $ _vget m >=> \case
VGetE msg -> return (VGetE msg)
VGetR _ s' -> _vget k s'
{-# INLINE fail #-}
{-# INLINE return #-}
{-# INLINE (>>=) #-}
{-# INLINE (>>) #-}
instance Alternative VGet where
empty = mzero
(<|>) = mplus
{-# INLINE empty #-}
{-# INLINE (<|>) #-}
instance MonadPlus VGet where
mzero = fail "mzero"
mplus f g = VGet $ \ s ->
_vget f s >>= \case
VGetE _ -> _vget g s
r -> return r
{-# INLINE mzero #-}
{-# INLINE mplus #-}
-- | To be utilized with VCache, a value must be serializable as a
-- simple sequence of binary data and child VRefs. Also, to put then
-- get a value must result in equivalent values. Further, values are
-- Typeable to support memory caching of values loaded.
--
-- Developers must ensure that `get` on the serialization from `put`
-- returns the same value. And `get` should be backwards compatible
-- to older versions of the same type. Consider version wrappers,
-- cf. SafeCopy package.
--
class (Typeable a) => VCacheable a where
-- | Serialize a value as a stream of bytes and value references.
put :: a -> VPut ()
-- | Parse a value from its serialized representation into memory.
get :: VGet a
| dmbarbour/haskell-vcache | hsrc_lib/Database/VCache/Types.hs | bsd-2-clause | 24,112 | 0 | 19 | 5,504 | 3,928 | 2,291 | 1,637 | -1 | -1 |
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE BangPatterns #-}
module Search.Stats
(
MTFCounter, TFCounter(TFCounter)
, newMTFCounter, countTermFrequencies
, tfFreeze, tfSize
) where
import qualified Data.Vector.Unboxed.Mutable as MVU
import qualified Data.Vector.Unboxed as VU
import Data.Binary
import qualified Data.Binary.Put as P
import qualified Data.Binary.Get as G
import Control.Monad (foldM, liftM)
import Control.Concurrent.MVar
import Search.Common
type MCounterArray = MVU.IOVector Word32
data MTFCounter = MTFCounter (MVar MCounterArray) (MVar Int)
newtype TFCounter = TFCounter (VU.Vector Word32)
tfFreeze :: MTFCounter -> IO TFCounter
tfFreeze (MTFCounter vref mref) = do
m <- takeMVar mref
v <- takeMVar vref
frozen <- VU.freeze $ MVU.take (m+1) v
putMVar vref v
putMVar mref m
return $ TFCounter frozen
instance Binary TFCounter where
put (TFCounter v) = VU.mapM_ P.putWord32be v
get = liftM (TFCounter . VU.fromList) freqs
where freqs = do
empty <- G.isEmpty
if empty
then return []
else do freq <- G.getWord32be
rest <- freqs
return $ freq : rest
_DEFAULT_SIZE_ :: Int
_DEFAULT_SIZE_ = 1024
newMTFCounter :: IO MTFCounter
newMTFCounter = do
vref <- newMVar =<< MVU.replicate _DEFAULT_SIZE_ 0
mref <- newMVar 0
return $ MTFCounter vref mref
countTokenDoc' :: Int -> MCounterArray -> TokenDoc -> IO (Int, MCounterArray)
countTokenDoc' curMax curV doc = foldM add (curMax, curV) $ tokensFromDoc doc
where add (cm,cv) (Token tw) = do
let t = fromIntegral tw
let nm = max t cm
!nv <- do let l = MVU.length cv
if t >= l then enlarge cv (max l (t-l+1)) else return cv
cur <- MVU.unsafeRead nv t
let new = if (cur+1) < cur -- Overflow
then cur
else cur+1
MVU.unsafeWrite nv t new
return (nm, nv)
enlarge v by = do
v' <- MVU.replicate (n+by) 0
MVU.unsafeCopy (MVU.unsafeSlice 0 n v') v
return v'
where
n = MVU.length v
countTermFrequencies :: MTFCounter -> TokenDoc -> IO ()
countTermFrequencies (MTFCounter vref mref) doc = do
curm <- takeMVar mref
curv <- takeMVar vref
(!newm, !newv) <- countTokenDoc' curm curv doc
putMVar vref newv
putMVar mref newm
tfSize :: TFCounter -> Int
tfSize (TFCounter v) = VU.length v
| jdimond/diplomarbeit | lib/Search/Stats.hs | bsd-3-clause | 2,664 | 3 | 19 | 846 | 841 | 431 | 410 | 74 | 3 |
{-# LANGUAGE CPP #-}
#if !defined(TESTING) && __GLASGOW_HASKELL__ >= 703
{-# LANGUAGE Safe #-}
#endif
#include "containers.h"
-----------------------------------------------------------------------------
-- |
-- Module : Data.Set
-- Copyright : (c) Daan Leijen 2002
-- License : BSD-style
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable
--
-- An efficient implementation of sets.
--
-- These modules are intended to be imported qualified, to avoid name
-- clashes with Prelude functions, e.g.
--
-- > import Data.Set (Set)
-- > import qualified Data.Set as Set
--
-- The implementation of 'Set' is based on /size balanced/ binary trees (or
-- trees of /bounded balance/) as described by:
--
-- * Stephen Adams, \"/Efficient sets: a balancing act/\",
-- Journal of Functional Programming 3(4):553-562, October 1993,
-- <http://www.swiss.ai.mit.edu/~adams/BB/>.
--
-- * J. Nievergelt and E.M. Reingold,
-- \"/Binary search trees of bounded balance/\",
-- SIAM journal of computing 2(1), March 1973.
--
-- Note that the implementation is /left-biased/ -- the elements of a
-- first argument are always preferred to the second, for example in
-- 'union' or 'insert'. Of course, left-biasing can only be observed
-- when equality is an equivalence relation instead of structural
-- equality.
--
-- /Warning/: The size of the set must not exceed @maxBound::Int@. Violation of
-- this condition is not detected and if the size limit is exceeded, its
-- behaviour is undefined.
-----------------------------------------------------------------------------
module Data.Set (
-- * Strictness properties
-- $strictness
-- * Set type
#if !defined(TESTING)
Set -- instance Eq,Ord,Show,Read,Data,Typeable
#else
Set(..)
#endif
-- * Operators
, (\\)
-- * Query
, S.null
, size
, member
, notMember
, lookupLT
, lookupGT
, lookupLE
, lookupGE
, isSubsetOf
, isProperSubsetOf
-- * Construction
, empty
, singleton
, insert
, delete
-- * Combine
, union
, unions
, difference
, intersection
-- * Filter
, S.filter
, partition
, split
, splitMember
, splitRoot
-- * Indexed
, lookupIndex
, findIndex
, lookupElem
, elemAt
, deleteAt
-- * Map
, S.map
, mapMonotonic
-- * Folds
, S.foldr
, S.foldl
-- ** Strict folds
, foldr'
, foldl'
-- ** Legacy folds
, fold
-- * Min\/Max
, findMin
, findMax
, deleteMin
, deleteMax
, deleteFindMin
, deleteFindMax
, maxView
, minView
-- * Conversion
-- ** List
, elems
, toList
, fromList
-- ** Ordered list
, toAscList
, toDescList
, fromAscList
, fromDistinctAscList
-- * Debugging
, showTree
, showTreeWith
, valid
#if defined(TESTING)
-- Internals (for testing)
, bin
, balanced
, link
, merge
#endif
) where
import Data.Set.Base as S
-- $strictness
--
-- This module satisfies the following strictness property:
--
-- * Key arguments are evaluated to WHNF
--
-- Here are some examples that illustrate the property:
--
-- > delete undefined s == undefined
| shockkolate/containers | Data/Set.hs | bsd-3-clause | 3,962 | 0 | 5 | 1,513 | 282 | 213 | 69 | 58 | 0 |
{-# LANGUAGE OverloadedStrings, PackageImports #-}
import Control.Applicative
import Control.Monad
import "monads-tf" Control.Monad.Trans
import Data.HandleLike
import System.Environment
import Network
import Network.PeyoTLS.ReadFile
import Network.PeyoTLS.Client
import "crypto-random" Crypto.Random
import qualified Data.ByteString.Char8 as BSC
cipherSuites :: [CipherSuite]
cipherSuites = [
"TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256",
"TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA",
"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256",
"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA",
"TLS_DHE_RSA_WITH_AES_128_CBC_SHA256",
"TLS_DHE_RSA_WITH_AES_128_CBC_SHA",
"TLS_RSA_WITH_AES_128_CBC_SHA256",
"TLS_RSA_WITH_AES_128_CBC_SHA" ]
main :: IO ()
main = do
d : _ <- getArgs
ca <- readCertificateStore [d ++ "/cacert.pem"]
h <- connectTo "localhost" $ PortNumber 443
g <- cprgCreate <$> createEntropyPool :: IO SystemRNG
(`run` g) $ do
p <- open' h "localhost" cipherSuites [] ca
hlPut p "GET / HTTP/1.1 \r\n"
hlPut p "Host: localhost\r\n\r\n"
doUntil BSC.null (hlGetLine p) >>= liftIO . mapM_ BSC.putStrLn
hlClose p
doUntil :: Monad m => (a -> Bool) -> m a -> m [a]
doUntil p rd = rd >>= \x ->
(if p x then return . (: []) else (`liftM` doUntil p rd) . (:)) x
| YoshikuniJujo/peyotls | peyotls/examples/eccClient.hs | bsd-3-clause | 1,255 | 18 | 14 | 178 | 374 | 200 | 174 | 36 | 2 |
module Main where
import Criterion.Main
infixl 9 !?
_ !? n | n < 0 = Nothing
[] !? _ = Nothing
(x:_) !? 0 = Just x
(_:xs) !? n = xs !? (n - 1)
myList :: [Int]
myList = [1..9999]
main :: IO ()
main = defaultMain
[ bench "index list 9999"
$ whnf (myList !!) 9998
, bench "index list maybe index 9999"
$ whnf (myList !?) 9998
] | nicklawls/haskellbook | src/Bench.hs | bsd-3-clause | 364 | 0 | 9 | 112 | 172 | 89 | 83 | 15 | 1 |
module Main (main) where
import Control.Monad
import System.Console.GetOpt
import System.Environment
import System.Exit
import System.IO
import Language.Hudson.PrettyPrinter
data Options = Options { optVerbose :: Bool
, optInput :: IO String
, optOutput :: String -> IO ()
}
startOptions :: Options
startOptions = Options { optVerbose = False
, optInput = getContents
, optOutput = putStr
}
options :: [ OptDescr (Options -> IO Options) ]
options =
[ Option "i" ["input"]
(ReqArg
(\arg opt -> return opt { optInput = readFile arg })
"FILE")
"Input file"
, Option "o" ["output"]
(ReqArg
(\arg opt -> return opt { optOutput = writeFile arg })
"FILE")
"Output file"
, Option "s" ["string"]
(ReqArg
(\arg opt -> return opt { optInput = return arg })
"FILE")
"Input string"
-- , Option "v" ["verbose"]
-- (NoArg
-- (\opt -> return opt { optVerbose = True })
-- "Enable verbose messages")
, Option "V" ["version"]
(NoArg
(\_ -> do
hPutStrLn stderr "Version 0.01"
exitWith ExitSuccess))
"Print version"
, Option "h" ["help"]
(NoArg
(\_ -> do
prg <- getProgName
hPutStrLn stderr (usageInfo prg options)
exitWith ExitSuccess))
"Show help"
]
main :: IO ()
main = do
args <- getArgs
-- Parse options, getting a list of option actions
let (actions, nonOptions, errors) = getOpt RequireOrder options args
case nonOptions of
[] -> return ()
_ -> (putStrLn $ concat nonOptions) >> exitFailure
case errors of
[] -> return ()
_ -> (putStrLn $ concat errors) >> exitFailure
-- Here we thread startOptions through all supplied option actions
opts <- foldl (>>=) (return startOptions) actions
let Options { optVerbose = verbose
, optInput = input
, optOutput = output } = opts
when verbose (hPutStrLn stderr "verbose enabled")
srcData <- input
case prettifyString srcData of -- TODO: Add newline in PrettyPrinter
(Left err) -> hPutStrLn stderr err
(Right p) -> return p >>= output | jschaf/hudson-dev | src/hudsonpp.hs | bsd-3-clause | 2,465 | 0 | 16 | 910 | 632 | 333 | 299 | 63 | 4 |
{-# LANGUAGE Rank2Types #-}
module YaLedger.Types.Output
(ASCII (..),
CSV (..),
OutputFormat (..),
defaultOutputFormat
) where
import YaLedger.Output.Tables
import YaLedger.Output.ASCII
import YaLedger.Output.CSV
import YaLedger.Output.HTML
data OutputFormat =
OASCII ASCII
| OCSV CSV
| OHTML HTML
deriving (Eq, Show)
defaultOutputFormat :: OutputFormat
defaultOutputFormat = OASCII ASCII
| portnov/yaledger | YaLedger/Types/Output.hs | bsd-3-clause | 425 | 0 | 6 | 80 | 101 | 64 | 37 | 17 | 1 |
{-# LANGUAGE PolyKinds, DataKinds, TemplateHaskell, TypeFamilies,
GADTs, TypeOperators, RankNTypes, FlexibleContexts, UndecidableInstances,
FlexibleInstances, ScopedTypeVariables, MultiParamTypeClasses,
OverlappingInstances, KindSignatures #-}
module Oxymoron.Scene.Uniform where
import Data.Singletons
import qualified Oxymoron.Description.Uniform as Desc
data Uniform :: Desc.Uniform -> * where
Uniform :: Sing a -> ToUniformValue a -> Uniform a
type family ToUniformValue (a :: Desc.Uniform) :: *
--instance IsAllocated UTUnsignedInt
--instance IsAllocated (UTImage Allocated b)
--glUniform :: (OpenGL m, IsAllocated a) => Uniform Bound a -> m ()
--glUniform = undefined
--testGood :: (OpenGL m) => m ()
--testGood = glUniform (undefined :: Uniform Bound (UTImage Allocated TEXTURE_2D))
--testBad :: (OpenGL m) => m ()
--testBad = glUniform (undefined :: Uniform Bound (UTImage Unallocated TEXTURE_2D))
| jfischoff/oxymoron | src/Oxymoron/Scene/Uniform.hs | bsd-3-clause | 947 | 0 | 8 | 151 | 82 | 53 | 29 | 10 | 0 |
{-#LANGUAGE PatternGuards #-}
module Twilio.Types.AuthToken
( -- * Authentication Token
AuthToken
, getAuthToken
, parseAuthToken
) where
import Control.Monad
import Data.Aeson
import Data.Char
import Data.Text (Text)
import qualified Data.Text as T
-- | Your authentication token is used to make authenticated REST API requests
-- to your Twilio account.
newtype AuthToken = AuthToken { getAuthToken' :: Text }
deriving (Show, Eq, Ord)
-- | Get the 'Text' representation of an 'AuthToken'.
getAuthToken :: AuthToken -> Text
getAuthToken = getAuthToken'
-- | Parse a 'Text' to an 'AuthToken'.
parseAuthToken :: Text -> Maybe AuthToken
parseAuthToken = parseAuthToken'
parseAuthToken' :: MonadPlus m => Text -> m AuthToken
parseAuthToken' token
| T.length token == 32
, T.all (\x -> isLower x || isNumber x) token
= return $ AuthToken token
| otherwise
= mzero
instance FromJSON AuthToken where
parseJSON (String v) = parseAuthToken' v
parseJSON _ = mzero
| seagreen/twilio-haskell | src/Twilio/Types/AuthToken.hs | bsd-3-clause | 990 | 0 | 12 | 180 | 236 | 129 | 107 | 27 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Turbinado.Server.StandardResponse
-- Copyright : (c) Alson Kemp 2008, Andreas Farre, Niklas Broberg, 2004
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer : Alson Kemp ([email protected])
-- Stability : experimental
-- Portability : portable
--
-- A set of functions to create standard HTTP responses.
-----------------------------------------------------------------------------
module Turbinado.Server.StandardResponse where
import Data.List
import Data.Maybe
import Network.HTTP
import Network.HTTP.Headers
import System.Locale
import System.Time
import Turbinado.Environment.Types
import Turbinado.Environment.Response
import Turbinado.Controller.Monad
import Turbinado.Utility.Data
-- import HSP.Data
instance Eq Header where
(==) (Header hn1 _) (Header hn2 _) = hn1 == hn2
addEmptyResponse :: (HasEnvironment m) => m ()
addEmptyResponse =
do t <- liftIO $ getClockTime
setResponse (Response (0,0,0)
""
(startingHeaders t)
""
)
fileNotFoundResponse :: (HasEnvironment m) => FilePath -> m ()
fileNotFoundResponse fp =
do t <- liftIO $ getClockTime
setResponse (Response (4,0,4)
"File Not Found"
(startingHeaders t ++ [Header HdrContentLength $ show $ length body])
(body))
where body = "<html><body>\n <p><big>404 File Not Found</big></p>\n <p>Requested resource: "++ fp ++ "</p>\n </body></html>"
cachedContentResponse :: (HasEnvironment m) => Int -> String -> String -> m ()
cachedContentResponse age ct body =
do pageResponse [ Header HdrCacheControl $ "max-age=" ++ (show age) ++ ", public"
, Header HdrContentType ct]
body
pageResponse :: (HasEnvironment m) => [Header] -> String -> m ()
pageResponse hds body =
do t <- liftIO $ getClockTime
r <- getEnvironment >>= (return . fromJust' "StandardResponse : pageResponse" . getResponse)
setResponse $ foldl
(\rs (Header hn s) -> replaceHeader hn s rs)
(Response
(2,0,0)
"OK"
(rspHeaders r ++ [Header HdrContentLength $ show $ length body])
body
)
hds
redirectResponse :: (HasEnvironment m) => String -> m ()
redirectResponse l =
do t <- liftIO $ getClockTime
r <- getEnvironment >>= (return . fromJust' "StandardResponse : redirectResponse" . getResponse)
setResponse (Response (3,0,2) "OK" (rspHeaders r ++ [Header HdrLocation l]) "")
errorResponse :: (HasEnvironment m) => String -> m ()
errorResponse err =
do t <- liftIO $ getClockTime
setResponse (Response (5,0,0) "Internal Server Error"
(startingHeaders t ++ [Header HdrContentLength $ show $ length body]) body)
where body = "<html><body>\n <p><big>500 Internal Server Error</big></p>\n <p>Error specification:<br/>\n" ++ err ++ "</p>\n </body></html>"
badReqResponse :: (HasEnvironment m) => m ()
badReqResponse =
do t <- liftIO $ getClockTime
setResponse (Response (4,0,0) "Bad Request"
(startingHeaders t ++ [Header HdrContentLength $ show $ length body]) body)
where body = "<html><body>\n <p><big>400 Bad Request</big></p>\n </body></html>"
startingHeaders t = [ Header HdrServer "Turbinado www.turbinado.org"
, Header HdrContentType "text/html; charset=UTF-8"
, Header HdrDate $ formatCalendarTime defaultTimeLocale rfc822DateFormat $ toUTCTime t
]
| abuiles/turbinado-blog | Turbinado/Server/StandardResponse.hs | bsd-3-clause | 3,842 | 4 | 16 | 1,080 | 912 | 475 | 437 | 65 | 1 |
-- |
-- Module: $Header$
-- Description: Experiment to make help messages easier to create.
-- Copyright: (c) 2019-2020 Peter Trško
-- License: BSD3
--
-- Maintainer: [email protected]
-- Stability: experimental
-- Portability: GHC specific language extensions.
--
-- Experiment to make help messages easier to create. Highly experimental!
module CommandWrapper.Core.Help.Message
( Annotation(..)
, Annotated(..)
, HelpMessage(..)
, Paragraph
, Usage
-- * Combinators
, longOption
, shortOption
, metavar
, command
, value
, (<+>)
, alternatives
, optionalAlternatives
, requiredAlternatives
, braces
, brackets
, squotes
, dquotes
, reflow
, subcommand
, optionalSubcommand
, optionalMetavar
, helpOptions
-- * Rendering
, renderAnnotated
, renderParagraph
, render
, defaultStyle
-- ** IO
, hPutHelp
, helpMessage -- TODO: TMP
)
where
import Data.Bool (otherwise)
import Data.Char (Char)
import Data.Eq (Eq, (==))
import Data.Foldable (foldMap)
import Data.Function (($), (.))
import Data.Functor (Functor, (<$>), fmap)
import Data.Int (Int)
import qualified Data.List as List (intercalate, intersperse)
import Data.Maybe (Maybe(Just, Nothing), maybe)
import Data.Monoid (mconcat, mempty)
import Data.Semigroup (Semigroup, (<>))
import Data.String (IsString(fromString))
import GHC.Generics (Generic)
import System.IO (Handle, IO)
import Text.Show (Show)
import Data.Text (Text)
import qualified Data.Text as Text (null, uncons, unsnoc, words)
import Data.Text.Prettyprint.Doc (Doc, Pretty(pretty))
import qualified Data.Text.Prettyprint.Doc as Pretty
import qualified Data.Text.Prettyprint.Doc.Render.Terminal as Pretty
import qualified System.Console.Terminal.Size as Terminal (Window)
import CommandWrapper.Core.Config.ColourOutput (ColourOutput)
import CommandWrapper.Core.Message (hPutDoc)
data Annotation
= Plain
| Option
| Metavar
| Value
| Command
deriving stock (Eq, Generic, Show)
-- TODO: At the moment @Annotated Plain \"\"@ and @Annotated Plain \" \"@ have
-- a special meaning. Better encoding would be desirable, however, that will
-- complicate the implementation at the moment.
data Annotated a = Annotated
{ annotation :: Annotation
, content :: a
}
deriving stock (Eq, Functor, Generic, Show)
-- | @\\s -> 'Annotated'{'annotation' = 'Plain', 'content' = 'fromString' s}@
instance IsString s => IsString (Annotated s) where
fromString = Annotated Plain . fromString
type Paragraph a = [Annotated a]
type Usage a = [Annotated a]
data Section a = Section
{ name :: Paragraph a
, content :: [Paragraph a]
}
deriving stock (Eq, Functor, Generic, Show)
data HelpMessage a = HelpMessage
{ description :: Paragraph a
, usage :: [Usage a]
, sections :: [Section a]
, message :: [Paragraph a]
}
deriving stock (Eq, Functor, Generic, Show)
-- {{{ Combinators ------------------------------------------------------------
-- |
-- >>> longOption "foo" :: Annotated Text
-- Annotated{annotation = Option, content = "--foo"}
longOption :: (IsString s, Semigroup s) => s -> Annotated s
longOption content = Annotated
{ annotation = Option
, content = "--" <> content
}
-- |
-- >>> shortOption 'f' :: Annotated Text
-- Annotated{annotation = Option, content = "-f"}
shortOption :: IsString s => Char -> Annotated s
shortOption c = Annotated
{ annotation = Option
, content = fromString ('-' : [c])
}
metavar :: s -> Annotated s
metavar = Annotated Metavar
command :: s -> Annotated s
command = Annotated Command
value :: s -> Annotated s
value = Annotated Command
(<+>) :: IsString s => [Annotated s] -> [Annotated s] -> [Annotated s]
l <+> r = l <> [""] <> r
brackets :: IsString s => [Annotated s] -> [Annotated s]
brackets c = "[" : c <> ["]"]
braces :: IsString s => [Annotated s] -> [Annotated s]
braces c = "{" : c <> ["}"]
squotes :: IsString s => [Annotated s] -> [Annotated s]
squotes c = "'" : c <> ["'"]
dquotes :: IsString s => [Annotated s] -> [Annotated s]
dquotes c = "\"" : c <> ["\""]
alternatives :: IsString s => [[Annotated s]] -> [Annotated s]
alternatives = List.intercalate ["|"]
optionalAlternatives :: IsString s => [[Annotated s]] -> [Annotated s]
optionalAlternatives = brackets . alternatives
requiredAlternatives :: IsString s => [[Annotated s]] -> [Annotated s]
requiredAlternatives = braces . alternatives
reflow :: Paragraph Text -> Paragraph Text
reflow = foldMap words
where
words :: Annotated Text -> [Annotated Text]
words a@Annotated{..} = case annotation of
Plain
| Text.null content -> [a]
| content == " " -> [a]
| otherwise -> mconcat
[ preserveSpaceAtTheBeginning content
, Annotated Plain <$> List.intersperse "" (Text.words content)
, preserveSpaceAtTheEnd content
]
Option -> [a]
Metavar -> [a]
Value -> [a]
Command -> [a]
where
preserveSpaceAtTheBeginning t = case Text.uncons t of
Nothing -> []
Just (' ', _) -> [Annotated Plain ""]
_ -> []
preserveSpaceAtTheEnd t = case Text.unsnoc t of
Nothing -> []
Just (_, ' ') -> [Annotated Plain ""]
_ -> []
-- | @['metavar' \"SUBCOMMAND\"]@
subcommand :: IsString s => [Annotated s]
subcommand = [metavar "SUBCOMMAND"]
-- | @'metavar' \"SUBCOMMAND\"@
optionalSubcommand :: IsString s => [Annotated s]
optionalSubcommand = brackets subcommand
optionalMetavar :: IsString s => s -> [Annotated s]
optionalMetavar s = brackets [metavar s]
helpOptions :: (IsString s, Semigroup s) => [Annotated s]
helpOptions = alternatives
[ [longOption "help"]
, [shortOption 'h']
]
-- }}} Combinators ------------------------------------------------------------
-- {{{ Rendering --------------------------------------------------------------
renderAnnotated :: (Eq a, IsString a, Pretty a) => Annotated a -> Doc Annotation
renderAnnotated Annotated{..} = case annotation of
Plain
| content == "" ->
Pretty.softline
| content == " " ->
" "
| otherwise ->
Pretty.annotate annotation (pretty content)
_ ->
Pretty.annotate annotation (pretty content)
renderParagraph :: Paragraph Text -> Doc Annotation
renderParagraph = foldMap renderAnnotated . reflow
render :: HelpMessage Text -> Doc Annotation
render HelpMessage{..} = Pretty.vsep
[ renderParagraph description
, ""
, renderSection "Usage:" (usage)
, Pretty.vsep (renderSections sections)
, Pretty.vsep (renderParagraph <$> message)
]
where
renderSection :: Doc Annotation -> [Paragraph Text] -> Doc Annotation
renderSection d ds =
Pretty.nest 2 $ Pretty.vsep $ d : "" : (fmap renderParagraph ds <> [""])
renderSections :: [Section Text] -> [Doc Annotation]
renderSections = fmap \Section{..} ->
renderSection (renderParagraph name) content
defaultStyle :: Annotation -> Pretty.AnsiStyle
defaultStyle = \case
Plain -> mempty
Option -> Pretty.colorDull Pretty.Green
Metavar -> Pretty.colorDull Pretty.Green
Value -> Pretty.colorDull Pretty.Green
Command -> Pretty.color Pretty.Magenta
-- {{{ I/O --------------------------------------------------------------------
hPutHelp
:: (Maybe (Terminal.Window Int) -> Pretty.LayoutOptions)
-> (Annotation -> Pretty.AnsiStyle)
-> ColourOutput
-> Handle
-> HelpMessage Text
-> IO ()
hPutHelp mkLayoutOptions style colourOutput h =
hPutDoc mkLayoutOptions style colourOutput h . render
-- }}} I/O --------------------------------------------------------------------
-- }}} Rendering --------------------------------------------------------------
helpMessage :: Text -> Maybe Text -> HelpMessage Text
helpMessage usedName description = HelpMessage
{ description = [maybe defaultDescription (Annotated Plain) description]
, usage =
[ [Annotated Plain usedName] <+> subcommand <+> subcommandArguments
, [Annotated Plain usedName] <+> ["help"]
<+> optionalMetavar "HELP_OPTIONS"
<+> optionalSubcommand
, [Annotated Plain usedName] <+> ["config"]
<+> optionalMetavar "CONFIG_OPTIONS"
<+> optionalSubcommand
, [Annotated Plain usedName] <+> ["version"]
<+> optionalMetavar "VERSION_OPTIONS"
, [Annotated Plain usedName] <+> ["completion"]
<+> optionalMetavar "COMPLETION_OPTIONS"
, [Annotated Plain usedName] <+> requiredAlternatives
[ [longOption "version"]
, [shortOption 'V']
]
, [Annotated Plain usedName] <+> braces helpOptions
]
, sections = []
, message = []
}
-- , Help.section (Pretty.annotate Help.dullGreen "GLOBAL_OPTIONS" <> ":")
-- [ Help.optionDescription ["-v"]
-- [ Pretty.reflow "Increment verbosity by one level. Can be used"
-- , Pretty.reflow "multiple times."
-- ]
-- , Help.optionDescription ["--verbosity=VERBOSITY"]
-- [ Pretty.reflow "Set verbosity level to"
-- , Help.metavar "VERBOSITY" <> "."
-- , Pretty.reflow "Possible values of"
-- , Help.metavar "VERBOSITY", "are"
-- , Pretty.squotes (Help.value "silent") <> ","
-- , Pretty.squotes (Help.value "normal") <> ","
-- , Pretty.squotes (Help.value "verbose") <> ","
-- , "and"
-- , Pretty.squotes (Help.value "annoying") <> "."
-- ]
-- , Help.optionDescription ["--silent", "-s"]
-- (silentDescription "quiet")
-- , Help.optionDescription ["--quiet", "-q"]
-- (silentDescription "silent")
-- , Help.optionDescription ["--colo[u]r=WHEN"]
-- [ "Set", Help.metavar "WHEN"
-- , Pretty.reflow "colourised output should be produced. Possible"
-- , Pretty.reflow "values of"
-- , Help.metavar "WHEN", "are"
-- , Pretty.squotes (Help.value "always") <> ","
-- , Pretty.squotes (Help.value "auto") <> ","
-- , "and", Pretty.squotes (Help.value "never") <> "."
-- ]
-- , Help.optionDescription ["--no-colo[u]r"]
-- [ Pretty.reflow "Same as"
-- , Pretty.squotes (Help.longOption "colour=never") <> "."
-- ]
-- , Help.optionDescription ["--[no-]aliases"]
-- [ "Apply or ignore", Help.metavar "SUBCOMMAND", "aliases."
-- , Pretty.reflow "This is useful when used from e.g. scripts to\
-- \ avoid issues with user defined aliases interfering with how\
-- \ the script behaves."
-- ]
-- , Help.optionDescription ["--version", "-V"]
-- [ Pretty.reflow "Print version information to stdout and exit."
-- ]
-- , Help.optionDescription ["--help", "-h"]
-- [ Pretty.reflow "Print this help and exit."
-- ]
-- ]
-- , Help.section (Help.metavar "SUBCOMMAND" <> ":")
-- [ Pretty.reflow "Name of either internal or external subcommand."
-- ]
-- , ""
-- ]
where
-- silentDescription altOpt =
-- [ "Silent mode. Suppress normal diagnostic or result output. Same as "
-- , Pretty.squotes (Help.longOption altOpt) <> ",", "and"
-- , Pretty.squotes (Help.longOption "verbosity=silent") <> "."
-- ]
defaultDescription :: Annotated Text
defaultDescription = "Toolset of commands for working developer."
subcommandArguments =
brackets [metavar "SUBCOMMAND_ARGUMENTS"]
| trskop/command-wrapper | command-wrapper-core/src/CommandWrapper/Core/Help/Message.hs | bsd-3-clause | 11,748 | 0 | 17 | 2,830 | 2,575 | 1,436 | 1,139 | -1 | -1 |
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Control.Yield.Cont where
import Control.Monad.Trans.Cont
import Control.Monad.Trans.Class
import Control.Monad (liftM)
infix 2 `provide`
infix 1 `using`
newtype Producing o i m a
= Producing { using :: forall r. (o -> ContT r m i) -> ContT r m a }
newtype Consuming a m i o
= Consuming { provide :: i -> Producing o i m a }
data ProducerState o i m a
= Produced o (Consuming a m i o)
| Done a
fromStep :: Monad m => m (ProducerState o i m a) -> Producing o i m a
fromStep p = Producing $ \yield' -> lift p >>= \s -> case s of
Done a -> return a
Produced o k -> do
i <- yield' o
k `provide` i `using` yield'
resume :: Monad m => Producing o i m a -> m (ProducerState o i m a)
resume p = runContT (p `using` yield') (return . Done) where
-- yield' :: o -> ContT (ProducerState o i m a) m i
yield' o = ContT $ \k -> return $ Produced o $ Consuming (fromStep . k)
-- Alternate implementations
---------------------------------------------------------------------------
yield :: Monad m => o -> Producing o i m i
yield o = Producing ($ o)
pfold :: forall m n o i r.
(Monad m, Monad n)
=> (forall x. m x -> n x)
-> (o -> n i) -> Producing o i m r -> n r
pfold morph yield' p = runContT c return where
c = hoist morph p `using` lift . yield'
-- ew! Want to implement this more... continuation-y
hoist :: (Monad m, Monad n)
=> (forall x. m x -> n x)
-> Producing o i m r -> Producing o i n r
hoist morph = go where
go p = fromStep $ liftM convert (morph (resume p)) where
convert (Done r) = Done r
convert (Produced o k) = Produced o (Consuming (go . provide k))
| DanBurton/yield | Control/Yield/Cont.hs | bsd-3-clause | 1,690 | 0 | 15 | 398 | 709 | 378 | 331 | 39 | 2 |
module LG.Identify (identifyNodes) where
import LG.Base
import LG.Term
import LG.Graph
import LG.Base
import LG.Term
import qualified Data.Map as Map
import qualified Data.Set as Set
-- A (simple) identification contains two references to a node: one will be the
-- premise of the axiom link; the other the conclusion.
type Identification = (Identifier, Identifier)
-- An IdentificationProfile is a set of identifications, representing all
-- identifications that will happen in one contingent universe for the
-- given composition graph.
type IdentificationProfile = Set.Set Identification
-- A verbose identification contains information not just about which two nodes
-- identify, but also the graphs they are in
type VerboseIdentification = ((CompositionGraph, LeafNode), (CompositionGraph, LeafNode))
fromVerboseIdentifications :: [VerboseIdentification] -> [Identification]
fromVerboseIdentifications = map fromVerboseIdentification
fromVerboseIdentification :: VerboseIdentification -> Identification
fromVerboseIdentification ((_, Leaf (id1:@_)), (_, Leaf (id2:@_))) = (id1, id2)
-- identifyNodes is used to identify leaf nodes in a composition graph in a maximal way,
-- that is: all possible combinations of identification are tried out, exhaustively.
--
-- See M&M, p. 7: "We obtain a proof structure of (s </> s) <\> np ⇒ s / (np \ s) by
-- identifying atomic formulas"
--
-- Note that the returned composition graphs are not guaranteed to be proof nets, only
-- guaranteed to have no more possibilities of identifying leaf nodes!
--
-- (TODO: fix this) Also note that this function does not take node order into account,
-- and so will produce a proof net for 'mary likes john' as well as 'john likes mary' if
-- they're both of the form 'np <x> (np\s)/np<x> np'.
--
-- Input : A (ordered) list of input formulas that corresponds to the order of words. Node identifiers must not clash.
-- Output: A list of composition graphs in which the atomic nodes of the input graphs are connected maximally
identifyNodes :: [CompositionGraph] -> [CompositionGraph]
identifyNodes subgraphs = Set.toList (Set.map (identifyNodes' (Map.unions subgraphs)) identificationProfiles)
where identificationProfiles = Set.map Set.toList (generateIdentificationProfiles subgraphs)
-- Function that recursively applies node identifications to a composition graph
--
-- Input: A composition graph and a list of identifications. An identification is a pair of node identifiers.
-- Output: Composition graph with all node identifications applied to it
identifyNodes' graph [] = graph
identifyNodes' graph (identification:xs) = identifyNodes' (graphAfterIdentification identification graph) xs
-- Completes an identification: id1 and id2 are removed from the graph, and linkMe1 and linkMe2
-- get a new axioma link between them:
--
-- * linkMe2
-- | * linkMe2
-- X id2 -> |
-- X id1 * linkMe1
-- |
-- * linkMe1
--
-- Note that axiom link collapse (M&M, p. 23: Def 3.2; bullet 3) happens implicitly in this
-- function as id1 and id2 are removed from the graph.
--
-- Complexity: O(log n)
graphAfterIdentification :: Identification -> CompositionGraph -> CompositionGraph
graphAfterIdentification (id1,id2) g0 = g3
where newLink = Just (linkMe1:|:linkMe2)
Just (Node _ _ Nothing (Just (linkMe1:|:_))) = Map.lookup id1 g0
Just (Node _ _ (Just (_:|:linkMe2)) Nothing) = Map.lookup id2 g1
g1 = setIsPremiseOf newLink (referee linkMe1) g0
g3 = ((Map.delete id1).(Map.delete id2)) g2
g2 = setIsConclusionOf newLink (referee linkMe2) g1
-- Input : A (ordered) list of input formulas that corresponds to the order of words. Node identifiers must not clash.
-- Output: Set of sets of possible node identifications that guarantee that the merged graph will be connected
generateIdentificationProfiles :: [CompositionGraph] -> Set.Set IdentificationProfile
generateIdentificationProfiles subgraphs = maximalProfiles
where subgraphLeafNodes = map (\g -> (g, leafNodes g)) subgraphs
allPairings = generateIdentifications subgraphLeafNodes -- Gives us a list of pairing for every leaf node.
allProfiles = getProfilesFromPossiblePairings allPairings
validProfiles = getValidProfiles subgraphs allProfiles
validSimpleProfiles = map (Set.fromList . fromVerboseIdentifications) validProfiles
maximalProfiles = Set.fromList $ filter (isMaximalInRegardTo validSimpleProfiles) validSimpleProfiles -- Filter out profiles that are strict subsets of other profiles
-- TODO we might be able to make this more efficient by clustering
-- our VerboseIdentifications per Node, so that in this function we
-- don't generate profiles where a node occurs more than once as
-- the premise/conclusion in the identification profile, but that
-- would make our code so much more complex.
getProfilesFromPossiblePairings :: [VerboseIdentification] -> [[VerboseIdentification]]
getProfilesFromPossiblePairings = subsets
-- Filter identification profiles to those that are valid.
getValidProfiles :: [CompositionGraph] -> [[VerboseIdentification]] -> [[VerboseIdentification]]
getValidProfiles graphs = filter (isValidProfile graphs)
-- A profile is valid if:
-- - The resulting graph is connected
-- - Across all identifications, nodes are at most once the premise and at most once the conclusion of the axiom link
isValidProfile :: [CompositionGraph] -> [VerboseIdentification] -> Bool
isValidProfile graphs profile =
allGraphsAreTouched (Set.fromList graphs) profile &&
hasNoDuplicates (fromVerboseIdentifications profile)
hasNoDuplicates :: [Identification] -> Bool
hasNoDuplicates [] = True
hasNoDuplicates ((id1,id2):idts) =
isNotId1 id1 idts &&
isNotId2 id2 idts &&
hasNoDuplicates idts
where isNotId1 _ [] = True
isNotId1 id ((jd,_):xs) = if id == jd then False else isNotId1 id xs
isNotId2 _ [] = True
isNotId2 id ((_,jd):xs) = if id == jd then False else isNotId2 id xs
allGraphsAreTouched :: Set.Set CompositionGraph -> [VerboseIdentification] -> Bool
allGraphsAreTouched graphSet profile =
((length commonTerritories) == 1) && ((commonTerritories !! 0) == graphSet)
where
graphTerritories = map (\(g1,g2)->Set.fromList [g1,g2]) $ map getGraphPair profile
commonTerritories = amassCommonTerritory graphTerritories []
-- Returns just the graphs from a verbose identification
getGraphPair :: VerboseIdentification -> (CompositionGraph, CompositionGraph)
getGraphPair ((g1, _), (g2, _)) = (g1, g2)
amassCommonTerritory (p1:p2:ps) noMatch =
if (Set.intersection p1 p2) /= Set.empty
then amassCommonTerritory ((Set.union p1 p2):noMatch) [] --Start over with new union
else amassCommonTerritory (p2:ps) (p1:noMatch)
amassCommonTerritory commonTerritories noMatch = commonTerritories++noMatch
type LeafSubgraph = (CompositionGraph, [LeafNode])
-- This function gives us back all possible pairings of leaf nodes.
-- Note that a - b and b - a duplicates are weeded out in `getPossIdsForLeafWith`: we only get id1 is the upper and id2 the lower.
generateIdentifications :: [LeafSubgraph] -> [VerboseIdentification]
generateIdentifications leafGraphs = generateIdentifications' isolatedNodes leafGraphs []
where isolatedNodes = map isolateNodesForGraph leafGraphs
isolateNodesForGraph (g, ns) = map (\x->(g,x)) ns
generateIdentifications' :: [[(CompositionGraph, LeafNode)]]
-> [LeafSubgraph]
-> [VerboseIdentification]
-> [VerboseIdentification]
generateIdentifications' [] _ acc = reverse acc
generateIdentifications' (subgraphLeafNodes:ns) allLeafs acc = generateIdentifications' ns allLeafs (a++acc)
where a = getPossIdsForLeafs subgraphLeafNodes allLeafs []
getPossIdsForLeafs [] _ acc = reverse acc
getPossIdsForLeafs ((c1, l):ls) allLeafNodes acc = getPossIdsForLeafs ls allLeafNodes (possibilities++acc)
where possibilities = getPossIdsForLeaf (c1, l) allLeafNodes []
getPossIdsForLeaf :: (CompositionGraph, LeafNode) -> [(CompositionGraph, [LeafNode])] -> [VerboseIdentification] -> [VerboseIdentification]
getPossIdsForLeaf _ [] acc = reverse acc
getPossIdsForLeaf leaf ((c2, otherLeafs):rest) acc = getPossIdsForLeaf leaf rest (possibilities++acc)
where possibilities = leaf `getPossIdsForLeafWith` (c2, otherLeafs)
getPossIdsForLeafWith :: (CompositionGraph, LeafNode) -> (CompositionGraph, [LeafNode]) -> [VerboseIdentification]
getPossIdsForLeafWith (c1, (leaf@(Leaf (id1:@(Node formula1 _ downlink1 uplink1))))) (c2, otherLeafs) =
[((c1, leaf), (c2, otherLeaf)) | otherLeaf@(Leaf (id2:@(Node formula2 _ downlink2 uplink2))) <- otherLeafs,
leaf/=otherLeaf, -- We can't identify exactly the same node
sameName formula1 formula2, -- Select pairs with the same formula (polarity doesn't matter)
downlink1 == Nothing && uplink2 == Nothing, -- Select pairs that are not saturated
if uplink1/=Nothing then not(uplink1 == downlink2) else True -- Don't match up atoms that are already connected with an axiom link
]
-- Replaces premise of node in given map for given Identifier with given link. (Note: this does not check whether the given node id is *actually* a premise of the given link)
--
-- Complexity: O(log n)
setIsPremiseOf :: Maybe Link -> Identifier -> CompositionGraph -> CompositionGraph
setIsPremiseOf premOf id g = Map.insert id (Node f t premOf concOf) g
where Just (Node f t _ concOf) = if Map.lookup id g == Nothing then error ((show id)++" not found") else Map.lookup id g
-- Replaces conclusion of node in given map for given Identifier with given link. (Note: this does not check whether the given node id is *actually* a conclusion of the given link)
--
-- Complexity: O(log n)
setIsConclusionOf :: Maybe Link -> Identifier -> CompositionGraph -> CompositionGraph
setIsConclusionOf concOf id g = Map.insert id (Node f t premOf concOf) g
where Just (Node f t premOf _) = Map.lookup id g
-- Return the name of an atomic formula
getNameOfAtomicFormula (P (AtomP s)) = Just s
getNameOfAtomicFormula (N (AtomN s)) = Just s
getNameOfAtomicFormula _ = Nothing
-- Returns whether node a and b are both atomic and have the same formula name
sameName a b = (aName == bName) && (aName /= Nothing)
where aName = getNameOfAtomicFormula a
bName = getNameOfAtomicFormula b
-- NOTE: this function is not correct: it should leave the main formula intact, while deleting the active
-- formula. This is not always the case. Currently, we ignore this function because it is not needed for
-- any of the following steps. (Validation collapses *all* axiom links anyway and it's an extra complication
-- for term labeling.)
--
-- See M&M, p. 23: "all axiom links connecting terms of the same type (value or context) are collapsed."
collapseAxiomLinks :: CompositionGraph -> CompositionGraph
collapseAxiomLinks g = collapseConclusionLinks (((map (\(Node _ _ _ l)->l)) . (filter isAxiomConclusion) . Map.elems) g) g
where isAxiomConclusion (Node _ _ _ (Just (_ :|: _))) = True
isAxiomConclusion _ = False
collapseConclusionLinks :: [Maybe Link] -> CompositionGraph -> CompositionGraph
collapseConclusionLinks [] g = g
collapseConclusionLinks (Just (Active id1 :|: Active id2):xs) g0 = if sameTermTypes t1 t2 then g1 else g
where Just (Node f1 t1 premOf1 concOf1) = Map.lookup id1 g0
Just (Node f2 t2 premOf2 concOf2) = Map.lookup id2 g0
newNode = (Node f1 t1 premOf2 concOf1)
sameTermTypes (Ev _) (Ev _) = True
sameTermTypes (Va _) (Va _) = True
sameTermTypes _ _ = False
g1 :: CompositionGraph
g1 = ((replaceIdInConclusion id2 id1 premOf2) . (Map.insert id1 newNode) . (Map.delete id2) . (Map.delete id1)) g0
replaceIdInConclusion :: Identifier -> Identifier -> Maybe Link -> CompositionGraph -> CompositionGraph
replaceIdInConclusion _ _ Nothing g = g
replaceIdInConclusion replaceMe withMe (Just l) g = replaceIdInConclusion' replaceMe withMe (map referee (succedents l)) g
replaceIdInConclusion' replaceMe withMe [] g = g
replaceIdInConclusion' replaceMe withMe (id:xs) g0 = g1
where Just (Node f t premOf (Just link)) = Map.lookup id g0
g1 = Map.insert id newNode g0
newNode = (Node f t premOf (Just (replaceInLink replaceMe withMe link)))
replaceInLink :: Identifier -> Identifier -> Link -> Link
replaceInLink replaceMe withMe (prems :○: concs) = (replaceInList replaceMe withMe prems) :○: (replaceInList replaceMe withMe concs)
replaceInLink replaceMe withMe (prems :●: concs) = (replaceInList replaceMe withMe prems) :○: (replaceInList replaceMe withMe concs)
replaceInLink replaceMe withMe (prem :|: conc) = p :|: c
where p = if replaceMe==(referee prem) then (Active withMe) else prem
c = if replaceMe==(referee conc) then (Active withMe) else conc
replaceInList replaceMe withMe inList = map replaceIdInTentance inList
replaceIdInTentance t@(Active x) = if x==replaceMe then Active withMe else t
replaceIdInTentance t@(MainT x) = if x==replaceMe then MainT withMe else t
-------------
-- SET UTILS
-------------
-- NOTE: I can't decide whether to put these functions in another module
-- Generates all subsets of a given list
subsets :: [a] -> [[a]]
subsets [] = [[]]
subsets (x:xs) = (map (x:) y) ++ y
where y = subsets xs
-- Returns whether s1 is a maximal subset in regards to all other
-- sets, that is, whether s1 is not a proper subset of any other
-- set.
isMaximalInRegardTo [] _ = True
isMaximalInRegardTo (s2:xs) s1 = if s1 `Set.isProperSubsetOf` s2 then False else isMaximalInRegardTo xs s1 | jgonggrijp/net-prove | src/LG/Identify.hs | bsd-3-clause | 14,424 | 1 | 16 | 3,129 | 3,129 | 1,696 | 1,433 | 142 | 15 |
-----------------------------------------------------------------------------
-- | Module : Data.These
--
-- The 'These' type and associated operations. Now enhanced with @Control.Lens@ magic!
module Data.These (
These(..)
-- * Functions to get rid of 'These'
, these
, fromThese
, mergeThese
, mergeTheseWith
-- * Traversals
, here, there
-- * Prisms
, _This, _That, _These
-- * Case selections
, justThis
, justThat
, justThese
, catThis
, catThat
, catThese
, partitionThese
-- * Case predicates
, isThis
, isThat
, isThese
-- * Map operations
, mapThese
, mapThis
, mapThat
-- $align
) where
import Control.Applicative (Applicative(..))
import Control.Monad
import Data.Bifoldable
import Data.Bifunctor
import Data.Bitraversable
import Data.Foldable
import Data.Functor.Bind
import Data.Maybe (isJust, mapMaybe)
import Data.Profunctor
import Data.Semigroup (Semigroup(..), Monoid(..))
import Data.Semigroup.Bifoldable
import Data.Semigroup.Bitraversable
import Data.Traversable
import Prelude hiding (foldr)
-- --------------------------------------------------------------------------
-- | The 'These' type represents values with two non-exclusive possibilities.
--
-- This can be useful to represent combinations of two values, where the
-- combination is defined if either input is. Algebraically, the type
-- @These A B@ represents @(A + B + AB)@, which doesn't factor easily into
-- sums and products--a type like @Either A (B, Maybe A)@ is unclear and
-- awkward to use.
--
-- 'These' has straightforward instances of 'Functor', 'Monad', &c., and
-- behaves like a hybrid error/writer monad, as would be expected.
data These a b = This a | That b | These a b
deriving (Eq, Ord, Read, Show)
-- | Case analysis for the 'These' type.
these :: (a -> c) -> (b -> c) -> (a -> b -> c) -> These a b -> c
these l _ _ (This a) = l a
these _ r _ (That x) = r x
these _ _ lr (These a x) = lr a x
-- | Takes two default values and produces a tuple.
fromThese :: a -> b -> These a b -> (a, b)
fromThese _ x (This a ) = (a, x)
fromThese a _ (That x ) = (a, x)
fromThese _ _ (These a x) = (a, x)
-- | Coalesce with the provided operation.
mergeThese :: (a -> a -> a) -> These a a -> a
mergeThese = these id id
-- | BiMap and coalesce results with the provided operation.
mergeTheseWith :: (a -> c) -> (b -> c) -> (c -> c -> c) -> These a b -> c
mergeTheseWith f g op t = mergeThese op $ mapThese f g t
-- | A @Traversal@ of the first half of a 'These', suitable for use with @Control.Lens@.
here :: (Applicative f) => (a -> f b) -> These a t -> f (These b t)
here f (This x) = This <$> f x
here f (These x y) = flip These y <$> f x
here _ (That x) = pure (That x)
-- | A @Traversal@ of the second half of a 'These', suitable for use with @Control.Lens@.
there :: (Applicative f) => (a -> f b) -> These t a -> f (These t b)
there _ (This x) = pure (This x)
there f (These x y) = These x <$> f y
there f (That x) = That <$> f x
-- <cmccann> is there a recipe for creating suitable definitions anywhere?
-- <edwardk> not yet
-- <edwardk> prism bt seta = dimap seta (either pure (fmap bt)) . right'
-- (let's all pretend I know how this works ok)
prism bt seta = dimap seta (either pure (fmap bt)) . right'
-- | A 'Prism' selecting the 'This' constructor.
_This :: (Choice p, Applicative f) => p a (f a) -> p (These a b) (f (These a b))
_This = prism This (these Right (Left . That) (\x y -> Left $ These x y))
-- | A 'Prism' selecting the 'That' constructor.
_That :: (Choice p, Applicative f) => p b (f b) -> p (These a b) (f (These a b))
_That = prism That (these (Left . This) Right (\x y -> Left $ These x y))
-- | A 'Prism' selecting the 'These' constructor. 'These' names are ridiculous!
_These :: (Choice p, Applicative f) => p (a, b) (f (a, b)) -> p (These a b) (f (These a b))
_These = prism (uncurry These) (these (Left . This) (Left . That) (\x y -> Right (x, y)))
-- | @'justThis' = preview '_This'@
justThis :: These a b -> Maybe a
justThis (This a) = Just a
justThis _ = Nothing
-- | @'justThat' = preview '_That'@
justThat :: These a b -> Maybe b
justThat (That x) = Just x
justThat _ = Nothing
-- | @'justThese' = preview '_These'@
justThese :: These a b -> Maybe (a, b)
justThese (These a x) = Just (a, x)
justThese _ = Nothing
isThis, isThat, isThese :: These a b -> Bool
-- | @'isThis' = 'isJust' . 'justThis'@
isThis = isJust . justThis
-- | @'isThat' = 'isJust' . 'justThat'@
isThat = isJust . justThat
-- | @'isThese' = 'isJust' . 'justThese'@
isThese = isJust . justThese
-- | 'Bifunctor' map.
mapThese :: (a -> c) -> (b -> d) -> These a b -> These c d
mapThese f _ (This a ) = This (f a)
mapThese _ g (That x) = That (g x)
mapThese f g (These a x) = These (f a) (g x)
-- | @'mapThis' = over 'here'@
mapThis :: (a -> c) -> These a b -> These c b
mapThis f = mapThese f id
-- | @'mapThat' = over 'there'@
mapThat :: (b -> d) -> These a b -> These a d
mapThat f = mapThese id f
-- | Select all 'This' constructors from a list.
catThis :: [These a b] -> [a]
catThis = mapMaybe justThis
-- | Select all 'That' constructors from a list.
catThat :: [These a b] -> [b]
catThat = mapMaybe justThat
-- | Select all 'These' constructors from a list.
catThese :: [These a b] -> [(a, b)]
catThese = mapMaybe justThese
-- | Select each constructor and partition them into separate lists.
partitionThese :: [These a b] -> ( [(a, b)], ([a], [b]) )
partitionThese [] = ([], ([], []))
partitionThese (These x y:xs) = first ((x, y):) $ partitionThese xs
partitionThese (This x :xs) = second (first (x:)) $ partitionThese xs
partitionThese (That y:xs) = second (second (y:)) $ partitionThese xs
-- $align
--
-- For zipping and unzipping of structures with 'These' values, see
-- "Data.Align".
instance (Semigroup a, Semigroup b) => Semigroup (These a b) where
This a <> This b = This (a <> b)
This a <> That y = These a y
This a <> These b y = These (a <> b) y
That x <> This b = These b x
That x <> That y = That (x <> y)
That x <> These b y = These b (x <> y)
These a x <> This b = These (a <> b) x
These a x <> That y = These a (x <> y)
These a x <> These b y = These (a <> b) (x <> y)
instance Functor (These a) where
fmap _ (This x) = This x
fmap f (That y) = That (f y)
fmap f (These x y) = These x (f y)
instance Foldable (These a) where
foldr f z = foldr f z . justThat
instance Traversable (These a) where
traverse _ (This a) = pure $ This a
traverse f (That x) = That <$> f x
traverse f (These a x) = These a <$> f x
sequenceA (This a) = pure $ This a
sequenceA (That x) = That <$> x
sequenceA (These a x) = These a <$> x
instance Bifunctor These where
bimap = mapThese
first = mapThis
second = mapThat
instance Bifoldable These where
bifold = these id id mappend
bifoldr f g z = these (`f` z) (`g` z) (\x y -> x `f` (y `g` z))
bifoldl f g z = these (z `f`) (z `g`) (\x y -> (z `f` x) `g` y)
instance Bifoldable1 These where
bifold1 = these id id (<>)
instance Bitraversable These where
bitraverse f _ (This x) = This <$> f x
bitraverse _ g (That x) = That <$> g x
bitraverse f g (These x y) = These <$> f x <*> g y
bimapM f _ (This x) = liftM This (f x)
bimapM _ g (That x) = liftM That (g x)
bimapM f g (These x y) = liftM2 These (f x) (g y)
instance Bitraversable1 These where
bitraverse1 f _ (This x) = This <$> f x
bitraverse1 _ g (That x) = That <$> g x
bitraverse1 f g (These x y) = These <$> f x <.> g y
instance (Monoid a) => Apply (These a) where
This a <.> _ = This a
That _ <.> This b = This b
That f <.> That x = That (f x)
That f <.> These b x = These b (f x)
These a _ <.> This b = This (mappend a b)
These a f <.> That x = These a (f x)
These a f <.> These b x = These (mappend a b) (f x)
instance (Monoid a) => Applicative (These a) where
pure = That
(<*>) = (<.>)
instance (Monoid a) => Bind (These a) where
This a >>- _ = This a
That x >>- k = k x
These a x >>- k = case k x of
This b -> This (mappend a b)
That y -> These a y
These b y -> These (mappend a b) y
instance (Monoid a) => Monad (These a) where
return = pure
(>>=) = (>>-)
| andrewthad/these | Data/These.hs | bsd-3-clause | 9,194 | 0 | 11 | 2,883 | 3,391 | 1,752 | 1,639 | 161 | 1 |
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Pos.Explorer.Web.Transform
( ExplorerProd
, runExplorerProd
, liftToExplorerProd
, explorerServeWebReal
, explorerPlugin
, notifierPlugin
) where
import Universum
import qualified Control.Exception.Safe as E
import Control.Monad.Except (MonadError (throwError))
import qualified Control.Monad.Reader as Mtl
import Servant.Server (Handler, hoistServer)
import Pos.Chain.Block (HasBlockConfiguration)
import Pos.Chain.Genesis as Genesis (Config (..))
import Pos.Chain.Ssc (HasSscConfiguration)
import Pos.Chain.Update (HasUpdateConfiguration)
import Pos.Configuration (HasNodeConfiguration)
import Pos.DB.Txp (MempoolExt, MonadTxpLocal (..))
import Pos.Infra.Diffusion.Types (Diffusion)
import Pos.Infra.Reporting (MonadReporting (..))
import Pos.Recovery ()
import Pos.Util.CompileInfo (HasCompileInfo)
import Pos.WorkMode (RealMode, RealModeContext (..))
import Pos.Explorer.BListener (ExplorerBListener,
runExplorerBListener)
import Pos.Explorer.ExtraContext (ExtraContext, ExtraContextT,
makeExtraCtx, runExtraContextT)
import Pos.Explorer.Socket.App (NotifierSettings, notifierApp)
import Pos.Explorer.Txp (ExplorerExtraModifier, eTxNormalize,
eTxProcessTransaction)
import Pos.Explorer.Web.Api (explorerApi)
import Pos.Explorer.Web.Server (explorerApp, explorerHandlers,
explorerServeImpl)
-----------------------------------------------------------------
-- Transformation to `Handler`
-----------------------------------------------------------------
type RealModeE = RealMode ExplorerExtraModifier
type ExplorerProd = ExtraContextT (ExplorerBListener RealModeE)
type instance MempoolExt ExplorerProd = ExplorerExtraModifier
instance MonadTxpLocal RealModeE where
txpNormalize = eTxNormalize
txpProcessTx = eTxProcessTransaction
instance MonadTxpLocal ExplorerProd where
txpNormalize pm txValRules = lift . lift . txpNormalize pm txValRules
txpProcessTx genesisConfig txpConfig = lift . lift . txpProcessTx genesisConfig txpConfig
-- | Use the 'RealMode' instance.
-- FIXME instance on a type synonym.
instance MonadReporting ExplorerProd where
report = lift . lift . report
runExplorerProd :: ExtraContext -> ExplorerProd a -> RealModeE a
runExplorerProd extraCtx = runExplorerBListener . runExtraContextT extraCtx
liftToExplorerProd :: RealModeE a -> ExplorerProd a
liftToExplorerProd = lift . lift
type HasExplorerConfiguration =
( HasBlockConfiguration
, HasNodeConfiguration
, HasUpdateConfiguration
, HasSscConfiguration
, HasCompileInfo
)
notifierPlugin
:: HasExplorerConfiguration
=> Genesis.Config
-> NotifierSettings
-> Diffusion ExplorerProd
-> ExplorerProd ()
notifierPlugin genesisConfig settings _ = notifierApp genesisConfig settings
explorerPlugin
:: HasExplorerConfiguration
=> Genesis.Config
-> Word16
-> Diffusion ExplorerProd
-> ExplorerProd ()
explorerPlugin genesisConfig = flip $ explorerServeWebReal genesisConfig
explorerServeWebReal
:: HasExplorerConfiguration
=> Genesis.Config
-> Diffusion ExplorerProd
-> Word16
-> ExplorerProd ()
explorerServeWebReal genesisConfig diffusion port = do
rctx <- ask
let handlers = explorerHandlers genesisConfig diffusion
server = hoistServer
explorerApi
(convertHandler genesisConfig rctx)
handlers
app = explorerApp (pure server)
explorerServeImpl app port
convertHandler
:: Genesis.Config
-> RealModeContext ExplorerExtraModifier
-> ExplorerProd a
-> Handler a
convertHandler genesisConfig rctx handler =
let extraCtx = makeExtraCtx genesisConfig
ioAction = realRunner $
runExplorerProd extraCtx
handler
in liftIO ioAction `E.catches` excHandlers
where
realRunner :: forall t . RealModeE t -> IO t
realRunner act = Mtl.runReaderT act rctx
excHandlers = [E.Handler catchServant]
catchServant = throwError
| input-output-hk/pos-haskell-prototype | explorer/src/Pos/Explorer/Web/Transform.hs | mit | 4,482 | 0 | 12 | 1,028 | 867 | 487 | 380 | -1 | -1 |
module RewriteLBNF where
-- Haskell module generated by the BNF converter
import AbsLBNF
transGrammar :: Grammar -> Grammar
transGrammar x = case x of
Grammar defs -> Grammar $ defs >>= transDef
transDef :: Def -> [Def]
transDef x = case x of
Rule label cat items -> [x, Internal (transLabel label) cat (addPos items)]
_ -> [x]
transLabel :: Label -> Label
transLabel x = case x of
LabNoP (Id id) -> LabNoP $ Id $ transIdent id
_ -> x
transIdent :: Ident -> Ident
transIdent x = case x of
Ident str -> Ident $ "Pos" ++ str
addPos is = NTerminal (IdCat (Ident "Span")) : is-- mkInt : mkInt : is
mkInt = NTerminal (IdCat (Ident "Integer"))
| juodaspaulius/clafer-old-customBNFC | src/Language/Clafer/Front/lbnf/RewriteLBNF.hs | mit | 667 | 0 | 11 | 150 | 256 | 131 | 125 | 18 | 2 |
{- |
Module : $Header$
Copyright : (c) Felix Gabriel Mance
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : provisional
Portability : portable
RDF syntax parser
-}
module RDF.Parse where
import Common.Parsec
import Common.Lexer
import Common.AnnoParser (newlineOrEof)
import Common.Token (criticalKeywords)
import Common.Id
import qualified Common.GlobalAnnotations as GA (PrefixMap)
import OWL2.AS
import OWL2.Parse hiding (stringLiteral, literal, skips, uriP)
import RDF.AS
import RDF.Symbols
import Data.Either
import qualified Data.Map as Map
import Text.ParserCombinators.Parsec
uriP :: CharParser st QName
uriP =
skips $ try $ checkWithUsing showQN uriQ $ \ q ->
not (null $ namePrefix q) || notElem (localPart q) criticalKeywords
-- * hets symbols parser
rdfEntityType :: CharParser st RDFEntityType
rdfEntityType = choice $ map (\ f -> keyword (show f) >> return f)
rdfEntityTypes
{- | parses an entity type (subject, predicate or object) followed by a
comma separated list of IRIs -}
rdfSymbItems :: GenParser Char st SymbItems
rdfSymbItems = do
ext <- optionMaybe rdfEntityType
iris <- rdfSymbs
return $ SymbItems ext iris
-- | parse a comma separated list of uris
rdfSymbs :: GenParser Char st [IRI]
rdfSymbs = uriP >>= \ u -> do
commaP `followedWith` uriP
us <- rdfSymbs
return $ u : us
<|> return [u]
-- | parse a possibly kinded list of comma separated symbol pairs
rdfSymbMapItems :: GenParser Char st SymbMapItems
rdfSymbMapItems = do
ext <- optionMaybe rdfEntityType
iris <- rdfSymbPairs
return $ SymbMapItems ext iris
-- | parse a comma separated list of uri pairs
rdfSymbPairs :: GenParser Char st [(IRI, Maybe IRI)]
rdfSymbPairs = uriPair >>= \ u -> do
commaP `followedWith` uriP
us <- rdfSymbPairs
return $ u : us
<|> return [u]
-- * turtle syntax parser
skips :: CharParser st a -> CharParser st a
skips = (<< skipMany
(forget space <|> parseComment <|> nestCommentOut <?> ""))
charOrQuoteEscape :: CharParser st String
charOrQuoteEscape = try (string "\\\"") <|> fmap return anyChar
longLiteral :: CharParser st (String, Bool)
longLiteral = do
string "\"\"\""
ls <- flat $ manyTill charOrQuoteEscape $ try $ string "\"\"\""
return (ls, True)
shortLiteral :: CharParser st (String, Bool)
shortLiteral = do
char '"'
ls <- flat $ manyTill charOrQuoteEscape $ try $ string "\""
return (ls, False)
stringLiteral :: CharParser st RDFLiteral
stringLiteral = do
(s, b) <- try longLiteral <|> shortLiteral
do
string cTypeS
d <- datatypeUri
return $ RDFLiteral b s $ Typed d
<|> do
string "@"
t <- skips $ optionMaybe languageTag
return $ RDFLiteral b s $ Untyped t
<|> skips (return $ RDFLiteral b s $ Typed $ mkQName "string")
literal :: CharParser st RDFLiteral
literal = do
f <- skips $ try floatingPointLit
<|> fmap decToFloat decimalLit
return $ RDFNumberLit f
<|> stringLiteral
parseBase :: CharParser st Base
parseBase = do
pkeyword "@base"
base <- skips uriP
skips $ char '.'
return $ Base base
parsePrefix :: CharParser st Prefix
parsePrefix = do
pkeyword "@prefix"
p <- skips (option "" prefix << char ':')
i <- skips uriP
skips $ char '.'
return $ PrefixR p i
parsePredicate :: CharParser st Predicate
parsePredicate = fmap Predicate $ skips uriP
parseSubject :: CharParser st Subject
parseSubject =
fmap Subject (skips uriP)
<|> fmap SubjectList
(between (skips $ char '[') (skips $ char ']') $ skips parsePredObjList)
<|> fmap SubjectCollection
(between (skips $ char '(') (skips $ char ')') $ many parseObject)
parseObject :: CharParser st Object
parseObject = fmap ObjectLiteral literal <|> fmap Object parseSubject
parsePredObjects :: CharParser st PredicateObjectList
parsePredObjects = do
pr <- parsePredicate
objs <- sepBy parseObject $ skips $ char ','
return $ PredicateObjectList pr objs
parsePredObjList :: CharParser st [PredicateObjectList]
parsePredObjList = sepEndBy parsePredObjects $ skips $ char ';'
parseTriples :: CharParser st Triples
parseTriples = do
s <- parseSubject
ls <- parsePredObjList
skips $ char '.'
return $ Triples s ls
parseComment :: CharParser st ()
parseComment = do
tryString "#"
forget $ skips $ manyTill anyChar newlineOrEof
parseStatement :: CharParser st Statement
parseStatement = fmap BaseStatement parseBase
<|> fmap PrefixStatement parsePrefix <|> fmap Statement parseTriples
basicSpec :: GA.PrefixMap -> CharParser st TurtleDocument
basicSpec pm = do
many parseComment
ls <- many parseStatement
let td = TurtleDocument
dummyQName (Map.map transIri $ convertPrefixMap pm) ls
-- return $ trace (show $ Map.union predefinedPrefixes (prefixMap td)) td
return td
where transIri s = QN "" s Full s nullRange
predefinedPrefixes :: RDFPrefixMap
predefinedPrefixes = Map.fromList $ zip
["rdf", "rdfs", "dc", "owl", "ex", "xsd"]
$ rights $ map (parse uriQ "")
[ "<http://www.w3.org/1999/02/22-rdf-syntax-ns#>"
, "<http://www.w3.org/2000/01/rdf-schema#>"
, "<http://purl.org/dc/elements/1.1/>"
, "<http://www.w3.org/2002/07/owl#>"
, "<http://www.example.org/>"
, "<http://www.w3.org/2001/XMLSchema#>" ]
| keithodulaigh/Hets | RDF/Parse.hs | gpl-2.0 | 5,396 | 0 | 14 | 1,135 | 1,553 | 764 | 789 | 138 | 1 |
{-|
A simple 'Amount' is some quantity of money, shares, or anything else.
It has a (possibly null) 'CommoditySymbol' and a numeric quantity:
@
$1
£-50
EUR 3.44
GOOG 500
1.5h
90 apples
0
@
It may also have an assigned 'Price', representing this amount's per-unit
or total cost in a different commodity. If present, this is rendered like
so:
@
EUR 2 \@ $1.50 (unit price)
EUR 2 \@\@ $3 (total price)
@
A 'MixedAmount' is zero or more simple amounts, so can represent multiple
commodities; this is the type most often used:
@
0
$50 + EUR 3
16h + $13.55 + AAPL 500 + 6 oranges
@
When a mixed amount has been \"normalised\", it has no more than one amount
in each commodity and no zero amounts; or it has just a single zero amount
and no others.
Limited arithmetic with simple and mixed amounts is supported, best used
with similar amounts since it mostly ignores assigned prices and commodity
exchange rates.
-}
{-# LANGUAGE CPP, StandaloneDeriving, RecordWildCards, OverloadedStrings #-}
module Hledger.Data.Amount (
-- * Amount
amount,
nullamt,
missingamt,
num,
usd,
eur,
gbp,
hrs,
at,
(@@),
amountWithCommodity,
-- ** arithmetic
costOfAmount,
divideAmount,
-- ** rendering
amountstyle,
showAmount,
cshowAmount,
showAmountWithZeroCommodity,
showAmountDebug,
showAmountWithoutPrice,
maxprecision,
maxprecisionwithpoint,
setAmountPrecision,
withPrecision,
canonicaliseAmount,
-- * MixedAmount
nullmixedamt,
missingmixedamt,
mixed,
amounts,
filterMixedAmount,
filterMixedAmountByCommodity,
normaliseMixedAmountSquashPricesForDisplay,
normaliseMixedAmount,
-- ** arithmetic
costOfMixedAmount,
divideMixedAmount,
averageMixedAmounts,
isNegativeAmount,
isNegativeMixedAmount,
isZeroAmount,
isReallyZeroAmount,
isZeroMixedAmount,
isReallyZeroMixedAmount,
isReallyZeroMixedAmountCost,
-- ** rendering
showMixedAmount,
showMixedAmountOneLine,
showMixedAmountDebug,
showMixedAmountWithoutPrice,
showMixedAmountOneLineWithoutPrice,
cshowMixedAmountWithoutPrice,
cshowMixedAmountOneLineWithoutPrice,
showMixedAmountWithZeroCommodity,
showMixedAmountWithPrecision,
setMixedAmountPrecision,
canonicaliseMixedAmount,
-- * misc.
ltraceamount,
tests_Hledger_Data_Amount
) where
import Data.Char (isDigit)
import Data.Decimal (roundTo)
import Data.Function (on)
import Data.List
import Data.Map (findWithDefault)
import Data.Maybe
-- import Data.Text (Text)
import qualified Data.Text as T
import Test.HUnit
import Text.Printf
import qualified Data.Map as M
import Hledger.Data.Types
import Hledger.Data.Commodity
import Hledger.Utils
deriving instance Show MarketPrice
amountstyle = AmountStyle L False 0 (Just '.') Nothing
-------------------------------------------------------------------------------
-- Amount
instance Show Amount where
show _a@Amount{..}
-- debugLevel < 2 = showAmountWithoutPrice a
-- debugLevel < 3 = showAmount a
| debugLevel < 6 =
printf "Amount {acommodity=%s, aquantity=%s, ..}" (show acommodity) (show aquantity)
| otherwise = --showAmountDebug a
printf "Amount {acommodity=%s, aquantity=%s, aprice=%s, astyle=%s}" (show acommodity) (show aquantity) (showPriceDebug aprice) (show astyle)
instance Num Amount where
abs a@Amount{aquantity=q} = a{aquantity=abs q}
signum a@Amount{aquantity=q} = a{aquantity=signum q}
fromInteger i = nullamt{aquantity=fromInteger i}
negate a@Amount{aquantity=q} = a{aquantity=(-q)}
(+) = similarAmountsOp (+)
(-) = similarAmountsOp (-)
(*) = similarAmountsOp (*)
-- | The empty simple amount.
amount, nullamt :: Amount
amount = Amount{acommodity="", aquantity=0, aprice=NoPrice, astyle=amountstyle, amultiplier=False}
nullamt = amount
-- | A temporary value for parsed transactions which had no amount specified.
missingamt :: Amount
missingamt = amount{acommodity="AUTO"}
-- Handy amount constructors for tests.
-- usd/eur/gbp round their argument to a whole number of pennies/cents.
num n = amount{acommodity="", aquantity=n}
hrs n = amount{acommodity="h", aquantity=n, astyle=amountstyle{asprecision=2, ascommodityside=R}}
usd n = amount{acommodity="$", aquantity=roundTo 2 n, astyle=amountstyle{asprecision=2}}
eur n = amount{acommodity="€", aquantity=roundTo 2 n, astyle=amountstyle{asprecision=2}}
gbp n = amount{acommodity="£", aquantity=roundTo 2 n, astyle=amountstyle{asprecision=2}}
amt `at` priceamt = amt{aprice=UnitPrice priceamt}
amt @@ priceamt = amt{aprice=TotalPrice priceamt}
-- | Apply a binary arithmetic operator to two amounts, which should
-- be in the same commodity if non-zero (warning, this is not checked).
-- A zero result keeps the commodity of the second amount.
-- The result's display style is that of the second amount, with
-- precision set to the highest of either amount.
-- Prices are ignored and discarded.
-- Remember: the caller is responsible for ensuring both amounts have the same commodity.
similarAmountsOp :: (Quantity -> Quantity -> Quantity) -> Amount -> Amount -> Amount
similarAmountsOp op Amount{acommodity=_, aquantity=q1, astyle=AmountStyle{asprecision=p1}}
Amount{acommodity=c2, aquantity=q2, astyle=s2@AmountStyle{asprecision=p2}} =
-- trace ("a1:"++showAmountDebug a1) $ trace ("a2:"++showAmountDebug a2) $ traceWith (("= :"++).showAmountDebug)
amount{acommodity=c2, aquantity=q1 `op` q2, astyle=s2{asprecision=max p1 p2}}
-- c1==c2 || q1==0 || q2==0 =
-- otherwise = error "tried to do simple arithmetic with amounts in different commodities"
-- | Convert an amount to the specified commodity, ignoring and discarding
-- any assigned prices and assuming an exchange rate of 1.
amountWithCommodity :: CommoditySymbol -> Amount -> Amount
amountWithCommodity c a = a{acommodity=c, aprice=NoPrice}
-- | Convert an amount to the commodity of its assigned price, if any. Notes:
--
-- - price amounts must be MixedAmounts with exactly one component Amount (or there will be a runtime error) XXX
--
-- - price amounts should be positive, though this is not currently enforced
costOfAmount :: Amount -> Amount
costOfAmount a@Amount{aquantity=q, aprice=price} =
case price of
NoPrice -> a
UnitPrice p@Amount{aquantity=pq} -> p{aquantity=pq * q}
TotalPrice p@Amount{aquantity=pq} -> p{aquantity=pq * signum q}
-- | Divide an amount's quantity by a constant.
divideAmount :: Amount -> Quantity -> Amount
divideAmount a@Amount{aquantity=q} d = a{aquantity=q/d}
-- | Is this amount negative ? The price is ignored.
isNegativeAmount :: Amount -> Bool
isNegativeAmount Amount{aquantity=q} = q < 0
digits = "123456789" :: String
-- | Does this amount appear to be zero when displayed with its given precision ?
isZeroAmount :: Amount -> Bool
isZeroAmount a -- a==missingamt = False
| otherwise = (null . filter (`elem` digits) . showAmountWithoutPriceOrCommodity) a
-- | Is this amount "really" zero, regardless of the display precision ?
isReallyZeroAmount :: Amount -> Bool
isReallyZeroAmount Amount{aquantity=q} = q == 0
-- | Get the string representation of an amount, based on its commodity's
-- display settings except using the specified precision.
showAmountWithPrecision :: Int -> Amount -> String
showAmountWithPrecision p = showAmount . setAmountPrecision p
-- | Set an amount's display precision.
setAmountPrecision :: Int -> Amount -> Amount
setAmountPrecision p a@Amount{astyle=s} = a{astyle=s{asprecision=p}}
-- | Set an amount's display precision, flipped.
withPrecision :: Amount -> Int -> Amount
withPrecision = flip setAmountPrecision
-- | Get a string representation of an amount for debugging,
-- appropriate to the current debug level. 9 shows maximum detail.
showAmountDebug :: Amount -> String
showAmountDebug Amount{acommodity="AUTO"} = "(missing)"
showAmountDebug Amount{..} = printf "Amount {acommodity=%s, aquantity=%s, aprice=%s, astyle=%s}" (show acommodity) (show aquantity) (showPriceDebug aprice) (show astyle)
-- | Get the string representation of an amount, without any \@ price.
showAmountWithoutPrice :: Amount -> String
showAmountWithoutPrice a = showAmount a{aprice=NoPrice}
-- | Colour version.
cshowAmountWithoutPrice :: Amount -> String
cshowAmountWithoutPrice a = cshowAmount a{aprice=NoPrice}
-- | Get the string representation of an amount, without any price or commodity symbol.
showAmountWithoutPriceOrCommodity :: Amount -> String
showAmountWithoutPriceOrCommodity a = showAmount a{acommodity="", aprice=NoPrice}
showPrice :: Price -> String
showPrice NoPrice = ""
showPrice (UnitPrice pa) = " @ " ++ showAmount pa
showPrice (TotalPrice pa) = " @@ " ++ showAmount pa
showPriceDebug :: Price -> String
showPriceDebug NoPrice = ""
showPriceDebug (UnitPrice pa) = " @ " ++ showAmountDebug pa
showPriceDebug (TotalPrice pa) = " @@ " ++ showAmountDebug pa
-- | Get the string representation of an amount, based on its
-- commodity's display settings. String representations equivalent to
-- zero are converted to just \"0\". The special "missing" amount is
-- displayed as the empty string.
showAmount :: Amount -> String
showAmount = showAmountHelper False
-- | Colour version. For a negative amount, adds ANSI codes to change the colour,
-- currently to hard-coded red.
cshowAmount :: Amount -> String
cshowAmount a =
(if isNegativeAmount a then color Dull Red else id) $
showAmountHelper False a
showAmountHelper :: Bool -> Amount -> String
showAmountHelper _ Amount{acommodity="AUTO"} = ""
showAmountHelper showzerocommodity a@(Amount{acommodity=c, aprice=p, astyle=AmountStyle{..}}) =
case ascommodityside of
L -> printf "%s%s%s%s" (T.unpack c') space quantity' price
R -> printf "%s%s%s%s" quantity' space (T.unpack c') price
where
quantity = showamountquantity a
displayingzero = null $ filter (`elem` digits) $ quantity
(quantity',c') | displayingzero && not showzerocommodity = ("0","")
| otherwise = (quantity, quoteCommoditySymbolIfNeeded c)
space = if (not (T.null c') && ascommodityspaced) then " " else "" :: String
price = showPrice p
-- | Like showAmount, but show a zero amount's commodity if it has one.
showAmountWithZeroCommodity :: Amount -> String
showAmountWithZeroCommodity = showAmountHelper True
-- | Get the string representation of the number part of of an amount,
-- using the display settings from its commodity.
showamountquantity :: Amount -> String
showamountquantity Amount{aquantity=q, astyle=AmountStyle{asprecision=p, asdecimalpoint=mdec, asdigitgroups=mgrps}} =
punctuatenumber (fromMaybe '.' mdec) mgrps $ qstr
where
-- isint n = fromIntegral (round n) == n
qstr -- p == maxprecision && isint q = printf "%d" (round q::Integer)
| p == maxprecisionwithpoint = show q
| p == maxprecision = chopdotzero $ show q
| otherwise = show $ roundTo (fromIntegral p) q
-- | Replace a number string's decimal point with the specified character,
-- and add the specified digit group separators. The last digit group will
-- be repeated as needed.
punctuatenumber :: Char -> Maybe DigitGroupStyle -> String -> String
punctuatenumber dec mgrps s = sign ++ reverse (applyDigitGroupStyle mgrps (reverse int)) ++ frac''
where
(sign,num) = break isDigit s
(int,frac) = break (=='.') num
frac' = dropWhile (=='.') frac
frac'' | null frac' = ""
| otherwise = dec:frac'
applyDigitGroupStyle :: Maybe DigitGroupStyle -> String -> String
applyDigitGroupStyle Nothing s = s
applyDigitGroupStyle (Just (DigitGroups c gs)) s = addseps (repeatLast gs) s
where
addseps [] s = s
addseps (g:gs) s
| length s <= g = s
| otherwise = let (part,rest) = splitAt g s
in part ++ [c] ++ addseps gs rest
repeatLast [] = []
repeatLast gs = init gs ++ repeat (last gs)
chopdotzero str = reverse $ case reverse str of
'0':'.':s -> s
s -> s
-- | For rendering: a special precision value which means show all available digits.
maxprecision :: Int
maxprecision = 999998
-- | For rendering: a special precision value which forces display of a decimal point.
maxprecisionwithpoint :: Int
maxprecisionwithpoint = 999999
-- like journalCanonicaliseAmounts
-- | Canonicalise an amount's display style using the provided commodity style map.
canonicaliseAmount :: M.Map CommoditySymbol AmountStyle -> Amount -> Amount
canonicaliseAmount styles a@Amount{acommodity=c, astyle=s} = a{astyle=s'}
where
s' = findWithDefault s c styles
-------------------------------------------------------------------------------
-- MixedAmount
instance Show MixedAmount where
show
| debugLevel < 3 = intercalate "\\n" . lines . showMixedAmountWithoutPrice
-- debugLevel < 6 = intercalate "\\n" . lines . showMixedAmount
| otherwise = showMixedAmountDebug
instance Num MixedAmount where
fromInteger i = Mixed [fromInteger i]
negate (Mixed as) = Mixed $ map negate as
(+) (Mixed as) (Mixed bs) = normaliseMixedAmount $ Mixed $ as ++ bs
(*) = error' "error, mixed amounts do not support multiplication"
abs = error' "error, mixed amounts do not support abs"
signum = error' "error, mixed amounts do not support signum"
-- | The empty mixed amount.
nullmixedamt :: MixedAmount
nullmixedamt = Mixed []
-- | A temporary value for parsed transactions which had no amount specified.
missingmixedamt :: MixedAmount
missingmixedamt = Mixed [missingamt]
-- | Convert amounts in various commodities into a normalised MixedAmount.
mixed :: [Amount] -> MixedAmount
mixed = normaliseMixedAmount . Mixed
-- | Simplify a mixed amount's component amounts:
--
-- * amounts in the same commodity are combined unless they have different prices or total prices
--
-- * multiple zero amounts, all with the same non-null commodity, are replaced by just the last of them, preserving the commodity and amount style (all but the last zero amount are discarded)
--
-- * multiple zero amounts with multiple commodities, or no commodities, are replaced by one commodity-less zero amount
--
-- * an empty amount list is replaced by one commodity-less zero amount
--
-- * the special "missing" mixed amount remains unchanged
--
normaliseMixedAmount :: MixedAmount -> MixedAmount
normaliseMixedAmount = normaliseHelper False
normaliseHelper :: Bool -> MixedAmount -> MixedAmount
normaliseHelper squashprices (Mixed as)
| missingamt `elem` as = missingmixedamt -- missingamt should always be alone, but detect it even if not
| null nonzeros = Mixed [newzero]
| otherwise = Mixed nonzeros
where
newzero = case filter (/= "") (map acommodity zeros) of
_:_ -> last zeros
_ -> nullamt
(zeros, nonzeros) = partition isReallyZeroAmount $
map sumSimilarAmountsUsingFirstPrice $
groupBy groupfn $
sortBy sortfn $
as
sortfn | squashprices = compare `on` acommodity
| otherwise = compare `on` \a -> (acommodity a, aprice a)
groupfn | squashprices = (==) `on` acommodity
| otherwise = \a1 a2 -> acommodity a1 == acommodity a2 && combinableprices a1 a2
combinableprices Amount{aprice=NoPrice} Amount{aprice=NoPrice} = True
combinableprices Amount{aprice=UnitPrice p1} Amount{aprice=UnitPrice p2} = p1 == p2
combinableprices _ _ = False
tests_normaliseMixedAmount = [
"normaliseMixedAmount" ~: do
-- assertEqual "missing amount is discarded" (Mixed [nullamt]) (normaliseMixedAmount $ Mixed [usd 0, missingamt])
assertEqual "any missing amount means a missing mixed amount" missingmixedamt (normaliseMixedAmount $ Mixed [usd 0, missingamt])
assertEqual "unpriced same-commodity amounts are combined" (Mixed [usd 2]) (normaliseMixedAmount $ Mixed [usd 0, usd 2])
-- amounts with same unit price are combined
normaliseMixedAmount (Mixed [usd 1 `at` eur 1, usd 1 `at` eur 1]) `is` Mixed [usd 2 `at` eur 1]
-- amounts with different unit prices are not combined
normaliseMixedAmount (Mixed [usd 1 `at` eur 1, usd 1 `at` eur 2]) `is` Mixed [usd 1 `at` eur 1, usd 1 `at` eur 2]
-- amounts with total prices are not combined
normaliseMixedAmount (Mixed [usd 1 @@ eur 1, usd 1 @@ eur 1]) `is` Mixed [usd 1 @@ eur 1, usd 1 @@ eur 1]
]
-- | Like normaliseMixedAmount, but combine each commodity's amounts
-- into just one by throwing away all prices except the first. This is
-- only used as a rendering helper, and could show a misleading price.
normaliseMixedAmountSquashPricesForDisplay :: MixedAmount -> MixedAmount
normaliseMixedAmountSquashPricesForDisplay = normaliseHelper True
tests_normaliseMixedAmountSquashPricesForDisplay = [
"normaliseMixedAmountSquashPricesForDisplay" ~: do
normaliseMixedAmountSquashPricesForDisplay (Mixed []) `is` Mixed [nullamt]
assertBool "" $ isZeroMixedAmount $ normaliseMixedAmountSquashPricesForDisplay
(Mixed [usd 10
,usd 10 @@ eur 7
,usd (-10)
,usd (-10) @@ eur 7
])
]
-- | Sum same-commodity amounts in a lossy way, applying the first
-- price to the result and discarding any other prices. Only used as a
-- rendering helper.
sumSimilarAmountsUsingFirstPrice :: [Amount] -> Amount
sumSimilarAmountsUsingFirstPrice [] = nullamt
sumSimilarAmountsUsingFirstPrice as = (sumStrict as){aprice=aprice $ head as}
-- -- | Sum same-commodity amounts. If there were different prices, set
-- -- the price to a special marker indicating "various". Only used as a
-- -- rendering helper.
-- sumSimilarAmountsNotingPriceDifference :: [Amount] -> Amount
-- sumSimilarAmountsNotingPriceDifference [] = nullamt
-- sumSimilarAmountsNotingPriceDifference as = undefined
-- | Get a mixed amount's component amounts.
amounts :: MixedAmount -> [Amount]
amounts (Mixed as) = as
-- | Filter a mixed amount's component amounts by a predicate.
filterMixedAmount :: (Amount -> Bool) -> MixedAmount -> MixedAmount
filterMixedAmount p (Mixed as) = Mixed $ filter p as
-- | Return an unnormalised MixedAmount containing exactly one Amount
-- with the specified commodity and the quantity of that commodity
-- found in the original. NB if Amount's quantity is zero it will be
-- discarded next time the MixedAmount gets normalised.
filterMixedAmountByCommodity :: CommoditySymbol -> MixedAmount -> MixedAmount
filterMixedAmountByCommodity c (Mixed as) = Mixed as'
where
as' = case filter ((==c) . acommodity) as of
[] -> [nullamt{acommodity=c}]
as'' -> [sum as'']
-- | Convert a mixed amount's component amounts to the commodity of their
-- assigned price, if any.
costOfMixedAmount :: MixedAmount -> MixedAmount
costOfMixedAmount (Mixed as) = Mixed $ map costOfAmount as
-- | Divide a mixed amount's quantities by a constant.
divideMixedAmount :: MixedAmount -> Quantity -> MixedAmount
divideMixedAmount (Mixed as) d = Mixed $ map (flip divideAmount d) as
-- | Calculate the average of some mixed amounts.
averageMixedAmounts :: [MixedAmount] -> MixedAmount
averageMixedAmounts [] = 0
averageMixedAmounts as = sum as `divideMixedAmount` fromIntegral (length as)
-- | Is this mixed amount negative, if it can be normalised to a single commodity ?
isNegativeMixedAmount :: MixedAmount -> Maybe Bool
isNegativeMixedAmount m = case as of [a] -> Just $ isNegativeAmount a
_ -> Nothing
where as = amounts $ normaliseMixedAmountSquashPricesForDisplay m
-- | Does this mixed amount appear to be zero when displayed with its given precision ?
isZeroMixedAmount :: MixedAmount -> Bool
isZeroMixedAmount = all isZeroAmount . amounts . normaliseMixedAmountSquashPricesForDisplay
-- | Is this mixed amount "really" zero ? See isReallyZeroAmount.
isReallyZeroMixedAmount :: MixedAmount -> Bool
isReallyZeroMixedAmount = all isReallyZeroAmount . amounts . normaliseMixedAmountSquashPricesForDisplay
-- | Is this mixed amount "really" zero, after converting to cost
-- commodities where possible ?
isReallyZeroMixedAmountCost :: MixedAmount -> Bool
isReallyZeroMixedAmountCost = isReallyZeroMixedAmount . costOfMixedAmount
-- -- | MixedAmount derived Eq instance in Types.hs doesn't know that we
-- -- want $0 = EUR0 = 0. Yet we don't want to drag all this code over there.
-- -- For now, use this when cross-commodity zero equality is important.
-- mixedAmountEquals :: MixedAmount -> MixedAmount -> Bool
-- mixedAmountEquals a b = amounts a' == amounts b' || (isZeroMixedAmount a' && isZeroMixedAmount b')
-- where a' = normaliseMixedAmountSquashPricesForDisplay a
-- b' = normaliseMixedAmountSquashPricesForDisplay b
-- | Get the string representation of a mixed amount, after
-- normalising it to one amount per commodity. Assumes amounts have
-- no or similar prices, otherwise this can show misleading prices.
showMixedAmount :: MixedAmount -> String
showMixedAmount = showMixedAmountHelper False False
-- | Like showMixedAmount, but zero amounts are shown with their
-- commodity if they have one.
showMixedAmountWithZeroCommodity :: MixedAmount -> String
showMixedAmountWithZeroCommodity = showMixedAmountHelper True False
-- | Get the one-line string representation of a mixed amount.
showMixedAmountOneLine :: MixedAmount -> String
showMixedAmountOneLine = showMixedAmountHelper False True
showMixedAmountHelper :: Bool -> Bool -> MixedAmount -> String
showMixedAmountHelper showzerocommodity useoneline m =
join $ map showamt $ amounts $ normaliseMixedAmountSquashPricesForDisplay m
where
join | useoneline = intercalate ", "
| otherwise = vConcatRightAligned
showamt | showzerocommodity = showAmountWithZeroCommodity
| otherwise = showAmount
-- | Compact labelled trace of a mixed amount, for debugging.
ltraceamount :: String -> MixedAmount -> MixedAmount
ltraceamount s = traceWith (((s ++ ": ") ++).showMixedAmount)
-- | Set the display precision in the amount's commodities.
setMixedAmountPrecision :: Int -> MixedAmount -> MixedAmount
setMixedAmountPrecision p (Mixed as) = Mixed $ map (setAmountPrecision p) as
-- | Get the string representation of a mixed amount, showing each of its
-- component amounts with the specified precision, ignoring their
-- commoditys' display precision settings.
showMixedAmountWithPrecision :: Int -> MixedAmount -> String
showMixedAmountWithPrecision p m =
vConcatRightAligned $ map (showAmountWithPrecision p) $ amounts $ normaliseMixedAmountSquashPricesForDisplay m
-- | Get an unambiguous string representation of a mixed amount for debugging.
showMixedAmountDebug :: MixedAmount -> String
showMixedAmountDebug m | m == missingmixedamt = "(missing)"
| otherwise = printf "Mixed [%s]" as
where as = intercalate "\n " $ map showAmountDebug $ amounts m
-- | Get the string representation of a mixed amount, but without
-- any \@ prices.
showMixedAmountWithoutPrice :: MixedAmount -> String
showMixedAmountWithoutPrice m = concat $ intersperse "\n" $ map showfixedwidth as
where
(Mixed as) = normaliseMixedAmountSquashPricesForDisplay $ stripPrices m
stripPrices (Mixed as) = Mixed $ map stripprice as where stripprice a = a{aprice=NoPrice}
width = maximum $ map (length . showAmount) as
showfixedwidth = printf (printf "%%%ds" width) . showAmountWithoutPrice
-- | Colour version.
cshowMixedAmountWithoutPrice :: MixedAmount -> String
cshowMixedAmountWithoutPrice m = concat $ intersperse "\n" $ map showamt as
where
(Mixed as) = normaliseMixedAmountSquashPricesForDisplay $ stripPrices m
stripPrices (Mixed as) = Mixed $ map stripprice as where stripprice a = a{aprice=NoPrice}
width = maximum $ map (length . showAmount) as
showamt a =
(if isNegativeAmount a then color Dull Red else id) $
printf (printf "%%%ds" width) $ showAmountWithoutPrice a
-- | Get the one-line string representation of a mixed amount, but without
-- any \@ prices.
showMixedAmountOneLineWithoutPrice :: MixedAmount -> String
showMixedAmountOneLineWithoutPrice m = concat $ intersperse ", " $ map showAmountWithoutPrice as
where
(Mixed as) = normaliseMixedAmountSquashPricesForDisplay $ stripPrices m
stripPrices (Mixed as) = Mixed $ map stripprice as where stripprice a = a{aprice=NoPrice}
-- | Colour version.
cshowMixedAmountOneLineWithoutPrice :: MixedAmount -> String
cshowMixedAmountOneLineWithoutPrice m = concat $ intersperse ", " $ map cshowAmountWithoutPrice as
where
(Mixed as) = normaliseMixedAmountSquashPricesForDisplay $ stripPrices m
stripPrices (Mixed as) = Mixed $ map stripprice as where stripprice a = a{aprice=NoPrice}
-- | Canonicalise a mixed amount's display styles using the provided commodity style map.
canonicaliseMixedAmount :: M.Map CommoditySymbol AmountStyle -> MixedAmount -> MixedAmount
canonicaliseMixedAmount styles (Mixed as) = Mixed $ map (canonicaliseAmount styles) as
-------------------------------------------------------------------------------
-- misc
tests_Hledger_Data_Amount = TestList $
tests_normaliseMixedAmount
++ tests_normaliseMixedAmountSquashPricesForDisplay
++ [
-- Amount
"costOfAmount" ~: do
costOfAmount (eur 1) `is` eur 1
costOfAmount (eur 2){aprice=UnitPrice $ usd 2} `is` usd 4
costOfAmount (eur 1){aprice=TotalPrice $ usd 2} `is` usd 2
costOfAmount (eur (-1)){aprice=TotalPrice $ usd 2} `is` usd (-2)
,"isZeroAmount" ~: do
assertBool "" $ isZeroAmount $ amount
assertBool "" $ isZeroAmount $ usd 0
,"negating amounts" ~: do
let a = usd 1
negate a `is` a{aquantity=(-1)}
let b = (usd 1){aprice=UnitPrice $ eur 2}
negate b `is` b{aquantity=(-1)}
,"adding amounts without prices" ~: do
let a1 = usd 1.23
let a2 = usd (-1.23)
let a3 = usd (-1.23)
(a1 + a2) `is` usd 0
(a1 + a3) `is` usd 0
(a2 + a3) `is` usd (-2.46)
(a3 + a3) `is` usd (-2.46)
sum [a1,a2,a3,-a3] `is` usd 0
-- highest precision is preserved
let ap1 = usd 1 `withPrecision` 1
ap3 = usd 1 `withPrecision` 3
(asprecision $ astyle $ sum [ap1,ap3]) `is` 3
(asprecision $ astyle $ sum [ap3,ap1]) `is` 3
-- adding different commodities assumes conversion rate 1
assertBool "" $ isZeroAmount (a1 - eur 1.23)
,"showAmount" ~: do
showAmount (usd 0 + gbp 0) `is` "0"
-- MixedAmount
,"adding mixed amounts to zero, the commodity and amount style are preserved" ~: do
(sum $ map (Mixed . (:[]))
[usd 1.25
,usd (-1) `withPrecision` 3
,usd (-0.25)
])
`is` Mixed [usd 0 `withPrecision` 3]
,"adding mixed amounts with total prices" ~: do
(sum $ map (Mixed . (:[]))
[usd 1 @@ eur 1
,usd (-2) @@ eur 1
])
`is` (Mixed [usd 1 @@ eur 1
,usd (-2) @@ eur 1
])
,"showMixedAmount" ~: do
showMixedAmount (Mixed [usd 1]) `is` "$1.00"
showMixedAmount (Mixed [usd 1 `at` eur 2]) `is` "$1.00 @ €2.00"
showMixedAmount (Mixed [usd 0]) `is` "0"
showMixedAmount (Mixed []) `is` "0"
showMixedAmount missingmixedamt `is` ""
,"showMixedAmountWithoutPrice" ~: do
let a = usd 1 `at` eur 2
showMixedAmountWithoutPrice (Mixed [a]) `is` "$1.00"
showMixedAmountWithoutPrice (Mixed [a, (-a)]) `is` "0"
]
| ony/hledger | hledger-lib/Hledger/Data/Amount.hs | gpl-3.0 | 27,731 | 0 | 18 | 5,442 | 6,116 | 3,284 | 2,832 | 385 | 4 |
{-# LANGUAGE CPP, MagicHash #-}
{-# OPTIONS_GHC -funbox-strict-fields #-}
--
-- (c) The University of Glasgow 2002-2006
--
-- | ByteCodeInstrs: Bytecode instruction definitions
module ETA.Interactive.ByteCodeInstr (
BCInstr(..), ProtoBCO(..), bciStackUse, BreakInfo (..)
) where
#include "HsVersions.h"
import ETA.Interactive.ByteCodeItbls ( ItblPtr )
import ETA.CodeGen.ArgRep
import ETA.Core.PprCore
import ETA.Types.Type
import ETA.Utils.Outputable
import ETA.Utils.FastString
import ETA.BasicTypes.Name
import ETA.BasicTypes.Id
import ETA.Core.CoreSyn
import ETA.BasicTypes.Literal
import ETA.BasicTypes.DataCon
-- import ETA.BasicTypes.Var
import ETA.BasicTypes.VarSet
import ETA.Prelude.PrimOp
import ETA.BasicTypes.Module (Module)
import GHC.Exts
import Data.Word
-- ----------------------------------------------------------------------------
-- Bytecode instructions
data ProtoBCO a
= ProtoBCO {
protoBCOName :: a, -- name, in some sense
protoBCOInstrs :: [BCInstr], -- instrs
-- arity and GC info
protoBCOBitmap :: [Int],-- TODO:[StgWord],
protoBCOBitmapSize :: Word16,
protoBCOArity :: Int,
-- what the BCO came from
protoBCOExpr :: Either [AnnAlt Id VarSet] (AnnExpr Id VarSet),
-- malloc'd pointers
protoBCOPtrs :: [Either ItblPtr (Ptr ())]
}
type LocalLabel = Word16
data BCInstr
-- Messing with the stack
= STKCHECK Word
-- Push locals (existing bits of the stack)
| PUSH_L !Word16{-offset-}
| PUSH_LL !Word16 !Word16{-2 offsets-}
| PUSH_LLL !Word16 !Word16 !Word16{-3 offsets-}
-- Push a ptr (these all map to PUSH_G really)
| PUSH_G Name
| PUSH_PRIMOP PrimOp
| PUSH_BCO (ProtoBCO Name)
-- Push an alt continuation
| PUSH_ALTS (ProtoBCO Name)
| PUSH_ALTS_UNLIFTED (ProtoBCO Name) ArgRep
-- Pushing literals
| PUSH_UBX (Either Literal (Ptr ())) Word16
-- push this int/float/double/addr, on the stack. Word16
-- is # of words to copy from literal pool. Eitherness reflects
-- the difficulty of dealing with MachAddr here, mostly due to
-- the excessive (and unnecessary) restrictions imposed by the
-- designers of the new Foreign library. In particular it is
-- quite impossible to convert an Addr to any other integral
-- type, and it appears impossible to get hold of the bits of
-- an addr, even though we need to assemble BCOs.
-- various kinds of application
| PUSH_APPLY_N
| PUSH_APPLY_V
| PUSH_APPLY_F
| PUSH_APPLY_D
| PUSH_APPLY_L
| PUSH_APPLY_P
| PUSH_APPLY_PP
| PUSH_APPLY_PPP
| PUSH_APPLY_PPPP
| PUSH_APPLY_PPPPP
| PUSH_APPLY_PPPPPP
| SLIDE Word16{-this many-} Word16{-down by this much-}
-- To do with the heap
| ALLOC_AP !Word16 -- make an AP with this many payload words
| ALLOC_AP_NOUPD !Word16 -- make an AP_NOUPD with this many payload words
| ALLOC_PAP !Word16 !Word16 -- make a PAP with this arity / payload words
| MKAP !Word16{-ptr to AP is this far down stack-} !Word16{-number of words-}
| MKPAP !Word16{-ptr to PAP is this far down stack-} !Word16{-number of words-}
| UNPACK !Word16 -- unpack N words from t.o.s Constr
| PACK DataCon !Word16
-- after assembly, the DataCon is an index into the
-- itbl array
-- For doing case trees
| LABEL LocalLabel
| TESTLT_I Int LocalLabel
| TESTEQ_I Int LocalLabel
| TESTLT_W Word LocalLabel
| TESTEQ_W Word LocalLabel
| TESTLT_F Float LocalLabel
| TESTEQ_F Float LocalLabel
| TESTLT_D Double LocalLabel
| TESTEQ_D Double LocalLabel
-- The Word16 value is a constructor number and therefore
-- stored in the insn stream rather than as an offset into
-- the literal pool.
| TESTLT_P Word16 LocalLabel
| TESTEQ_P Word16 LocalLabel
| CASEFAIL
| JMP LocalLabel
-- For doing calls to C (via glue code generated by libffi)
| CCALL Word16 -- stack frame size
(Ptr ()) -- addr of the glue code
Word16 -- whether or not the call is interruptible
-- (XXX: inefficient, but I don't know
-- what the alignment constraints are.)
-- For doing magic ByteArray passing to foreign calls
| SWIZZLE Word16 -- to the ptr N words down the stack,
Word16 -- add M (interpreted as a signed 16-bit entity)
-- To Infinity And Beyond
| ENTER
| RETURN -- return a lifted value
| RETURN_UBX ArgRep -- return an unlifted value, here's its rep
-- Breakpoints
| BRK_FUN (MutableByteArray# RealWorld) Word16 BreakInfo
data BreakInfo
= BreakInfo
{ breakInfo_module :: Module
, breakInfo_number :: {-# UNPACK #-} !Int
, breakInfo_vars :: [(Id,Word16)]
, breakInfo_resty :: Type
}
instance Outputable BreakInfo where
ppr info = text "BreakInfo" <+>
parens (ppr (breakInfo_module info) <+>
ppr (breakInfo_number info) <+>
ppr (breakInfo_vars info) <+>
ppr (breakInfo_resty info))
-- -----------------------------------------------------------------------------
-- Printing bytecode instructions
instance Outputable a => Outputable (ProtoBCO a) where
ppr (ProtoBCO name instrs bitmap bsize arity origin malloced)
= (text "ProtoBCO" <+> ppr name <> char '#' <> int arity
<+> text (show malloced) <> colon)
$$ nest 3 (case origin of
Left alts -> vcat (zipWith (<+>) (char '{' : repeat (char ';'))
(map (pprCoreAltShort.deAnnAlt) alts)) <+> char '}'
Right rhs -> pprCoreExprShort (deAnnotate rhs))
$$ nest 3 (text "bitmap: " <+> text (show bsize) <+> ppr bitmap)
$$ nest 3 (vcat (map ppr instrs))
-- Print enough of the Core expression to enable the reader to find
-- the expression in the -ddump-prep output. That is, we need to
-- include at least a binder.
pprCoreExprShort :: CoreExpr -> SDoc
pprCoreExprShort expr@(Lam _ _)
= let
(bndrs, _) = collectBinders expr
in
char '\\' <+> sep (map (pprBndr LambdaBind) bndrs) <+> arrow <+> ptext (sLit "...")
pprCoreExprShort (Case _expr var _ty _alts)
= ptext (sLit "case of") <+> ppr var
pprCoreExprShort (Let (NonRec x _) _) = ptext (sLit "let") <+> ppr x <+> ptext (sLit ("= ... in ..."))
pprCoreExprShort (Let (Rec bs) _) = ptext (sLit "let {") <+> ppr (fst (head bs)) <+> ptext (sLit ("= ...; ... } in ..."))
pprCoreExprShort (Tick t e) = ppr t <+> pprCoreExprShort e
pprCoreExprShort (Cast e _) = pprCoreExprShort e <+> ptext (sLit "`cast` T")
pprCoreExprShort e = pprCoreExpr e
pprCoreAltShort :: CoreAlt -> SDoc
pprCoreAltShort (con, args, expr) = ppr con <+> sep (map ppr args) <+> ptext (sLit "->") <+> pprCoreExprShort expr
instance Outputable BCInstr where
ppr (STKCHECK n) = text "STKCHECK" <+> ppr n
ppr (PUSH_L offset) = text "PUSH_L " <+> ppr offset
ppr (PUSH_LL o1 o2) = text "PUSH_LL " <+> ppr o1 <+> ppr o2
ppr (PUSH_LLL o1 o2 o3) = text "PUSH_LLL" <+> ppr o1 <+> ppr o2 <+> ppr o3
ppr (PUSH_G nm) = text "PUSH_G " <+> ppr nm
ppr (PUSH_PRIMOP op) = text "PUSH_G " <+> text "GHC.PrimopWrappers."
<> ppr op
ppr (PUSH_BCO bco) = hang (text "PUSH_BCO") 2 (ppr bco)
ppr (PUSH_ALTS bco) = hang (text "PUSH_ALTS") 2 (ppr bco)
ppr (PUSH_ALTS_UNLIFTED bco pk) = hang (text "PUSH_ALTS_UNLIFTED" <+> ppr pk) 2 (ppr bco)
ppr (PUSH_UBX (Left lit) nw) = text "PUSH_UBX" <+> parens (ppr nw) <+> ppr lit
ppr (PUSH_UBX (Right aa) nw) = text "PUSH_UBX" <+> parens (ppr nw) <+> text (show aa)
ppr PUSH_APPLY_N = text "PUSH_APPLY_N"
ppr PUSH_APPLY_V = text "PUSH_APPLY_V"
ppr PUSH_APPLY_F = text "PUSH_APPLY_F"
ppr PUSH_APPLY_D = text "PUSH_APPLY_D"
ppr PUSH_APPLY_L = text "PUSH_APPLY_L"
ppr PUSH_APPLY_P = text "PUSH_APPLY_P"
ppr PUSH_APPLY_PP = text "PUSH_APPLY_PP"
ppr PUSH_APPLY_PPP = text "PUSH_APPLY_PPP"
ppr PUSH_APPLY_PPPP = text "PUSH_APPLY_PPPP"
ppr PUSH_APPLY_PPPPP = text "PUSH_APPLY_PPPPP"
ppr PUSH_APPLY_PPPPPP = text "PUSH_APPLY_PPPPPP"
ppr (SLIDE n d) = text "SLIDE " <+> ppr n <+> ppr d
ppr (ALLOC_AP sz) = text "ALLOC_AP " <+> ppr sz
ppr (ALLOC_AP_NOUPD sz) = text "ALLOC_AP_NOUPD " <+> ppr sz
ppr (ALLOC_PAP arity sz) = text "ALLOC_PAP " <+> ppr arity <+> ppr sz
ppr (MKAP offset sz) = text "MKAP " <+> ppr sz <+> text "words,"
<+> ppr offset <+> text "stkoff"
ppr (MKPAP offset sz) = text "MKPAP " <+> ppr sz <+> text "words,"
<+> ppr offset <+> text "stkoff"
ppr (UNPACK sz) = text "UNPACK " <+> ppr sz
ppr (PACK dcon sz) = text "PACK " <+> ppr dcon <+> ppr sz
ppr (LABEL lab) = text "__" <> ppr lab <> colon
ppr (TESTLT_I i lab) = text "TESTLT_I" <+> int i <+> text "__" <> ppr lab
ppr (TESTEQ_I i lab) = text "TESTEQ_I" <+> int i <+> text "__" <> ppr lab
ppr (TESTLT_W i lab) = text "TESTLT_W" <+> int (fromIntegral i) <+> text "__" <> ppr lab
ppr (TESTEQ_W i lab) = text "TESTEQ_W" <+> int (fromIntegral i) <+> text "__" <> ppr lab
ppr (TESTLT_F f lab) = text "TESTLT_F" <+> float f <+> text "__" <> ppr lab
ppr (TESTEQ_F f lab) = text "TESTEQ_F" <+> float f <+> text "__" <> ppr lab
ppr (TESTLT_D d lab) = text "TESTLT_D" <+> double d <+> text "__" <> ppr lab
ppr (TESTEQ_D d lab) = text "TESTEQ_D" <+> double d <+> text "__" <> ppr lab
ppr (TESTLT_P i lab) = text "TESTLT_P" <+> ppr i <+> text "__" <> ppr lab
ppr (TESTEQ_P i lab) = text "TESTEQ_P" <+> ppr i <+> text "__" <> ppr lab
ppr CASEFAIL = text "CASEFAIL"
ppr (JMP lab) = text "JMP" <+> ppr lab
ppr (CCALL off marshall_addr int) = text "CCALL " <+> ppr off
<+> text "marshall code at"
<+> text (show marshall_addr)
<+> (if int == 1
then text "(interruptible)"
else empty)
ppr (SWIZZLE stkoff n) = text "SWIZZLE " <+> text "stkoff" <+> ppr stkoff
<+> text "by" <+> ppr n
ppr ENTER = text "ENTER"
ppr RETURN = text "RETURN"
ppr (RETURN_UBX pk) = text "RETURN_UBX " <+> ppr pk
ppr (BRK_FUN _breakArray index info) = text "BRK_FUN" <+> text "<array>" <+> ppr index <+> ppr info
-- -----------------------------------------------------------------------------
-- The stack use, in words, of each bytecode insn. These _must_ be
-- correct, or overestimates of reality, to be safe.
-- NOTE: we aggregate the stack use from case alternatives too, so that
-- we can do a single stack check at the beginning of a function only.
-- This could all be made more accurate by keeping track of a proper
-- stack high water mark, but it doesn't seem worth the hassle.
protoBCOStackUse :: ProtoBCO a -> Word
protoBCOStackUse bco = sum (map bciStackUse (protoBCOInstrs bco))
bciStackUse :: BCInstr -> Word
bciStackUse STKCHECK{} = 0
bciStackUse PUSH_L{} = 1
bciStackUse PUSH_LL{} = 2
bciStackUse PUSH_LLL{} = 3
bciStackUse PUSH_G{} = 1
bciStackUse PUSH_PRIMOP{} = 1
bciStackUse PUSH_BCO{} = 1
bciStackUse (PUSH_ALTS bco) = 2 + protoBCOStackUse bco
bciStackUse (PUSH_ALTS_UNLIFTED bco _) = 2 + protoBCOStackUse bco
bciStackUse (PUSH_UBX _ nw) = fromIntegral nw
bciStackUse PUSH_APPLY_N{} = 1
bciStackUse PUSH_APPLY_V{} = 1
bciStackUse PUSH_APPLY_F{} = 1
bciStackUse PUSH_APPLY_D{} = 1
bciStackUse PUSH_APPLY_L{} = 1
bciStackUse PUSH_APPLY_P{} = 1
bciStackUse PUSH_APPLY_PP{} = 1
bciStackUse PUSH_APPLY_PPP{} = 1
bciStackUse PUSH_APPLY_PPPP{} = 1
bciStackUse PUSH_APPLY_PPPPP{} = 1
bciStackUse PUSH_APPLY_PPPPPP{} = 1
bciStackUse ALLOC_AP{} = 1
bciStackUse ALLOC_AP_NOUPD{} = 1
bciStackUse ALLOC_PAP{} = 1
bciStackUse (UNPACK sz) = fromIntegral sz
bciStackUse LABEL{} = 0
bciStackUse TESTLT_I{} = 0
bciStackUse TESTEQ_I{} = 0
bciStackUse TESTLT_W{} = 0
bciStackUse TESTEQ_W{} = 0
bciStackUse TESTLT_F{} = 0
bciStackUse TESTEQ_F{} = 0
bciStackUse TESTLT_D{} = 0
bciStackUse TESTEQ_D{} = 0
bciStackUse TESTLT_P{} = 0
bciStackUse TESTEQ_P{} = 0
bciStackUse CASEFAIL{} = 0
bciStackUse JMP{} = 0
bciStackUse ENTER{} = 0
bciStackUse RETURN{} = 0
bciStackUse RETURN_UBX{} = 1
bciStackUse CCALL{} = 0
bciStackUse SWIZZLE{} = 0
bciStackUse BRK_FUN{} = 0
-- These insns actually reduce stack use, but we need the high-tide level,
-- so can't use this info. Not that it matters much.
bciStackUse SLIDE{} = 0
bciStackUse MKAP{} = 0
bciStackUse MKPAP{} = 0
bciStackUse PACK{} = 1 -- worst case is PACK 0 words
| pparkkin/eta | compiler/ETA/Interactive/ByteCodeInstr.hs | bsd-3-clause | 13,902 | 0 | 22 | 4,314 | 3,504 | 1,767 | 1,737 | 260 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.License
-- Copyright : Isaac Jones 2003-2005
--
-- Maintainer : Isaac Jones <[email protected]>
-- Stability : alpha
-- Portability : portable
--
-- The License datatype. For more information about these and other
-- open-source licenses, you may visit <http://www.opensource.org/>.
--
-- I am not a lawyer, but as a general guideline, most Haskell
-- software seems to be released under a BSD3 license, which is very
-- open and free. If you don't want to restrict the use of your
-- software or its source code, use BSD3 or PublicDomain.
{- 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 Isaac Jones nor the names of other
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR 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 Distribution.License (
License(..)
) where
-- |This datatype indicates the license under which your package is
-- released. It is also wise to add your license to each source file.
-- The 'AllRightsReserved' constructor is not actually a license, but
-- states that you are not giving anyone else a license to use or
-- distribute your work. The comments below are general guidelines.
-- Please read the licenses themselves and consult a lawyer if you are
-- unsure of your rights to release the software.
data License = GPL -- ^GNU Public License. Source code must accompany alterations.
| LGPL -- ^Lesser GPL, Less restrictive than GPL, useful for libraries.
| BSD3 -- ^3-clause BSD license, newer, no advertising clause. Very free license.
| BSD4 -- ^4-clause BSD license, older, with advertising clause.
| PublicDomain -- ^Holder makes no claim to ownership, least restrictive license.
| AllRightsReserved -- ^No rights are granted to others. Undistributable. Most restrictive.
| {- ... | -} OtherLicense -- ^Some other license.
deriving (Read, Show, Eq)
| alekar/hugs | packages/Cabal/Distribution/License.hs | bsd-3-clause | 3,334 | 2 | 6 | 665 | 89 | 67 | 22 | 10 | 0 |
-- |
-- Module : Data.Array.Accelerate.CUDA.Array.Sugar
-- Copyright : [2008..2014] Manuel M T Chakravarty, Gabriele Keller
-- [2009..2014] Trevor L. McDonell
-- License : BSD3
--
-- Maintainer : Trevor L. McDonell <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
module Data.Array.Accelerate.CUDA.Array.Sugar (
module Data.Array.Accelerate.Array.Sugar,
fromFunction, allocateArray, useArray, useArrayAsync,
) where
import Control.Monad.Trans
import Data.Array.Accelerate.CUDA.State
import Data.Array.Accelerate.CUDA.Array.Data
import Data.Array.Accelerate.Array.Sugar hiding ( fromFunction, allocateArray )
import qualified Data.Array.Accelerate.Array.Sugar as Sugar
-- Create an array from its representation function, uploading the result to the
-- device
--
fromFunction :: (Shape sh, Elt e) => sh -> (sh -> e) -> CIO (Array sh e)
fromFunction sh f =
let arr = Sugar.fromFunction sh f
in do
useArray arr
return arr
-- Allocate a new, uninitialised Accelerate array on host and device
--
allocateArray :: (Shape dim, Elt e) => dim -> CIO (Array dim e)
allocateArray sh = do
arr <- liftIO $ Sugar.allocateArray sh
mallocArray arr
return arr
| AccelerateHS/accelerate-cuda | Data/Array/Accelerate/CUDA/Array/Sugar.hs | bsd-3-clause | 1,284 | 0 | 10 | 245 | 257 | 152 | 105 | 19 | 1 |
--------------------------------------------------------------------------------
-- | Various IRC utilities
{-# LANGUAGE OverloadedStrings #-}
module NumberSix.Util.Irc
( mode
, meAction
, kick
) where
--------------------------------------------------------------------------------
import Control.Monad (when)
import Data.Text (Text)
--------------------------------------------------------------------------------
import NumberSix.Irc
import NumberSix.Util
--------------------------------------------------------------------------------
-- | Make an action a /me command
meAction :: Text -> Text
meAction x = "\SOHACTION " <> x <> "\SOH"
--------------------------------------------------------------------------------
-- | Kick someone
kick :: Text -> Text -> Irc ()
kick nick reason = do
channel <- getChannel
myNick <- getNick
-- The bot won't kick itself
when (not $ nick ==? myNick) $
writeMessage "KICK" [channel, nick, reason]
--------------------------------------------------------------------------------
-- | Change the mode for a user
mode :: Text -- ^ Mode change string (e.g. @+v@)
-> Text -- ^ Target user
-> Irc () -- ^ No result
mode mode' nick = do
channel <- getChannel
writeMessage "MODE" [channel, mode', nick]
| itkovian/number-six | src/NumberSix/Util/Irc.hs | bsd-3-clause | 1,357 | 0 | 11 | 264 | 217 | 122 | 95 | 23 | 1 |
module Expression (
-- * Expressions
Expr, Predicate, Args, Ways,
-- ** Construction and modification
expr, exprIO, arg, remove,
-- ** Predicates
(?), stage, stage0, stage1, stage2, notStage0, package, notPackage,
packageOneOf, libraryPackage, builder, way, input, inputs, output, outputs,
-- ** Evaluation
interpret, interpretInContext,
-- * Convenient accessors
getBuildRoot, getContext, getOutputs, getInputs,
getInput, getOutput, getContextData,
-- * Re-exports
module Base,
module Builder,
module Context,
) where
import Base
import Builder
import Context hiding (stage, package, way)
import Expression.Type
import Hadrian.Expression hiding (Expr, Predicate, Args)
import Hadrian.Haskell.Cabal.Type
import Hadrian.Oracles.Cabal
-- | Get values from a configured cabal stage.
getContextData :: (ContextData -> a) -> Expr a
getContextData key = do
contextData <- expr . readContextData =<< getContext
return $ key contextData
-- | Is the build currently in the provided stage?
stage :: Stage -> Predicate
stage s = (s ==) <$> getStage
-- | Is a particular package being built?
package :: Package -> Predicate
package p = (p ==) <$> getPackage
packageOneOf :: [Package] -> Predicate
packageOneOf ps = (`elem` ps) <$> getPackage
-- | This type class allows the user to construct both precise builder
-- predicates, such as @builder (Ghc CompileHs Stage1)@, as well as predicates
-- covering a set of similar builders. For example, @builder (Ghc CompileHs)@
-- matches any stage, and @builder Ghc@ matches any stage and any GHC mode.
class BuilderPredicate a where
-- | Is a particular builder being used?
builder :: a -> Predicate
instance BuilderPredicate Builder where
builder b = (b ==) <$> getBuilder
instance BuilderPredicate a => BuilderPredicate (Stage -> a) where
builder f = builder . f =<< getStage
instance BuilderPredicate a => BuilderPredicate (CcMode -> a) where
builder f = do
b <- getBuilder
case b of
Cc c _ -> builder (f c)
_ -> return False
instance BuilderPredicate a => BuilderPredicate (GhcMode -> a) where
builder f = do
b <- getBuilder
case b of
Ghc c _ -> builder (f c)
_ -> return False
instance BuilderPredicate a => BuilderPredicate (FilePath -> a) where
builder f = do
b <- getBuilder
case b of
Configure path -> builder (f path)
_ -> return False
-- | Is the current build 'Way' equal to a certain value?
way :: Way -> Predicate
way w = (w ==) <$> getWay
-- | Is the build currently in stage 0?
stage0 :: Predicate
stage0 = stage Stage0
-- | Is the build currently in stage 1?
stage1 :: Predicate
stage1 = stage Stage1
-- | Is the build currently in stage 2?
stage2 :: Predicate
stage2 = stage Stage2
-- | Is the build /not/ in stage 0 right now?
notStage0 :: Predicate
notStage0 = notM stage0
-- | Is a certain package /not/ built right now?
notPackage :: Package -> Predicate
notPackage = notM . package
-- | Is a library package currently being built?
libraryPackage :: Predicate
libraryPackage = isLibrary <$> getPackage
| sdiehl/ghc | hadrian/src/Expression.hs | bsd-3-clause | 3,230 | 0 | 13 | 759 | 735 | 413 | 322 | 66 | 1 |
{-# LANGUAGE CPP #-}
module UU.Parsing.Merge((<||>), pMerged, list_of) where
import UU.Parsing
-- ==== merging
-- e.g. chars_digs = cat3 `pMerged` (list_of pDig <||> list_of pL <||> list_of pU)
-- parsing "12abCD1aV" now returns "121abaCDV", so the sequence of
-- recognised elements is stored in three lists, which are then passed to cat3
(<||>) :: IsParser p s => (c,p (d -> d),e -> f -> g) -> (h,p (i -> i),g -> j -> k) -> ((c,h),p ((d,i) -> (d,i)),e -> (f,j) -> k)
(pe, pp, punp) <||> (qe, qp, qunp)
=( (pe, qe)
, (\f (pv, qv) -> (f pv, qv)) <$> pp
<|>
(\f (pv, qv) -> (pv, f qv)) <$> qp
, \f (x, y) -> qunp (punp f x) y
)
pMerged :: IsParser p s => c -> (d,p (d -> d),c -> d -> e) -> p e
sem `pMerged` (units, alts, unp)
= let pres = alts <*> pres `opt` units
in unp sem <$> pres
list_of :: IsParser p s => p c -> ([d],p ([c] -> [c]),e -> e)
list_of p = ([], (:) <$> p, id)
| guillep19/uulib | src/UU/Parsing/Merge.hs | bsd-3-clause | 919 | 0 | 12 | 226 | 471 | 271 | 200 | 16 | 1 |
module Client
( getServerStatus
, stopServer
, serverCommand
) where
import Control.Exception (tryJust)
import Control.Monad (guard)
import Network (PortID(UnixSocket), connectTo)
import System.Exit (exitFailure, exitWith)
import System.IO (Handle, hClose, hFlush, hGetLine, hPutStrLn, stderr)
import System.IO.Error (isDoesNotExistError)
import Daemonize (daemonize)
import Server (createListenSocket, startServer)
import Types (ClientDirective(..), Command(..), CommandExtra(..), ServerDirective(..))
import Util (readMaybe)
connect :: FilePath -> IO Handle
connect sock = do
connectTo "" (UnixSocket sock)
getServerStatus :: FilePath -> IO ()
getServerStatus sock = do
h <- connect sock
hPutStrLn h $ show SrvStatus
hFlush h
startClientReadLoop h
stopServer :: FilePath -> IO ()
stopServer sock = do
h <- connect sock
hPutStrLn h $ show SrvExit
hFlush h
startClientReadLoop h
serverCommand :: FilePath -> Command -> CommandExtra -> IO ()
serverCommand sock cmd cmdExtra = do
r <- tryJust (guard . isDoesNotExistError) (connect sock)
case r of
Right h -> do
hPutStrLn h $ show (SrvCommand cmd cmdExtra)
hFlush h
startClientReadLoop h
Left _ -> do
s <- createListenSocket sock
daemonize False $ startServer sock (Just s)
serverCommand sock cmd cmdExtra
startClientReadLoop :: Handle -> IO ()
startClientReadLoop h = do
msg <- hGetLine h
let clientDirective = readMaybe msg
case clientDirective of
Just (ClientStdout out) -> putStrLn out >> startClientReadLoop h
Just (ClientStderr err) -> hPutStrLn stderr err >> startClientReadLoop h
Just (ClientExit exitCode) -> hClose h >> exitWith exitCode
Just (ClientUnexpectedError err) -> hClose h >> unexpectedError err
Nothing -> do
hClose h
unexpectedError $
"The server sent an invalid message to the client: " ++ show msg
unexpectedError :: String -> IO ()
unexpectedError err = do
hPutStrLn stderr banner
hPutStrLn stderr err
hPutStrLn stderr banner
exitFailure
where banner = replicate 78 '*'
| ranjitjhala/hdevtools | src/Client.hs | mit | 2,209 | 0 | 15 | 543 | 705 | 343 | 362 | 61 | 5 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedStrings #-}
module Lazyfoo.Lesson10 (main) where
import Control.Monad
import Foreign.C.Types
import Linear
import Linear.Affine
import SDL (($=))
import qualified SDL
import Paths_sdl2 (getDataFileName)
#if !MIN_VERSION_base(4,8,0)
import Control.Applicative
#endif
screenWidth, screenHeight :: CInt
(screenWidth, screenHeight) = (640, 480)
data Texture = Texture SDL.Texture (V2 CInt)
loadTexture :: SDL.Renderer -> FilePath -> IO Texture
loadTexture r filePath = do
surface <- getDataFileName filePath >>= SDL.loadBMP
size <- SDL.surfaceDimensions surface
format <- SDL.surfaceFormat surface
key <- SDL.mapRGB format (V3 0 maxBound maxBound)
SDL.colorKey surface $= Just key
t <- SDL.createTextureFromSurface r surface
SDL.freeSurface surface
return (Texture t size)
renderTexture :: SDL.Renderer -> Texture -> Point V2 CInt -> IO ()
renderTexture r (Texture t size) xy =
SDL.renderCopy r t Nothing (Just $ SDL.Rectangle xy size)
main :: IO ()
main = do
SDL.initialize [SDL.InitVideo]
SDL.HintRenderScaleQuality $= SDL.ScaleLinear
do renderQuality <- SDL.get SDL.HintRenderScaleQuality
when (renderQuality /= SDL.ScaleLinear) $
putStrLn "Warning: Linear texture filtering not enabled!"
window <-
SDL.createWindow
"SDL Tutorial"
SDL.defaultWindow {SDL.windowInitialSize = V2 screenWidth screenHeight}
SDL.showWindow window
renderer <-
SDL.createRenderer
window
(-1)
(SDL.RendererConfig
{ SDL.rendererType = SDL.AcceleratedRenderer
, SDL.rendererTargetTexture = False
})
SDL.renderDrawColor renderer $= V4 maxBound maxBound maxBound maxBound
fooTexture <- loadTexture renderer "examples/lazyfoo/foo.bmp"
backgroundTexture <- loadTexture renderer "examples/lazyfoo/background.bmp"
let loop = do
let collectEvents = do
e <- SDL.pollEvent
case e of
Nothing -> return []
Just e' -> (e' :) <$> collectEvents
events <- collectEvents
let quit = any (== SDL.QuitEvent) $ map SDL.eventPayload events
SDL.renderDrawColor renderer $= V4 maxBound maxBound maxBound maxBound
SDL.renderClear renderer
renderTexture renderer backgroundTexture 0
renderTexture renderer fooTexture (P (V2 240 190))
SDL.renderPresent renderer
unless quit loop
loop
SDL.destroyRenderer renderer
SDL.destroyWindow window
SDL.quit
| bj4rtmar/sdl2 | examples/lazyfoo/Lesson10.hs | bsd-3-clause | 2,513 | 0 | 21 | 550 | 731 | 352 | 379 | 67 | 2 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
module Main where
import Data.Functor.Misc
import Control.Monad.Primitive
import Control.Monad.IO.Class
import Data.Dependent.Sum
import Control.Concurrent.STM
import Control.Applicative
import System.IO.Unsafe
import Data.IORef
import Control.DeepSeq
import Control.Exception (evaluate)
import Control.Monad
import Reflex
import Reflex.Host.Class
import System.Mem
import System.IO
import Criterion.Main
import qualified Data.Traversable as T
import qualified Data.Dependent.Map as DM
main :: IO ()
main = defaultMain
[ bgroup "micro" micros ]
instance NFData (IORef a) where
rnf x = seq x ()
instance NFData (TVar a) where
rnf x = seq x ()
newtype WHNF a = WHNF a
instance NFData (WHNF a) where
rnf (WHNF a) = seq a ()
withSetup :: NFData b => String -> SpiderHost a -> (a -> SpiderHost b) -> Benchmark
withSetup name setup action = env (WHNF <$> runSpiderHost setup) $ \ ~(WHNF a) ->
bench name . nfIO $ runSpiderHost (action a)
withSetupWHNF :: String -> SpiderHost a -> (a -> SpiderHost b) -> Benchmark
withSetupWHNF name setup action = env (WHNF <$> runSpiderHost setup) $ \ ~(WHNF a) ->
bench name . whnfIO $ runSpiderHost (action a)
micros :: [Benchmark]
micros =
[ bench "newIORef" $ whnfIO $ void $ newIORef ()
, env (newIORef (42 :: Int)) (bench "readIORef" . whnfIO . readIORef)
, bench "newTVar" $ whnfIO $ void $ newTVarIO ()
, env (newTVarIO (42 :: Int)) (bench "readTVar" . whnfIO . readTVarIO)
, bench "newEventWithTrigger" $ whnfIO . void $ runSpiderHost $ newEventWithTrigger $
\trigger -> return () <$ evaluate trigger
, bench "newEventWithTriggerRef" $ whnfIO . void $ runSpiderHost newEventWithTriggerRef
, withSetupWHNF "subscribeEvent" newEventWithTriggerRef $ subscribeEvent . fst
, withSetupWHNF "subscribeSwitch"
(join $ hold <$> fmap fst newEventWithTriggerRef <*> fmap fst newEventWithTriggerRef)
(subscribeEvent . switch)
, withSetupWHNF "subscribeMerge(1)" (setupMerge 1) $ \(ev,_) -> subscribeEvent ev
, withSetupWHNF "subscribeMerge(100)" (setupMerge 100) (subscribeEvent . fst)
, withSetupWHNF "subscribeMerge(10000)" (setupMerge 10000) (subscribeEvent . fst)
, bench "runHostFrame" $ whnfIO $ runSpiderHost $ runHostFrame $ return ()
, withSetupWHNF "fireEventsAndRead(single/single)"
(newEventWithTriggerRef >>= subscribePair)
(\(subd, trigger) -> fireAndRead trigger (42 :: Int) subd)
, withSetupWHNF "fireEventsOnly"
(newEventWithTriggerRef >>= subscribePair)
(\(subd, trigger) -> do
Just key <- liftIO $ readIORef trigger
fireEvents [key :=> (42 :: Int)])
, withSetupWHNF "fireEventsAndRead(head/merge1)"
(setupMerge 1 >>= subscribePair)
(\(subd, t:riggers) -> fireAndRead t (42 :: Int) subd)
, withSetupWHNF "fireEventsAndRead(head/merge100)"
(setupMerge 100 >>= subscribePair)
(\(subd, t:riggers) -> fireAndRead t (42 :: Int) subd)
, withSetupWHNF "fireEventsAndRead(head/merge10000)"
(setupMerge 10000 >>= subscribePair)
(\(subd, t:riggers) -> fireAndRead t (42 :: Int) subd)
, withSetupWHNF "fireEventsOnly(head/merge100)"
(setupMerge 100 >>= subscribePair)
(\(subd, t:riggers) -> do
Just key <- liftIO $ readIORef t
fireEvents [key :=> (42 :: Int)])
, withSetupWHNF "hold" newEventWithTriggerRef $ \(ev,trigger) -> hold (42 :: Int) ev
, withSetupWHNF "sample" (newEventWithTriggerRef >>= hold (42 :: Int) . fst) sample
]
setupMerge :: Int
-> SpiderHost (Event Spider (DM.DMap (Const2 Int a)),
[IORef (Maybe (EventTrigger Spider a))])
setupMerge num = do
(evs, triggers) <- unzip <$> replicateM 100 newEventWithTriggerRef
let !m = DM.fromList [WrapArg (Const2 i) :=> v | (i,v) <- zip [0..] evs]
pure (merge m, triggers)
subscribePair :: (Event Spider a, b) -> SpiderHost (EventHandle Spider a, b)
subscribePair (ev, b) = (,b) <$> subscribeEvent ev
fireAndRead :: IORef (Maybe (EventTrigger Spider a)) -> a -> EventHandle Spider b
-> SpiderHost (Maybe b)
fireAndRead trigger val subd = do
Just key <- liftIO $ readIORef trigger
fireEventsAndRead [key :=> val] $ readEvent subd >>= T.sequence
| k0001/reflex | bench/Main.hs | bsd-3-clause | 4,291 | 0 | 15 | 800 | 1,509 | 788 | 721 | 94 | 1 |
{-# LANGUAGE TemplateHaskell, TypeFamilies #-}
module T10306 where
import Language.Haskell.TH
import GHC.TypeLits
-- Attempting to reify a built-in type family like (+) previously
-- caused a crash, because it has no equations
$(do x <- reify ''(+)
case x of
FamilyI (ClosedTypeFamilyD _ _ _ _ []) _ -> return []
_ -> error $ show x
)
| siddhanathan/ghc | testsuite/tests/th/T10306.hs | bsd-3-clause | 397 | 0 | 15 | 120 | 91 | 47 | 44 | 8 | 0 |
module M (f) where
f :: Int -> Int
f i = go [ 1, 0 ]
where
go :: [Int] -> Int
go [] = undefined
go [1] = undefined
go (x:xs) | x == i = 2
| otherwise = go xs
| urbanslug/ghc | testsuite/tests/codeGen/should_compile/T9303.hs | bsd-3-clause | 213 | 0 | 10 | 99 | 107 | 56 | 51 | 8 | 3 |
{-# htermination (lookup :: Tup0 -> (List (Tup2 Tup0 a)) -> Maybe a) #-}
import qualified Prelude
data MyBool = MyTrue | MyFalse
data List a = Cons a (List a) | Nil
data Tup0 = Tup0 ;
data Tup2 a b = Tup2 a b ;
data Maybe a = Nothing | Just a ;
esEsTup0 :: Tup0 -> Tup0 -> MyBool
esEsTup0 Tup0 Tup0 = MyTrue;
lookup0 k x y xys MyTrue = lookup k xys;
otherwise :: MyBool;
otherwise = MyTrue;
lookup1 k x y xys MyTrue = Just y;
lookup1 k x y xys MyFalse = lookup0 k x y xys otherwise;
lookup2 k (Cons (Tup2 x y) xys) = lookup1 k x y xys (esEsTup0 k x);
lookup3 k Nil = Nothing;
lookup3 vy vz = lookup2 vy vz;
lookup k Nil = lookup3 k Nil;
lookup k (Cons (Tup2 x y) xys) = lookup2 k (Cons (Tup2 x y) xys);
| ComputationWithBoundedResources/ara-inference | doc/tpdb_trs/Haskell/basic_haskell/lookup_1.hs | mit | 726 | 0 | 9 | 179 | 324 | 170 | 154 | 18 | 1 |
module LynCrypt.Util where
slice a b xs = (take (b'-a'+1)) $ (drop a' xs)
where a' = fromIntegral a :: Int
b' = fromIntegral b :: Int
| Sintrastes/LynCrypt | src/LynCrypt/Util.hs | mit | 149 | 0 | 10 | 42 | 71 | 38 | 33 | 4 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
module Nunavut.Activator (
propA,
backpropA,
unsafeBackpropA,
activatorFunc,
activatorDeriv,
softmax,
logistic,
tanhActivator,
relu,
linear,
Activator
) where
import Control.Lens ((%=), (^.), _2)
import Control.Monad.Identity (Identity, runIdentity)
import Control.Monad.Trans (lift)
import Control.Monad.Trans.RWS (get, mapRWST)
import Control.Monad.Writer (MonadWriter, tell)
import Data.Monoid (mempty)
import Numeric.LinearAlgebra (diag, maxElement, outer)
import Nunavut.Activator.Internal (Activator (..), ActivatorType (..),
activatorDeriv, activatorFunc)
import Nunavut.Newtypes (Jacobian, elementwise, fromMtx,
fromVec, l1Norm, toVec, trans,
(<>))
import Nunavut.Propogation (Backpropogation, PropData,
PropData (..), preActivated,
withBias, withoutBias)
import Nunavut.Signals (Signal)
import Nunavut.Util (Error, ifDimsMatch)
{--------------------------------------------------------------------------
- Propogation -
--------------------------------------------------------------------------}
propA :: (Monad m, MonadWriter PropData m)
=> Activator -> Signal -> m Signal
propA a sig = do
tell $ PData mempty [sig]
return . withBias $ (a ^. activatorFunc) sig
unsafeBackpropA :: Backpropogation Activator Identity
unsafeBackpropA a err = do
(_, pData) <- get
let jac = (a ^. activatorDeriv) (head $ pData ^. preActivated)
_2 . preActivated %= tail
return . (trans jac <>) . withoutBias $ err
backpropA :: Backpropogation Activator (Either Error)
backpropA a err = do
(_, pData) <- get
let preA = head $ pData ^. preActivated
checkedErr <- checkErr preA
mapRWST (return . runIdentity) . unsafeBackpropA a $ checkedErr
where checkErr preA = lift $ ifDimsMatch "backpropA" (\_ -> const err) preA (withoutBias err)
{--------------------------------------------------------------------------
- Helper Functions -
--------------------------------------------------------------------------}
diagActivator ::
ActivatorType
-> (Double -> Double)
-> (Double -> Double)
-> Activator
diagActivator t f d = Activator t (elementwise f) (toDiag d)
where toDiag d' = fromMtx . diag . toVec . elementwise d'
logistic :: Activator
logistic = diagActivator Logistic logisticFunc logisticDeriv
relu :: Activator
relu = diagActivator RectifiedLinear reluFunc reluDeriv
linear :: Activator
linear = diagActivator Linear id $ const 1
tanhActivator :: Activator
tanhActivator = diagActivator Tanh tanh ((1 -) . (** 2) . tanh)
logisticFunc :: Double -> Double
logisticFunc z = 1 / (1 + exp (-z))
logisticDeriv :: Double -> Double
logisticDeriv z = s * (1 - s)
where s = logisticFunc z
reluFunc :: Double -> Double
reluFunc z = max z 0
reluDeriv :: Double -> Double
reluDeriv z
| z <= 0 = 0
| otherwise = 1
softmax :: Activator
softmax = Activator Softmax softmaxFunc softmaxDeriv
softmaxFunc :: Signal -> Signal
softmaxFunc v = elementwise (/ l1Norm exponentiated) exponentiated
where exponentiated = elementwise (exp . (\e -> e - maxV)) v
maxV = maxElement . toVec $ v
softmaxDeriv :: Signal -> Jacobian
softmaxDeriv v = fromMtx $ diag s - (s `outer` s)
where s = toVec . softmaxFunc $ v'
v' = fromVec . toVec $ v
| markcwhitfield/nunavut | src/Nunavut/Activator.hs | mit | 4,419 | 0 | 13 | 1,676 | 1,029 | 564 | 465 | -1 | -1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedStrings #-}
module Web.Cookie
( -- * Server to client
-- ** Data type
SetCookie
, setCookieName
, setCookieValue
, setCookiePath
, setCookieExpires
, setCookieMaxAge
, setCookieDomain
, setCookieHttpOnly
, setCookieSecure
, setCookieSameSite
, SameSiteOption
, sameSiteLax
, sameSiteStrict
, sameSiteNone
-- ** Functions
, parseSetCookie
, renderSetCookie
, defaultSetCookie
, def
-- * Client to server
, Cookies
, parseCookies
, renderCookies
-- ** UTF8 Version
, CookiesText
, parseCookiesText
, renderCookiesText
-- * Expires field
, expiresFormat
, formatCookieExpires
, parseCookieExpires
) where
import qualified Data.ByteString as S
import qualified Data.ByteString.Char8 as S8
import Data.Char (toLower, isDigit)
import Data.ByteString.Builder (Builder, byteString, char8)
import Data.ByteString.Builder.Extra (byteStringCopy)
#if !(MIN_VERSION_base(4,8,0))
import Data.Monoid (mempty, mappend, mconcat)
#endif
import Data.Word (Word8)
import Data.Ratio (numerator, denominator)
import Data.Time (UTCTime (UTCTime), toGregorian, fromGregorian, formatTime, parseTimeM, defaultTimeLocale)
import Data.Time.Clock (DiffTime, secondsToDiffTime)
import Control.Arrow (first, (***))
import Data.Text (Text)
import Data.Text.Encoding (encodeUtf8Builder, decodeUtf8With)
import Data.Text.Encoding.Error (lenientDecode)
import Data.Maybe (isJust)
import Data.Default.Class (Default (def))
import Control.DeepSeq (NFData (rnf))
-- | Textual cookies. Functions assume UTF8 encoding.
type CookiesText = [(Text, Text)]
parseCookiesText :: S.ByteString -> CookiesText
parseCookiesText =
map (go *** go) . parseCookies
where
go = decodeUtf8With lenientDecode
renderCookiesText :: CookiesText -> Builder
renderCookiesText = renderCookiesBuilder . map (encodeUtf8Builder *** encodeUtf8Builder)
type Cookies = [(S.ByteString, S.ByteString)]
-- | Decode the value of a \"Cookie\" request header into key/value pairs.
parseCookies :: S.ByteString -> Cookies
parseCookies s
| S.null s = []
| otherwise =
let (x, y) = breakDiscard 59 s -- semicolon
in parseCookie x : parseCookies y
parseCookie :: S.ByteString -> (S.ByteString, S.ByteString)
parseCookie s =
let (key, value) = breakDiscard 61 s -- equals sign
key' = S.dropWhile (== 32) key -- space
in (key', value)
breakDiscard :: Word8 -> S.ByteString -> (S.ByteString, S.ByteString)
breakDiscard w s =
let (x, y) = S.break (== w) s
in (x, S.drop 1 y)
type CookieBuilder = (Builder, Builder)
renderCookiesBuilder :: [CookieBuilder] -> Builder
renderCookiesBuilder [] = mempty
renderCookiesBuilder cs =
foldr1 go $ map renderCookie cs
where
go x y = x `mappend` char8 ';' `mappend` y
renderCookie :: CookieBuilder -> Builder
renderCookie (k, v) = k `mappend` char8 '=' `mappend` v
renderCookies :: Cookies -> Builder
renderCookies = renderCookiesBuilder . map (byteString *** byteString)
-- | Data type representing the key-value pair to use for a cookie, as well as configuration options for it.
--
-- ==== Creating a SetCookie
--
-- 'SetCookie' does not export a constructor; instead, use 'defaultSetCookie' and override values (see <http://www.yesodweb.com/book/settings-types> for details):
--
-- @
-- import Web.Cookie
-- :set -XOverloadedStrings
-- let cookie = 'defaultSetCookie' { 'setCookieName' = "cookieName", 'setCookieValue' = "cookieValue" }
-- @
--
-- ==== Cookie Configuration
--
-- Cookies have several configuration options; a brief summary of each option is given below. For more information, see <http://tools.ietf.org/html/rfc6265#section-4.1.2 RFC 6265> or <https://en.wikipedia.org/wiki/HTTP_cookie#Cookie_attributes Wikipedia>.
data SetCookie = SetCookie
{ setCookieName :: S.ByteString -- ^ The name of the cookie. Default value: @"name"@
, setCookieValue :: S.ByteString -- ^ The value of the cookie. Default value: @"value"@
, setCookiePath :: Maybe S.ByteString -- ^ The URL path for which the cookie should be sent. Default value: @Nothing@ (The browser defaults to the path of the request that sets the cookie).
, setCookieExpires :: Maybe UTCTime -- ^ The time at which to expire the cookie. Default value: @Nothing@ (The browser will default to expiring a cookie when the browser is closed).
, setCookieMaxAge :: Maybe DiffTime -- ^ The maximum time to keep the cookie, in seconds. Default value: @Nothing@ (The browser defaults to expiring a cookie when the browser is closed).
, setCookieDomain :: Maybe S.ByteString -- ^ The domain for which the cookie should be sent. Default value: @Nothing@ (The browser defaults to the current domain).
, setCookieHttpOnly :: Bool -- ^ Marks the cookie as "HTTP only", i.e. not accessible from Javascript. Default value: @False@
, setCookieSecure :: Bool -- ^ Instructs the browser to only send the cookie over HTTPS. Default value: @False@
, setCookieSameSite :: Maybe SameSiteOption -- ^ The "same site" policy of the cookie, i.e. whether it should be sent with cross-site requests. Default value: @Nothing@
}
deriving (Eq, Show)
-- | Data type representing the options for a <https://tools.ietf.org/html/draft-west-first-party-cookies-07#section-4.1 SameSite cookie>
data SameSiteOption = Lax
| Strict
| None
deriving (Show, Eq)
instance NFData SameSiteOption where
rnf x = x `seq` ()
-- | Directs the browser to send the cookie for <https://tools.ietf.org/html/rfc7231#section-4.2.1 safe requests> (e.g. @GET@), but not for unsafe ones (e.g. @POST@)
sameSiteLax :: SameSiteOption
sameSiteLax = Lax
-- | Directs the browser to not send the cookie for /any/ cross-site request, including e.g. a user clicking a link in their email to open a page on your site.
sameSiteStrict :: SameSiteOption
sameSiteStrict = Strict
-- |
-- Directs the browser to send the cookie for cross-site requests.
--
-- @since 0.4.5
sameSiteNone :: SameSiteOption
sameSiteNone = None
instance NFData SetCookie where
rnf (SetCookie a b c d e f g h i) =
a `seq`
b `seq`
rnfMBS c `seq`
rnf d `seq`
rnf e `seq`
rnfMBS f `seq`
rnf g `seq`
rnf h `seq`
rnf i
where
-- For backwards compatibility
rnfMBS Nothing = ()
rnfMBS (Just bs) = bs `seq` ()
-- | @'def' = 'defaultSetCookie'@
instance Default SetCookie where
def = defaultSetCookie
-- | A minimal 'SetCookie'. All fields are 'Nothing' or 'False' except @'setCookieName' = "name"@ and @'setCookieValue' = "value"@. You need this to construct a 'SetCookie', because it does not export a constructor. Equivalently, you may use 'def'.
--
-- @since 0.4.2.2
defaultSetCookie :: SetCookie
defaultSetCookie = SetCookie
{ setCookieName = "name"
, setCookieValue = "value"
, setCookiePath = Nothing
, setCookieExpires = Nothing
, setCookieMaxAge = Nothing
, setCookieDomain = Nothing
, setCookieHttpOnly = False
, setCookieSecure = False
, setCookieSameSite = Nothing
}
renderSetCookie :: SetCookie -> Builder
renderSetCookie sc = mconcat
[ byteString (setCookieName sc)
, char8 '='
, byteString (setCookieValue sc)
, case setCookiePath sc of
Nothing -> mempty
Just path -> byteStringCopy "; Path="
`mappend` byteString path
, case setCookieExpires sc of
Nothing -> mempty
Just e -> byteStringCopy "; Expires=" `mappend`
byteString (formatCookieExpires e)
, case setCookieMaxAge sc of
Nothing -> mempty
Just ma -> byteStringCopy"; Max-Age=" `mappend`
byteString (formatCookieMaxAge ma)
, case setCookieDomain sc of
Nothing -> mempty
Just d -> byteStringCopy "; Domain=" `mappend`
byteString d
, if setCookieHttpOnly sc
then byteStringCopy "; HttpOnly"
else mempty
, if setCookieSecure sc
then byteStringCopy "; Secure"
else mempty
, case setCookieSameSite sc of
Nothing -> mempty
Just Lax -> byteStringCopy "; SameSite=Lax"
Just Strict -> byteStringCopy "; SameSite=Strict"
Just None -> byteStringCopy "; SameSite=None"
]
parseSetCookie :: S.ByteString -> SetCookie
parseSetCookie a = SetCookie
{ setCookieName = name
, setCookieValue = value
, setCookiePath = lookup "path" flags
, setCookieExpires =
lookup "expires" flags >>= parseCookieExpires
, setCookieMaxAge =
lookup "max-age" flags >>= parseCookieMaxAge
, setCookieDomain = lookup "domain" flags
, setCookieHttpOnly = isJust $ lookup "httponly" flags
, setCookieSecure = isJust $ lookup "secure" flags
, setCookieSameSite = case lookup "samesite" flags of
Just "Lax" -> Just Lax
Just "Strict" -> Just Strict
Just "None" -> Just None
_ -> Nothing
}
where
pairs = map (parsePair . dropSpace) $ S.split 59 a ++ [S8.empty] -- 59 = semicolon
(name, value) = head pairs
flags = map (first (S8.map toLower)) $ tail pairs
parsePair = breakDiscard 61 -- equals sign
dropSpace = S.dropWhile (== 32) -- space
expiresFormat :: String
expiresFormat = "%a, %d-%b-%Y %X GMT"
-- | Format a 'UTCTime' for a cookie.
formatCookieExpires :: UTCTime -> S.ByteString
formatCookieExpires =
S8.pack . formatTime defaultTimeLocale expiresFormat
parseCookieExpires :: S.ByteString -> Maybe UTCTime
parseCookieExpires =
fmap fuzzYear . parseTimeM True defaultTimeLocale expiresFormat . S8.unpack
where
-- See: https://github.com/snoyberg/cookie/issues/5
fuzzYear orig@(UTCTime day diff)
| x >= 70 && x <= 99 = addYear 1900
| x >= 0 && x <= 69 = addYear 2000
| otherwise = orig
where
(x, y, z) = toGregorian day
addYear x' = UTCTime (fromGregorian (x + x') y z) diff
-- | Format a 'DiffTime' for a cookie.
formatCookieMaxAge :: DiffTime -> S.ByteString
formatCookieMaxAge difftime = S8.pack $ show (num `div` denom)
where rational = toRational difftime
num = numerator rational
denom = denominator rational
parseCookieMaxAge :: S.ByteString -> Maybe DiffTime
parseCookieMaxAge bs
| all isDigit unpacked = Just $ secondsToDiffTime $ read unpacked
| otherwise = Nothing
where unpacked = S8.unpack bs
| snoyberg/cookie | Web/Cookie.hs | mit | 10,553 | 0 | 13 | 2,355 | 2,146 | 1,196 | 950 | 208 | 10 |
{-# LANGUAGE QuasiQuotes, ViewPatterns #-}
module Y2017.M12.D11.Solution where
import Control.Arrow (first)
import Control.Monad (void)
import Control.Monad.State
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as B
import Database.PostgreSQL.Simple
import Database.PostgreSQL.Simple.SqlQQ
import Database.PostgreSQL.Simple.Types
import System.Random
-- below imports available via 1HaskellADay git repository
import Store.SQL.Connection
import Store.SQL.Util.Indexed
{--
An exponential probability distribution looks like the attached image (see
Y2017/M12/D11/exponential-histogram.png), and can be computed, thus:
-ln(1 - rndx)
where x is some number, possibly 'randomly' generated (with the quote, or if
you are getting true random numbers, like from random.org, then: without the
quote. Hey, I'm easy!)
--}
-- 1. write the exponential distribution, that, given a number, computes it
negLn :: Double -> Double
negLn x = -log (1 - x)
-- 2. Generate 10,000 random numbers from the exponential distribution
-- in the Integer range from 5000 - 25000
rndExpRange :: RandomGen g => (Integer, Integer) -> State g Integer
rndExpRange (f,c) =
get >>= \gen ->
let (comp, g) = first negLn (random gen) in
put g >>
return ((f +) . round $ fromIntegral (c - f) * comp)
{--
>>> evalState (rndExpRange (5000,25000)) <$> getStdGen
13628
>>> take 10 . evalState (mapM (const (rndExpRange (5000,25000)))
(replicate 10000 ())) <$> getStdGen
[13628,10506,28190,39568,19095,8851,11727,16811,6949,31534]
YAY!
--}
{-- BONUS -----------------------------------------------------------------
For each of the ids in the article table of the NYT article archive, generate
a random integer in the range from 5000 - 25000 on the exponential distribution,
and update the view_count column with that value.
--}
fetchIdsStmt :: Query
fetchIdsStmt = [sql|SELECT id from article|]
fetcher :: Connection -> IO [Index]
fetcher = flip query_ fetchIdsStmt
-- must do this to avoid long hang-time on mass updates:
updatesStmt :: IxValue Integer -> ByteString
updatesStmt (IxV i vc) =
B.pack ("UPDATE article SET view_count=" ++ show vc
++ " WHERE id=" ++ show i ++ "; ")
updater :: Connection -> [IxValue Integer] -> IO ()
updater conn = void . execute_ conn . Query . B.unlines . map updatesStmt
-- executeMany has a 'feature' around formating multiple ? in a query. So we
-- have this work-around of bulk-update-as-many-updates-in-one-transaction.
-- make sure you do this in bulk, or it make take a while.
-- so, of course, you need a artid -> rndexp -> IxVal mapping function
viewCountsById :: Index -> Integer -> IxValue Integer
viewCountsById (idx -> artid) = IxV artid
-- and there you go!
{--
>>> connectInfo
ConnectInfo {connectHost = "...",...}
>>> conn <- connect it
>>> rnds <- evalState (mapM (const (rndExpRange (5000,25000))) (replicate 10000 ())) <$> getStdGen
>>> ids <- fetcher conn
>>> updater conn (zipWith viewCountsById ids rnds)
--}
-- ... do we want to create an application of this? This ... IS supposed to be
-- a one-time thing, so we'll only do this like ten times or so, smh.
| geophf/1HaskellADay | exercises/HAD/Y2017/M12/D11/Solution.hs | mit | 3,197 | 1 | 16 | 561 | 443 | 250 | 193 | 33 | 1 |
type Persona = (Nombre, Edad, Sexo, Caracteristicas, [Enfermedad], [Deporte], [Ocupacion])
type Nombre = [Char]
type Edad = Int
type Sexo = Char
type Caracteristicas = (Peso, Altura, Contextura)
type Altura = Double
type Peso = Double
type Contextura = [Char]
type Enfermedad = [Char]
type Deporte = [Char]
type Ocupacion = [Char]
personasDeEjemplo :: [Persona]
personasDeEjemplo = [("Mariano", 20, 'M', (68.0, 169.0, "Mediana"), [], ["basket"], ["estudiante"]),
("Leandro", 12, 'M', (38.0, 123.0, "Mediana"), ["alergias"], ["futbol", "skate", "taekwondo"], ["estudiante"]),
("Gisella", 30, 'F', (59.0, 162.0, "Pequeña"), [], ["pilates"], ["ama de casa", "maestra"]),
("Mara", 42, 'F', (88.0, 195.0, "Grande"), ["diabetes", "alergias"], [],["abogada", "profesora"]),
("Osvaldo", 25, 'M', (98.0, 165.0, "Grande"), [], [], ["empleado"])
]
caloriasPorTarea :: [([Char], Int)]
caloriasPorTarea = [("basket",1100), ("futbol",1100), ("skate",800), ("maestra", 320), ("estudiante", 220), ("empleado", 480)]
enfermedadesPeligrosas = ["diabetes", "asma", "anemia"]
darNombre (nombre, _, _, _, _, _, _) = nombre
darPeso (_, _, _, (peso, _, _), _, _, _) = peso
darEnfermedades (_, _, _, _, enfermedad, _, _) = enfermedad
--1)
sedentaria :: Persona -> Bool
sedentaria (_, _, _, _, _, deportes, ocupaciones) = (deportes == []) && (2 > (length ocupaciones))
--2)
activa :: Persona -> Bool
activa (_, _, _, _, _, deportes, ocupaciones) = (deportes /= []) || (2 <= (length ocupaciones))
--3)
pesoIdeal :: Persona -> Double
pesoIdeal (_, _, _, (_, altura, _), _, _, _) = 0.75 * (altura - 150) + 50
--4)
imc :: Persona -> Double
imc (_, _, _, (peso, altura, _), _, _, _) = imcDadoPesoYAltura peso altura
imcDadoPesoYAltura peso altura = 10000 * peso / (altura * altura)
--5)
estado :: Persona -> [Char]
estado (_, edad, _, (peso, altura, _), _, _, _) | edad > 24 = darEstado(round(imcDadoPesoYAltura peso altura) - (div (edad - 25) 10))
| otherwise = "error"
darEstado imc | imc < 20 = "bajo peso"
| (20 <= imc) && (imc < 25) = "peso normal"
| (25 >= imc) && (imc < 30) = "sobrepeso"
| otherwise = "obesidad"
--6)
personasEnEstado :: [Char] -> [Persona] -> [Nombre]
personasEnEstado estadoDado listaPersonas = [darNombre persona | persona <- listaPersonas, tieneEstado estadoDado persona]
tieneEstado estadoDado persona = (estadoDado == estado persona)
--7)
--a)
seleccionarPersonas :: (Persona -> Bool) -> [Persona] -> [Nombre]
seleccionarPersonas f listaPersonas = map darNombre (filter f listaPersonas)
--b)
practicaUnDeporteDado :: Deporte -> Persona -> Bool
practicaUnDeporteDado deporte (_, _, _, _, _, listaDeportes, _) = (filter (== deporte) listaDeportes) /= []
esMujer :: Persona -> Bool
esMujer (_, _, sexo, _, _, _, _) = sexo == 'F'
--c)
dentroDelRango :: Double -> Persona -> Bool
dentroDelRango rango persona = rango > (porcentajeDeDiferencia persona)
-- Esta formula no esta bien pero no se cual sera.
porcentajeDeDiferencia persona = 100 * abs(1 - (pesoIdeal persona / darPeso persona))
--8)
diferenciaDePeso :: [Persona] -> [(Nombre, Peso, Peso, Double)]
diferenciaDePeso listaPersonas = map darNuevaTupla listaPersonas
darNuevaTupla persona = (darNombre persona, pesoIdeal persona, darPeso persona, porcentajeDeDiferencia persona)
--9)
estaEnRiesgo :: Persona -> Bool
estaEnRiesgo persona = (porcentajeDeDiferencia persona > 80) || tieneEnfermedadPeligrosa persona
tieneEnfermedadPeligrosa persona = (filter esEnfermedadPeligrosa (darEnfermedades persona)) /= []
esEnfermedadPeligrosa enfermedad = elem enfermedad enfermedadesPeligrosas
--10)
calorias :: Persona -> [([Char], Int)] -> Int
calorias (_, _, _, _, _, deportes, ocupaciones) listaTareas = darCaloriasTotal (deportes ++ ocupaciones) listaTareas
darCaloriasTotal tareasRealizadas listaTareas = sumarCalorias (calcularCalorias tareasRealizadas listaTareas) tareasRealizadas (promedioLista (map snd listaTareas))
sumarCalorias listaCalorias tareasRealizadas promedio = sum listaCalorias + cantidadTareasNoEncontradas listaCalorias tareasRealizadas * promedio
calcularCalorias tareasRealizadas listaTareas = map (darCaloriasPorTarea listaTareas) (filter (seEncuentraTarea listaTareas) tareasRealizadas)
seEncuentraTarea listaTareas tarea = elem tarea (map fst listaTareas)
darCaloriasPorTarea listaTareas tarea = snd(head(filter ((== tarea) . fst) listaTareas))
cantidadTareasNoEncontradas listaCalorias listaTareas = length listaTareas - length listaCalorias
promedioLista lista = div (sum lista) (length lista)
| matiasm15/Haskell | TP Nutricionista.hs | mit | 4,692 | 0 | 12 | 834 | 1,743 | 999 | 744 | 67 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Nauva.Catalog.Types
( Page(..)
, Leaf(..)
, Directory(..)
, onlyLeaves
) where
import Data.Text (Text)
import Data.Monoid
import Nauva.Internal.Types
data Page
= PLeaf !Leaf
| PDirectory !Directory
data Leaf = Leaf
{ leafHref :: !Text
, leafTitle :: !Text
, leafElement :: !Element
}
data Directory = Directory
{ directoryTitle :: !Text
, directoryChildren :: ![Leaf]
}
-- | Return a flat list of 'Leaf' values. Useful when you want to enumerate all
-- (directly referenceable) URLs inside the catalog.
onlyLeaves :: [Page] -> [Leaf]
onlyLeaves [] = []
onlyLeaves (x:xs) = case x of
PLeaf leaf -> leaf : onlyLeaves xs
PDirectory d -> directoryChildren d <> onlyLeaves xs
| wereHamster/nauva | pkg/hs/nauva-catalog/src/Nauva/Catalog/Types.hs | mit | 835 | 0 | 10 | 236 | 210 | 119 | 91 | 38 | 2 |
{-|
Module : FRP.AST
Description : Abstract Syntax Tree
This module implements the AST of FRP programs
-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE NamedFieldPuns #-}
module FRP.AST (
Name
, Label
, EvalTerm
, Env
, initEnv
, Qualifier(..)
, Type(..)
, isStable
, typeAnn
, TyPrim(..)
, Term(..)
, Lit(..)
, Pattern(..)
, Value(..)
, valToTerm
, BinOp(..)
, Decl(..)
, Program(..)
, paramsToLams
, fixifyDecl
, unitFunc
) where
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as M
import Data.Set (Set)
import qualified Data.Set as S
import Data.String (IsString (..))
import FRP.Pretty
import Data.Data
-- |A Name is just a String for now
type Name = String
-- |A pointer label is just an Integer
type Label = Integer
-- -----------------------------------------------------------------------------
-- EvalTerm
-- -----------------------------------------------------------------------------
-- |A Term for evaluation is just annotated with unit
type EvalTerm = Term ()
instance IsString (EvalTerm) where
fromString x = TmVar () x
instance Num (EvalTerm) where
fromInteger = TmLit () . LNat . fromInteger
x + y = TmBinOp () Add x y
x * y = TmBinOp () Mult x y
x - y = TmBinOp () Sub x y
abs _x = undefined
signum = undefined
-- -----------------------------------------------------------------------------
-- Env
-- -----------------------------------------------------------------------------
-- |An evaluation environment is map from name to either
-- a term (lazy eval) or a value (strict)
type Env = Map String (Either EvalTerm Value)
instance Pretty (Map String (Either (Term a) Value)) where
ppr n env = char '[' $+$ nest 2 body $+$ char ']' where
body = vcat $ punctuate (char ',') $
map (\(k,v) -> text k <+> text "|->" <+> ppr (n+1) v) $ M.toList env
-- |The initial environment
initEnv :: Env
initEnv = M.empty
-- -----------------------------------------------------------------------------
-- Qualifier
-- -----------------------------------------------------------------------------
-- |A Qualifier qualifies a value as being available now,
-- always (stable) or later
data Qualifier
= QNow
| QStable
| QLater
deriving (Show, Eq, Data, Typeable)
instance Pretty Qualifier where
ppr n = \case
QNow -> text "now"
QStable -> text "stable"
QLater -> text "later"
-- -----------------------------------------------------------------------------
-- Type
-- -----------------------------------------------------------------------------
infixr 9 `TyArr`
-- |A Type in the FRP language
data Type a
-- |Type variable
= TyVar a Name
-- |Product type
| TyProd a (Type a) (Type a)
-- |Sum type
| TySum a (Type a) (Type a)
-- |Arrow (function) type
| TyArr a (Type a) (Type a)
-- |Later type
| TyLater a (Type a)
-- |Stable type
| TyStable a (Type a)
-- |Type of streams
| TyStream a (Type a)
-- |Recursive types
| TyRec a Name (Type a)
-- |Type of allocator tokens
| TyAlloc a
-- |Primitive types
| TyPrim a TyPrim
deriving (Show, Eq, Functor, Data, Typeable)
instance IsString (Type ()) where
fromString x = TyVar () x
instance Pretty (Type a) where
ppr n type' = case type' of
TyVar _a name -> text name
TyProd _a ty ty' -> prns (ppr (n+1) ty <+> text "*" <+> ppr (n+1) ty')
TySum _a ty ty' -> prns (ppr (n+1) ty <+> text "+" <+> ppr (n+1) ty')
TyArr _a ty ty' -> prns $ ppr (n+1) ty <+> text "->" <+> ppr 0 ty'
TyLater _a ty -> text "@" <> ppr (n+1) ty
TyStable _a ty -> text "#" <> ppr (n+1) ty
TyStream _a ty -> prns $ char 'S' <+> ppr (n+1) ty
TyRec _a nm ty -> prns $ text "mu" <+> text nm <> char '.' <+> ppr 0 ty
TyAlloc _a -> text "alloc"
TyPrim _a p -> ppr n p
where
prns = if (n > 0)
then parens
else id
-- |Get the annotation of a type (typically position in source)
typeAnn :: Type a -> a
typeAnn = \case
TyVar a _ -> a
TyProd a _ _ -> a
TySum a _ _ -> a
TyArr a _ _ -> a
TyLater a _ -> a
TyStable a _ -> a
TyStream a _ -> a
TyRec a _ _ -> a
TyAlloc a -> a
TyPrim a _ -> a
-- |Checks if a 'Type' is Stable
isStable :: Type t -> Bool
isStable (TyPrim _ _ ) = True
isStable (TyProd _ a b) = isStable a && isStable b
isStable (TySum _ a b) = isStable a && isStable b
isStable (TyStable _ _) = True
isStable _ = False
-- |Primitive types (bool, nat or unit)
data TyPrim = TyBool | TyNat | TyUnit | TyBot deriving (Show, Eq, Data, Typeable)
instance Pretty TyPrim where
ppr n = text . \case
TyBool -> "Bool"
TyNat -> "Nat"
TyUnit -> "()"
TyBot -> "_|_"
-- -----------------------------------------------------------------------------
-- Term
-- -----------------------------------------------------------------------------
-- |Terms in the FRP language
data Term a
-- |fst
= TmFst a (Term a)
-- |snd
| TmSnd a (Term a)
-- |A tuple
| TmTup a (Term a) (Term a)
-- |Left injection
| TmInl a (Term a)
-- |Right injection
| TmInr a (Term a)
-- |Case pattern match
| TmCase a (Term a) (Name, (Term a)) (Name, (Term a))
-- |A lambda
| TmLam a Name (Maybe (Type a)) (Term a)
-- |A variable use
| TmVar a Name
-- |Application of a term to another term
| TmApp a (Term a) (Term a)
-- |Stream Cons
| TmCons a (Term a) (Term a)
-- |@out@ for recursive type elimination
| TmOut a (Type a) (Term a)
-- |@into@ for recursive type introduction
| TmInto a (Type a) (Term a)
-- |Attempt to make a value stable
| TmStable a (Term a)
-- |Delay a value with an allocation token
| TmDelay a (Term a) (Term a)
-- |Promote a term of a stable type
| TmPromote a (Term a)
-- |A let binding with a a pattern
| TmLet a Pattern (Term a) (Term a)
-- |A value-level literal
| TmLit a Lit
-- |A binary operation
| TmBinOp a BinOp (Term a) (Term a)
-- |If-then-else
| TmITE a (Term a) (Term a) (Term a)
-- |A pointer (not syntactic)
| TmPntr a Label
-- |A pointer dereference (not syntactic)
| TmPntrDeref a Label
-- |An allocator token
| TmAlloc a
-- |A fixpoint!
| TmFix a Name (Maybe (Type a)) (Term a)
-- |Haskell input
| TmInput a Name
deriving (Show, Eq, Functor, Data, Typeable)
instance Pretty (Term a) where
ppr n term = case term of
TmFst _a trm -> text "fst" <+> ppr (n+1) trm
TmSnd _a trm -> text "snd" <+> ppr (n+1) trm
TmTup _a trm trm' -> parens $ ppr (n+1) trm <> comma <+> ppr (n+1) trm'
TmInl _a trm -> text "inl" <+> prns (ppr (n+1) trm)
TmInr _a trm -> text "inr" <+> prns (ppr (n+1) trm)
TmCase _a trm (vl, trml) (vr, trmr) ->
text "case" <+> ppr 0 trm <+> text "of"
$$ nest (2) (text "| inl" <+> text vl <+> text "->" <+> ppr (0) trml)
$$ nest (2) (text "| inr" <+> text vr <+> text "->" <+> ppr (0) trmr)
TmLam _a b mty trm ->
let pty = maybe mempty (\t -> char ':' <> ppr 0 t) mty
maybePrns = maybe id (const parens) mty
in prns (text "\\" <> maybePrns (text b <> pty) <+> text "->" <+> ppr (n) trm)
TmFix _a b ty trm -> prns (text "fix" <+> text b <> char '.' <+> ppr (n+1) trm)
TmVar _a v -> text v
TmApp _a trm trm' -> prns (ppr 0 trm <+> ppr (n+1) trm')
TmCons _a hd tl -> text "cons" <> parens (ppr (n+1) hd <> comma <+> ppr (n+1) tl)
TmDelay _a alloc trm -> text "delay" <> parens (ppr 0 alloc <> comma <+> ppr 0 trm)
TmStable _a trm -> text "stable" <> parens (ppr 0 trm)
TmPromote _a trm -> text "promote" <> parens (ppr 0 trm)
TmLet _a ptn trm trm' -> text "let" <+> ppr (0) ptn <+> text "="
<+> ppr (n) trm <+> text "in" $$ ppr (0) trm'
TmLit _a l -> ppr n l
TmBinOp _a op l r -> prns (ppr (n+1) l <+> ppr n op <+> ppr (n+1) r)
TmITE _a b trmt trmf ->
text "if" <+> ppr n b
$$ nest 2 (text "then" <+> ppr (n+1) trmt)
$$ nest 2 (text "else" <+> ppr (n+1) trmf)
TmPntr _a pntr -> text "&[" <> integer pntr <> text "]"
TmPntrDeref _a pntr -> text "*[" <> integer pntr <> text "]"
TmAlloc _a -> text "<>"
TmOut _a ty trm -> text "out" <+> parens (ppr 0 ty)
<+> prns (ppr (n) trm)
TmInto _a ty trm -> text "into" <+> parens (ppr 0 ty)
<+> prns (ppr (n) trm)
TmInput _a nm -> text "input" <> (parens . text) nm
where
prns = if (n > 0)
then parens
else id
-- |Get the free variables in a term
freeVars :: Term a -> [Name]
freeVars = S.toList . go where
go = \case
TmFst a t -> go t
TmSnd a t -> go t
TmTup a t1 t2 -> go t1 +++ go t2
TmInl a t -> go t
TmInr a t -> go t
TmCase a t (ln, lt) (rn, rt) -> (go lt // ln) +++ (go rt // rn)
TmLam a nm mty t -> go t // nm
TmVar a nm -> S.singleton nm
TmApp a t1 t2 -> go t1 +++ go t2
TmCons a t1 t2 -> go t1 +++ go t2
TmOut a _ t -> go t
TmInto a _ t -> go t
TmStable a t -> go t
TmDelay a t1 t2 -> go t1 +++ go t2
TmPromote a t -> go t
TmLet a pat t1 t2 -> (go t1 +++ go t2) \\ bindings pat
TmLit a l -> S.empty
TmBinOp a op t1 t2 -> go t1 +++ go t2
TmITE a b tt tf -> go b +++ go tt +++ go tf
TmPntr a lbl -> S.empty
TmPntrDeref a lbl -> S.empty
TmAlloc a -> S.empty
TmFix a nm mty t -> go t // nm
TmInput a nm -> S.empty
(+++) = S.union
(//) = flip S.delete
(\\) = (S.\\)
-- Get the bindings in a pattern
bindings = \case
PBind nm -> S.singleton nm
PDelay nm -> S.singleton nm
PCons pat1 pat2 -> bindings pat1 +++ bindings pat2
PStable pat -> bindings pat
PTup pat1 pat2 -> bindings pat1 +++ bindings pat2
-- -----------------------------------------------------------------------------
-- Value
-- -----------------------------------------------------------------------------
-- |A Value is a term that is evaluated to normal form
data Value
-- |A tuple
= VTup Value Value
-- |Left injection
| VInl Value
-- |Right injection
| VInr Value
-- |A closure
| VClosure Name EvalTerm Env
-- |A pointer
| VPntr Label
-- |An allocation token
| VAlloc
-- |A stable value
| VStable Value
-- |A value of a recursive type
| VInto Value
-- |A stream Cons
| VCons Value Value
-- |A value literal
| VLit Lit
deriving (Show, Eq, Data, Typeable)
-- Convert a value back into a term
valToTerm :: Value -> EvalTerm
valToTerm = \case
VTup a b -> TmTup () (valToTerm a) (valToTerm b)
VInl v -> TmInl () (valToTerm v)
VInr v -> TmInr () (valToTerm v)
VClosure x e env -> TmLam () x Nothing (fmap (const ()) e)
VPntr l -> TmPntr () l
VAlloc -> TmAlloc ()
VStable v -> TmStable () (valToTerm v)
VInto v -> TmInto () (TyPrim () TyUnit) (valToTerm v)
VCons hd tl -> TmCons () (valToTerm hd) (valToTerm tl)
VLit l -> TmLit () l
instance Pretty Value where
ppr x = ppr x . valToTerm
-- -----------------------------------------------------------------------------
-- Pattern
-- -----------------------------------------------------------------------------
-- |A Pattern used in a let binding
data Pattern
= PBind Name -- ^Bind a name
| PDelay Name -- ^Bind a delayed name
| PCons Pattern Pattern -- ^Match on a Cons cell
| PStable Pattern -- ^Match on a stable value
| PTup Pattern Pattern -- ^Match on tuple
deriving (Show, Eq, Data, Typeable)
instance Pretty Pattern where
ppr n pat = case pat of
PBind nm -> text nm
PCons p1 p2 -> text "cons" <> parens (ppr (n+1) p1 <> comma <+> ppr (n+1) p2)
PDelay p1 -> text "delay" <> parens (text p1)
PStable p1 -> text "stable" <> parens (ppr (n+1) p1)
PTup p1 p2 -> char '(' <> ppr 0 p1 <> char ',' <+> ppr 0 p2 <> char ')'
instance IsString Pattern where
fromString x = PBind x
-- -----------------------------------------------------------------------------
-- BinOp
-- -----------------------------------------------------------------------------
-- |A binary operator
data BinOp
= Add
| Sub
| Mult
| Div
| And
| Or
| Leq
| Lt
| Geq
| Gt
| Eq
deriving (Show, Eq, Data, Typeable)
instance Pretty BinOp where
ppr _ op = text $ case op of
Add -> "+"
Sub -> "-"
Mult -> "*"
Div -> "/"
And -> "&&"
Or -> "||"
Leq -> "<="
Lt -> "<"
Geq -> ">="
Gt -> ">"
Eq -> "=="
-- -----------------------------------------------------------------------------
-- A value literal
-- -----------------------------------------------------------------------------
data Lit
= LNat Int
| LBool Bool
| LUnit
| LUndefined
deriving (Show, Eq, Data, Typeable)
instance Pretty Lit where
ppr _ lit = case lit of
LNat i -> if (i >= 0) then int i else parens (int i)
LBool b -> text $ show b
LUnit -> text "()"
LUndefined -> text "undefined"
-- -----------------------------------------------------------------------------
-- Decl
-- -----------------------------------------------------------------------------
-- |A declaration has an annotation, a type, a name and a body that is a term
data Decl a =
Decl { _ann :: a
, _type :: Type a
, _name :: Name
, _body :: Term a
}
deriving (Show, Eq, Functor, Data, Typeable)
instance Pretty (Decl a) where
ppr n = go n . unfixifyDecl where
go n (Decl _a ty nm bd) =
let (bs, bd') = bindings bd
in text nm <+> char ':' <+> ppr n ty
$$ hsep (map text (nm : bs)) <+> char '='
$$ nest 2 (ppr 0 bd' <> char '.')
where
bindings (TmLam _a x _ b) =
let (y, b') = bindings b
in (x:y, b')
bindings b = ([], b)
-- -----------------------------------------------------------------------------
-- Program
-- -----------------------------------------------------------------------------
-- |A Program is simply a list of declarations and a list of imports.
-- The imports are not used right now though (and cannot be parsed either)
data Program a = Program { _imports :: [String], _decls :: [Decl a] }
deriving (Show, Eq, Functor, Data, Typeable)
instance Pretty (Program a) where
ppr n (Program {_decls = decls}) =
vcat (map (\d -> ppr n d <> char '\n') decls)
-- -----------------------------------------------------------------------------
-- Utility functions
-- -----------------------------------------------------------------------------
-- |Convert any functor to a unit-functor
unitFunc :: Functor f => f a -> f ()
unitFunc = fmap (const ())
-- |Desugar a multi-parameter lambda to nested lambdas
-- @\x y z -> x (y z)@ becomes
-- @\x -> \y -> \z -> x (y z)$
paramsToLams :: a -> [(String, Maybe (Type a))] -> Term a -> Term a
paramsToLams b = foldl (\acc (x,t) y -> acc (TmLam b x t y)) id
-- |Desugar a recursive definition to a fixpoint
fixifyDecl :: Decl t -> Decl t
fixifyDecl decl@(Decl {_ann, _name, _type, _body}) =
if _name `elem` freeVars _body
then decl {_body = TmFix _ann _name (Just _type) _body}
else decl
-- |Convert a fixpoint back into a recursive definition
-- FIXME: Will only work if the name bound by fix is _name
unfixifyDecl :: Decl t -> Decl t
unfixifyDecl decl@(Decl {_ann, _name, _type, _body}) =
case _body of
TmFix _a nm mty bd ->
if nm == _name
then decl {_body = bd}
else decl
_ -> decl | adamschoenemann/simple-frp | src/FRP/AST.hs | mit | 16,352 | 0 | 19 | 4,819 | 5,458 | 2,787 | 2,671 | -1 | -1 |
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
module Data.Vinyl.Lens
( RElem(..)
, RSubset(..)
, REquivalent
, type (∈)
, type (⊆)
, type (≅)
, type (<:)
, type (:~:)
) where
import Data.Vinyl.Core
import Data.Vinyl.Functor
import Data.Vinyl.TypeLevel
import Data.Typeable (Proxy(..))
-- | The presence of a field in a record is witnessed by a lens into its value.
-- The third parameter to 'RElem', @i@, is there to help the constraint solver
-- realize that this is a decidable predicate with respect to the judgemental
-- equality in @k@.
class i ~ RIndex r rs => RElem (r :: k) (rs :: [k]) (i :: Nat) where
-- | We can get a lens for getting and setting the value of a field which is
-- in a record. As a convenience, we take a proxy argument to fix the
-- particular field being viewed. These lenses are compatible with the @lens@
-- library. Morally:
--
-- > rlens :: sing r => Lens' (Rec f rs) (f r)
rlens
:: Functor g
=> sing r
-> (f r -> g (f r))
-> Rec f rs
-> g (Rec f rs)
-- | For Vinyl users who are not using the @lens@ package, we provide a getter.
rget
:: sing r
-> Rec f rs
-> f r
rget k = getConst . rlens k Const
-- | For Vinyl users who are not using the @lens@ package, we also provide a
-- setter. In general, it will be unambiguous what field is being written to,
-- and so we do not take a proxy argument here.
rput
:: f r
-> Rec f rs
-> Rec f rs
rput y = getIdentity . rlens Proxy (\_ -> Identity y)
-- This is an internal convenience stolen from the @lens@ library.
lens
:: Functor f
=> (t -> s)
-> (t -> a -> b)
-> (s -> f a)
-> t
-> f b
lens sa sbt afb s = fmap (sbt s) $ afb (sa s)
{-# INLINE lens #-}
instance RElem r (r ': rs) Z where
rlens _ f (x :& xs) = fmap (:& xs) (f x)
{-# INLINE rlens #-}
instance (RIndex r (s ': rs) ~ S i, RElem r rs i) => RElem r (s ': rs) (S i) where
rlens p f (x :& xs) = fmap (x :&) (rlens p f xs)
{-# INLINE rlens #-}
-- | If one field set is a subset another, then a lens of from the latter's
-- record to the former's is evident. That is, we can either cast a larger
-- record to a smaller one, or we may replace the values in a slice of a
-- record.
class is ~ RImage rs ss => RSubset (rs :: [k]) (ss :: [k]) is where
-- | This is a lens into a slice of the larger record. Morally, we have:
--
-- > rsubset :: Lens' (Rec f ss) (Rec f rs)
rsubset
:: Functor g
=> (Rec f rs -> g (Rec f rs))
-> Rec f ss
-> g (Rec f ss)
-- | The getter of the 'rsubset' lens is 'rcast', which takes a larger record
-- to a smaller one by forgetting fields.
rcast
:: Rec f ss
-> Rec f rs
rcast = getConst . rsubset Const
{-# INLINE rcast #-}
-- | The setter of the 'rsubset' lens is 'rreplace', which allows a slice of
-- a record to be replaced with different values.
rreplace
:: Rec f rs
-> Rec f ss
-> Rec f ss
rreplace rs = getIdentity . rsubset (\_ -> Identity rs)
{-# INLINE rreplace #-}
instance RSubset '[] ss '[] where
rsubset = lens (const RNil) const
instance (RElem r ss i , RSubset rs ss is) => RSubset (r ': rs) ss (i ': is) where
rsubset = lens (\ss -> rget Proxy ss :& rcast ss) set
where
set :: Rec f ss -> Rec f (r ': rs) -> Rec f ss
set ss (r :& rs) = rput r $ rreplace rs ss
-- | Two record types are equivalent when they are subtypes of each other.
type REquivalent rs ss is js = (RSubset rs ss is, RSubset ss rs js)
-- | A shorthand for 'RElem' which supplies its index.
type r ∈ rs = RElem r rs (RIndex r rs)
-- | A shorthand for 'RSubset' which supplies its image.
type rs ⊆ ss = RSubset rs ss (RImage rs ss)
-- | A shorthand for 'REquivalent' which supplies its images.
type rs ≅ ss = REquivalent rs ss (RImage rs ss) (RImage ss rs)
-- | A non-unicode equivalent of @(⊆)@.
type rs <: ss = rs ⊆ ss
-- | A non-unicode equivalent of @(≅)@.
type rs :~: ss = rs ≅ ss
| plow-technologies/Vinyl | Data/Vinyl/Lens.hs | mit | 4,274 | 0 | 14 | 1,119 | 1,111 | 604 | 507 | -1 | -1 |
{-# OPTIONS_GHC -F -pgmF hspec-discover #-}
--module Main where
--
--import Test.Hspec
--
--main :: IO ()
--main = hspec $ do
-- describe "trivial" $ do
-- it "should be true" $ do
-- True `shouldBe` True
| parsonsmatt/QuickLift | test/Spec.hs | mit | 215 | 0 | 2 | 48 | 12 | 11 | 1 | 1 | 0 |
module TigerColor
(
color
, Allocation
)
where
import TigerInterference
import TigerTemp
import TigerRegisters
import qualified TigerGraph as Gr
import qualified Data.Map as Map
import Data.List
import Data.Maybe
type Allocation = Map.Map Temp Register
reducelist :: [Maybe a] -> [a]
reducelist xs = reducelist' xs []
where reducelist' [] list = list
reducelist' (a:as) list = case a of
Nothing -> reducelist' as list
Just a' -> reducelist' as (a':list)
canreduce :: IGraph -> Allocation -> Int -> Maybe (Gr.Node Temp)
canreduce (IGRAPH gr tn _ _) coloring deg =
let ns = Gr.nodes gr
coloredtemps = Map.keys coloring
coloredunodes = reducelist $ map (flip Map.lookup tn) coloredtemps
colorednodes = map (fromJust . flip Gr.labeledNode gr) coloredunodes
rest = ns \\ colorednodes
degree n = length $ Gr.adj n gr
in case rest of
[] -> Nothing
xs -> case find (\n -> degree n < deg) xs of
Just n' -> Just n'
Nothing -> Nothing
allcolored :: IGraph -> Allocation -> Bool
allcolored (IGRAPH gr _ _ _) coloring =
let ns = Gr.nodes gr
temps = map snd ns
in all (\t -> Map.member t coloring) temps
getcolor :: (Gr.Node Temp) -> Allocation -> Maybe Register
getcolor n coloring = Map.lookup (snd n) coloring
color :: IGraph -> Allocation -> [Register] -> Allocation
color ig@(IGRAPH gr tn gt mvs) initial colors =
case canreduce ig initial $ length colors of
Nothing -> if allcolored ig initial then initial else error "Compiler error: Not enough colors for register allocation."
Just n -> let un = fst n
neighborcolors = reducelist $ map (flip getcolor initial) $ Gr.adj n gr
availcolors = colors \\ neighborcolors
g' = Gr.rmNode un gr
coloring = color (IGRAPH g' tn gt mvs) initial $ tail availcolors
in Map.insert (snd n) (head availcolors) coloring
| hengchu/tiger-haskell | src/tigercolor.hs | mit | 2,037 | 0 | 16 | 593 | 710 | 359 | 351 | 48 | 3 |
{-# LANGUAGE DoAndIfThenElse #-}
{-|
Copyright (c) 2014 Maciej Bendkowski
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-}
module ParserUtils where
import Control.Monad
import Data.Char
{-|
Recursive descent parser type definition.
-}
newtype Parser a = Parser (String -> [(a, String)])
parse :: Parser a -> String -> [(a, String)]
parse (Parser p) = p
{-|
Monadic parser definition.
-}
instance Monad Parser where
return x = Parser $ \s -> [(x, s)]
p >>= f = Parser $ \s -> concat [ parse (f x) s' | (x, s') <- parse p s]
instance MonadPlus Parser where
mzero = Parser $ const []
p `mplus` q = Parser $ \s -> parse p s ++ parse q s
{-|
Deterministic choice argument
-}
dmplus :: Parser a -> Parser a -> Parser a
p `dmplus` q = Parser $ \s -> case parse (p `mplus` q) s of
(x:_) -> [x]
_ -> []
{-|
Single char parser
-}
item :: Parser Char
item = Parser $ \s -> case s of
x:xs -> [(x, xs)]
_ -> []
{-|
Single char predicate parser
-}
itemPred :: (Char -> Bool) -> Parser Char
itemPred p = do
x <- item
if p x then return x
else mzero
{-|
Single functional char parser
-}
char :: Char -> Parser Char
char x = itemPred (x ==)
{-|
Single functional string parser
-}
str :: String -> Parser String
str "" = return ""
str (x:xs) = do
_ <- char x
_ <- str xs
return (x:xs)
{-|
Kleene star operator
-}
star :: Parser a -> Parser [a]
star p = pstar p `dmplus` return []
{-|
Kleene plus operator
-}
pstar :: Parser a -> Parser [a]
pstar p = do
x <- p
xs <- star p
return (x:xs)
{-|
Whitespace parser
-}
space :: Parser String
space = star $ itemPred isSpace
{-|
Token parser removing trailing space.
-}
token :: Parser a -> Parser a
token p = do
x <- p
_ <- space
return x
{-|
Symbolic token parser
-}
symb :: String -> Parser String
symb s = token $ str s
{-|
Applies a parser removing leading whitespace.
-}
apply :: Parser a -> String -> [(a, String)]
apply p = parse (do { _ <- space; p }) | maciej-bendkowski/LCCLUtils | src/ParserUtils.hs | mit | 3,534 | 0 | 12 | 1,218 | 767 | 399 | 368 | 52 | 2 |
module E14 where
type MyType = Integer
definition :: MyType
definition = definitionOne * definitionTwo
where
definitionOne :: MyType
definitionTwo :. MyType -- German keyboard.
definitionOne = 1
definitionTwo = 1
{-
type MyType = Integer
definition :: MyType
definition = definitionOne * definitionTwo
where
definitionOne :: MyType
definitionTwo :: MyType
definitionOne = 1
definitionTwo = 1
-} | pascal-knodel/haskell-craft | Examples/· Errors/E14.hs | mit | 610 | 0 | 8 | 273 | 51 | 30 | 21 | -1 | -1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
module Phb.Types.Project where
import BasePrelude hiding (index)
import Prelude ()
import Control.Lens
import Data.Text (Text)
import Data.Time
import Database.Persist (Entity, Key)
import Phb.Db.Enums
import qualified Phb.Db.Internal as D
data ProjectStatus = ProjectStatus
{ _projectStatusKey :: Key D.ProjectStatus
, _projectStatusPhase :: Text
, _projectStatusColour :: StatusColourEnum
, _projectStatusDesc :: Maybe Text
} deriving Show
makeLenses ''ProjectStatus
data TargetDate = TargetDate
{ _targetDateDay :: Day
, _targetDateDesc :: Text
, _targetDateHandwavy :: Maybe Text
} deriving Show
makeLenses ''TargetDate
data Project = Project
{ _projectKey :: Key D.Project
, _projectName :: Text
, _projectCustomers :: [Entity D.Customer]
, _projectStatuses :: [ProjectStatus]
, _projectStakeholders :: [Entity D.Person]
, _projectTargetDates :: [TargetDate]
, _projectEffortDays :: Double
, _projectPriority :: Int
, _projectStarted :: Day
, _projectFinished :: Maybe Day
, _projectNotes :: [Entity D.ProjectNote]
} deriving Show
makeLenses ''Project
projectStatusLatest :: IndexedTraversal' Int Project ProjectStatus
projectStatusLatest = projectStatuses . traversed . index 0
projectNoteLatest :: IndexedTraversal' Int Project (Entity D.ProjectNote)
projectNoteLatest = projectNotes . traversed . index 0
| benkolera/phb | hs/Phb/Types/Project.hs | mit | 1,551 | 0 | 11 | 312 | 354 | 206 | 148 | 43 | 1 |
doSomething a
|a==0 =putStrLn "hello"
|otherwise = putStrLn "bye"
| sushantmahajan/programs | haskell/test.hs | cc0-1.0 | 74 | 1 | 8 | 17 | 32 | 14 | 18 | 3 | 1 |
{-# LANGUAGE TemplateHaskell #-}
module PL.Struktur where
import PL.Signatur
import PL.Util
import Autolib.TES.Identifier
import Autolib.FiniteMap
import Autolib.Size
import Autolib.Set
import Autolib.Reader
import Autolib.ToDoc
import Autolib.Reporter
import Data.Typeable
data Predicate u = Predicate { unPredicate :: Set [u] }
deriving ( Eq, Ord, Typeable )
instance Size ( Predicate u ) where
size ( Predicate s ) = cardinality s
instance ToDoc u => ToDoc ( Predicate u ) where
toDoc ( Predicate ts ) = as_set ts
data Tuple a = Tuple [a]
instance ToDoc a => ToDoc ( Tuple a ) where
toDoc ( Tuple xs ) = parens $ Autolib.ToDoc.sepBy comma $ map toDoc xs
as_set ts = braces $ Autolib.ToDoc.sepBy comma $ do
t <- setToList $ ts
return $ toDoc $ Tuple t
instance ( Ord u, Reader u ) => Reader ( Predicate u ) where
reader = fmap Predicate from_set
data Function u = Function { unFunction :: FiniteMap [u] u }
deriving ( Eq, Ord, Typeable )
instance Size ( Function u ) where
size ( Function f ) = sizeFM f
instance ( Ord u, ToDoc u ) => ToDoc ( Function u ) where
toDoc ( Function fm ) = as_set $ mkSet $ do
( xs, y ) <- fmToList fm
return $ xs ++ [y]
instance ( Ord u, Reader u ) => Reader ( Function u ) where
reader = do
tuples <- from_set
return $ Function $ listToFM $ do
tu <- setToList $ tuples
return ( init tu, last tu )
from_set :: ( Ord u, Reader u ) => Parser ( Set [u] )
from_set = fmap mkSet
$ my_braces $ ( `Autolib.Reader.sepBy` my_comma )
$ tuple
tuple :: Reader u => Parser [u]
tuple = do my_parens $ ( `Autolib.Reader.sepBy` my_comma ) $ reader
<|> do x <- reader ; return [x]
instance Reader u => Reader ( Tuple u ) where
reader = fmap Tuple tuple
data Ord u => Struktur u =
Struktur { universum :: Set u
, predicates :: FiniteMap Identifier ( Predicate u )
, functions :: FiniteMap Identifier ( Function u )
}
deriving ( Eq, Ord, Typeable )
instance Ord u => Size ( Struktur u ) where
size s = cardinality ( universum s )
+ sum ( do ( r, rr ) <- fmToList $ predicates s ; return $ size rr )
+ sum ( do ( f, ff ) <- fmToList $ functions s ; return $ size ff )
instance ( ToDoc u, Ord u ) => Signed ( Struktur u ) where
check sig s = do
let dom = universum s
checkit "Funktionssymbol"
( keysFM . unFunction ) ( funktionen sig ) ( functions s ) dom
checkit "Relationssymbol"
( setToList . unPredicate ) ( relationen sig ) ( predicates s ) dom
checkit tag get_args arities values dom = do
required_symbols_are_present tag get_args arities values
no_additional_symbols tag arities values
check_domain_for tag dom values
check_domain_for tag dom values = sequence_ $ do
( k, v ) <- fmToList values
let msg = vcat
[ text "Interpretation für" <+> text tag <+> toDoc k
, text "verwendet Elemente außerhalb des Universums:"
]
return $ check_domain msg dom v
class Check_Domain con where
check_domain :: ( Ord u, ToDoc u )
=> Doc -> Set u -> con u
-> Reporter ()
instance Check_Domain Function where
check_domain tag dom fun = sequence_ $ do
( ks, v ) <- fmToList $ unFunction fun
let ok = all ( `elementOf` dom ) $ v : ks
return $ when ( not ok ) $ reject $ vcat
[ tag
, nest 4 $ toDoc ( Tuple $ ks ++ [v] )
]
instance Check_Domain Predicate where
check_domain tag dom pred = sequence_ $ do
ks <- setToList $ unPredicate pred
let ok = all ( `elementOf` dom ) ks
return $ when ( not ok ) $ reject $ vcat
[ tag
, nest 4 $ toDoc ( Tuple ks )
]
no_additional_symbols tag arities values = sequence_ $ do
( f, _ ) <- fmToList values
return $ case lookupFM arities f of
Just _ -> return ()
Nothing -> reject $ hsep [ text tag, toDoc f, text "ist nicht in Signatur" ]
required_symbols_are_present tag get_args arities values = sequence_ $ do
( f, arity ) <- fmToList $ arities
return $ do
this <- find_or_complain tag values f
sequence_ $ do
arg <- get_args this
return $ do
when ( length arg /= arity ) $ reject $ vcat
[ text "Interpretation für" <+> text tag <+> toDoc f
, text "Falsche Stelligkeit für" <+> toDoc arg
]
empty :: Ord u
=> Signatur
-> Set u
-> Struktur u
empty sig uni =
Struktur { universum = uni
, predicates = listToFM $ do
( p, a ) <- fmToList $ relationen sig
return ( p, Predicate emptySet )
, functions = listToFM $ do
( f, a ) <- fmToList $ funktionen sig
return ( f, Function emptyFM )
}
$(derives [makeReader, makeToDoc] [''Struktur])
-- local variables:
-- mode: haskell
-- end:
| florianpilz/autotool | src/PL/Struktur.hs | gpl-2.0 | 4,897 | 170 | 13 | 1,437 | 1,728 | 922 | 806 | 121 | 2 |
{-# LANGUAGE TemplateHaskell #-}
module Persistence.Schema.MappingOrigin where
import Data.List (isPrefixOf)
import Database.Persist.TH
data MappingOrigin = SeeTarget
| SeeSource
| TEST
| DGLinkVerif
| DGImpliesLink
| DGLinkExtension
| DGLinkTranslation
| DGLinkClosedLenv
| DGLinkImports
| DGLinkIntersect
| DGLinkMorph
| DGLinkInst
| DGLinkInstArg
| DGLinkView
| DGLinkAlign
| DGLinkFitView
| DGLinkFitViewImp
| DGLinkProof
| DGLinkFlatteningUnion
| DGLinkFlatteningRename
| DGLinkRefinement
deriving Eq
instance Show MappingOrigin where
show SeeTarget = "see_target"
show SeeSource = "see_source"
show TEST = "test"
show DGLinkVerif = "dg_link_verif"
show DGImpliesLink = "dg_implies_link"
show DGLinkExtension = "dg_link_extension"
show DGLinkTranslation = "dg_link_translation"
show DGLinkClosedLenv = "dg_link_closed_lenv"
show DGLinkImports = "dg_link_imports"
show DGLinkIntersect = "dg_link_intersect"
show DGLinkMorph = "dg_link_morph"
show DGLinkInst = "dg_link_inst"
show DGLinkInstArg = "dg_link_inst_arg"
show DGLinkView = "dg_link_view"
show DGLinkAlign = "dg_link_align"
show DGLinkFitView = "dg_link_fit_view"
show DGLinkFitViewImp = "dg_link_fit_view_imp"
show DGLinkProof = "dg_link_proof"
show DGLinkFlatteningUnion = "dg_link_flattening_union"
show DGLinkFlatteningRename = "dg_link_flattening_rename"
show DGLinkRefinement = "dg_link_refinement"
instance Read MappingOrigin where
readsPrec _ input
| show SeeTarget `isPrefixOf` input = [(SeeTarget, drop (length $ show SeeTarget) input)]
| show SeeSource `isPrefixOf` input = [(SeeSource, drop (length $ show SeeSource) input)]
| show TEST `isPrefixOf` input = [(TEST, drop (length $ show TEST) input)]
| show DGLinkVerif `isPrefixOf` input = [(DGLinkVerif, drop (length $ show DGLinkVerif) input)]
| show DGImpliesLink `isPrefixOf` input = [(DGImpliesLink, drop (length $ show DGImpliesLink) input)]
| show DGLinkExtension `isPrefixOf` input = [(DGLinkExtension, drop (length $ show DGLinkExtension) input)]
| show DGLinkTranslation `isPrefixOf` input = [(DGLinkTranslation, drop (length $ show DGLinkTranslation) input)]
| show DGLinkClosedLenv `isPrefixOf` input = [(DGLinkClosedLenv, drop (length $ show DGLinkClosedLenv) input)]
| show DGLinkImports `isPrefixOf` input = [(DGLinkImports, drop (length $ show DGLinkImports) input)]
| show DGLinkIntersect `isPrefixOf` input = [(DGLinkIntersect, drop (length $ show DGLinkIntersect) input)]
| show DGLinkMorph `isPrefixOf` input = [(DGLinkMorph, drop (length $ show DGLinkMorph) input)]
| show DGLinkInst `isPrefixOf` input = [(DGLinkInst, drop (length $ show DGLinkInst) input)]
| show DGLinkInstArg `isPrefixOf` input = [(DGLinkInstArg, drop (length $ show DGLinkInstArg) input)]
| show DGLinkView `isPrefixOf` input = [(DGLinkView, drop (length $ show DGLinkView) input)]
| show DGLinkAlign `isPrefixOf` input = [(DGLinkAlign, drop (length $ show DGLinkAlign) input)]
| show DGLinkFitView `isPrefixOf` input = [(DGLinkFitView, drop (length $ show DGLinkFitView) input)]
| show DGLinkFitViewImp `isPrefixOf` input = [(DGLinkFitViewImp, drop (length $ show DGLinkFitViewImp) input)]
| show DGLinkProof `isPrefixOf` input = [(DGLinkProof, drop (length $ show DGLinkProof) input)]
| show DGLinkFlatteningUnion `isPrefixOf` input = [(DGLinkFlatteningUnion, drop (length $ show DGLinkFlatteningUnion) input)]
| show DGLinkFlatteningRename `isPrefixOf` input = [(DGLinkFlatteningRename, drop (length $ show DGLinkFlatteningRename) input)]
| show DGLinkRefinement `isPrefixOf` input = [(DGLinkRefinement, drop (length $ show DGLinkRefinement) input)]
| otherwise = []
derivePersistField "MappingOrigin"
| spechub/Hets | Persistence/Schema/MappingOrigin.hs | gpl-2.0 | 4,161 | 0 | 12 | 970 | 1,184 | 626 | 558 | 73 | 0 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE NoImplicitPrelude #-}
-- TODO: Less dependencies. I wonder if there's a tool that can tell me about unused imports
module Data.Stdf.Parser
( parseFile
, parse
)
where
import Data.Binary.Get hiding (Fail)
import qualified Data.ByteString.Lazy.Char8 as BL
import qualified Data.ByteString.Char8 as Char8
import Data.Bits (testBit, (.&.), shiftR)
import Control.Applicative
import Prelude hiding (Left, Right, replicate)
import qualified Prelude
import Control.Monad
import qualified Data.ByteString.Base64 as Base64
import qualified Data.Text.Encoding as Text
import qualified Data.Text.Lazy as Text
import GHC.Char
import Data.Ix (range)
import Data.Binary.IEEE754
import Codec.Compression.GZip
import Data.Time.Clock
import Data.Time.Clock.POSIX
import Data.Maybe
import Data.Word
import Data.Stdf.Types
import Debug.Trace
-- JSON gotcha: can't encode ByteString
-- Have to convert character strings to Text-latin1
-- Encoding base64 for raw binary data
-- I was thinking of supporting the CPU_TYPE for converting numbers
-- with different endianness then I realized I would have to support
-- different floating-point encodings from old Sun and DEC architectures
-- and I was like fuck that. All my testers and all my computers are x86
-- anyway.
getFar :: Get Rec
getFar = Far <$> getWord8 <*> getWord8
getAtr :: Get Rec
getAtr = Atr <$> getTime <*> mcn
getTime :: Get (Maybe UTCTime)
getTime = do
secs <- u4
return $ if secs == 0 then Nothing else Just $ posixSecondsToUTCTime $ realToFrac secs
getMilliseconds :: Get (Maybe Milliseconds)
getMilliseconds = do
milliseconds <- mu4
return $ Milliseconds <$> milliseconds
getMinutes :: Get (Maybe Minutes)
getMinutes = do
mins <- u2
return $ if mins == 65535 then Nothing else Just $ Minutes mins
getMir :: Get Rec
getMir = Mir <$> getTime <*> getTime <*> u1 <*> mc1<*> mc1 <*> mc1 <*> getMinutes
<*> mc1 <*> cn <*> cn <*> cn <*> cn <*> cn <*> mcn
<*> mcn <*> mcn <*> mcn <*> mcn <*> mcn <*> mcn
<*> mcn <*> mcn <*> mcn <*> mcn <*> mcn <*> mcn
<*> mcn <*> mcn <*> mcn <*> mcn <*> mcn <*> mcn
<*> mcn <*> mcn <*> mcn <*> mcn <*> mcn <*> mcn
getMrr :: Get Rec
getMrr = Mrr <$> getTime <*> mc1 <*> mcn <*> mcn
getPcr :: Get Rec
getPcr = Pcr <$> u1 <*> u1 <*> u4 <*> mu4 <*> mu4 <*> mu4 <*> mu4
getHbr :: Get Rec
getHbr = Hbr <$> u1 <*> u1 <*> u2 <*> u4 <*> getPassFailBin <*> mcn
getSbr :: Get Rec
getSbr = Sbr <$> u1 <*> u1 <*> u2 <*> u4 <*> getPassFailBin <*> mcn
getPmr :: Get Rec
getPmr = Pmr <$> u2 <*> mu2e0 <*> mcn <*> mcn <*> mcn <*> u1 <*> u1
getPgr :: Get Rec
getPgr = Pgr <$> u2 <*> mcn <*> getU2List
getPlr :: Get Rec
getPlr = do
k <- fromIntegral <$> u2
indexes <- replicateM k u2
grpMode <- replicateM k u2
let grpModes = map toGroupMode grpMode
grpRdx <- replicateM k u1
let radixes = map toRadix grpRdx
pgmChaR <- replicateM k mcn
rtnChaR <- replicateM k mcn
pgmChaL <- replicateM k mcn
rtnChaL <- replicateM k mcn
-- let pgmChars = zipWith (++) pgmChaL pgmChaR
-- let rtnChars = zipWith (++) rtnChaL rtnChaR
return $ Plr indexes grpModes radixes pgmChaR rtnChaR pgmChaL rtnChaL
toGroupMode :: U2 -> GroupMode
toGroupMode 00 = UnknownGroupMode
toGroupMode 10 = Normal
toGroupMode 20 = SameCycleIO
toGroupMode 21 = SameCycleMidband
toGroupMode 22 = SameCycleValid
toGroupMode 23 = SameCycleWindowSustain
toGroupMode 30 = DualDrive
toGroupMode 31 = DualDriveMidband
toGroupMode 32 = DualDriveValid
toGroupMode 33 = DualDriveWindowSustain
toGroupMode x = OtherGroupMode x
toRadix :: U1 -> Radix
toRadix 0 = DefaultRadix
toRadix 2 = Binary
toRadix 8 = Octal
toRadix 10 = Decimal
toRadix 16 = Hexadecimal
toRadix 20 = Symbolic
toRadix x = OtherRadix x
getRdr :: Get Rec
getRdr = Rdr <$> getU2List
getSdr :: Get Rec
getSdr = Sdr <$> u1 <*> u1 <*> getU1List <*> mcn <*> mcn
<*> mcn <*> mcn <*> mcn <*> mcn <*> mcn <*> mcn <*> mcn
<*> mcn <*> mcn <*> mcn <*> mcn <*> mcn <*> mcn <*> mcn
getWir :: Get Rec
getWir = Wir <$> u1 <*> u1 <*> getTime <*> mcn
getWrr :: Get Rec
getWrr = Wrr <$> u1 <*> u1 <*> getTime <*> u4 <*> mu4 <*> mu4 <*> mu4
<*> mu4 <*> mcn <*> mcn <*> mcn <*> mcn <*> mcn <*> mcn
getWcr :: Get Rec
getWcr = Wcr <$> mr4 <*> mr4 <*> mr4 <*> getWaferUnits <*> getDirection
<*> mi2 <*> mi2 <*> getDirection <*> getDirection
getPassFailBin :: Get PassFailBin
getPassFailBin = do
c <- c1
return $ case c of
'P' -> PassBin
'F' -> FailBin
' ' -> UnknownBin
_ -> OtherBin c
getDirection :: Get (Maybe Direction)
getDirection = charToDirection <$> c1
where charToDirection 'U' = Just Up
charToDirection 'D' = Just Down
charToDirection 'L' = Just Left
charToDirection 'R' = Just Right
charToDirection ' ' = Nothing
charToDirection x = Just $ OtherDirection x
getWaferUnits :: Get (Maybe WaferUnits)
getWaferUnits = numToUnits <$> u1
where numToUnits 0 = Nothing
numToUnits 1 = Just Inches
numToUnits 2 = Just Centimeters
numToUnits 3 = Just Millimeters
numToUnits 4 = Just Mils
numToUnits x = Just $ OtherUnits x
-- TODO: there's a pattern here
getU1List :: Get [U1]
getU1List = do
cnt <- u1
let listLen = fromIntegral cnt
replicateM listLen u1
getU2List :: Get [U2]
getU2List = do
cnt <- u2
let listLen = fromIntegral cnt
replicateM listLen u2
u1 :: Get Word8
u1 = getWord8
u2 :: Get Word16
u2 = getWord16le
u4 :: Get Word32
u4 = getWord32le
r4 :: Get R4
r4 = getFloat32le
r8 :: Get R8
r8 = getFloat64le
i1 :: Get I1
i1 = fromIntegral <$> u1
i2 :: Get I2
i2 = fromIntegral <$> u2
i4 :: Get I4
i4 = fromIntegral <$> u4
mu2, mu2e0 :: Get (Maybe U2)
mu2 = missing (65535 :: U2) <$> u2
mu2e0 = missing (0 :: U2) <$> u2
mu1e0, mu1e255 :: Get (Maybe U1)
mu1e0 = missing (0 :: U1) <$> u1
mu1e255 = missing (255 :: U1) <$> u1
missing :: Eq a => a -> a -> Maybe a
missing n m =
if m == n
then Nothing
else Just m
c1 :: Get Char
c1 = (chr . fromIntegral) <$> u1
mc1 :: Get (Maybe C1)
mc1 = getMaybe c1 ' '
mcn :: Get (Maybe Char8.ByteString)
mcn = getMaybe cn ""
mr4 :: Get (Maybe R4)
mr4 = getMaybe r4 0.0
getMaybe :: Eq a => Get a -> a -> Get (Maybe a)
getMaybe get missingVal = do
x <- get
return $ if x == missingVal
then Nothing
else Just x
mi2 :: Get (Maybe I2)
mi2 = do
x <- i2
return $ case x + 1 of
(-32767) -> Nothing
_ -> Just x
mu4 :: Get (Maybe U4)
mu4 = do
x <- u4
return $ case x of
4294967295 -> Nothing
_ -> Just x
cn :: Get Char8.ByteString
cn = do
cnlen <- u1
case cnlen of
0 -> return ""
_ -> getByteString (fromIntegral cnlen)
bit :: U1 -> Int -> Bool
bit = testBit
getPartFlag :: Get PartFlag
getPartFlag = do
b <- u1
return PartFlag { supersedesPartId = bit b 0
, supersedesXY = bit b 1
, abnormalEnd = bit b 2
, failed = bit b 3
, noPassFailInfo = bit b 4 }
getPrr :: Get Rec
getPrr = Prr <$> u1 <*> u1 <*> getPartFlag <*> u2 <*> u2 <*> mu2
<*> mi2 <*> mi2 <*> getMilliseconds <*> mcn <*> mcn <*> mcn
getPir :: Get Rec
getPir = Pir <$> u1 <*> u1
getTsr :: Get Rec
getTsr = do
headNum <- u1
siteNum <- u1
testTyp <- getTestType
testNum <- u4
execCnt <- mu4
failCnt <- mu4
alrmCnt <- mu4
testNam <- mcn
seqNam <- mcn
testLbl <- mcn
optempty <- isEmpty
optFlag <- if optempty then return Nothing else Just <$> u1
empty2 <- isEmpty
timeInfo <- if empty2
then return $ Prelude.replicate 5 Nothing
else replicateM 5 (Just <$> r4)
let [testTim, testMin, testMax, tstSums, tstSqrs] = zipWith
checkOptBit (optBits optFlag) timeInfo
return $ Tsr headNum siteNum testTyp testNum execCnt failCnt
alrmCnt testNam seqNam testLbl
testTim testMin testMax tstSums tstSqrs
where
optBits :: Maybe U1 -> [Bool]
optBits Nothing = Prelude.replicate 5 True
optBits (Just x) = map (testBit x) [2, 0, 1, 4, 5]
checkOptBit True _ = Nothing
checkOptBit False ti = ti
getTestType = charToTestType <$> c1
charToTestType 'P' = Parametric
charToTestType 'F' = Functional
charToTestType 'M' = MultiResultParametric
charToTestType ' ' = UnknownTestType
charToTestType x = OtherTestType x
decodeTestFlags :: U1 -> [TestFlag]
decodeTestFlags fl = if fl == 0
then [Pass]
else mkFlagList mapTf fl
where
mapTf 0 = Alarm
mapTf 1 = Invalid -- bit 1
mapTf 2 = Unreliable -- bit 2
mapTf 3 = Timeout -- bit 3
mapTf 4 = NotExecuted -- bit 4
mapTf 5 = Aborted -- bit 5
mapTf 6 = InValid -- bit 6
mapTf _ = Fail -- bit 7
decodeParametricFlags :: U1 -> [ParametricFlag]
decodeParametricFlags = mkFlagList mapPf
where
mapPf 0 = ScaleError -- I could probably get this from Enum duh
mapPf 1 = DriftError -- bit 1
mapPf 2 = Oscillation -- bit 2
mapPf 3 = FailHighLimit -- bit 3
mapPf 4 = FailLowLimit -- bit 4
mapPf 5 = PassAlternateLimits -- bit 5
mapPf 6 = PassOnEqLowLimit -- bit 6
mapPf _ = PassOnEqHighLimit -- bit 7
mkFlagList :: (Int -> a) -> U1 -> [a]
mkFlagList func flags = [func bi | bi <- range (0, 7), testBit flags bi]
getDecodeFlags :: (U1 -> [a]) -> Get [a]
getDecodeFlags decodeF = do
fl <- u1
return $ decodeF fl
getTestFlags :: Get [TestFlag]
getTestFlags = getDecodeFlags decodeTestFlags
getParametricFlags :: Get [ParametricFlag]
getParametricFlags = getDecodeFlags decodeParametricFlags
getPtr :: Get Rec
getPtr = do
ptrTestNum <- u4
ptrHeadNum <- u1
ptrSiteNum <- u1
testFlags <- getTestFlags
parametricFlags <- getParametricFlags
result <- r4 -- depends on testFlags and parametric flags
testText <- mcn
-- optionalInfo <- getOptionalInfo
-- record may end here
optionalInfo <- getOptionalInfo
let mresult = if validResult testFlags parametricFlags
then Just result
else Nothing
return $ Ptr ptrTestNum
ptrHeadNum
ptrSiteNum
testFlags
parametricFlags
mresult
testText
optionalInfo
where
validResult tf pf = all (`elem` [Pass, Fail]) tf
&& all (`notElem` [ScaleError, DriftError, Oscillation]) pf
getOptionalInfo :: Get (Maybe [OptionalInfo])
getOptionalInfo = do
alarmId <- liftA AlarmId <$> mcn
-- check we're not at the end of the buffer
noInfo <- isEmpty
info0 <- if noInfo
then return []
else getOptionalInfo'
let info1 = alarmId : info0
let info2 = catMaybes info1
return $ if Prelude.null info2 then Nothing else Just info2
getOptionalInfo' :: Get [Maybe OptionalInfo]
getOptionalInfo' = do
optFlag <- u1 -- getOptFlag
let [ invalidResultExp, -- bit 0
_, -- bit 1
invalidLowSpecLimit, -- bit 2
invalidHighSpecLimit, -- bit 3
invalidLowLimit, -- bit 4
invalidHighLimit, -- bit 5
invalidLowTestLimit, -- bit 6
invalidHighTestLimit ] -- bit 7
= Prelude.map (testBit optFlag) $ range (0,7)
let invalidLowTest = invalidLowLimit || invalidLowTestLimit
let invalidHighTest = invalidHighLimit || invalidHighTestLimit
resScal <- liftA ResultExp <$> getOnFalse invalidResultExp i1
llmScal <- liftA LowLimitExp <$> getOnFalse invalidLowTest i1
hlmScal <- liftA HighLimitExp <$> getOnFalse invalidHighTest i1
loLimit <- liftA LowLimit <$> getOnFalse invalidLowTest r4
hiLimit <- liftA HighLimit <$> getOnFalse invalidHighTest r4
units <- liftA Units <$> mcn
cResFmt <- liftA CResultFormat <$> mcn
cLlmFmt <- liftA CLowLimitFormat <$> mcn
cHlmFmt <- liftA CHighLimitFormat <$> mcn
loSpec <- liftA LowSpecLimit <$> getOnFalse invalidLowSpecLimit r4
hiSpec <- liftA HighSpecLimit <$> getOnFalse invalidHighSpecLimit r4
let info = [resScal, llmScal, hlmScal, loLimit, hiLimit, units,
cResFmt, cLlmFmt, cHlmFmt, loSpec]
return info
getDef :: Show a => a -> Get a -> Get a
getDef def getter = do
e <- isEmpty
if e then return def else getter
getMpr :: Get Rec
getMpr = do
testNum <- u4
headNum <- u1
siteNum <- u1
testFlg <- getTestFlags
parmFlg <- getParametricFlags
-- TODO: Must carry state. If these return early then you're supposed
-- to fill in the "optional" values with whatever they were set to the
-- first time. Uniquely, MPR's TEXT_TXT (name) field is optional
--
-- record may end here if no more info
j <- fromIntegral <$> getDef 0 u2
-- record may end here if no more info
k <- fromIntegral <$> getDef 0 u2
rtnStat <- if j == 0 then return $ Nothing
else Just . ReturnedStates <$> getNibbles j
rtnRslt <- if k == 0 then return $ Nothing else Just .Results <$> replicateM k r4
testTxt <- liftA Label <$> (getDef Nothing mcn)
alarmId <- liftA AlarmId <$> (getDef Nothing mcn)
optFlag <- getDef 255 u1
-- TODO: Should be given by previous record with the same testId as this
-- one if missing:
resScal0 <- getDef 0 i1
llmScal0 <- getDef 0 i1
hlmScal0 <- getDef 0 i1
loLimit0 <- getDef 0.0 r4
hiLimit0 <- getDef 0.0 r4
startIn0 <- getDef 0.00 r4
incrIn0 <- getDef 0.00 r4
rtnIndx0 <- getDef [] (replicateM j u2)
units <- liftA Units <$> getDef Nothing mcn
unitsIn <- liftA StartingInputUnits <$> getDef Nothing mcn
cResfmt <- liftA CResultFormat <$> getDef Nothing mcn
cLlmfmt <- liftA CLowLimitFormat <$> getDef Nothing mcn
cHlmfmt <- liftA CHighLimitFormat <$> getDef Nothing mcn
loSpec0 <- getDef 0.0 r4
hiSpec0 <- getDef 0.0 r4
let rtnIndx = if Prelude.null rtnIndx0 then Nothing
else Just $ PinIndecies rtnIndx0
unlessBit b x | testBit optFlag b = Nothing
| otherwise = Just x
resScal = unlessBit 0 $ ResultExp resScal0
startIn = unlessBit 1 $ StartingInput startIn0
incrIn = unlessBit 1 $ IncrementInput incrIn0
loSpec = unlessBit 2 $ LowSpecLimit loSpec0
hiSpec = unlessBit 3 $ HighSpecLimit hiSpec0
loLimit = unlessBit 4 $ LowLimit loLimit0
llmScal = unlessBit 4 $ LowLimitExp llmScal0
hiLimit = unlessBit 5 $ HighLimit hiLimit0
hlmScal = unlessBit 5 $ HighLimitExp hlmScal0
-- Bits 6 and 7 seem comp ely redundnat with 4 and 5
-- I think 6 and 7 mean this test has no limit
-- Where 4 and 5 means it has a limit set by a preious record
-- I'll leave bits 6 and 7 as TODO.
info = catMaybes [resScal, llmScal, hlmScal, loLimit, hiLimit, startIn,
incrIn, rtnIndx, units, unitsIn, cResfmt, cLlmfmt,
cHlmfmt, loSpec, hiSpec, testTxt, rtnStat, rtnRslt]
return $ Mpr testNum headNum siteNum testFlg parmFlg (Just info)
-- Take a list of bytes and split into exactly n nibbles
fromNibbles :: [U1] -> Int -> [U1]
fromNibbles [] _ = []
fromNibbles _ 0 = []
fromNibbles [byte] 1 = [0xF .&. byte]
fromNibbles [byte] 2 = [0xF .&. byte, byte `shiftR` 4]
fromNibbles (byte:bytes) n = 0xF .&. byte : byte `shiftR` 4 : fromNibbles bytes (n - 2)
getNibbles :: Int -> Get [U1]
getNibbles nnibs = do
let nbytes = nnibs `div` 2 + if odd nnibs then 1 else 0
bytes <- replicateM nbytes u1
return $ fromNibbles bytes nnibs
getOnFalse :: Bool -> Get a -> Get (Maybe a)
getOnFalse cond get = do
x <- get
return $ if cond
then Nothing
else Just x
getFtr :: Get Rec
getFtr = do
testNum <- u4
headNum <- u1
siteNum <- u1
testFlag <- getTestFlags -- doesn't use the invalid bit
-- record may end here, before rtnIcnt or pgmIcnt -- check isEmpty
optempty <- isEmpty
(cycleCnt, relVadr, reptCnt, numFail, xFail, yFail, vectOff) <-
if optempty
then
return
(Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing)
else
do
optFlag <- u1
let
[ noCycleCnt
, noRelVadr
, noReptCnt
, noNumFail
, noXYFail
, noVectOff
] = Prelude.map (testBit optFlag) $ range (0, 5)
-- Turns out you're supposed to get the byte
-- even if it's invalid
-- For a format seemingly obsessed with saving
-- a few bytes, this is surprising
a <- getOnFalse noCycleCnt u4
b <- getOnFalse noRelVadr u4
c <- getOnFalse noReptCnt u4
d <- getOnFalse noNumFail u4
e <- getOnFalse noXYFail i4
f <- getOnFalse noXYFail i4
g <- getOnFalse noVectOff i2
return (a,b,c,d,e,f,g)
-- may end here
emptyj <- isEmpty
j <- if emptyj then return 0
else fromIntegral <$> u2
-- may end here
emptyk <- isEmpty
k <- if emptyk then return 0
else fromIntegral <$> u2
emptymi <- isEmpty
(rtnIndx, rtnStat, pgmIndx, pgmStat, failPin, vecNam, timeSet, opCode, testTxt, alarmId, progTxt, rsltTxt, patgNum, spinMap) <-
if emptymi
then return
(Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing)
else do
rtnIndx <- replicateM j u2
rtnStat <- getNibbles j
pgmIndx <- replicateM k u2
pgmStat <- getNibbles k
failPin <- getBitField
vecNam <- mcn
timeSet <- mcn
opCode <- mcn
testTxt <- mcn
alarmId <- mcn
progTxt <- mcn
rsltTxt <- mcn
-- can it end here?
patgNum <- mu1e255
spinMap <- getBitField
let rtnIndx' = if j == 0 then Nothing else Just rtnIndx
let rtnStat' = if j == 0 then Nothing else Just rtnStat
let pgmIndx' = if k == 0 then Nothing else Just pgmIndx
let pgmStat' = if k == 0 then Nothing else Just pgmStat
let failPin' = if Prelude.null failPin then Nothing else Just failPin
let spinMap' = if Prelude.null spinMap then Nothing else Just spinMap
return $ ( rtnIndx'
, rtnStat'
, pgmIndx'
, pgmStat'
, failPin'
, vecNam
, timeSet
, opCode
, testTxt
, alarmId
, progTxt
, rsltTxt
, patgNum
, spinMap' )
return $
Ftr testNum headNum siteNum testFlag
cycleCnt relVadr reptCnt numFail xFail yFail vectOff
rtnIndx rtnStat pgmIndx pgmStat failPin vecNam timeSet opCode testTxt alarmId progTxt rsltTxt patgNum spinMap
-- TODO: BitField type like [U1] which toJson prints as hex "FF AF 12 or like STDFreader print bits 10000000 00010101
getBitField :: Get [U1]
getBitField = do
nbits <- u2
let nbytes = let (mbytes, mbits) = nbits `divMod` 8
obytes = mbytes + if mbits == 0 then 0 else 1
in fromIntegral obytes
replicateM nbytes u1
getByteField :: Get [U1]
getByteField = do
nbytes <- fromIntegral <$> u1
replicateM nbytes u1
getBps :: Get Rec
getBps = Bps <$> mcn
getEps :: Get Rec
getEps = return Eps
getGdr :: Get Rec
getGdr = do
fieldCount <- fromIntegral <$> u2
fields <- replicateM fieldCount getGdrField
return $ Gdr fields
getGdrField :: Get GdrField
getGdrField = do
fieldType <- fromIntegral <$> u1
case fieldType of
0 -> return GPad
1 -> GU1 <$> u1
2 -> GU2 <$> u2
3 -> GU4 <$> u4
4 -> GI1 <$> i1
5 -> GI2 <$> i2
6 -> GI4 <$> i4
7 -> GFloat <$> r4
8 -> GDouble <$> r8
10 -> GStr <$> cn
11 -> GBytes <$> getByteField -- first 2 bytes are length in bytes
12 -> GData <$> getBitField -- first 2 bytes are length in bits. I think I wrote something like this already
13 -> GNibble <$> (liftM head . getNibbles) 1
_ -> return GPad -- So don't crash on broken GDR
getDtr :: Get Rec
getDtr = Dtr <$> cn
----------------------------------------------------------------
getRawRec :: Integral a => a -> Get Rec
getRawRec reclen = do
bytes <- getByteString (fromIntegral reclen)
return Raw { raw = Base64.encode bytes }
-- First get the 'len' number of bytes
-- Although you could just parse the stream directly you would be
-- disapointed when a buggy STDF had some fields of the wrong width
-- in records you didn't even care about and you lose the ability
-- to read the rest of the stream forever
getRec :: Header -> Get Rec
getRec hdr = do
record <- getLazyByteString (fromIntegral $ len hdr)
return $ processRec hdr record
-- | Attach handlers for specific headers here
-- Check after getting something that the entire record was consumed
processRec :: Header -> BL.ByteString -> Rec
processRec hdr = runGet $ do
r <- specificGet hdr
leftOver <- getRemainingLazyByteString
let leftOverBytes = BL.length leftOver
when (leftOverBytes > 0) $ do
traceM $ "Warning, " ++ show leftOverBytes ++ " leftover bytes:"
traceShowM leftOver
traceM "In record:"
traceShowM r
return r
-- typStdfInfo = 0
-- subFar = 10
-- subAtr = 20
-- typPerLot = 1
-- subMir = 10
-- subMrr = 20
-- subPcr = 30
-- subHbr = 40
-- subSbr = 50
-- subPmr = 60
-- subPgr = 62
-- subPlr = 63
-- subRdr = 70
-- subSdr = 80
-- typPerWafer = 2
-- subWir = 10
-- subWrr = 20
-- subWcr = 30
-- typPerPart = 5
-- subPir = 10
-- subPrr = 20
-- typPerTest = 10
-- subTsr = 30
-- typPerTestExec = 15
-- subPtr = 10
-- subMpr = 15
-- subFtr = 20
-- typPerProgSeg = 20
-- subBps = 10
-- subEps = 20
-- typGeneric = 50
-- subGdr = 10
-- subDtr = 30
-- Dispatch table for record types
specificGet :: Header -> Get Rec
-- STDF file info
specificGet (Header _ 0 10) = getFar
specificGet (Header _ 0 20) = getAtr
-- Per Lot info
specificGet (Header _ 1 10) = getMir
specificGet (Header _ 1 20) = getMrr
specificGet (Header _ 1 30) = getPcr
specificGet (Header _ 1 40) = getHbr
specificGet (Header _ 1 50) = getSbr
specificGet (Header _ 1 60) = getPmr
specificGet (Header _ 1 62) = getPgr
specificGet (Header _ 1 63) = getPlr
specificGet (Header _ 1 70) = getRdr
specificGet (Header _ 1 80) = getSdr
-- Per Wafer Info
specificGet (Header _ 2 10) = getWir
specificGet (Header _ 2 20) = getWrr
specificGet (Header _ 2 30) = getWcr
-- Per-Part Info
specificGet (Header _ 5 10) = getPir
specificGet (Header _ 5 20) = getPrr
-- Per-Test
specificGet (Header _ 10 30) = getTsr
-- -- Per-Test-Execution
specificGet (Header _ 15 10) = getPtr
specificGet (Header _ 15 15) = getMpr
specificGet (Header _ 15 20) = getFtr
-- -- Per-Program-Segment
specificGet (Header _ 20 10) = getBps
specificGet (Header _ 20 20) = getEps
-- -- Generic Data
specificGet (Header _ 50 10) = getGdr
specificGet (Header _ 50 30) = getDtr
--
specificGet (Header hdrlen _ _) = do
r <- getRawRec hdrlen
traceM "Warning, unknown record:"
traceShowM r
return r
getBinRec :: Get BinRec
getBinRec = do
hdr <- getHeader
record <- getRec hdr
return $! BinRec hdr record -- needs to be strict?
getHeader :: Get Header
getHeader = Header <$> getWord16le <*> getWord8 <*> getWord8
nextRec :: Get Rec
nextRec = do
record <- getBinRec
return $ rec record
getStdf :: Get Stdf
getStdf = do
stdfempty <- isEmpty
if stdfempty
then return []
else do record <- nextRec
recs <- getStdf
return (record:recs)
isGzipped :: BL.ByteString -> IO Bool
isGzipped bs = do
let magic = runGet getWord16le bs
return $ magic == 0x8b1f
-- | Parse an optionally-gzipped stdf file
parseFile :: String -> IO Stdf
parseFile fn = do
bs <- BL.readFile fn
isgz <- isGzipped bs
let decompressed = decompress bs
return $ parse $ if isgz then decompressed else bs
-- | Parse an Stdf from a ByteString in case you want to open your own files or
-- | parse a stream off the tester or something
parse :: BL.ByteString -> Stdf
parse = runGet getStdf
| gitfoxi/Stdf | Data/Stdf/Parser.hs | gpl-2.0 | 26,028 | 1 | 42 | 8,395 | 7,210 | 3,653 | 3,557 | 611 | 14 |
{- |
Module : $Header$
Description : Symbols of propositional logic
Copyright : (c) Dominik Luecke, Uni Bremen 2007
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : experimental
Portability : portable
Definition of symbols for propositional logic
-}
module Temporal.Symbol
(
Symbol (..) -- Symbol type
, pretty -- pretty printing for Symbols
, symOf -- Extracts the symbols out of a signature
, getSymbolMap -- Determines the symbol map
, getSymbolName -- Determines the name of a symbol
, idToRaw -- Creates a raw symbol
, symbolToRaw -- Convert symbol to raw symbol
, matches -- does a symbol match a raw symbol?
, applySymMap -- application function for symbol maps
) where
import qualified Common.Id as Id
import Common.Doc
import Common.DocUtils
import qualified Data.Set as Set
import qualified Data.Map as Map
import qualified Temporal.Sign as Sign
import qualified Temporal.Morphism as Morphism
-- | Datatype for symbols
newtype Symbol = Symbol {symName :: Id.Id}
deriving (Show, Eq, Ord)
instance Pretty Symbol where
pretty = printSymbol
instance Id.GetRange Symbol where
getRange = Id.getRange . symName
printSymbol :: Symbol -> Doc
printSymbol x = pretty $ symName x
-- | Extraction of symbols from a signature
symOf :: Sign.Sign -> Set.Set Symbol
symOf x = Set.fold (\y -> Set.insert Symbol{symName = y}) Set.empty $
Sign.items x
-- | Determines the symbol map of a morhpism
getSymbolMap :: Morphism.Morphism -> Map.Map Symbol Symbol
getSymbolMap f = Map.foldWithKey
(\ k a -> Map.insert Symbol{symName=k} Symbol{symName=a})
Map.empty $ Morphism.propMap f
-- | Determines the name of a symbol
getSymbolName :: Symbol -> Id.Id
getSymbolName sym = symName sym
-- | make a raw_symbol
idToRaw :: Id.Id -> Symbol
idToRaw mid = Symbol {symName = mid}
-- | convert to raw symbol
symbolToRaw :: Symbol -> Symbol
symbolToRaw = id
-- | does a smybol match a raw symbol?
matches :: Symbol -> Symbol -> Bool
matches s1 s2 = s1 == s2
-- | application function for Symbol Maps
applySymMap :: Map.Map Symbol Symbol -> Symbol -> Symbol
applySymMap smap idt = Map.findWithDefault idt idt $ smap
| nevrenato/Hets_Fork | Temporal/Symbol.hs | gpl-2.0 | 2,387 | 0 | 11 | 593 | 466 | 268 | 198 | 43 | 1 |
{-# LANGUAGE CPP #-}
module Infernu.Util (checkFiles, annotatedSource, checkSource) where
import Control.Monad (forM, when)
import Data.Maybe (catMaybes)
import Data.List (intercalate)
import qualified Data.Set as Set
import qualified Language.ECMAScript3.Parser as ES3Parser
import qualified Language.ECMAScript3.PrettyPrint as ES3Pretty
import qualified Language.ECMAScript3.Syntax as ES3
import qualified Text.Parsec.Pos as Pos
import Text.PrettyPrint.ANSI.Leijen (Pretty (..), (<+>), string, renderPretty, Doc, displayS)
import Infernu.Prelude
import Infernu.Options (Options(..))
import Infernu.Parse (translate)
-- TODO move pretty stuff to Pretty module
import Infernu.Infer (getAnnotations, minifyVars, runTypeInference)
import Infernu.Types (QualType)
import Infernu.Source (GenInfo(..), Source(..), TypeError(..))
zipByPos :: [(Pos.SourcePos, String)] -> [(Int, String)] -> [String]
zipByPos [] xs = map snd xs
zipByPos _ [] = []
zipByPos ps'@((pos, s):ps) xs'@((i,x):xs) = if Pos.sourceLine pos == i
then formattedAnnotation : zipByPos ps xs'
else x : zipByPos ps' xs
where indentToColumn n = replicate (n-1) ' '
isMultiline = length sLines > 1
sLines = lines s
formattedAnnotation = if isMultiline
then ("/*"
++ indentToColumn (Pos.sourceColumn pos - 2)
++ head sLines
++ "\n"
++ (intercalate "\n" . map (\l -> indentToColumn (Pos.sourceColumn pos) ++ l) $ tail sLines) ++ " */")
else "//" ++ indentToColumn (Pos.sourceColumn pos - 2) ++ s
indexList :: [a] -> [(Int, a)]
indexList = zip [1..]
checkSource :: String -> Either TypeError [(Source, QualType)]
checkSource src = case ES3Parser.parseFromString src of
Left parseError -> Left $ TypeError { source = Source (GenInfo True Nothing, Pos.initialPos "<global>"), message = string (show parseError) }
Right expr -> -- case ES3.isValid expr of
-- False -> Left $ TypeError { source = Source (GenInfo True, Pos.initialPos "<global>"), message = "Invalid syntax" }
-- True ->
fmap getAnnotations $ fmap minifyVars $ runTypeInference $ fmap Source $ translate $ ES3.unJavaScript expr
checkFiles :: Options -> [String] -> IO (Either TypeError [(Source, QualType)])
checkFiles options fileNames = do
expr <- concatMap ES3.unJavaScript <$> forM fileNames ES3Parser.parseFromFile
when (optShowParsed options) $ putStrLn $ show $ ES3Pretty.prettyPrint expr
let expr' = fmap Source $ translate $ expr
when (optShowCore options) $ putStrLn $ show $ pretty expr'
let expr'' = fmap minifyVars $ runTypeInference expr'
res = fmap getAnnotations expr''
return res
showWidth :: Int -> Doc -> String
showWidth w x = displayS (renderPretty 0.4 w x) ""
showDoc :: Doc -> String
showDoc = showWidth 120
annotatedSource :: [(Source, QualType)] -> [String] -> String
annotatedSource xs sourceCode = unlines $ zipByPos (prettyRes $ unGenInfo $ filterGen xs) indexedSource
where indexedSource = indexList sourceCode
unGenInfo :: [(Source, QualType)] -> [(String, Pos.SourcePos, QualType)]
unGenInfo = catMaybes . map (\(Source (g, s), q) -> fmap (\n -> (n, s, q)) $ declName g)
filterGen :: [(Source, QualType)] -> [(Source, QualType)]
filterGen = filter (\(Source (g, _), _) -> not . isGen $ g)
prettyRes = Set.toList . Set.fromList . fmap (\(n, s, q) -> (s, showDoc $ pretty n <+> string ":" <+> pretty q))
| sinelaw/infernu | src/Infernu/Util.hs | gpl-2.0 | 4,054 | 0 | 21 | 1,274 | 1,218 | 669 | 549 | 61 | 3 |
-- Main.hs -- The entry point for the babel sequence generator
-- Copyright (C) 2017 Quytelda Kahja <[email protected]>
--
-- This file is part of babel.
-- babel is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
-- babel is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
-- You should have received a copy of the GNU General Public License
-- along with babel. If not, see <http://www.gnu.org/licenses/>.
module Main where
import Control.Monad(when, replicateM)
import Data.List.Split
import Data.Version
import System.Console.GetOpt
import System.Environment
import System.Exit (exitSuccess, exitFailure)
import System.IO
import CFG
releaseVersion :: Version
releaseVersion = Version [2, 2, 0] ["unstable"]
-- | The Options record holds a representation of the runtime configuration.
data Options = Options { optHelp :: Bool
, optNumber :: Int
, optOutput :: (String -> IO ())
, optCrypt :: Bool
, optDumpTree :: Bool
, optTemplate :: [Symbol]
, optVersion :: Bool
}
-- | @defaults@ is the default runtime configuration record.
defaults :: Options
defaults = Options { optHelp = False
, optNumber = 1
, optOutput = putStrLn
, optCrypt = False
, optDumpTree = False
, optTemplate = ["S"]
, optVersion = False
}
-- | @options@ describes the supported command-line arguments
options :: [OptDescr (Options -> Options)]
options =
[ Option ['h'] ["help"]
(NoArg (\opt -> opt {optHelp = True}))
"Display help and usage information."
, Option ['n'] []
(ReqArg (\str opt -> opt {optNumber = (read str :: Int)}) "N")
"Generate N different sequences."
, Option ['o'] ["output"]
(ReqArg (\path opt -> opt {optOutput = writeFile path}) "FILE")
"Redirect output to FILE."
, Option ['c'] ["crypto"]
(NoArg (\opt -> opt {optCrypt = True}))
"Use cryptographically secure random expansion."
, Option ['d'] ["dump-tree"]
(NoArg (\opt -> opt {optDumpTree = True}))
"Dump the CFG symbol tree."
, Option ['t'] ["template"]
(ReqArg (\syms opt -> opt {optTemplate = splitOn ":" syms}) "SYMBOLS")
"Use SYMBOLS as the starting symbols (\"S\" is the default.)."
, Option ['v'] ["version"]
(NoArg (\opt -> opt {optVersion = True}))
"Display version information."
]
main :: IO ()
main = do
-- argument parsing
args <- getArgs
let (actions, params, errs) = getOpt RequireOrder options args
when (not $ null errs) $ do
hPutStrLn stderr (unlines errs)
failUsageInfo
let getOptions = foldl ( . ) id actions
Options { optHelp = help
, optOutput = output
, optCrypt = crypt
, optDumpTree = dumpTree
, optNumber = number
, optTemplate = template
, optVersion = version
} = getOptions defaults
when version $ do
putStrLn (releaseInfo "babel" releaseVersion)
exitSuccess
when help $ do
putStrLn (usageInfo header options)
exitSuccess
when (null params) $ do
hPutStrLn stderr "You must provide a grammar file."
failUsageInfo
-- Load the grammar file
description <- readFile (head params)
case parseCFG crypt description of
Left err -> hPutStrLn stderr (show err)
Right cfg -> do
when dumpTree (putStrLn $ show cfg)
let expansion = concat <$> mapM (expand cfg) template
results <- replicateM number expansion
output (unlines results)
where
header = "Usage: babel [OPTION...] GRAMMAR_FILE"
releaseInfo pgm ver = pgm ++ " " ++ showVersion ver
failUsageInfo = putStrLn (usageInfo header options) >> exitFailure
| quytelda/babel | src/Main.hs | gpl-3.0 | 4,264 | 0 | 18 | 1,207 | 969 | 531 | 438 | 85 | 2 |
import ClassA
data A = A | B
instance A Int where
id2 x = x
| Helium4Haskell/helium | test/classesQualified/DataClassName.hs | gpl-3.0 | 64 | 0 | 6 | 20 | 30 | 16 | 14 | 4 | 0 |
{-# LANGUAGE FlexibleContexts, TypeOperators #-}
module Mudblood.Contrib.MG
( module Mudblood.Contrib.MG.Profile
, module Mudblood.Contrib.MG.State
, module Mudblood.Contrib.MG.Mapper
, module Mudblood.Contrib.MG.GMCP
, module Mudblood.Contrib.MG.Combat
, module Mudblood.Contrib.MG.Guilds
, module Mudblood.Contrib.MG.Communication
) where
import Data.Has (Has, FieldOf, fieldOf, (:&:), (&))
import Control.Lens hiding ((&))
import Mudblood
import Mudblood.Contrib.MG.Profile
import Mudblood.Contrib.MG.State
import Mudblood.Contrib.MG.Mapper
import Mudblood.Contrib.MG.GMCP
import Mudblood.Contrib.MG.Combat
import Mudblood.Contrib.MG.Guilds
import Mudblood.Contrib.MG.Communication
| talanis85/mudblood | src/Mudblood/Contrib/MG.hs | gpl-3.0 | 722 | 0 | 5 | 94 | 157 | 113 | 44 | 19 | 0 |
{-# LANGUAGE ScopedTypeVariables, GADTs #-}
module Utils where
import Data.Set (Set(..))
import qualified Data.Set as Set
import Control.Monad.Trans
import Data.Traversable as Traversable
import Control.Monad
import qualified Data.Generics as Generics
import Data.Proxy
import Data.Typeable hiding (typeOf)
import Control.Monad.Except
import Unsafe.Coerce
mapSet f = Set.fromList . map f . Set.toList
fst3 (x,y,z) = x
snd3 (x,y,z) = y
thr3 (x,y,z) = z
fst4 (x,y,z,w) = x
snd4 (x,y,z,w) = y
thr4 (x,y,z,w) = z
fou4 (x1,x2,x3,x4) = x4
fst5 = (\(x1,x2,x3,x4,x5) -> x1)
fou5 = (\(x1,x2,x3,x4,x5) -> x4)
fst6 = (\(x1,x2,x3,x4,x5,x6) -> x1)
snd6 = (\(x1,x2,x3,x4,x5,x6) -> x2)
thr6 = (\(x1,x2,x3,x4,x5,x6) -> x3)
fou6 = (\(x1,x2,x3,x4,x5,x6) -> x4)
fit6 = (\(x1,x2,x3,x4,x5,x6) -> x5)
sit6 = (\(x1,x2,x3,x4,x5,x6) -> x6)
funit :: Functor f => f a -> f ()
funit = fmap (const ())
fconst :: Functor f => b -> f a -> f b
fconst b = fmap (const b)
lift2 :: (MonadTrans t1,Monad (t2 m),MonadTrans t2,Monad m) => m a -> t1 (t2 m) a
lift2 = lift . lift
funzip :: Traversable t => t (a,b) -> (t a,t b)
funzip xs = (fmap fst xs,fmap snd xs)
funzip3 :: Traversable t => t (a,b,c) -> (t a,t b,t c)
funzip3 xs = (fmap fst3 xs,fmap snd3 xs,fmap thr3 xs)
funzip4 :: Traversable t => t (a,b,c,e) -> (t a,t b,t c,t e)
funzip4 xs = (fmap fst4 xs,fmap snd4 xs,fmap thr4 xs,fmap fou4 xs)
mapAndUnzipM :: (Monad m,Traversable t) => (c -> m (a,b)) -> t c -> m (t a,t b)
mapAndUnzipM f = liftM funzip . Traversable.mapM f
mapAndUnzip3M :: (Monad m,Traversable t) => (c -> m (a,b,d)) -> t c -> m (t a,t b,t d)
mapAndUnzip3M f = liftM funzip3 . Traversable.mapM f
mapAndUnzip4M :: (Monad m,Traversable t) => (c -> m (a,b,d,e)) -> t c -> m (t a,t b,t d,t e)
mapAndUnzip4M f = liftM funzip4 . Traversable.mapM f
mapFst :: (a -> b) -> (a,c) -> (b,c)
mapFst f (x,y) = (f x,y)
mapSnd :: (c -> b) -> (a,c) -> (a,b)
mapSnd f (x,y) = (x,f y)
mapSndM :: Monad m => (c -> m b) -> (a,c) -> m (a,b)
mapSndM f (x,y) = do
y' <- f y
return (x,y')
concatMapM :: Monad m => (a -> m [b]) -> [a] -> m [b]
concatMapM f = liftM concat . mapM f
-- | A monomorphic type representation to support type equality
data TypeOf a where
TypeOf :: Typeable a => TypeRep -> TypeOf a
compareTypeOf :: TypeOf a -> TypeOf b -> Ordering
compareTypeOf (TypeOf t1) (TypeOf t2) = compare t1 t2
data EqT a b where
EqT :: EqT a a -- evidence that two types are equal
NeqT :: EqT a b -- evidence that two types are not equal
typeRep :: Typeable a => TypeOf a
typeRep = typeOf (error "typeRep")
typeOf :: Typeable a => a -> TypeOf a
typeOf = typeOfProxy . proxyOf
proxyOf :: a -> Proxy a
proxyOf _ = Proxy
typeOfProxy :: Typeable a => Proxy a -> TypeOf a
typeOfProxy p = TypeOf (Generics.typeOf p)
eqTypeOf :: TypeOf a -> TypeOf b -> EqT a b
eqTypeOf (TypeOf t1) (TypeOf t2) = if t1 == t2 then unsafeCoerce EqT else NeqT
catchErrorMaybe :: MonadError e m => m a -> m (Maybe a)
catchErrorMaybe m = catchError (liftM Just m) (const $ return Nothing)
| hpacheco/jasminv | src/Utils.hs | gpl-3.0 | 3,029 | 0 | 10 | 620 | 1,727 | 937 | 790 | 75 | 2 |
{-# LANGUAGE BangPatterns, TypeSynonymInstances #-}
module Main where
import Prelude hiding (init, Left, Right)
import Types
import CPUDefs
import PPUDefs
import CPU
import PPU
import Loader
import PPUHelpers (ppuDecodeAction, getPPUActions)
import CPUHelpers
import Data.Array.ST
import Control.Monad.Reader
import System.IO
import System.Environment (getArgs)
import NESDL
-- import CPUST
import CpuCPS
import qualified Control.Monad.ST.Lazy as Lazy
type Cycle = Int
{-
-- on keypress -> setBit
-- on keyrelease -> clearBit
-- FIXME maybe input race condition while reading?
insertKey :: Maybe Input -> CPU s ()
insertKey Nothing = return ()
insertKey (Just (Input t p k)) = writePlayer (playerFun p) (pattern (getBit k) t)
where
getBit key = case key of
A -> 0; B -> 1; Select -> 2; Start -> 3;
Up -> 4; Down -> 5; Left -> 6; Right -> 7
playerFun player = if player == P1 then player1 else player2
pattern i KeyPress = (`setBit` i)
pattern i KeyRelease = (`clearBit` i)
-}
main :: IO ()
main = do
hSetBuffering stdout NoBuffering
sdlInit
args <- getArgs
case args of
[arg] -> do
rom <- loadRom arg
ks <- return (repeat (error "key?!"))
-- let pxs = runSystem rom ks -- unified looping
let pxs = puller rom ks -- enterprise pulling
drawFrame pxs
_ -> do fail "wrong number of arguments"
forever (return ())
print "LazyNES 1.0"
drawFrame :: [Pixel] -> IO ()
drawFrame pxs = do
draw frame
drawFrame rest
where
(frame, rest) = splitAt (256*240) pxs
puller :: HDRiNES -> [Maybe Input] -> [Pixel]
puller (HDRiNES p c _ _) ks = pxs
where (pxs, ppus) = execPPU c (execCPU p ks ([NOP]:ppus))
-- Like puller, but with unified looping instead
runSystem :: HDRiNES -> [Maybe Input] -> [Pixel]
runSystem (HDRiNES p c _ _) ks = Lazy.runST (do
(cpu,ppu) <- Lazy.strictToLazyST $ initSys p c
unified cpu ppu ks [NOP] )
-- runs the cpu and ppu as one unit.
-- needs to get the environments from the both units as input
-- as initCPU below
unified :: CPUEnv s -> PPUEnv s -> [Maybe Input] -> [Action] -> Lazy.ST s [Pixel]
unified _ _ [] _ = error "always some input"
unified cpuenv ppuenv (inp:inps) acts = do
c <- Lazy.strictToLazyST $ stepCPU cpuenv inp acts
(pxs,as) <- Lazy.strictToLazyST $ stepPPU ppuenv c
pxss <- unified cpuenv ppuenv inps as
return $ pxs ++ pxss
execPPU :: [Operand] -> [(Cycle,Action)] -> ([Pixel],[[Action]])
execPPU chrR c = Lazy.runST (do
(_,env) <- Lazy.strictToLazyST $ initSys [] chrR
loopPPU env c)
execCPU :: [Operand] -> [Maybe Input] -> [[Action]] -> [(Cycle,Action)]
execCPU prgR inp acts = Lazy.runST (do
(env,_) <- Lazy.strictToLazyST $ initSys prgR []
loopCPU env inp acts)
-- Given PRGROM and CHRROM, initialize the environments for
-- CPU and PPU.
initSys :: [Operand] -> [Operand] -> ST s (CPUEnv s,PPUEnv s)
initSys prgR chrR = do
cpu <- return CPUEnv
`ap` newSTRef 0x0 -- | A
`ap` newSTRef 0x0 -- | X
`ap` newSTRef 0x0 -- | Y
`ap` newSTRef 0xFF -- | SP
`ap` newSTRef 0x8000 -- | PC
`ap` newSTRef 0x0 -- | Status
`ap` newSTRef (Just Reset) -- | IRQ
`ap` newArray (0x0000, 0x07FF) 0x0 -- | Lower memory
`ap` newArray (0x2000, 0x2007) 0x0 -- | PPU registers
`ap` newArray (0x4000, 0xFFFF) 0x0 -- | Upper memory
`ap` newSTRef NOP -- | Action
`ap` newSTRef (InputState 0 0) -- | Player 1
`ap` newSTRef (InputState 0 0) -- | Player 2
ppu <- return PPUEnv
`ap` newSTRef (PPUState 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00)
`ap` newArray (0x0000, 0x2000) 0x0 -- |
`ap` newArray (0x2000, 0x3000) 0x0 -- |
`ap` newArray (0x3F00, 0x3F20) 0x0 -- |
`ap` newArray (0x00, 0xFF) 0x0 -- | SPR-RAM
`ap` newSTRef 0 -- |
`ap` newSTRef 0 -- |
`ap` newSTRef 0 -- |
`ap` newSTRef 0 -- |
`ap` newSTRef 0 -- |
`ap` newSTRef 0 -- |
`ap` newSTRef [] -- |
`ap` newSTRef True -- |
`ap` newSTRef [] -- | [Action]
writeBinToMemST (patternTables ppu) chrR 0x0000
writeBinToMemST (uppMem cpu) prgR 0x8000
return (cpu,ppu)
------------------------------------------------------------------------------
-- CPU
-- | (Lazy) Will call a strict step.
loopCPU :: CPUEnv s -> [Maybe Input] -> [[Action]] -> Lazy.ST s [(Cycle, Action)]
loopCPU _ [] _ = error "Always input"
loopCPU _ _ [] = error "Always more actions"
loopCPU env (k:ks) (as:ass) = do
cpu <- Lazy.strictToLazyST (stepCPU env k as)
cpus <- loopCPU env ks ass
return $ cpu:cpus
-- | (Strict) step.
stepCPU :: CPUEnv s -> Maybe Input -> [Action] -> ST s (Cycle, Action)
stepCPU env _ as = runCpuCPS m return env
-- flip runReaderT env $ runCPUST m
where
m = do handlePPUAction as
c <- (handleIRQ >> fetch >>= execute)
a <- getCPUAction
return $ (c, a)
------------------------------------------------------------------------------
-- PPU
-- (Lazy) Will step a strict ppu.
loopPPU :: PPUEnv s -> [(Cycle, Action)] -> Lazy.ST s ([Pixel], [[Action]])
loopPPU _ [] = error "Always more"
loopPPU env (x:xs) = do
(pxs, as) <- Lazy.strictToLazyST $ stepPPU env x
~(pxs', as') <- loopPPU env xs
return $ (pxs++pxs', as:as')
-- (Strict)
stepPPU :: PPUEnv s -> (Cycle, Action) -> ST s ([Pixel], [Action])
stepPPU env (cc,a) = flip runReaderT env $ do
ppuDecodeAction a
ps <- runPPU (cc * 3)
as <- getPPUActions
return (ps, as)
| tobsan/yane | Enterprise.hs | gpl-3.0 | 6,146 | 0 | 24 | 1,961 | 1,828 | 973 | 855 | 119 | 2 |
module Numeric (showInt, showOct, showHex, showDouble, show, showTime) where {
-- A partial implementation of the Haskell "Numeric" library module.
-- With the addition of the functions show and time;
showInt, showOct, showHex :: Int -> (String -> String);
showInt = showIntAtBase 10 intToDigit; -- NB: Non-negative integers only!
showOct = showIntAtBase 8 intToDigit;
showHex = showIntAtBase 16 intToDigit;
show :: Int -> String;
show n =
if n < 0 then
'-' : (showInt (-n) "")
else
showInt n "" ;
primitive primShowDouble :: Double -> String; -- An efficient, built-in conversion
showDouble :: Double -> String;
showDouble = primShowDouble;
-- The value of
-- showTime gmtOffset ms
-- where:
-- ms is the time in milliseconds since the start of 1970
-- gmtOffset is the offset, in hours, relative to GMT
-- is a string giving the number of days, hours, minutes and seconds since the start of 1970
showTime :: Int -> Int -> String;
showTime gmtOffset ms' =
let { ms = ms' `mod` 1000;
sec' = ms' `div` 1000;
sec = sec' `mod` 60;
min' = sec' `div` 60;
min = min' `mod` 60;
hr' = (min' `div` 60) + gmtOffset;
hr = hr' `mod` 24;
day' = hr' `div` 24
} in showInt day' (" days, " ++ showInt hr (" hrs, " ++ showInt min ("mins, " ++ showInt sec " secs")));
-- ------------------------------------------------------------------------
showIntAtBase :: Int -> (Int -> Char) -> Int -> (String -> String);
showIntAtBase base intToDig n rest =
if n < 0 then
error "Numeric.showIntAtBase: can't show negative numbers"
else
let { d = rem n base; q = quot n base;
rest' = intToDig d : rest
} in if q == 0 then
rest'
else
showIntAtBase base intToDigit q rest';
intToDigit :: Int -> Char;
intToDigit i =
if (i >= 0) && (i <= 9) then chr (ord '0' + i)
else if (i >= 10) && (i <= 15) then chr (ord 'a' + i - 10)
else error "Numeric.intToDigit: not a digit"
}
| ckaestne/CIDE | CIDE_Language_Haskell/test/fromviral/Numeric.hs | gpl-3.0 | 2,195 | 3 | 16 | 696 | 578 | 334 | 244 | -1 | -1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.AndroidManagement.Enterprises.Devices.Operations.Get
-- 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)
--
-- Gets the latest state of a long-running operation. Clients can use this
-- method to poll the operation result at intervals as recommended by the
-- API service.
--
-- /See:/ <https://developers.google.com/android/management Android Management API Reference> for @androidmanagement.enterprises.devices.operations.get@.
module Network.Google.Resource.AndroidManagement.Enterprises.Devices.Operations.Get
(
-- * REST Resource
EnterprisesDevicesOperationsGetResource
-- * Creating a Request
, enterprisesDevicesOperationsGet
, EnterprisesDevicesOperationsGet
-- * Request Lenses
, edogXgafv
, edogUploadProtocol
, edogAccessToken
, edogUploadType
, edogName
, edogCallback
) where
import Network.Google.AndroidManagement.Types
import Network.Google.Prelude
-- | A resource alias for @androidmanagement.enterprises.devices.operations.get@ method which the
-- 'EnterprisesDevicesOperationsGet' request conforms to.
type EnterprisesDevicesOperationsGetResource =
"v1" :>
Capture "name" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :> Get '[JSON] Operation
-- | Gets the latest state of a long-running operation. Clients can use this
-- method to poll the operation result at intervals as recommended by the
-- API service.
--
-- /See:/ 'enterprisesDevicesOperationsGet' smart constructor.
data EnterprisesDevicesOperationsGet =
EnterprisesDevicesOperationsGet'
{ _edogXgafv :: !(Maybe Xgafv)
, _edogUploadProtocol :: !(Maybe Text)
, _edogAccessToken :: !(Maybe Text)
, _edogUploadType :: !(Maybe Text)
, _edogName :: !Text
, _edogCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'EnterprisesDevicesOperationsGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'edogXgafv'
--
-- * 'edogUploadProtocol'
--
-- * 'edogAccessToken'
--
-- * 'edogUploadType'
--
-- * 'edogName'
--
-- * 'edogCallback'
enterprisesDevicesOperationsGet
:: Text -- ^ 'edogName'
-> EnterprisesDevicesOperationsGet
enterprisesDevicesOperationsGet pEdogName_ =
EnterprisesDevicesOperationsGet'
{ _edogXgafv = Nothing
, _edogUploadProtocol = Nothing
, _edogAccessToken = Nothing
, _edogUploadType = Nothing
, _edogName = pEdogName_
, _edogCallback = Nothing
}
-- | V1 error format.
edogXgafv :: Lens' EnterprisesDevicesOperationsGet (Maybe Xgafv)
edogXgafv
= lens _edogXgafv (\ s a -> s{_edogXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
edogUploadProtocol :: Lens' EnterprisesDevicesOperationsGet (Maybe Text)
edogUploadProtocol
= lens _edogUploadProtocol
(\ s a -> s{_edogUploadProtocol = a})
-- | OAuth access token.
edogAccessToken :: Lens' EnterprisesDevicesOperationsGet (Maybe Text)
edogAccessToken
= lens _edogAccessToken
(\ s a -> s{_edogAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
edogUploadType :: Lens' EnterprisesDevicesOperationsGet (Maybe Text)
edogUploadType
= lens _edogUploadType
(\ s a -> s{_edogUploadType = a})
-- | The name of the operation resource.
edogName :: Lens' EnterprisesDevicesOperationsGet Text
edogName = lens _edogName (\ s a -> s{_edogName = a})
-- | JSONP
edogCallback :: Lens' EnterprisesDevicesOperationsGet (Maybe Text)
edogCallback
= lens _edogCallback (\ s a -> s{_edogCallback = a})
instance GoogleRequest
EnterprisesDevicesOperationsGet
where
type Rs EnterprisesDevicesOperationsGet = Operation
type Scopes EnterprisesDevicesOperationsGet =
'["https://www.googleapis.com/auth/androidmanagement"]
requestClient EnterprisesDevicesOperationsGet'{..}
= go _edogName _edogXgafv _edogUploadProtocol
_edogAccessToken
_edogUploadType
_edogCallback
(Just AltJSON)
androidManagementService
where go
= buildClient
(Proxy ::
Proxy EnterprisesDevicesOperationsGetResource)
mempty
| brendanhay/gogol | gogol-androidmanagement/gen/Network/Google/Resource/AndroidManagement/Enterprises/Devices/Operations/Get.hs | mpl-2.0 | 5,233 | 0 | 15 | 1,115 | 700 | 411 | 289 | 103 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.CloudTasks.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.CloudTasks.Types.Sum where
import Network.Google.Prelude hiding (Bytes)
-- | The response_view specifies which subset of the Task will be returned.
-- By default response_view is BASIC; not all information is retrieved by
-- default because some data, such as payloads, might be desirable to
-- return only when needed because of its large size or because of the
-- sensitivity of data that it contains. Authorization for FULL requires
-- \`cloudtasks.tasks.fullView\` [Google
-- IAM](https:\/\/cloud.google.com\/iam\/) permission on the Task resource.
data ProjectsLocationsQueuesTasksListResponseView
= ViewUnspecified
-- ^ @VIEW_UNSPECIFIED@
-- Unspecified. Defaults to BASIC.
| Basic
-- ^ @BASIC@
-- The basic view omits fields which can be large or can contain sensitive
-- data. This view does not include the body in AppEngineHttpRequest.
-- Bodies are desirable to return only when needed, because they can be
-- large and because of the sensitivity of the data that you choose to
-- store in it.
| Full
-- ^ @FULL@
-- All information is returned. Authorization for FULL requires
-- \`cloudtasks.tasks.fullView\` [Google
-- IAM](https:\/\/cloud.google.com\/iam\/) permission on the Queue
-- resource.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable ProjectsLocationsQueuesTasksListResponseView
instance FromHttpApiData ProjectsLocationsQueuesTasksListResponseView where
parseQueryParam = \case
"VIEW_UNSPECIFIED" -> Right ViewUnspecified
"BASIC" -> Right Basic
"FULL" -> Right Full
x -> Left ("Unable to parse ProjectsLocationsQueuesTasksListResponseView from: " <> x)
instance ToHttpApiData ProjectsLocationsQueuesTasksListResponseView where
toQueryParam = \case
ViewUnspecified -> "VIEW_UNSPECIFIED"
Basic -> "BASIC"
Full -> "FULL"
instance FromJSON ProjectsLocationsQueuesTasksListResponseView where
parseJSON = parseJSONText "ProjectsLocationsQueuesTasksListResponseView"
instance ToJSON ProjectsLocationsQueuesTasksListResponseView where
toJSON = toJSONText
-- | Output only. The view specifies which subset of the Task has been
-- returned.
data TaskView
= TVViewUnspecified
-- ^ @VIEW_UNSPECIFIED@
-- Unspecified. Defaults to BASIC.
| TVBasic
-- ^ @BASIC@
-- The basic view omits fields which can be large or can contain sensitive
-- data. This view does not include the body in AppEngineHttpRequest.
-- Bodies are desirable to return only when needed, because they can be
-- large and because of the sensitivity of the data that you choose to
-- store in it.
| TVFull
-- ^ @FULL@
-- All information is returned. Authorization for FULL requires
-- \`cloudtasks.tasks.fullView\` [Google
-- IAM](https:\/\/cloud.google.com\/iam\/) permission on the Queue
-- resource.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable TaskView
instance FromHttpApiData TaskView where
parseQueryParam = \case
"VIEW_UNSPECIFIED" -> Right TVViewUnspecified
"BASIC" -> Right TVBasic
"FULL" -> Right TVFull
x -> Left ("Unable to parse TaskView from: " <> x)
instance ToHttpApiData TaskView where
toQueryParam = \case
TVViewUnspecified -> "VIEW_UNSPECIFIED"
TVBasic -> "BASIC"
TVFull -> "FULL"
instance FromJSON TaskView where
parseJSON = parseJSONText "TaskView"
instance ToJSON TaskView where
toJSON = toJSONText
-- | Output only. The state of the queue. \`state\` can only be changed by
-- calling PauseQueue, ResumeQueue, or uploading
-- [queue.yaml\/xml](https:\/\/cloud.google.com\/appengine\/docs\/python\/config\/queueref).
-- UpdateQueue cannot be used to change \`state\`.
data QueueState
= StateUnspecified
-- ^ @STATE_UNSPECIFIED@
-- Unspecified state.
| Running
-- ^ @RUNNING@
-- The queue is running. Tasks can be dispatched. If the queue was created
-- using Cloud Tasks and the queue has had no activity (method calls or
-- task dispatches) for 30 days, the queue may take a few minutes to
-- re-activate. Some method calls may return NOT_FOUND and tasks may not be
-- dispatched for a few minutes until the queue has been re-activated.
| Paused
-- ^ @PAUSED@
-- Tasks are paused by the user. If the queue is paused then Cloud Tasks
-- will stop delivering tasks from it, but more tasks can still be added to
-- it by the user.
| Disabled
-- ^ @DISABLED@
-- The queue is disabled. A queue becomes \`DISABLED\` when
-- [queue.yaml](https:\/\/cloud.google.com\/appengine\/docs\/python\/config\/queueref)
-- or
-- [queue.xml](https:\/\/cloud.google.com\/appengine\/docs\/standard\/java\/config\/queueref)
-- is uploaded which does not contain the queue. You cannot directly
-- disable a queue. When a queue is disabled, tasks can still be added to a
-- queue but the tasks are not dispatched. To permanently delete this queue
-- and all of its tasks, call DeleteQueue.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable QueueState
instance FromHttpApiData QueueState where
parseQueryParam = \case
"STATE_UNSPECIFIED" -> Right StateUnspecified
"RUNNING" -> Right Running
"PAUSED" -> Right Paused
"DISABLED" -> Right Disabled
x -> Left ("Unable to parse QueueState from: " <> x)
instance ToHttpApiData QueueState where
toQueryParam = \case
StateUnspecified -> "STATE_UNSPECIFIED"
Running -> "RUNNING"
Paused -> "PAUSED"
Disabled -> "DISABLED"
instance FromJSON QueueState where
parseJSON = parseJSONText "QueueState"
instance ToJSON QueueState where
toJSON = toJSONText
-- | The response_view specifies which subset of the Task will be returned.
-- By default response_view is BASIC; not all information is retrieved by
-- default because some data, such as payloads, might be desirable to
-- return only when needed because of its large size or because of the
-- sensitivity of data that it contains. Authorization for FULL requires
-- \`cloudtasks.tasks.fullView\` [Google
-- IAM](https:\/\/cloud.google.com\/iam\/) permission on the Task resource.
data CreateTaskRequestResponseView
= CTRRVViewUnspecified
-- ^ @VIEW_UNSPECIFIED@
-- Unspecified. Defaults to BASIC.
| CTRRVBasic
-- ^ @BASIC@
-- The basic view omits fields which can be large or can contain sensitive
-- data. This view does not include the body in AppEngineHttpRequest.
-- Bodies are desirable to return only when needed, because they can be
-- large and because of the sensitivity of the data that you choose to
-- store in it.
| CTRRVFull
-- ^ @FULL@
-- All information is returned. Authorization for FULL requires
-- \`cloudtasks.tasks.fullView\` [Google
-- IAM](https:\/\/cloud.google.com\/iam\/) permission on the Queue
-- resource.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable CreateTaskRequestResponseView
instance FromHttpApiData CreateTaskRequestResponseView where
parseQueryParam = \case
"VIEW_UNSPECIFIED" -> Right CTRRVViewUnspecified
"BASIC" -> Right CTRRVBasic
"FULL" -> Right CTRRVFull
x -> Left ("Unable to parse CreateTaskRequestResponseView from: " <> x)
instance ToHttpApiData CreateTaskRequestResponseView where
toQueryParam = \case
CTRRVViewUnspecified -> "VIEW_UNSPECIFIED"
CTRRVBasic -> "BASIC"
CTRRVFull -> "FULL"
instance FromJSON CreateTaskRequestResponseView where
parseJSON = parseJSONText "CreateTaskRequestResponseView"
instance ToJSON CreateTaskRequestResponseView where
toJSON = toJSONText
-- | The HTTP method to use for the request. The default is POST. The app\'s
-- request handler for the task\'s target URL must be able to handle HTTP
-- requests with this http_method, otherwise the task attempt fails with
-- error code 405 (Method Not Allowed). See [Writing a push task request
-- handler](https:\/\/cloud.google.com\/appengine\/docs\/java\/taskqueue\/push\/creating-handlers#writing_a_push_task_request_handler)
-- and the App Engine documentation for your runtime on [How Requests are
-- Handled](https:\/\/cloud.google.com\/appengine\/docs\/standard\/python3\/how-requests-are-handled).
data AppEngineHTTPRequestHTTPMethod
= HTTPMethodUnspecified
-- ^ @HTTP_METHOD_UNSPECIFIED@
-- HTTP method unspecified
| Post'
-- ^ @POST@
-- HTTP POST
| Get'
-- ^ @GET@
-- HTTP GET
| Head'
-- ^ @HEAD@
-- HTTP HEAD
| Put'
-- ^ @PUT@
-- HTTP PUT
| Delete'
-- ^ @DELETE@
-- HTTP DELETE
| Patch'
-- ^ @PATCH@
-- HTTP PATCH
| Options
-- ^ @OPTIONS@
-- HTTP OPTIONS
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable AppEngineHTTPRequestHTTPMethod
instance FromHttpApiData AppEngineHTTPRequestHTTPMethod where
parseQueryParam = \case
"HTTP_METHOD_UNSPECIFIED" -> Right HTTPMethodUnspecified
"POST" -> Right Post'
"GET" -> Right Get'
"HEAD" -> Right Head'
"PUT" -> Right Put'
"DELETE" -> Right Delete'
"PATCH" -> Right Patch'
"OPTIONS" -> Right Options
x -> Left ("Unable to parse AppEngineHTTPRequestHTTPMethod from: " <> x)
instance ToHttpApiData AppEngineHTTPRequestHTTPMethod where
toQueryParam = \case
HTTPMethodUnspecified -> "HTTP_METHOD_UNSPECIFIED"
Post' -> "POST"
Get' -> "GET"
Head' -> "HEAD"
Put' -> "PUT"
Delete' -> "DELETE"
Patch' -> "PATCH"
Options -> "OPTIONS"
instance FromJSON AppEngineHTTPRequestHTTPMethod where
parseJSON = parseJSONText "AppEngineHTTPRequestHTTPMethod"
instance ToJSON AppEngineHTTPRequestHTTPMethod where
toJSON = toJSONText
-- | The response_view specifies which subset of the Task will be returned.
-- By default response_view is BASIC; not all information is retrieved by
-- default because some data, such as payloads, might be desirable to
-- return only when needed because of its large size or because of the
-- sensitivity of data that it contains. Authorization for FULL requires
-- \`cloudtasks.tasks.fullView\` [Google
-- IAM](https:\/\/cloud.google.com\/iam\/) permission on the Task resource.
data ProjectsLocationsQueuesTasksGetResponseView
= PLQTGRVViewUnspecified
-- ^ @VIEW_UNSPECIFIED@
-- Unspecified. Defaults to BASIC.
| PLQTGRVBasic
-- ^ @BASIC@
-- The basic view omits fields which can be large or can contain sensitive
-- data. This view does not include the body in AppEngineHttpRequest.
-- Bodies are desirable to return only when needed, because they can be
-- large and because of the sensitivity of the data that you choose to
-- store in it.
| PLQTGRVFull
-- ^ @FULL@
-- All information is returned. Authorization for FULL requires
-- \`cloudtasks.tasks.fullView\` [Google
-- IAM](https:\/\/cloud.google.com\/iam\/) permission on the Queue
-- resource.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable ProjectsLocationsQueuesTasksGetResponseView
instance FromHttpApiData ProjectsLocationsQueuesTasksGetResponseView where
parseQueryParam = \case
"VIEW_UNSPECIFIED" -> Right PLQTGRVViewUnspecified
"BASIC" -> Right PLQTGRVBasic
"FULL" -> Right PLQTGRVFull
x -> Left ("Unable to parse ProjectsLocationsQueuesTasksGetResponseView from: " <> x)
instance ToHttpApiData ProjectsLocationsQueuesTasksGetResponseView where
toQueryParam = \case
PLQTGRVViewUnspecified -> "VIEW_UNSPECIFIED"
PLQTGRVBasic -> "BASIC"
PLQTGRVFull -> "FULL"
instance FromJSON ProjectsLocationsQueuesTasksGetResponseView where
parseJSON = parseJSONText "ProjectsLocationsQueuesTasksGetResponseView"
instance ToJSON ProjectsLocationsQueuesTasksGetResponseView 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
-- | The response_view specifies which subset of the Task will be returned.
-- By default response_view is BASIC; not all information is retrieved by
-- default because some data, such as payloads, might be desirable to
-- return only when needed because of its large size or because of the
-- sensitivity of data that it contains. Authorization for FULL requires
-- \`cloudtasks.tasks.fullView\` [Google
-- IAM](https:\/\/cloud.google.com\/iam\/) permission on the Task resource.
data RunTaskRequestResponseView
= RTRRVViewUnspecified
-- ^ @VIEW_UNSPECIFIED@
-- Unspecified. Defaults to BASIC.
| RTRRVBasic
-- ^ @BASIC@
-- The basic view omits fields which can be large or can contain sensitive
-- data. This view does not include the body in AppEngineHttpRequest.
-- Bodies are desirable to return only when needed, because they can be
-- large and because of the sensitivity of the data that you choose to
-- store in it.
| RTRRVFull
-- ^ @FULL@
-- All information is returned. Authorization for FULL requires
-- \`cloudtasks.tasks.fullView\` [Google
-- IAM](https:\/\/cloud.google.com\/iam\/) permission on the Queue
-- resource.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable RunTaskRequestResponseView
instance FromHttpApiData RunTaskRequestResponseView where
parseQueryParam = \case
"VIEW_UNSPECIFIED" -> Right RTRRVViewUnspecified
"BASIC" -> Right RTRRVBasic
"FULL" -> Right RTRRVFull
x -> Left ("Unable to parse RunTaskRequestResponseView from: " <> x)
instance ToHttpApiData RunTaskRequestResponseView where
toQueryParam = \case
RTRRVViewUnspecified -> "VIEW_UNSPECIFIED"
RTRRVBasic -> "BASIC"
RTRRVFull -> "FULL"
instance FromJSON RunTaskRequestResponseView where
parseJSON = parseJSONText "RunTaskRequestResponseView"
instance ToJSON RunTaskRequestResponseView where
toJSON = toJSONText
-- | The HTTP method to use for the request. The default is POST.
data HTTPRequestHTTPMethod
= HTTPRHTTPMHTTPMethodUnspecified
-- ^ @HTTP_METHOD_UNSPECIFIED@
-- HTTP method unspecified
| HTTPRHTTPMPost'
-- ^ @POST@
-- HTTP POST
| HTTPRHTTPMGet'
-- ^ @GET@
-- HTTP GET
| HTTPRHTTPMHead'
-- ^ @HEAD@
-- HTTP HEAD
| HTTPRHTTPMPut'
-- ^ @PUT@
-- HTTP PUT
| HTTPRHTTPMDelete'
-- ^ @DELETE@
-- HTTP DELETE
| HTTPRHTTPMPatch'
-- ^ @PATCH@
-- HTTP PATCH
| HTTPRHTTPMOptions
-- ^ @OPTIONS@
-- HTTP OPTIONS
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable HTTPRequestHTTPMethod
instance FromHttpApiData HTTPRequestHTTPMethod where
parseQueryParam = \case
"HTTP_METHOD_UNSPECIFIED" -> Right HTTPRHTTPMHTTPMethodUnspecified
"POST" -> Right HTTPRHTTPMPost'
"GET" -> Right HTTPRHTTPMGet'
"HEAD" -> Right HTTPRHTTPMHead'
"PUT" -> Right HTTPRHTTPMPut'
"DELETE" -> Right HTTPRHTTPMDelete'
"PATCH" -> Right HTTPRHTTPMPatch'
"OPTIONS" -> Right HTTPRHTTPMOptions
x -> Left ("Unable to parse HTTPRequestHTTPMethod from: " <> x)
instance ToHttpApiData HTTPRequestHTTPMethod where
toQueryParam = \case
HTTPRHTTPMHTTPMethodUnspecified -> "HTTP_METHOD_UNSPECIFIED"
HTTPRHTTPMPost' -> "POST"
HTTPRHTTPMGet' -> "GET"
HTTPRHTTPMHead' -> "HEAD"
HTTPRHTTPMPut' -> "PUT"
HTTPRHTTPMDelete' -> "DELETE"
HTTPRHTTPMPatch' -> "PATCH"
HTTPRHTTPMOptions -> "OPTIONS"
instance FromJSON HTTPRequestHTTPMethod where
parseJSON = parseJSONText "HTTPRequestHTTPMethod"
instance ToJSON HTTPRequestHTTPMethod where
toJSON = toJSONText
| brendanhay/gogol | gogol-cloudtasks/gen/Network/Google/CloudTasks/Types/Sum.hs | mpl-2.0 | 17,298 | 0 | 11 | 3,885 | 1,955 | 1,085 | 870 | 227 | 0 |
import Data.List
primes = 2 : filter ((==1) . length . primeFactors) [3,5..]
primeFactors :: Int -> [Int]
primeFactors n = factor n primes
where
factor n (p:ps)
| p*p > n = [n]
| n `mod` p == 0 = p : factor (n `div` p) (p:ps)
| otherwise = factor n ps
test n x y = length (intersect x y) == 0 && length x >= n && length y >= n
n_dist :: Int -> [[Int]] -> Bool
n_dist n (x:[]) = True
n_dist n (x:(y:tl)) = (test n x y) && n_dist n (y:tl)
prob47 :: Int -> Int
prob47 n =
head [ x | x <- [2..],
let y = [x..x+n-1],
n_dist n (map (nub . primeFactors) y)]
main = print $ prob47 4
| jdavidberger/project-euler | prob47.hs | lgpl-3.0 | 678 | 3 | 13 | 234 | 407 | 205 | 202 | 18 | 1 |
module SSync.JSVector.Internal where
import Control.Applicative (Applicative(..))
newtype VectorMonad a = VectorMonad { runVectorMonad :: IO a }
instance Monad VectorMonad where
return = VectorMonad . return
(VectorMonad a) >>= b = VectorMonad $ a >>= runVectorMonad . b
instance Applicative VectorMonad where
pure = VectorMonad . pure
(VectorMonad f) <*> (VectorMonad v) = VectorMonad (f <*> v)
instance Functor VectorMonad where
fmap f (VectorMonad v) = VectorMonad (fmap f v)
| socrata-platform/ssync | src/main/haskell/SSync/JSVector/Internal.hs | apache-2.0 | 495 | 0 | 8 | 86 | 169 | 90 | 79 | 11 | 0 |
{-# LANGUAGE TypeFamilies #-}
module Entity where
class Entity e where
type EKey e
type EValue e
getKey :: e -> EKey e
getValue :: e -> EValue e
| sisioh/haskell-dddbase | src/Entity.hs | apache-2.0 | 156 | 0 | 8 | 40 | 46 | 26 | 20 | 7 | 0 |
-- |
-- Module : $Header$
-- Copyright : (c) 2013-2015 Galois, Inc.
-- License : BSD3
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable
module Cryptol.ModuleSystem.NamingEnv where
import Cryptol.ModuleSystem.Interface
import Cryptol.Parser.AST
import Cryptol.Parser.Names (namesP)
import Cryptol.Parser.Position
import qualified Cryptol.TypeCheck.AST as T
import Cryptol.Utils.PP
import Cryptol.Utils.Panic (panic)
import Data.Maybe (catMaybes)
import qualified Data.Map as Map
#if __GLASGOW_HASKELL__ < 710
import Control.Applicative (Applicative, (<$>), (<*>), pure)
import Data.Monoid (Monoid(..))
import Data.Foldable (foldMap)
import Data.Traversable (traverse)
#endif
-- Name Locations --------------------------------------------------------------
data NameOrigin = Local (Located QName)
| Imported QName
deriving (Show)
instance PP NameOrigin where
ppPrec _ o = case o of
Local lqn -> pp lqn
Imported (QName m n) -> pp n <+> trailer
where
trailer = case m of
Just mn -> text "from module" <+> pp mn
_ -> empty
-- Names -----------------------------------------------------------------------
data EName = EFromBind (Located QName)
| EFromNewtype (Located QName)
| EFromMod QName
deriving (Show)
data TName = TFromParam QName
| TFromSyn (Located QName)
| TFromNewtype (Located QName)
| TFromMod QName
deriving (Show)
class HasQName a where
qname :: a -> QName
origin :: a -> NameOrigin
instance HasQName TName where
qname tn = case tn of
TFromParam qn -> qn
TFromSyn lqn -> thing lqn
TFromNewtype lqn -> thing lqn
TFromMod qn -> qn
origin tn = case tn of
TFromParam qn -> Local Located { srcRange = emptyRange, thing = qn }
TFromSyn lqn -> Local lqn
TFromNewtype lqn -> Local lqn
TFromMod qn -> Imported qn
instance HasQName EName where
qname en = case en of
EFromBind lqn -> thing lqn
EFromNewtype lqn -> thing lqn
EFromMod qn -> qn
origin en = case en of
EFromBind lqn -> Local lqn
EFromNewtype lqn -> Local lqn
EFromMod qn -> Imported qn
-- Naming Environment ----------------------------------------------------------
-- XXX The fixity environment should be removed, and EName should include fixity
-- information.
data NamingEnv = NamingEnv { neExprs :: Map.Map QName [EName]
-- ^ Expr renaming environment
, neTypes :: Map.Map QName [TName]
-- ^ Type renaming environment
, neFixity:: Map.Map QName [Fixity]
} deriving (Show)
instance Monoid NamingEnv where
mempty =
NamingEnv { neExprs = Map.empty
, neTypes = Map.empty
, neFixity = Map.empty }
mappend l r =
NamingEnv { neExprs = Map.unionWith (++) (neExprs l) (neExprs r)
, neTypes = Map.unionWith (++) (neTypes l) (neTypes r)
, neFixity = Map.union (neFixity l) (neFixity r) }
mconcat envs =
NamingEnv { neExprs = Map.unionsWith (++) (map neExprs envs)
, neTypes = Map.unionsWith (++) (map neTypes envs)
, neFixity = Map.unions (map neFixity envs) }
-- | Singleton type renaming environment.
singletonT :: QName -> TName -> NamingEnv
singletonT qn tn = mempty { neTypes = Map.singleton qn [tn] }
-- | Singleton expression renaming environment.
singletonE :: QName -> EName -> NamingEnv
singletonE qn en = mempty { neExprs = Map.singleton qn [en] }
-- | Like mappend, but when merging, prefer values on the lhs.
shadowing :: NamingEnv -> NamingEnv -> NamingEnv
shadowing l r = NamingEnv
{ neExprs = Map.union (neExprs l) (neExprs r)
, neTypes = Map.union (neTypes l) (neTypes r)
, neFixity = Map.union (neFixity l) (neFixity r) }
travNamingEnv :: Applicative f => (QName -> f QName) -> NamingEnv -> f NamingEnv
travNamingEnv f ne = NamingEnv <$> neExprs' <*> neTypes' <*> pure (neFixity ne)
where
neExprs' = traverse (traverse travE) (neExprs ne)
neTypes' = traverse (traverse travT) (neTypes ne)
travE en = case en of
EFromBind lqn -> EFromBind <$> travLoc lqn
EFromNewtype lqn -> EFromNewtype <$> travLoc lqn
EFromMod qn -> EFromMod <$> f qn
travT tn = case tn of
TFromParam qn -> TFromParam <$> f qn
TFromSyn lqn -> TFromSyn <$> travLoc lqn
TFromNewtype lqn -> TFromNewtype <$> travLoc lqn
TFromMod qn -> TFromMod <$> f qn
travLoc loc = Located (srcRange loc) <$> f (thing loc)
-- | Things that define exported names.
class BindsNames a where
namingEnv :: a -> NamingEnv
instance BindsNames NamingEnv where
namingEnv = id
instance BindsNames a => BindsNames (Maybe a) where
namingEnv = foldMap namingEnv
instance BindsNames a => BindsNames [a] where
namingEnv = foldMap namingEnv
-- | Generate a type renaming environment from the parameters that are bound by
-- this schema.
instance BindsNames Schema where
namingEnv (Forall ps _ _ _) = foldMap namingEnv ps
-- | Produce a naming environment from an interface file, that contains a
-- mapping only from unqualified names to qualified ones.
instance BindsNames Iface where
namingEnv = namingEnv . ifPublic
-- | Translate a set of declarations from an interface into a naming
-- environment.
instance BindsNames IfaceDecls where
namingEnv binds = mconcat [ types, newtypes, vars ]
where
types = mempty
{ neTypes = Map.map (map (TFromMod . ifTySynName)) (ifTySyns binds)
}
newtypes = mempty
{ neTypes = Map.map (map (TFromMod . T.ntName)) (ifNewtypes binds)
, neExprs = Map.map (map (EFromMod . T.ntName)) (ifNewtypes binds)
}
vars = mempty
{ neExprs = Map.map (map (EFromMod . ifDeclName)) (ifDecls binds)
, neFixity = Map.fromList [ (n,fs) | ds <- Map.elems (ifDecls binds)
, all ifDeclInfix ds
, let fs = catMaybes (map ifDeclFixity ds)
n = ifDeclName (head ds) ]
}
-- | Translate names bound by the patterns of a match into a renaming
-- environment.
instance BindsNames Match where
namingEnv m = case m of
Match p _ -> namingEnv p
MatchLet b -> namingEnv b
instance BindsNames Bind where
namingEnv b = singletonE (thing qn) (EFromBind qn) `mappend` fixity
where
qn = bName b
fixity = case bFixity b of
Just f -> mempty { neFixity = Map.singleton (thing qn) [f] }
Nothing -> mempty
-- | Generate the naming environment for a type parameter.
instance BindsNames TParam where
namingEnv p = singletonT qn (TFromParam qn)
where
qn = mkUnqual (tpName p)
-- | Generate an expression renaming environment from a pattern. This ignores
-- type parameters that can be bound by the pattern.
instance BindsNames Pattern where
namingEnv p = foldMap unqualBind (namesP p)
where
unqualBind qn = singletonE (thing qn) (EFromBind qn)
-- | The naming environment for a single module. This is the mapping from
-- unqualified internal names to fully qualified names.
instance BindsNames Module where
namingEnv m = foldMap topDeclEnv (mDecls m)
where
topDeclEnv td = case td of
Decl d -> declEnv (tlValue d)
TDNewtype n -> newtypeEnv (tlValue n)
Include _ -> mempty
qual = fmap (\qn -> mkQual (thing (mName m)) (unqual qn))
qualBind ln = singletonE (thing ln) (EFromBind (qual ln))
qualType ln = singletonT (thing ln) (TFromSyn (qual ln))
declEnv d = case d of
DSignature ns _sig -> foldMap qualBind ns
DPragma ns _p -> foldMap qualBind ns
DBind b -> qualBind (bName b) `mappend` fixity b
DPatBind _pat _e -> panic "ModuleSystem" ["Unexpected pattern binding"]
DFixity{} -> panic "ModuleSystem" ["Unexpected fixity declaration"]
DType (TySyn lqn _ _) -> qualType lqn
DLocated d' _ -> declEnv d'
fixity b =
case bFixity b of
Just f -> mempty { neFixity = Map.singleton (thing (qual (bName b))) [f] }
Nothing -> mempty
newtypeEnv n = singletonT (thing qn) (TFromNewtype (qual qn))
`mappend` singletonE (thing qn) (EFromNewtype (qual qn))
where
qn = nName n
-- | The naming environment for a single declaration, unqualified. This is
-- meanat to be used for things like where clauses.
instance BindsNames Decl where
namingEnv d = case d of
DSignature ns _sig -> foldMap qualBind ns
DPragma ns _p -> foldMap qualBind ns
DBind b -> qualBind (bName b)
DPatBind _pat _e -> panic "ModuleSystem" ["Unexpected pattern binding"]
DFixity{} -> panic "ModuleSystem" ["Unexpected fixity declaration"]
DType (TySyn lqn _ _) -> qualType lqn
DLocated d' _ -> namingEnv d'
where
qualBind ln = singletonE (thing ln) (EFromBind ln)
qualType ln = singletonT (thing ln) (TFromSyn ln)
| ntc2/cryptol | src/Cryptol/ModuleSystem/NamingEnv.hs | bsd-3-clause | 9,318 | 0 | 19 | 2,611 | 2,676 | 1,371 | 1,305 | 172 | 6 |
{-# LANGUAGE OverloadedStrings #-}
module Twitter
( TwKeys
, twKeys
, post
) where
import Control.Monad.IO.Class (liftIO)
import Data.ByteString
import qualified Data.ByteString.Lazy as L
import qualified Data.ByteString.Char8 as BC
import Data.Conduit
import qualified Data.Conduit.Binary as CB
import Network.HTTP.Conduit
import Web.Authenticate.OAuth
import Article
data TwKeys = TK {
consumer_key :: ByteString,
consumer_secret :: ByteString,
access_token :: ByteString,
access_token_secret :: ByteString}
deriving (Show)
twKeys :: String -> String -> String -> String -> TwKeys
twKeys ck cs at ats = TK {
consumer_key = BC.pack ck,
consumer_secret = BC.pack cs,
access_token = BC.pack at,
access_token_secret = BC.pack ats}
post :: TwKeys -> Article -> IO L.ByteString
post keys a = runResourceT $ do
manager <- liftIO $ newManager def
req <- liftIO $ parseUrl "http://twitter.com/statuses/update.json"
request <- signOAuth oauth credential $ postMessage status req
response <- http request manager
responseBody response $$ CB.take 1024
where
credential = newCredential (access_token keys) (access_token_secret keys)
site = "https://api.twitter.com"
oauth = newOAuth {
oauthRequestUri = site ++ "/oauth/request_token",
oauthAccessTokenUri = site ++ "/oauth/access_token",
oauthAuthorizeUri = site ++ "/oauth/authorize",
oauthConsumerKey = consumer_key keys,
oauthConsumerSecret = consumer_secret keys}
status = BC.pack $ a_title a ++ " :: " ++ a_link a
postMessage :: MonadUnsafeIO m => ByteString -> Request m -> Request m
postMessage msg req = urlEncodedBody [("status", msg)] req
| yunomu/nicodicbot | src/Twitter.hs | bsd-3-clause | 1,731 | 0 | 10 | 356 | 468 | 256 | 212 | 44 | 1 |
-- CIS 194, Spring 2015
--
-- Test cases for HW 01
-- ghcid --command="stack repl"
module HW01Tests where
import HW01
import Testing
-- Exercise 1 -----------------------------------------
testLastDigit :: (Integer, Integer) -> Bool
testLastDigit (n, d) = lastDigit n == d
testDropLastDigit :: (Integer, Integer) -> Bool
testDropLastDigit (n, d) = dropLastDigit n == d
ex1Tests :: [Test]
ex1Tests = [ Test "lastDigit test" testLastDigit
[(123, 3), (1234, 4), (5, 5), (10, 0), (0, 0)]
, Test "dropLastDigit test" testDropLastDigit
[(123, 12), (1234, 123), (5, 0), (10, 1), (0,0)]
]
-- Exercise 2 -----------------------------------------
testToRevDigits :: (Integer, [Integer]) -> Bool
testToRevDigits (n, l) = (==) (toRevDigits n) l
ex2Tests :: [Test]
ex2Tests = [ Test "toRevDigits test" testToRevDigits
[(123, [3,2,1]), (1234, [4,3,2,1]), (5, [5]), (0, []), ((-17), [])]
]
-- Exercise 3 -----------------------------------------
testDoubleEveryOther :: ([Integer], [Integer]) -> Bool
testDoubleEveryOther (l1, l2) = (==) (doubleEveryOther l1) l2
ex3Tests :: [Test]
ex3Tests = [ Test "doubleEveryOther test" testDoubleEveryOther
[([1,2,3], [1,4,3]), ([1,2,3,4], [1,4,3,8]), ([1,2,3,4,5,6,7], [1,4,3,8,5,12,7]), ([5], [5]), ([], [])]
]
-- Exercise 4 -----------------------------------------
testSumDigits :: ([Integer], Integer) -> Bool
testSumDigits (l, n) = sumDigits l == n
ex4Tests :: [Test]
ex4Tests = [ Test "sumDigits test" testSumDigits
[([1,2,3], 6), ([10,2,33,4], 13), ([5], 5), ([], 0)]
]
-- Exercise 5 -----------------------------------------
testLuhn :: Integer -> Bool
testLuhn n = luhn n
ex5Tests :: [Test]
ex5Tests = [ Test "luhn test" testLuhn
[4662110665499438, 645937, 1859]
]
-- Exercise 6 -----------------------------------------
testHanoi :: (Integer, Peg, Peg, Peg, [Move]) -> Bool
testHanoi (n, p1, p2, p3, m) = hanoi n p1 p2 p3 == m
ex6Tests :: [Test]
ex6Tests = [ Test "hanoi test" testHanoi
[(1, "a", "b", "c", [("a","c")]), (2, "a", "b", "c", [("a","b"),("a","c"),("b","c")])]
]
-- All Tests ------------------------------------------
allTests :: [Test]
allTests = concat [ ex1Tests
, ex2Tests
, ex3Tests
, ex4Tests
, ex5Tests
, ex6Tests
]
| eatobin/cis194 | lesson1/src/HW01Tests.hs | bsd-3-clause | 2,471 | 0 | 10 | 604 | 940 | 583 | 357 | 44 | 1 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE LambdaCase #-}
-- | This module contains an SMTLIB2 interface for
-- 1. checking the validity, and,
-- 2. computing satisfying assignments
-- for formulas.
-- By implementing a binary interface over the SMTLIB2 format defined at
-- http://www.smt-lib.org/
-- http://www.grammatech.com/resource/smt/SMTLIBTutorial.pdf
module Language.Fixpoint.Smt.Interface (
-- * Commands
Command (..)
-- * Responses
, Response (..)
-- * Typeclass for SMTLIB2 conversion
, SMTLIB2 (..)
-- * Creating and killing SMTLIB2 Process
, Context (..)
, makeContext
, makeContextNoLog
, cleanupContext
-- * Execute Queries
, command
, smtWrite
-- * Query API
, smtDecl
, smtAssert
, smtCheckUnsat
, smtBracket
, smtDistinct
, smtDoInterpolate
, smtInterpolate
-- * Theory Symbols
-- , theorySymbols
-- smt_set_funs
-- * Check Validity
, checkValid, checkValidWithContext
, checkValids
, makeZ3Context
) where
import Language.Fixpoint.Types.Config (SMTSolver (..))
import Language.Fixpoint.Misc (errorstar)
import Language.Fixpoint.Types.Errors
import Language.Fixpoint.Utils.Files
import Language.Fixpoint.Types
import Language.Fixpoint.Smt.Types
import Language.Fixpoint.Smt.Theories (preamble)
import Language.Fixpoint.Smt.Serialize()
import Control.Applicative ((<|>))
import Control.Monad
import Data.Char
import Data.Monoid
import Data.List as L
import qualified Data.Text as T
import Data.Text.Format hiding (format)
import qualified Data.Text.IO as TIO
-- import qualified Data.Text.Lazy as LT
-- import qualified Data.Text.Lazy.IO as LTIO
import System.Directory
import System.Console.CmdArgs.Verbosity
import System.Exit hiding (die)
import System.FilePath
import System.IO (IOMode (..), hClose, hFlush, openFile)
import System.Process
import qualified Data.Attoparsec.Text as A
import qualified Debug.Trace as DT
{-
runFile f
= readFile f >>= runString
runString str
= runCommands $ rr str
runCommands cmds
= do me <- makeContext Z3
mapM_ (T.putStrLn . smt2) cmds
zs <- mapM (command me) cmds
return zs
-}
-- TODO take makeContext's Bool from caller instead of always using False?
makeZ3Context :: FilePath -> [(Symbol, Sort)] -> IO Context
makeZ3Context f xts
= do me <- makeContext False Z3 f
smtDecls me xts
return me
checkValidWithContext :: Context -> [(Symbol, Sort)] -> Expr -> Expr -> IO Bool
checkValidWithContext me xts p q
= smtBracket me $ do smtDecls me xts
smtAssert me $ pAnd [p, PNot q]
smtCheckUnsat me
-- | type ClosedPred E = {v:Pred | subset (vars v) (keys E) }
-- checkValid :: e:Env -> ClosedPred e -> ClosedPred e -> IO Bool
checkValid :: Bool -> FilePath -> [(Symbol, Sort)] -> Expr -> Expr -> IO Bool
checkValid u f xts p q
= do me <- makeContext u Z3 f
smtDecls me xts
smtAssert me $ pAnd [p, PNot q]
smtCheckUnsat me
-- | If you already HAVE a context, where all the variables have declared types
-- (e.g. if you want to make MANY repeated Queries)
-- checkValid :: e:Env -> [ClosedPred e] -> IO [Bool]
checkValids :: Bool -> FilePath -> [(Symbol, Sort)] -> [Expr] -> IO [Bool]
checkValids u f xts ps
= do me <- makeContext u Z3 f
smtDecls me xts
forM ps $ \p ->
smtBracket me $
smtAssert me (PNot p) >> smtCheckUnsat me
-- debugFile :: FilePath
-- debugFile = "DEBUG.smt2"
--------------------------------------------------------------------------
-- | SMT IO --------------------------------------------------------------
--------------------------------------------------------------------------
--------------------------------------------------------------------------
command :: Context -> Command -> IO Response
--------------------------------------------------------------------------
command me !cmd = {-# SCC "command" #-} say cmd >> hear cmd
where
say = smtWrite me . smt2
hear CheckSat = smtRead me
hear (GetValue _) = smtRead me
hear (Interpolate fi _) = smtRead me >>= \case
Unsat -> smtPred fi me
Sat -> error "Not UNSAT. No interpolation needed. Why did you call me?"
e -> error $ show e
hear _ = return Ok
smtWrite :: Context -> T.Text -> IO ()
smtWrite me !s = smtWriteRaw me s
smtRes :: Context -> A.IResult T.Text Response -> IO Response
smtRes me res = case A.eitherResult res of
Left e -> error e
Right r -> do
maybe (return ()) (\h -> hPutStrLnNow h $ format "; SMT Says: {}" (Only $ show r)) (cLog me)
when (verbose me) $
TIO.putStrLn $ format "SMT Says: {}" (Only $ show r)
return r
smtParse me parserP = DT.traceShowId <$> smtReadRaw me >>= A.parseWith (smtReadRaw me) parserP >>= smtRes me
smtRead :: Context -> IO Response
smtRead me = {-# SCC "smtRead" #-} smtParse me responseP
smtPred :: SInfo a -> Context -> IO Response
smtPred fi me = {-# SCC "smtPred" #-} smtParse me (Interpolant <$> parseLisp' fi <$> predP)
predP = {-# SCC "predP" #-}
(Lisp <$> (A.char '(' *> A.sepBy' predP (A.skipMany1 A.space) <* A.char ')'))
<|> (Sym <$> symbolP)
data Lisp = Sym Symbol | Lisp [Lisp] deriving (Eq,Show)
type PorE = Either Expr Expr
binOpStrings :: [T.Text]
binOpStrings = [ "+", "-", "*", "/", "mod"]
strToOp :: T.Text -> Bop
strToOp "+" = Plus
strToOp "-" = Minus
strToOp "*" = Times
strToOp "/" = Div
strToOp "mod" = Mod
strToOp _ = error "Op not found"
binRelStrings :: [T.Text]
binRelStrings = [ ">", "<", "<=", ">="]
strToRel :: T.Text -> Brel
strToRel ">" = Gt
strToRel ">=" = Ge
strToRel "<" = Lt
strToRel "<=" = Le
-- Do I need Ne Une Ueq?
strToRel _ = error "Rel not found"
parseLisp' :: SInfo a -> Lisp -> Expr
parseLisp' _ = toPred
where toPred :: Lisp -> Expr
toPred x = case parseLisp x of
Left p -> p
Right e -> error $ "expected Pred, got Expr: " ++ show e
toExpr :: Lisp -> Expr
toExpr x = case parseLisp x of
Left p -> error $ "expected Expr, got Pred: " ++ show p
Right e -> e
parseLisp :: Lisp -> PorE
parseLisp (Sym s)
| symbolText s == "true" = Left PTrue
| symbolText s == "false" = Left PFalse
| otherwise = Right $ EVar s
parseLisp (Lisp (Sym s:xs))
| symbolText s == "and" = Left $ PAnd $ L.map toPred xs
| symbolText s == "or" = Left $ POr $ L.map toPred xs
parseLisp (Lisp [Sym s,x])
| symbolText s == "not" = Left $ PNot $ toPred x
| symbolText s == "-" = Right $ ENeg $ toExpr x
| otherwise = Right $ EVar s -- ELit (dummyLoc s) $ fromJust $ lookup s (lits fi)
parseLisp (Lisp [Sym s,x,y])
| symbolText s == "=>" = Left $ PImp (toPred x) (toPred y)
| symbolText s `elem` binOpStrings = Right $ EBin (strToOp $ symbolText s) (toExpr x) (toExpr y)
| symbolText s `elem` binRelStrings = Left $ PAtom (strToRel $ symbolText s) (toExpr x) (toExpr y)
| symbolText s == "=" = Left $ case (parseLisp x, parseLisp y) of
(Left p, Left q) -> PIff p q
(Right p, Right q) -> PAtom Eq p q
_ -> error $ "Can't compare `" ++ show x ++ "` with`" ++ show y ++ "`. Kind Error."
parseLisp (Lisp [Sym s, x, y, z])
| symbolText s == "ite" = Right $ EIte (toPred x) (toExpr y) (toExpr z)
parseLisp (Lisp (Sym s:xs)) = Right $ EApp (dummyLoc s) $ L.map toExpr xs
parseLisp x = error $ show x ++ "is Nonsense Lisp!"
-- PBexp? When do I know to read one of these in?
responseP = {-# SCC "responseP" #-} A.char '(' *> sexpP
<|> A.string "sat" *> return Sat
<|> A.string "unsat" *> return Unsat
<|> A.string "unknown" *> return Unknown
sexpP = {-# SCC "sexpP" #-} A.string "error" *> (Error <$> errorP)
<|> Values <$> valuesP
errorP = A.skipSpace *> A.char '"' *> A.takeWhile1 (/='"') <* A.string "\")"
valuesP = A.many1' pairP <* A.char ')'
pairP = {-# SCC "pairP" #-}
do A.skipSpace
A.char '('
!x <- symbolP
A.skipSpace
!v <- valueP
A.char ')'
return (x,v)
symbolP = {-# SCC "symbolP" #-} symbol <$> A.takeWhile1 (\x -> x /= ')' && not (isSpace x))
valueP = {-# SCC "valueP" #-} negativeP
<|> A.takeWhile1 (\c -> not (c == ')' || isSpace c))
negativeP
= do v <- A.char '(' *> A.takeWhile1 (/=')') <* A.char ')'
return $ "(" <> v <> ")"
-- {- pairs :: {v:[a] | (len v) mod 2 = 0} -> [(a,a)] -}
-- pairs :: [a] -> [(a,a)]
-- pairs !xs = case L.splitAt 2 xs of
-- ([],_) -> []
-- ([x,y], zs) -> (x,y) : pairs zs
smtWriteRaw :: Context -> T.Text -> IO ()
smtWriteRaw me !s = {-# SCC "smtWriteRaw" #-} do
hPutStrLnNow (cOut me) s
-- whenLoud $ TIO.appendFile debugFile (s <> "\n")
maybe (return ()) (`hPutStrLnNow` s) (cLog me)
smtReadRaw :: Context -> IO Raw
smtReadRaw me = {-# SCC "smtReadRaw" #-} TIO.hGetLine (cIn me)
hPutStrLnNow h !s = TIO.hPutStrLn h s >> hFlush h
--------------------------------------------------------------------------
-- | SMT Context ---------------------------------------------------------
--------------------------------------------------------------------------
--------------------------------------------------------------------------
makeContext :: Bool -> SMTSolver -> FilePath -> IO Context
--------------------------------------------------------------------------
makeContext u s f
= do me <- makeProcess s
pre <- smtPreamble u s me
createDirectoryIfMissing True $ takeDirectory smtFile
hLog <- openFile smtFile WriteMode
let me' = me { cLog = Just hLog }
mapM_ (smtWrite me') pre
return me'
where
smtFile = extFileName Smt2 f
makeContextNoLog :: Bool -> SMTSolver -> IO Context
makeContextNoLog u s
= do me <- makeProcess s
pre <- smtPreamble u s me
mapM_ (smtWrite me) pre
return me
makeProcess :: SMTSolver -> IO Context
makeProcess s
= do (hOut, hIn, _ ,pid) <- runInteractiveCommand $ smtCmd s
loud <- isLoud
return Ctx { pId = pid
, cIn = hIn
, cOut = hOut
, cLog = Nothing
, verbose = loud }
--------------------------------------------------------------------------
cleanupContext :: Context -> IO ExitCode
--------------------------------------------------------------------------
cleanupContext (Ctx {..})
= do code <- waitForProcess pId
hClose cIn
hClose cOut
maybe (return ()) hClose cLog
return code
{- "z3 -smt2 -in" -}
{- "z3 -smtc SOFT_TIMEOUT=1000 -in" -}
{- "z3 -smtc -in MBQI=false" -}
smtCmd Z3 = "z3 pp.single-line=true -smt2 -in"
smtCmd Mathsat = "mathsat -input=smt2"
smtCmd Cvc4 = "cvc4 --incremental -L smtlib2"
-- DON'T REMOVE THIS! z3 changed the names of options between 4.3.1 and 4.3.2...
smtPreamble u Z3 me
= do smtWrite me "(get-info :version)"
v:_ <- T.words . (!!1) . T.splitOn "\"" <$> smtReadRaw me
if T.splitOn "." v `versionGreater` ["4", "3", "2"]
then return $ z3_432_options ++ preamble u Z3
else return $ z3_options ++ preamble u Z3
smtPreamble u s _
= return $ preamble u s
versionGreater (x:xs) (y:ys)
| x > y = True
| x == y = versionGreater xs ys
| x < y = False
versionGreater _ [] = True
versionGreater [] _ = False
versionGreater _ _ = errorstar "Interface.versionGreater called with bad arguments"
-----------------------------------------------------------------------------
-- | SMT Commands -----------------------------------------------------------
-----------------------------------------------------------------------------
smtPush, smtPop :: Context -> IO ()
smtPush me = interact' me Push
smtPop me = interact' me Pop
smtDecls :: Context -> [(Symbol, Sort)] -> IO ()
smtDecls me xts = forM_ xts (\(x,t) -> smtDecl me x t)
smtDecl :: Context -> Symbol -> Sort -> IO ()
smtDecl me x t = interact' me (Declare x ins out)
where
(ins, out) = deconSort t
deconSort :: Sort -> ([Sort], Sort)
deconSort t = case functionSort t of
Just (_, ins, out) -> (ins, out)
Nothing -> ([] , t )
smtAssert :: Context -> Expr -> IO ()
smtAssert me p = interact' me (Assert Nothing p)
smtDistinct :: Context -> [Expr] -> IO ()
smtDistinct me az = interact' me (Distinct az)
smtCheckUnsat :: Context -> IO Bool
smtCheckUnsat me = respSat <$> command me CheckSat
smtBracket :: Context -> IO a -> IO a
smtBracket me a = do smtPush me
r <- a
smtPop me
return r
smtDoInterpolate :: Context -> SInfo a -> Expr -> IO Expr
smtDoInterpolate me fi p = respInterp <$> command me (Interpolate fi p)
{-
smtLoadEnv :: Context -> [(Symbol, SortedReft)] -> IO ()
smtLoadEnv me env = mapM_ smtDecl' $ L.map (second sr_sort) env
where smtDecl' = uncurry $ smtDecl me
-}
smtInterpolate :: Context -> SInfo () -> Expr -> IO Expr
smtInterpolate me fi p = respInterp <$> command me (Interpolate fi p)
respInterp (Interpolant p') = p'
respInterp r = die $ err dummySpan $ "crash: SMTLIB2 respInterp = " ++ show r
respSat Unsat = True
respSat Sat = False
respSat Unknown = False
respSat r = die $ err dummySpan $ "crash: SMTLIB2 respSat = " ++ show r
interact' me cmd = void $ command me cmd
-- DON'T REMOVE THIS! z3 changed the names of options between 4.3.1 and 4.3.2...
z3_432_options
= [ "(set-option :auto-config false)"
, "(set-option :model true)"
, "(set-option :model.partial false)"
, "(set-option :smt.mbqi false)" ]
z3_options
= [ "(set-option :auto-config false)"
, "(set-option :model true)"
, "(set-option :model-partial false)"
, "(set-option :mbqi false)" ]
| rolph-recto/liquid-fixpoint | src/Language/Fixpoint/Smt/Interface.hs | bsd-3-clause | 14,715 | 0 | 17 | 4,027 | 4,034 | 2,055 | 1,979 | 278 | 11 |
{-# LANGUAGE CPP, MagicHash #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Binary.Builder
-- Copyright : Lennart Kolmodin, Ross Paterson
-- License : BSD3-style (see LICENSE)
--
-- Maintainer : Lennart Kolmodin <[email protected]>
-- Stability : experimental
-- Portability : portable to Hugs and GHC
--
-- Efficient construction of lazy bytestrings.
--
-----------------------------------------------------------------------------
#if defined(__GLASGOW_HASKELL__) && !defined(__HADDOCK__)
#include "MachDeps.h"
#endif
module Data.Binary.Builder (
-- * The Builder type
Builder
, toLazyByteString
-- * Constructing Builders
, empty
, singleton
, append
, fromByteString -- :: S.ByteString -> Builder
, fromLazyByteString -- :: L.ByteString -> Builder
-- * Flushing the buffer state
, flush
-- * Derived Builders
-- ** Big-endian writes
, putWord16be -- :: Word16 -> Builder
, putWord32be -- :: Word32 -> Builder
, putWord64be -- :: Word64 -> Builder
-- ** Little-endian writes
, putWord16le -- :: Word16 -> Builder
, putWord32le -- :: Word32 -> Builder
, putWord64le -- :: Word64 -> Builder
-- ** Host-endian, unaligned writes
, putWordhost -- :: Word -> Builder
, putWord16host -- :: Word16 -> Builder
, putWord32host -- :: Word32 -> Builder
, putWord64host -- :: Word64 -> Builder
-- ** Unicode
, putCharUtf8
) where
import Data.Word
import Foreign
import qualified Data.ByteString as S
import qualified Data.ByteString.Lazy as L
#if defined(__GLASGOW_HASKELL__) && !defined(__HADDOCK__)
import GHC.Base
import GHC.Word (Word32(..),Word16(..),Word64(..))
#if WORD_SIZE_IN_BITS < 64 && __GLASGOW_HASKELL__ >= 608
import GHC.Word (uncheckedShiftRL64#)
#endif
#endif
import Data.Binary.Builder.Common
import Data.Binary.Builder.Internal
------------------------------------------------------------------------
-- | /O(1)./ A Builder taking a single byte, satisfying
--
-- * @'toLazyByteString' ('singleton' b) = 'L.singleton' b@
--
singleton :: Word8 -> Builder
singleton = writeN 1 . flip poke
{-# INLINE singleton #-}
------------------------------------------------------------------------
-- | /O(1)./ A Builder taking a 'S.ByteString', satisfying
--
-- * @'toLazyByteString' ('fromByteString' bs) = 'L.fromChunks' [bs]@
--
fromByteString :: S.ByteString -> Builder
fromByteString bs
| S.null bs = empty
| otherwise = flush `append` mapBuilder (bs :)
{-# INLINE fromByteString #-}
-- | /O(1)./ A Builder taking a lazy 'L.ByteString', satisfying
--
-- * @'toLazyByteString' ('fromLazyByteString' bs) = bs@
--
fromLazyByteString :: L.ByteString -> Builder
fromLazyByteString bss = flush `append` mapBuilder (L.toChunks bss ++)
{-# INLINE fromLazyByteString #-}
------------------------------------------------------------------------
------------------------------------------------------------------------
-- | /O(n)./ Extract a lazy 'L.ByteString' from a 'Builder'.
-- The construction work takes place if and when the relevant part of
-- the lazy 'L.ByteString' is demanded.
--
toLazyByteString :: Builder -> L.ByteString
toLazyByteString m = L.fromChunks $ unsafePerformIO $ do
newBuffer defaultSize >>= runBuilder (m `append` flush) (const (return []))
------------------------------------------------------------------------
-- | Map the resulting list of bytestrings.
mapBuilder :: ([S.ByteString] -> [S.ByteString]) -> Builder
mapBuilder f = Builder (fmap f .)
------------------------------------------------------------------------
--
-- We rely on the fromIntegral to do the right masking for us.
-- The inlining here is critical, and can be worth 4x performance
--
-- | Write a Word16 in big endian format
putWord16be :: Word16 -> Builder
putWord16be w = writeN 2 $ \p -> do
poke p (fromIntegral (shiftr_w16 w 8) :: Word8)
poke (p `plusPtr` 1) (fromIntegral (w) :: Word8)
{-# INLINE putWord16be #-}
-- | Write a Word16 in little endian format
putWord16le :: Word16 -> Builder
putWord16le w = writeN 2 $ \p -> do
poke p (fromIntegral (w) :: Word8)
poke (p `plusPtr` 1) (fromIntegral (shiftr_w16 w 8) :: Word8)
{-# INLINE putWord16le #-}
-- putWord16le w16 = writeN 2 (\p -> poke (castPtr p) w16)
-- | Write a Word32 in big endian format
putWord32be :: Word32 -> Builder
putWord32be w = writeN 4 $ \p -> do
poke p (fromIntegral (shiftr_w32 w 24) :: Word8)
poke (p `plusPtr` 1) (fromIntegral (shiftr_w32 w 16) :: Word8)
poke (p `plusPtr` 2) (fromIntegral (shiftr_w32 w 8) :: Word8)
poke (p `plusPtr` 3) (fromIntegral (w) :: Word8)
{-# INLINE putWord32be #-}
--
-- a data type to tag Put/Check. writes construct these which are then
-- inlined and flattened. matching Checks will be more robust with rules.
--
-- | Write a Word32 in little endian format
putWord32le :: Word32 -> Builder
putWord32le w = writeN 4 $ \p -> do
poke p (fromIntegral (w) :: Word8)
poke (p `plusPtr` 1) (fromIntegral (shiftr_w32 w 8) :: Word8)
poke (p `plusPtr` 2) (fromIntegral (shiftr_w32 w 16) :: Word8)
poke (p `plusPtr` 3) (fromIntegral (shiftr_w32 w 24) :: Word8)
{-# INLINE putWord32le #-}
-- on a little endian machine:
-- putWord32le w32 = writeN 4 (\p -> poke (castPtr p) w32)
-- | Write a Word64 in big endian format
putWord64be :: Word64 -> Builder
#if WORD_SIZE_IN_BITS < 64
--
-- To avoid expensive 64 bit shifts on 32 bit machines, we cast to
-- Word32, and write that
--
putWord64be w =
let a = fromIntegral (shiftr_w64 w 32) :: Word32
b = fromIntegral w :: Word32
in writeN 8 $ \p -> do
poke p (fromIntegral (shiftr_w32 a 24) :: Word8)
poke (p `plusPtr` 1) (fromIntegral (shiftr_w32 a 16) :: Word8)
poke (p `plusPtr` 2) (fromIntegral (shiftr_w32 a 8) :: Word8)
poke (p `plusPtr` 3) (fromIntegral (a) :: Word8)
poke (p `plusPtr` 4) (fromIntegral (shiftr_w32 b 24) :: Word8)
poke (p `plusPtr` 5) (fromIntegral (shiftr_w32 b 16) :: Word8)
poke (p `plusPtr` 6) (fromIntegral (shiftr_w32 b 8) :: Word8)
poke (p `plusPtr` 7) (fromIntegral (b) :: Word8)
#else
putWord64be w = writeN 8 $ \p -> do
poke p (fromIntegral (shiftr_w64 w 56) :: Word8)
poke (p `plusPtr` 1) (fromIntegral (shiftr_w64 w 48) :: Word8)
poke (p `plusPtr` 2) (fromIntegral (shiftr_w64 w 40) :: Word8)
poke (p `plusPtr` 3) (fromIntegral (shiftr_w64 w 32) :: Word8)
poke (p `plusPtr` 4) (fromIntegral (shiftr_w64 w 24) :: Word8)
poke (p `plusPtr` 5) (fromIntegral (shiftr_w64 w 16) :: Word8)
poke (p `plusPtr` 6) (fromIntegral (shiftr_w64 w 8) :: Word8)
poke (p `plusPtr` 7) (fromIntegral (w) :: Word8)
#endif
{-# INLINE putWord64be #-}
-- | Write a Word64 in little endian format
putWord64le :: Word64 -> Builder
#if WORD_SIZE_IN_BITS < 64
putWord64le w =
let b = fromIntegral (shiftr_w64 w 32) :: Word32
a = fromIntegral w :: Word32
in writeN 8 $ \p -> do
poke (p) (fromIntegral (a) :: Word8)
poke (p `plusPtr` 1) (fromIntegral (shiftr_w32 a 8) :: Word8)
poke (p `plusPtr` 2) (fromIntegral (shiftr_w32 a 16) :: Word8)
poke (p `plusPtr` 3) (fromIntegral (shiftr_w32 a 24) :: Word8)
poke (p `plusPtr` 4) (fromIntegral (b) :: Word8)
poke (p `plusPtr` 5) (fromIntegral (shiftr_w32 b 8) :: Word8)
poke (p `plusPtr` 6) (fromIntegral (shiftr_w32 b 16) :: Word8)
poke (p `plusPtr` 7) (fromIntegral (shiftr_w32 b 24) :: Word8)
#else
putWord64le w = writeN 8 $ \p -> do
poke p (fromIntegral (w) :: Word8)
poke (p `plusPtr` 1) (fromIntegral (shiftr_w64 w 8) :: Word8)
poke (p `plusPtr` 2) (fromIntegral (shiftr_w64 w 16) :: Word8)
poke (p `plusPtr` 3) (fromIntegral (shiftr_w64 w 24) :: Word8)
poke (p `plusPtr` 4) (fromIntegral (shiftr_w64 w 32) :: Word8)
poke (p `plusPtr` 5) (fromIntegral (shiftr_w64 w 40) :: Word8)
poke (p `plusPtr` 6) (fromIntegral (shiftr_w64 w 48) :: Word8)
poke (p `plusPtr` 7) (fromIntegral (shiftr_w64 w 56) :: Word8)
#endif
{-# INLINE putWord64le #-}
-- on a little endian machine:
-- putWord64le w64 = writeN 8 (\p -> poke (castPtr p) w64)
------------------------------------------------------------------------
-- Unaligned, word size ops
-- | /O(1)./ A Builder taking a single native machine word. The word is
-- written in host order, host endian form, for the machine you're on.
-- On a 64 bit machine the Word is an 8 byte value, on a 32 bit machine,
-- 4 bytes. Values written this way are not portable to
-- different endian or word sized machines, without conversion.
--
putWordhost :: Word -> Builder
putWordhost w = writeN (sizeOf (undefined :: Word)) (\p -> poke (castPtr p) w)
{-# INLINE putWordhost #-}
-- | Write a Word16 in native host order and host endianness.
-- 2 bytes will be written, unaligned.
putWord16host :: Word16 -> Builder
putWord16host w16 = writeN (sizeOf (undefined :: Word16)) (\p -> poke (castPtr p) w16)
{-# INLINE putWord16host #-}
-- | Write a Word32 in native host order and host endianness.
-- 4 bytes will be written, unaligned.
putWord32host :: Word32 -> Builder
putWord32host w32 = writeN (sizeOf (undefined :: Word32)) (\p -> poke (castPtr p) w32)
{-# INLINE putWord32host #-}
-- | Write a Word64 in native host order.
-- On a 32 bit machine we write two host order Word32s, in big endian form.
-- 8 bytes will be written, unaligned.
putWord64host :: Word64 -> Builder
putWord64host w = writeN (sizeOf (undefined :: Word64)) (\p -> poke (castPtr p) w)
{-# INLINE putWord64host #-}
------------------------------------------------------------------------
-- Unicode
-- Code lifted from the text package by Bryan O'Sullivan.
-- | Write a character using UTF-8 encoding.
putCharUtf8 :: Char -> Builder
putCharUtf8 x = writeAtMost 4 $ \ p -> case undefined of
_ | n <= 0x7F -> poke p c >> return 1
| n <= 0x07FF -> do
poke p a2
poke (p `plusPtr` 1) b2
return 2
| n <= 0xFFFF -> do
poke p a3
poke (p `plusPtr` 1) b3
poke (p `plusPtr` 2) c3
return 3
| otherwise -> do
poke p a4
poke (p `plusPtr` 1) b4
poke (p `plusPtr` 2) c4
poke (p `plusPtr` 3) d4
return 4
where
n = ord x
c = fromIntegral n
(a2,b2) = ord2 x
(a3,b3,c3) = ord3 x
(a4,b4,c4,d4) = ord4 x
ord2 :: Char -> (Word8,Word8)
ord2 c = (x1,x2)
where
n = ord c
x1 = fromIntegral $ (n `shiftR` 6) + 0xC0
x2 = fromIntegral $ (n .&. 0x3F) + 0x80
ord3 :: Char -> (Word8,Word8,Word8)
ord3 c = (x1,x2,x3)
where
n = ord c
x1 = fromIntegral $ (n `shiftR` 12) + 0xE0
x2 = fromIntegral $ ((n `shiftR` 6) .&. 0x3F) + 0x80
x3 = fromIntegral $ (n .&. 0x3F) + 0x80
ord4 :: Char -> (Word8,Word8,Word8,Word8)
ord4 c = (x1,x2,x3,x4)
where
n = ord c
x1 = fromIntegral $ (n `shiftR` 18) + 0xF0
x2 = fromIntegral $ ((n `shiftR` 12) .&. 0x3F) + 0x80
x3 = fromIntegral $ ((n `shiftR` 6) .&. 0x3F) + 0x80
x4 = fromIntegral $ (n .&. 0x3F) + 0x80
------------------------------------------------------------------------
-- Unchecked shifts
{-# INLINE shiftr_w16 #-}
shiftr_w16 :: Word16 -> Int -> Word16
{-# INLINE shiftr_w32 #-}
shiftr_w32 :: Word32 -> Int -> Word32
{-# INLINE shiftr_w64 #-}
shiftr_w64 :: Word64 -> Int -> Word64
#if defined(__GLASGOW_HASKELL__) && !defined(__HADDOCK__)
shiftr_w16 (W16# w) (I# i) = W16# (w `uncheckedShiftRL#` i)
shiftr_w32 (W32# w) (I# i) = W32# (w `uncheckedShiftRL#` i)
#if WORD_SIZE_IN_BITS < 64
shiftr_w64 (W64# w) (I# i) = W64# (w `uncheckedShiftRL64#` i)
#if __GLASGOW_HASKELL__ <= 606
-- Exported by GHC.Word in GHC 6.8 and higher
foreign import ccall unsafe "stg_uncheckedShiftRL64"
uncheckedShiftRL64# :: Word64# -> Int# -> Word64#
#endif
#else
shiftr_w64 (W64# w) (I# i) = W64# (w `uncheckedShiftRL#` i)
#endif
#else
shiftr_w16 = shiftR
shiftr_w32 = shiftR
shiftr_w64 = shiftR
#endif
| beni55/binary | src/Data/Binary/Builder.hs | bsd-3-clause | 12,396 | 0 | 15 | 2,850 | 2,653 | 1,488 | 1,165 | 157 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.