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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
{-
H-99 Problems
Copyright 2015 (c) Adrian Nwankwo (Arcaed0x)
Problem : 11
Description : Modified run-length encoding.
License : MIT (See LICENSE file)
-}
-- | Data type from example.
data ListElemSize a = Multiple Int a | Single a
deriving (Show)
classifyAlike :: (Eq a) => [a] -> [ListElemSize a]
classifyAlike l = [sizeCheck x | x <- groupedAlikeList]
where groupedAlikeList = sameCongregate l
sizeCheck x = if (length x) > 1
then Multiple (length x) (head x)
else Single (head x)
sameCongregate :: (Eq a) => [a] -> [[a]]
sameCongregate [] = []
sameCongregate lst = firstAlikeElems : sameCongregate restOfList
where restOfList = drop (length firstAlikeElems) lst
firstAlikeElems = takeAlikeElems lst
takeAlikeElems [x] = [x]
takeAlikeElems (x:xs) = if x == (head xs)
then x : takeAlikeElems xs
else [x]
| Arcaed0x/H-99-Solutions | src/prob11.hs | mit | 1,022 | 17 | 11 | 348 | 282 | 146 | 136 | 17 | 3 |
{-# LANGUAGE BangPatterns #-}
module Main where
import Control.Concurrent hiding (Chan)
import Control.Concurrent.GoChan
import Control.Monad
import Criterion.Main
import System.Random
for xs f = map f xs
main :: IO ()
main =
defaultMain $
(for
[0, 2, 5]
(\size ->
bgroup
("buffer size " ++ show size)
[ bench "create" $ whnfIO (chanMake size :: IO (Chan Int))
, bench "send & recv" $ whnfIO (sendRecv size)
, bench "select send & recv with 1 case" $
whnfIO (select1 size)
, bench "select send & recv with 2 case" $
whnfIO (select2 size)
, bench "select send & recv with 3 case" $
whnfIO (select3 size)])) ++
[bench "no-threads send & recv" $ whnfIO sendRecvBuf]
{-# INLINE iters #-}
iters = 15
sendRecv :: Int -> IO ()
sendRecv !size = do
c <- chanMake size
forkIO $
do sendN c 0
chanClose c
drain c
where
drain !ch = do
mn <- chanRecv ch
case mn of
Msg n -> do
drain ch
_ -> return ()
sendN !ch !n = do
chanSend ch n
when (n < iters) (sendN ch (n + 1))
sendRecvBuf :: IO ()
sendRecvBuf = do
c <- chanMake 1
sendRecN c
where
sendRecN !ch = do
chanSend ch 42
void $ chanRecv ch
select1
:: Int -> IO ()
select1 !size = do
c1 <- chanMake size
forkIO $ ping c1 0
pong c1 0
where
ping !c1 !n = do
if (n < iters)
then do
chanSelect [Send c1 n (return ())] Nothing
ping c1 (n + 1)
else return ()
pong !c1 !n = do
if (n < iters)
then do
chanSelect [Recv c1 (const (return ()))] Nothing
pong c1 (n + 1)
else return ()
select2 :: Int -> IO ()
select2 !size = do
--lock <- newEmptyMVar
c1 <- chanMake size
c2 <- chanMake size
forkIO $ ping c1 c2 0
pong c1 c2 0
where
ping :: Chan Int -> Chan Int -> Int -> IO ()
ping !c1 !c2 !n = do
if (n < iters)
then do
chanSelect [Send c1 n (return ()), Send c2 n (return ())] Nothing
ping c1 c2 (n + 1)
else return ()
pong :: Chan Int -> Chan Int -> Int -> IO ()
pong !c1 !c2 !n = do
if (n < iters)
then do
chanSelect
[Recv c1 (const (return ())), Recv c2 (const (return ()))]
Nothing
pong c1 c2 (n + 1)
else return ()
select3 :: Int -> IO ()
select3 !size = do
--lock <- newEmptyMVar
c1 <- chanMake size
c2 <- chanMake size
c3 <- chanMake size
forkIO $ ping c1 c2 c3 0
pong c1 c2 c3 0
where
ping !c1 !c2 !c3 !n = do
if (n < iters)
then do
chanSelect
[ Send c1 n (return ())
, Send c2 n (return ())
, Send c3 n (return ())]
Nothing
ping c1 c2 c3 (n + 1)
else return ()
pong !c1 !c2 !c3 !n = do
if (n < iters)
then do
chanSelect
[ Recv c1 (const (return ()))
, Recv c2 (const (return ()))
, Recv c3 (const (return ()))]
Nothing
pong c1 c2 c3 (n + 1)
else return ()
| cstrahan/gochan | bench/Main.hs | mit | 3,612 | 0 | 19 | 1,651 | 1,348 | 635 | 713 | 117 | 3 |
{-# LANGUAGE OverloadedStrings #-}
module Smutt.HTTP.Server.Request.Content.Raw.Chunked where
import Data.IORef
import Control.Monad.Except
import Control.Concurrent.MVar
import Data.ByteString.Lazy (ByteString)
import qualified Data.ByteString.Lazy as BL
import qualified Data.ByteString.Lazy.Char8 as BLC
import Network.BufferedSocket (BufferedSocket)
import qualified Network.BufferedSocket as BS
import Smutt.HTTP.Server.Request (Request, ReadState)
import qualified Smutt.HTTP.Server.Request as Req
import Data.Char
import qualified Smutt.Util.Hex as Hex
import Smutt.HTTP.Server.Request.Content.Error
import qualified Smutt.HTTP.Header.Reader as Header
import Smutt.HTTP.Header (Header)
import Smutt.Util.ByteString
import Data.Monoid
import qualified Data.HashMap.Strict as HS
{-
All chunk headers should be read as soon as a read notices that there are no more bytes left in the current chunk.
-}
-- | Reads part of the request
readPart :: BufferedSocket -> MVar ReadState -> Int -> ExceptT ContentError IO (Int, ByteString)
readPart bSock rsMVar readLength = do
readState <- liftIO $ takeMVar rsMVar
let currentChunkSize = Req.chunkBytesLeft readState
(bytesRead, message, readState) <- readPartLoop bSock readState readLength
liftIO $ putMVar rsMVar readState
return (bytesRead, message)
readPartLoop :: BufferedSocket -> ReadState -> Int -> ExceptT ContentError IO (Int, ByteString, ReadState)
readPartLoop bSock readState readLength
| readLength == 0 = return (0, "", readState)
| readLength < bytesLeft = readPartOfChunk bSock readState readLength >>= \ (str,rs) -> return (readLength, str, rs)
| otherwise = do
(message, firstReadState) <- readChunk bSock readState
(restLen, nextMessage, secondReadState) <- readPartLoop bSock firstReadState (readLength - bytesLeft)
return (bytesLeft + restLen, message <> nextMessage, secondReadState)
where
bytesLeft = Req.chunkBytesLeft readState
readPartOfChunk :: BufferedSocket -> ReadState -> Int -> ExceptT ContentError IO (ByteString, ReadState)
readPartOfChunk bSock readState readLength = do
message <- liftIO $ BS.readString bSock readLength
return (message, readState{Req.chunkBytesLeft = Req.chunkBytesLeft readState - readLength})
-- | Reads all data available in the request
readAll :: BufferedSocket -> MVar ReadState -> ExceptT ContentError IO ByteString
readAll bSock rsMVar = do
readState <- liftIO $ takeMVar rsMVar
when (Req.chunkedEOF readState) $ liftIO (putMVar rsMVar readState) >> throwError EOF
(message, newReadState) <- readAllLoop bSock readState `catchError` (\e -> liftIO (putMVar rsMVar readState) >> throwError e)
liftIO $ putMVar rsMVar newReadState
return message
-- Reads all bytes until EOF is reached
readAllLoop :: BufferedSocket -> ReadState -> ExceptT ContentError IO (ByteString, ReadState)
readAllLoop bSock readState
| Req.chunkedEOF readState = return ("", readState)
| otherwise = do
(message, firstReadState) <- readChunk bSock readState
(nextMessage, secondReadState) <- readAllLoop bSock firstReadState
return (message <> nextMessage, secondReadState)
-- | Reads an entire chunk from start to end.
readChunk :: BufferedSocket -> ReadState -> ExceptT ContentError IO (ByteString, ReadState)
readChunk bSock readState = do
chunkMessage <- liftIO $ BS.readString bSock chunkBytesLeft
nextChunkSize <- readChunkLength bSock 1024
maybeTrailer <- if nextChunkSize == 0
then Just <$> readTrailer bSock readState
else return $ Nothing
let newReadState = readState{
Req.chunkedTotalRead = Req.chunkedTotalRead readState + chunkBytesLeft ,
Req.chunkBytesLeft = nextChunkSize,
Req.chunkedEOF = nextChunkSize == 0,
Req.trailer = maybeTrailer
}
return (chunkMessage, newReadState)
where
chunkBytesLeft = Req.chunkBytesLeft readState
-- May not actually read the header of the chunked message if there's bytes left in the current mssage
readChunkedHead :: BufferedSocket -> ReadState -> ExceptT ContentError IO ReadState
readChunkedHead bSock readState
| Req.chunkedEOF readState = throwError EOF
| chunkBytesLeft > 0 = return readState
| otherwise = do
chunkSize <- readChunkLength bSock 512
if chunkSize == 0
then do
trailer <- readTrailer bSock readState
return readState{Req.chunkBytesLeft = 0, Req.trailer = Just trailer, Req.chunkedEOF = True}
else return readState{Req.chunkBytesLeft = chunkSize}
where
chunkBytesLeft = Req.chunkBytesLeft readState
type ChunkSizeRowMaxLength = Int
-- | Reads the length of a chunk. Limits the length of
readChunkLength :: BufferedSocket -> ChunkSizeRowMaxLength -> ExceptT ContentError IO Int
readChunkLength bSock rowMaxSize = do
maybeLengthLineStr <- liftIO $ BS.readToSequenceLimited bSock crlf rowMaxSize
case maybeLengthLineStr of
Nothing -> throwError ChunkSizeStingTooLarge
Just lengthLineStr -> let
lengthStr = BLC.takeWhile (/=';') $ BLC.dropWhile isSpace lengthLineStr
maybeLength = Hex.toIntegral lengthStr
in case maybeLength of
Nothing -> throwError InvalidEncoding
Just chunkLength -> return chunkLength
-- Note to self the temp limit needs to be user decided
readTrailer :: BufferedSocket -> ReadState -> ExceptT ContentError IO Header
readTrailer bSock readState = do
header <- liftIO $ runExceptT $ Header.read tempLimit tempLimit bSock
case header of
Left _ -> throwError $ CustomError "Chunked trailer error"
Right hdr -> return hdr
where
tempLimit = 1024
nonChunkedBodyErrorMsg :: String
nonChunkedBodyErrorMsg = "Tried to read chunked data from non chunked request"
| black0range/Smutt | src/Smutt/HTTP/Server/Request/Content/Raw/Chunked.hs | mit | 5,824 | 2 | 17 | 1,102 | 1,461 | 760 | 701 | 101 | 3 |
module Grin.Show(
prettyFun,
prettyExp,
printGrin,
hPrintGrin,
graphGrin,
render
) where
import Char
import Control.Monad.Writer(tell,when,forM_,execWriter)
import Data.Maybe
import IO
import qualified Data.Map as Map
import qualified Data.Set as Set
import C.Prims
import Data.Graph.Inductive.Graph(mkGraph)
import Data.Graph.Inductive.Tree
import Doc.DocLike
import Doc.PPrint
import Doc.Pretty
import Grin.Grin
import Grin.Noodle
import Grin.Val
import Name.VConsts
import Options
import StringTable.Atom
import Support.CanType
import Support.FreeVars
import Util.Graphviz
import qualified Cmm.Op as Op
instance DocLike d => PPrint d Val where
pprintAssoc _ _ v = prettyVal v
instance PPrint Doc Exp where
pprint v = prettyExp empty v
pVar [] = empty
pVar v = prettyVals v <+> operator "<- "
pVar' v = prettyVals v <+> operator "<- "
prettyVals [] = prettyVal Unit
prettyVals [x] = prettyVal x
prettyVals xs = tupled (map prettyVal xs)
operator = text
keyword = text
tag x = text x
func = text
prim = text
isComplex (_ :>>= _) = True
isComplex _ = False
isOneLine (_ :>>= _) = False
isOneLine Case {} = False
isOneLine Let {} = False
isOneLine MkCont {} = False
isOneLine _ = True
{-# NOINLINE prettyExp #-}
prettyExp vl (e1 :>>= v :-> e2) | isComplex e1 = align $ ((pVar' v) <> (prettyExp empty e1)) <$> prettyExp vl e2
prettyExp vl (e1 :>>= v :-> e2) = align (prettyExp (pVar v) e1 <$> prettyExp vl e2)
prettyExp vl (Return []) = vl <> keyword "return" <+> text "()"
prettyExp vl (Return [v]) = vl <> keyword "return" <+> prettyVal v
prettyExp vl (Return vs) = vl <> keyword "return" <+> tupled (map prettyVal vs)
--prettyExp vl (Store v@Var {}) | getType v == tyDNode = vl <> keyword "demote" <+> prettyVal v
--prettyExp vl (Store v) = vl <> keyword "store" <+> prettyVal v
prettyExp vl (Error "" _) = vl <> prim "exitFailure"
prettyExp vl (Error s _) = vl <> keyword "error" <+> tshow s
prettyExp vl (BaseOp Eval [v]) = vl <> keyword "eval" <+> prettyVal v
prettyExp vl (BaseOp Coerce {} [v]) = vl <> keyword "coerce" <+> prettyVal v
prettyExp vl (BaseOp Apply {} vs) = vl <> keyword "apply" <+> hsep (map prettyVal vs)
prettyExp vl (App a vs _) = vl <> func (fromAtom a) <+> hsep (map prettyVal vs)
prettyExp vl Prim { expPrimitive = (Op (Op.BinOp bo _ _) _), expArgs = [x,y] } | Just (op,_) <- Op.binopInfix bo = vl <> prettyVal x <+> operator op <+> prettyVal y
prettyExp vl Prim { expPrimitive = (Op (Op.BinOp bo _ _) _), expArgs = [x,y] } = vl <> prettyVal x <+> char '`' <> tshow bo <> char '`' <+> prettyVal y
prettyExp vl Prim { expPrimitive = (Peek t), expArgs = [v] } = vl <> prim (show t) <> char '[' <> prettyVal v <> char ']'
prettyExp vl Prim { expPrimitive = ap, expArgs = vs } = vl <> prim (pprint ap) <+> hsep (map prettyVal vs)
prettyExp vl (GcRoots vs b) = vl <> keyword "withRoots" <> tupled (map prettyVal vs) <$> indent 2 (prettyExp empty b)
prettyExp vl (BaseOp Overwrite [x,y]) = vl <> keyword "overwrite" <+> prettyVal x <+> prettyVal y
prettyExp vl (BaseOp Redirect [x,y]) = vl <> keyword "redirect" <+> prettyVal x <+> prettyVal y
prettyExp vl (BaseOp PokeVal [x,y]) = vl <> keyword "pokeVal" <+> prettyVal x <+> prettyVal y
prettyExp vl (BaseOp PeekVal [x]) = vl <> keyword "peekVal" <+> prettyVal x
prettyExp vl (BaseOp Promote [x]) = vl <> keyword "promote" <+> prettyVal x
prettyExp vl (BaseOp NewRegister xs) = vl <> keyword "register" <+> tupled (map prettyVal xs)
prettyExp vl (BaseOp WriteRegister [r,x]) = vl <> prettyVal r <+> keyword ":=" <+> prettyVal x
prettyExp vl (BaseOp ReadRegister [r]) = vl <> keyword "*" <> prettyVal r
prettyExp vl (BaseOp GcPush xs) = vl <> keyword "gcPush" <+> tupled (map prettyVal xs)
prettyExp vl (BaseOp GcTouch xs) = vl <> keyword "gcTouch" <+> tupled (map prettyVal xs)
prettyExp vl (BaseOp Demote [x]) = vl <> keyword "demote" <+> prettyVal x
prettyExp vl (BaseOp (StoreNode b) [x]) = vl <> keyword ((if b then "d" else "i") ++ "store") <+> prettyVal x
prettyExp vl (BaseOp (StoreNode b) [x,y]) = vl <> keyword ((if b then "d" else "i") ++ "store") <+> prettyVal x <> char '@' <> prettyVal y
prettyExp vl (Case v vs) = vl <> keyword "case" <+> prettyVal v <+> keyword "of" <$> indent 2 (vsep (map f vs)) where
f (~[v] :-> e) | isOneLine e = prettyVal v <+> operator "->" <+> prettyExp empty e
f (~[v] :-> e) = prettyVal v <+> operator "->" <+> keyword "do" <$> indent 2 (prettyExp empty e)
prettyExp vl NewRegion { expLam = (r :-> body)} = vl <> keyword "region" <+> text "\\" <> prettyVals r <+> text "-> do" <$> indent 2 (prettyExp empty body)
--prettyExp vl MkCont { expCont = (r :-> body) } = vl <> keyword "continuation" <+> text "\\" <> prettyVal r <+> text "-> do" <$> indent 2 (prettyExp empty body)
prettyExp vl Let { expDefs = defs, expBody = body, .. } = vl <> keyword (if expIsNormal then "let" else "let*") <$> indent 4 (vsep $ map f defs) <$> text " in" <$> indent 2 (prettyExp empty body) where
f FuncDef { funcDefName = name, funcDefBody = as :-> body } = func (show name) <+> hsep (map prettyVal as) <+> operator "=" <+> keyword "do" <$> indent 2 (prettyExp empty body)
prettyExp vl Alloc { expValue = val, expCount = Lit n _, expRegion = r }| n == 1 = vl <> keyword "alloc" <+> prettyVal val <+> text "at" <+> prettyVal r
prettyExp vl Alloc { expValue = val, expCount = count, expRegion = r } = vl <> keyword "alloc" <+> prettyVal val <> text "[" <> prettyVal count <> text "]" <+> text "at" <+> prettyVal r
prettyExp vl Call { expValue = Item t (TyCall fun _ _), expArgs = vs, expJump = jump } | fun `elem` [Function,LocalFunction] = vl <> f jump <+> func (fromAtom t) <+> hsep (map prettyVal vs) where
f True = text "jump to"
f False = text "call"
prettyExp vl Call { expValue = Var v (TyCall fun _ _), expArgs = vs, expJump = jump} = vl <> f jump fun <+> pprint v <+> hsep (map prettyVal vs) where
f False Continuation = text "cut to"
f False Function = text "call"
f True Function = text "jump to"
f False Closure = text "enter"
f True Closure = text "jump into"
f x y = tshow (x,y)
prettyExp vl Call { expValue = ValPrim ap [] (TyCall Primitive' _ _), expArgs = vs } = vl <> prim (tshow ap) <+> hsep (map prettyVal vs)
prettyExp vl y = vl <> tshow y
{-# NOINLINE prettyVal #-}
prettyVal :: DocLike d => Val -> d
prettyVal s | Just [] <- valToList s = text "[]"
prettyVal s | Just st <- fromVal s = text $ show (st::String)
prettyVal s | Just vs <- valToList s = list $ map prettyVal vs
prettyVal (NodeC ch [t]) | ch == toAtom "CJhc.Prim.Char" = parens $ text "Char" <+> sc t where
sc (Lit n t) | t == tCharzh = tshow (chr $ fromIntegral n)
sc v = prettyVal v
prettyVal (NodeC t []) = parens $ tag (fromAtom t)
prettyVal (NodeC t vs) = parens $ tag (fromAtom t) <+> hsep (map prettyVal vs)
prettyVal (Index p off) = prettyVal p <> char '[' <> prettyVal off <> char ']'
prettyVal v@Var {} = tshow v
prettyVal (Lit i _) = tshow i
prettyVal (Const v) = char '&' <> prettyVal v
prettyVal (ValUnknown ty) = text "?::" <> tshow ty
prettyVal Unit = text "()"
prettyVal (Item a ty) = tshow a <> text "::" <> tshow ty
prettyVal (ValPrim aprim args ty) = f aprim args where
f aprim [] = pprint aprim <> text "::" <> tshow ty
f ((Op (Op.BinOp bo _ _) _)) [x,y] | Just (op,prec) <- Op.binopInfix bo = parens (pprintPrec prec x <+> text op <+> pprintPrec prec y)
f ((Op (Op.BinOp bo _ _) _)) [x,y] = parens $ pprintPrec 1 x <+> char '`' <> tshow bo <> char '`' <+> pprintPrec 1 y
f aprim xs = pprint aprim <> tupled (map prettyVal xs) <> text "::" <> tshow ty
instance DocLike d => PPrint d Var where
pprint (V i) = text $ 'v':show i
--pv (V 0) = char '_'
--pv (V i) = char 'v' <> tshow i
prettyFun :: (Atom,Lam) -> Doc
prettyFun (n,(as :-> e)) = func (fromAtom n) <+> hsep (map prettyVal as) <+> operator "=" <+> keyword "do" <$> indent 2 (prettyExp empty e)
render :: Doc -> String
render doc = displayS (renderPretty 0.95 (optColumns options) doc) ""
printGrin :: Grin -> IO ()
printGrin grin = hPrintGrin stderr grin
hPrintGrin :: Handle -> Grin -> IO ()
hPrintGrin handle grin@Grin { grinCafs = cafs } = do
when (not $ null cafs) $ do
hPutStrLn handle "-- Cafs"
mapM_ (hPutStrLn handle) $ map (\(x,y) -> show x ++ " := " ++ render (prettyVal y)) cafs
hPutStrLn handle "-- Functions"
forM_ (grinFuncs grin) $ \ f@(n,l :-> e) -> do
hPutStrLn handle . render $ func (fromAtom n) <+> operator "::" <+> tupled (map (tshow . getType) l) <+> operator "->" <+> tupled (map tshow (getType e))
hPutStrLn handle (render $ prettyFun f)
hPutStrLn handle ""
{-# NOINLINE graphGrin #-}
graphGrin :: Grin -> String
graphGrin grin = graphviz' gr [] fnode fedge where
nodes = zip [0..] (grinFuncs grin)
nodeMap = Map.fromList [ (y,x) | (x,(y,_)) <- nodes]
gr :: Gr (Atom,Lam) CallType
gr = mkGraph nodes [ (n,n2,tc) | (n,(_,_ :-> l)) <- nodes, (tc,fv) <- Set.toList (freeVars l), n2 <- maybeToList $ Map.lookup fv nodeMap ]
fnode :: (Atom,Lam) -> [(String,String)]
fnode (x,_ :-> e) = [("label",show x)]
++ (if hasError e then [("color","red")] else [])
++ (if x `elem` grinEntryPointNames grin then [("shape","box")] else [])
fedge :: CallType -> [(String,String)]
fedge TailCall = []
fedge StandardCall = [("style","dotted")]
hasError x = isNothing (hasError' x)
hasError' Error {} = Nothing
hasError' e = mapExpExp hasError' e
data CallType = TailCall | StandardCall
deriving(Ord,Show,Eq)
instance FreeVars Exp (Set.Set (CallType,Atom)) where
freeVars (a :>>= _ :-> b) = freeVars b `Set.union` Set.map (\ (_ :: CallType,y) -> (StandardCall, y)) (freeVars a)
freeVars (App a _ _) = Set.singleton (TailCall,a)
freeVars e = execWriter $ mapExpExp (\e -> tell (freeVars e) >> return e) e
| m-alvarez/jhc | src/Grin/Show.hs | mit | 9,839 | 0 | 18 | 2,050 | 4,517 | 2,257 | 2,260 | -1 | -1 |
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances, RecordWildCards #-}
module Language.PiCalc.Pretty(
-- * Pretty printing
Pretty
, pretty
, prettyProg
, prettyTerm
, prettyShort
-- * Program pretty printing options
, PrettyProgOpts(..)
, parseableProgOpts
, defProgOpts
-- * Term pretty printing options
, PrettyTermOpts(..)
, baseTermOpts
, parseableTermOpts
, defTermOpts
, unicodeStyle
, asciiStyle
, milnerStyle
, hoareStyle
-- ** Non parseable outputs
-- These options generate output which cannot parsed back by the parsers
-- defined in "Language.PiCalc.Parser"
, cspStyle
, ccsStyle
, colorHoareStyle
-- * Re-exports from "Text.PrettyPrint"
, render
, renderStyle
, Style(..)
, Mode(..)
, style
, nest
) where
import Text.PrettyPrint
import Language.PiCalc.Syntax.AST
import Language.PiCalc.Syntax.Term
import Language.PiCalc.Syntax.StdNF
import Language.PiCalc.Semantics.Substitutions
import Language.PiCalc.Semantics.Process
import qualified Data.MultiSet as MSet
import Data.Set (Set)
import qualified Data.Set as Set
import qualified Data.Map as Map
import Data.Char (isDigit)
angles p = char '<' <> p <> char '>'
-- angles p = char '⟨' <> p <> char '⟩' -- unicode angles are cool but look too similar to ()
dot = char '.'
-- | The function @pretty@ should return a @Doc@ which, when rendered, should be
-- parsed successfully by the parsers defined in "Language.PiCalc.Parser".
class Pretty a where
pretty :: a -> Doc
instance Pretty String where
pretty = text
instance Pretty Int where
pretty = int
instance Pretty PiName where
pretty PiName{static=name, unique=i,isGlobal=global}
| global = text name
| i < 0 = text $ attach name $ (show $ negate i)++"'"
| otherwise = text $ attach name $ show i
where
attach "" n = "unk" ++ n -- this should actually never happen...
attach name n
| isDigit $ last name = name ++ '_':n
| otherwise = name ++ n
instance Pretty Doc where
pretty = id
instance Pretty n => Pretty (PiAST n) where
pretty = prettyTerm parseableTermOpts
-- pretty ps | isZero ps = zeroSym
-- pretty (Parall ps) = parens $ sep $ punctOp parallSym $ map pretty $ MSet.elems ps
-- pretty (Alt alts)
-- | MSet.size alts == 1 = prefix $ head $ MSet.elems alts
-- | otherwise = parens $ sep $ punctOp sumSym $ map prefix $ MSet.elems alts
-- pretty (New names proc) = char 'ν' <> parens1 (Set.elems names) <> char '.' <> pretty proc
-- pretty (PiCall pvar args) = pretty pvar <> argList args
-- pretty (Bang proc) = bangSym <> pretty proc
instance (Pretty n) => Pretty (PiPrefix n) where
pretty (In x ns) = (pretty x) <> text "?" <> par1 comma parens (map pretty ns)
-- pretty (In x ns) = (pretty x) <> parens (nameList ns)
pretty (Out x ns) = (pretty x) <> text "!" <> par1 comma parens (map pretty ns)
-- pretty (Out x ns) = (pretty x) <> angles (nameList ns)
pretty Tau = text "τ"
instance (Pretty n, Ord n) => Pretty (PiProgAST n) where
pretty = prettyProg parseableProgOpts
instance Pretty NameSubst where
pretty σ = braces (sep $ punctuate comma $ map prettyassoc $ Map.toList σ)
where
prettyassoc (x,y) = pretty x <+> text "↦" <+> pretty y
instance Pretty StdNFTerm where
pretty = pretty.stdToTerm
instance Pretty PiAction where
pretty TauAction = text "τ"
pretty (SyncOn x) = text "Synch on" <+> pretty x
pretty (Unfolding t) = text "Unfolding def" <+> pretty t
pretty InitState = text "Initial state"
instance Pretty StdFactor where
pretty x = pretty $ new (Set.elems $ restrNames x) (seqTerm x)
instance Pretty p => Pretty (Set p) where
pretty x = braces $ sep $ punctuate comma $ map pretty $ Set.elems x
instance Pretty () where
pretty () = text "•"
data PrettyProgOpts = POpt {
termOpts :: PrettyTermOpts
, defSym :: Doc
, defList :: [Doc] -> Doc
, wrapProg :: Doc -> Doc
, wrapDef :: Doc -> Doc
}
parseableProgOpts = POpt {
termOpts = parseableTermOpts
, defSym = text ":="
, defList = listing
, wrapProg = id
, wrapDef = id
}
defProgOpts = parseableProgOpts
listing = foldr (\x d->(x $+$ d)) empty
data PrettyTermOpts = TOpt {
maxLvl :: Maybe Int -- ^ stop at a certain nesting level
, ellipsis :: Doc -- ^ displayed when omitting parts
, explicitZeros :: Bool -- ^ whether to omit zeros when unambiguous
, wrapTerm :: Doc -> Doc -- ^ used to print something before and after
, zeroSym :: Doc
, parallSym :: Doc
, sumSym :: Doc
, bangSym :: Doc
, prefixSym :: Doc
, argList :: [Doc] -> Doc
, nameList :: (Doc -> Doc) -> [Doc] -> Doc
, tauSym :: Doc
, inpSyn :: Doc -> [Doc] -> Doc
, outSyn :: Doc -> [Doc] -> Doc
, restrSyn :: [Doc] -> Doc -> Doc
, group :: Doc -> Doc
}
baseTermOpts = TOpt {
maxLvl = Nothing
, explicitZeros = False
, wrapTerm = id
--
, nameList = par1 comma
, zeroSym = text "0"
, sumSym = char '+'
, bangSym = char '*'
, prefixSym = dot
, argList = par0 comma brackets
, group = parens
--
, ellipsis = text "..."
, parallSym = char '|'
, restrSyn = (\ns p -> text "new" <+> par1 comma parens ns <> dot <> p)
, tauSym = text "tau"
--
, inpSyn = (\n ns -> n <> char '?' <> par1 comma parens ns)
, outSyn = (\n ns -> n <> char '!' <> par1 comma parens ns)
}
parseableTermOpts = hoareStyle $ unicodeStyle baseTermOpts
defTermOpts = parseableTermOpts
unicodeStyle opt = opt {
ellipsis = text "…"
, parallSym = char '‖'
, restrSyn = (\ns p -> char 'ν' <> nameList opt parens ns <> dot <> p)
, tauSym = char 'τ'
}
asciiStyle opt = opt{
ellipsis = text ".."
, parallSym = char '|'
, restrSyn = (\ns p -> text "new" <+> nameList opt parens ns <> dot <> p)
, tauSym = text "tau"
}
milnerStyle opt = opt{
inpSyn = (\n ns -> n <> prtNames parens ns)
, outSyn = (\n ns -> n <> prtNames angles ns)
}
where
prtNames p [] = p empty
prtNames p [x] = p x
prtNames p xs = nameList opt parens xs
hoareStyle opt = opt{
inpSyn = (\n ns -> n <> char '?' <> nameList opt parens ns)
, outSyn = (\n ns -> n <> char '!' <> nameList opt parens ns)
}
-- non parseable:
cspStyle opt = hoareStyle opt{
prefixSym = text "->"
, restrSyn = (\ns p -> p <+> char '\\' <+> (braces $ sep $ punctuate comma ns))
}
ccsStyle opt = milnerStyle opt{
prefixSym = dot
, restrSyn = (\ns p -> (sep $ map parens ns) <> p)
, bangSym = char '!'
}
colorHoareStyle opt = opt{
inpSyn = (\n ns -> text "\x1b[31m" <> n <> char '?' <> nameList opt parens ns <> text "\x1b[0m")
, outSyn = (\n ns -> text "\x1b[32m" <> n <> char '!' <> nameList opt parens ns <> text "\x1b[0m")
, restrSyn = (\ns p -> text "\x1b[34mν" <> nameList opt parens ns <> text "\x1b[0m" <> dot <> p)
}
prettyProg :: (Pretty n, Ord n) => PrettyProgOpts -> PiProgAST n -> Doc
prettyProg POpt{..} PiProg{..} = wrapProg $ globals $$ prettyTerm termOpts start $+$ prettyDefs
where
prettyDefs = defList $ map prettydef $ defsList defs
prettydef (p,(a,d)) = wrapDef $ hang ((pretty p <> prArgs a) <+> defSym) 4 (prettyTerm termOpts d)
prArgs args = argList termOpts $ map pretty args
globals | Set.null glob = empty
| otherwise = text "#global" <+> (sep $ punctuate space pglob) <+> text ";"
where
glob = getGlobals defs
pglob = map pretty $ Set.elems glob
prettyTerm :: (Pretty name) => PrettyTermOpts -> PiAST name -> Doc
prettyTerm TOpt{..} t = wrapTerm $ prt maxLvl t
where
prt (Just n) _ | n <= 0 = ellipsis
prt d t = case t of
_ | isZero t -> zeroSym
(Parall ps) -> group $ sep $ punctOp parallSym $ map (prt d') $ MSet.elems ps
(Alt alts)
| MSet.size alts == 1 -> prefix $ head $ MSet.elems alts
| otherwise -> group $ sep $ punctOp sumSym $ map prefix $ MSet.elems alts
(New names proc) -> restrSyn (map pretty $ Set.elems names) (prt d proc)
(PiCall pvar args) -> pretty pvar <> prArgs args
(Bang proc) -> parens $ bangSym <> prt d proc
where
d' = fmap (subtract 1) d
prefix (pre,proc)
| isZero proc && not explicitZeros = prtPre pre
| otherwise = prtPre pre <> prefixSym <>
case proc of
(New _ _) -> group $ prt d' proc
_ -> prt d' proc
prtPre (In x ns) = inpSyn (pretty x) (map pretty ns)
prtPre (Out x ns) = outSyn (pretty x) (map pretty ns)
prtPre Tau = tauSym
prArgs args = argList $ map pretty args
punctOp _ [] = []
punctOp op (x:xs) = x:map (op<+>) xs
prettyShort:: Int -> PiTerm -> Doc
prettyShort d = prettyTerm defTermOpts{maxLvl=Just d}
par1 _ _ [] = empty
par1 _ _ [d] = d
par1 s p y = p $ sep $ punctuate s y
par0 _ _ [] = empty
par0 s p y = p $ sep $ punctuate s y
-- nameList l = sep $ punctuate comma $ map pretty l
| bordaigorl/jamesbound | src/Language/PiCalc/Pretty.hs | gpl-2.0 | 9,403 | 0 | 15 | 2,741 | 3,049 | 1,603 | 1,446 | 202 | 11 |
module Text.XML.HaXml.DtdToHaskell.Instance
( mkInstance
) where
import List (intersperse)
import Text.XML.HaXml.DtdToHaskell.TypeDef
import Text.PrettyPrint.HughesPJ
-- | Convert typedef to appropriate instance declaration, either @XmlContent@,
-- @XmlAttributes@, or @XmlAttrType@.
mkInstance :: TypeDef -> Doc
-- no constructors
mkInstance (DataDef aux n fs []) =
let (frpat, frattr, topat, toattr) = attrpats fs
frretval = if null fs then ppHName n else frattr
topatval = if null fs then ppHName n else topat
in
text "instance XmlContent" <+> ppHName n <+> text "where" $$
nest 4 ( text "fromElem (CElem (Elem \"" <> ppXName n <> text "\""
<+> frpat <+> text "[]):rest) =" $$
nest 4 (text "(Just" <+> frretval <> text ", rest)") $$
text "fromElem (CMisc _:rest) = fromElem rest" $$
text "fromElem rest = (Nothing, rest)"
$$
text "toElem" <+> topatval <+> text "=" $$
nest 4 (text "[CElem (Elem \"" <> ppXName n <> text "\""
<+> toattr <+> text "[])]")
)
$$
mkInstanceAttrs Same n fs
-- single constructor, "real" (non-auxiliary) type
mkInstance (DataDef False n fs [(n0,sts)]) =
let vs = nameSupply sts
(frpat, frattr, topat, toattr) = attrpats fs
in
text "instance XmlContent" <+> ppHName n <+> text "where" $$
nest 4 ( text "fromElem (CElem (Elem \"" <> ppXName n <> text "\""
<+> frpat <+> text "c0):rest) =" $$
nest 4 (mkFrElem n sts vs (
text "(Just" <+> parens (mkCpat n0 frattr vs)
<> text ", rest)")
) $$
text "fromElem (CMisc _:rest) = fromElem rest" $$
text "fromElem rest = (Nothing, rest)"
$$
text "toElem" <+> parens (mkCpat n0 topat vs) <+> text "=" $$
nest 4 (text "[CElem (Elem \"" <> ppXName n <> text "\""
<+> toattr <+> parens (mkToElem sts vs) <> text ")]")
)
$$
mkInstanceAttrs Extended n fs
-- single constructor, auxiliary type
mkInstance (DataDef True n fs [(n0,sts)]) =
let vs = nameSupply sts
(frpat, frattr, topat, toattr) = attrpats fs
in
text "instance XmlContent" <+> ppHName n <+> text "where" $$
nest 4 ( text "fromElem c0 =" $$
mkFrAux True frattr [(n0,sts)]
$$
text "toElem" <+> parens (mkCpat n0 topat vs) <+> text "=" $$
-- nest 4 (text "[CElem (Elem \"" <> ppXName n <> text "\""
-- <+> toattr <+> parens (mkToElem sts vs) <> text ")]")
nest 4 (parens (mkToElem sts vs))
)
$$
mkInstanceAttrs Extended n fs
-- multiple constructors
mkInstance (DataDef aux n fs cs) =
let vs = nameSupply cs
(frpat, frattr, topat, toattr) = attrpats fs
mixattrs = if null fs then False else True
in
text "instance XmlContent" <+> ppHName n <+> text "where" $$
nest 4 ( ( if aux then text "fromElem c0 ="
else text "fromElem (CElem (Elem \"" <> ppXName n <> text "\""
<+> frpat <+> text "c0):rest) =" ) $$
mkFrAux aux frattr cs $$
text "fromElem (CMisc _:rest) = fromElem rest" $$
text "fromElem rest = (Nothing, rest)"
$$
if aux then vcat (map (mkToAux mixattrs) cs)
else vcat (map (mkToMult n topat toattr) cs)
)
$$
mkInstanceAttrs Extended n fs
-- enumeration of attribute values
mkInstance (EnumDef n es) =
text "instance XmlAttrType" <+> ppHName n <+> text "where" $$
nest 4 ( text "fromAttrToTyp n (n',v)" $$
nest 4 (text "| n==n' = translate (attr2str v)" $$
text "| otherwise = Nothing") $$
nest 2 (text "where" <+> mkTranslate es)
$$
vcat (map mkToAttr es)
)
data SameName = Same | Extended
mkInstanceAttrs :: SameName -> Name -> AttrFields -> Doc
mkInstanceAttrs s n [] = empty
mkInstanceAttrs s n fs =
let ppName = case s of { Same-> ppHName; Extended-> ppAName; }
in
text "instance XmlAttributes" <+> ppName n <+> text "where" $$
nest 4 ( text "fromAttrs as =" $$
nest 4 ( ppName n $$
nest 2 (vcat ((text "{" <+> mkFrFld n (head fs)):
map (\x-> comma <+> mkFrFld n x) (tail fs)) $$
text "}"))
$$
text "toAttrs v = catMaybes " $$
nest 4 (vcat ((text "[" <+> mkToFld (head fs)):
map (\x-> comma <+> mkToFld x) (tail fs)) $$
text "]")
)
-- respectively (frpat,frattr,topat,toattr)
attrpats :: AttrFields -> (Doc,Doc,Doc,Doc)
attrpats fs =
if null fs then (text "[]", empty, empty, text "[]")
else (text "as", parens (text "fromAttrs as"), text "as", parens (text "toAttrs as"))
mkFrElem :: Name -> [StructType] -> [Doc] -> Doc -> Doc
mkFrElem n sts vs inner =
foldr (frElem n) inner (zip3 sts vs cvs)
where
cvs = let ns = nameSupply2 vs
in zip ns (text "c0": init ns)
frElem n (st,v,(cvi,cvo)) inner =
parens (text "\\" <> parens (v<>comma<>cvi) <> text "->" $$
nest 2 inner) $$
parens (
case st of
(Maybe String) -> text "fromText" <+> cvo
(Maybe s) -> text "fromElem" <+> cvo
(List String) -> text "many fromText" <+> cvo
(List s) -> text "many fromElem" <+> cvo
(List1 s) -> text "definite fromElem"
<+> text "\"" <> text (show s)<> text "+\""
<+> text "\"" <> ppXName n <> text "\""
<+> cvo
(Tuple ss) -> text "definite fromElem"
<+> text "\"(" <> hcat (intersperse (text ",")
(map (text.show) ss))
<> text ")\""
<+> text "\"" <> ppXName n <> text "\""
<+> cvo
(OneOf ss) -> text "definite fromElem"
<+> text "\"OneOf\""
<+> text "\"" <> ppXName n <> text "\""
<+> cvo
(String) -> text "definite fromText" <+> text "\"text\" \"" <>
ppXName n <> text "\"" <+> cvo
(Any) -> text "definite fromElem" <+> text "\"ANY\" \"" <>
ppXName n <> text "\"" <+> cvo
(Defined m) -> text "definite fromElem" <+>
text "\"<" <> ppXName m <> text ">\" \"" <>
ppXName n <> text "\"" <+> cvo
(Defaultable _ _) -> text "nyi_fromElem_Defaultable" <+> cvo
)
mkToElem :: [StructType] -> [Doc] -> Doc
mkToElem [] [] = text "[]"
mkToElem sts vs =
fsep (intersperse (text "++") (zipWith toElem sts vs))
where
toElem st v =
case st of
(Maybe String) -> text "maybe [] toText" <+> v
(Maybe s) -> text "maybe [] toElem" <+> v
(List String) -> text "concatMap toText" <+> v
(List s) -> text "concatMap toElem" <+> v
(List1 s) -> text "toElem" <+> v
(Tuple ss) -> text "toElem" <+> v
(OneOf ss) -> text "toElem" <+> v
(String) -> text "toText" <+> v
(Any) -> text "toElem" <+> v
(Defined m) -> text "toElem" <+> v
(Defaultable _ _) -> text "nyi_toElem_Defaultable" <+> v
mkRpat :: [Doc] -> Doc
mkRpat [v] = v
mkRpat vs = (parens . hcat . intersperse comma) vs
mkCpat :: Name -> Doc -> [Doc] -> Doc
mkCpat n i vs = ppHName n <+> i <+> fsep vs
nameSupply,nameSupply2 :: [b] -> [Doc]
nameSupply ss = take (length ss) (map char ['a'..])
nameSupply2 ss = take (length ss) [ text ('c':v:[]) | v <- ['a'..]]
mkTranslate :: [Name] -> Doc
mkTranslate es =
vcat (map trans es) $$
text "translate _ = Nothing"
where
trans n = text "translate \"" <> ppXName n <> text "\" =" <+>
text "Just" <+> ppHName n
mkToAttr n = text "toAttrFrTyp n" <+> ppHName n <+> text "=" <+>
text "Just (n, str2attr" <+> doubleQuotes (ppXName n) <> text ")"
mkFrFld :: Name -> (Name,StructType) -> Doc
mkFrFld tag (n,st) =
ppHName n <+> text "=" <+>
( case st of
(Defaultable String s) -> text "defaultA fromAttrToStr" <+>
doubleQuotes (text s)
(Defaultable _ s) -> text "defaultA fromAttrToTyp" <+> text s
(Maybe String) -> text "possibleA fromAttrToStr"
(Maybe _) -> text "possibleA fromAttrToTyp"
String -> text "definiteA fromAttrToStr" <+>
doubleQuotes (ppXName tag)
_ -> text "definiteA fromAttrToTyp" <+>
doubleQuotes (ppXName tag)
) <+> doubleQuotes (ppXName n) <+> text "as"
mkToFld :: (Name,StructType) -> Doc
mkToFld (n,st) =
( case st of
(Defaultable String _) -> text "defaultToAttr toAttrFrStr"
(Defaultable _ _) -> text "defaultToAttr toAttrFrTyp"
(Maybe String) -> text "maybeToAttr toAttrFrStr"
(Maybe _) -> text "maybeToAttr toAttrFrTyp"
String -> text "toAttrFrStr"
_ -> text "toAttrFrTyp"
) <+> doubleQuotes (ppXName n) <+> parens (ppHName n <+> text "v")
mkFrAux :: Bool -> Doc -> [(Name,[StructType])] -> Doc
mkFrAux keeprest attrs cs = foldr frAux inner cs
where
inner = text "(Nothing, c0)"
rest = if keeprest then text "rest" else text "_"
frAux (n,sts) inner =
let vs = nameSupply sts in
nest 4 (text "case" <+> blah sts vs <+> text "of" $$
succpat sts vs <+> text "-> (Just" <+>
parens (mkCpat n attrs vs) <> text ", rest)"
$$
failpat sts <+> text "->" $$ nest 4 inner
)
blah [st] [v] =
blahblahblah st (text "c0")
blah sts vs =
let ns = nameSupply2 vs
cvs = zip ns (text "c0": init ns)
blahblah (st,v,(cvi,cvo)) inner =
parens (text "\\" <> parens (v<>comma<>cvi) <> text "->" $$
nest 2 inner) $$
blahblahblah st cvo
in
foldr blahblah (mkRpat (vs++[last ns])) (zip3 sts vs cvs)
blahblahblah st cvo = parens (
case st of
(Maybe String) -> text "fromText" <+> cvo
(Maybe s) -> text "fromElem" <+> cvo
(List String) -> text "many fromText" <+> cvo
(List s) -> text "many fromElem" <+> cvo
(List1 s) -> text "fromElem" <+> cvo
(Tuple ss) -> text "fromElem" <+> cvo -- ??
(OneOf ss) -> text "fromElem" <+> cvo
(String) -> text "fromText" <+> cvo
(Any) -> text "fromElem" <+> cvo
(Defined m) -> text "fromElem" <+> cvo
)
failpat sts =
let fp st =
case st of
(Maybe s) -> text "Nothing"
(List s) -> text "[]"
(List1 s) -> text "_"
(Tuple ss) -> text "_"
(OneOf ss) -> text "_"
(String) -> text "_"
(Any) -> text "_"
(Defined m) -> text "_"
in parens (hcat (intersperse comma (map fp sts++[text "_"])))
succpat sts vs =
let sp st v =
case st of
(Maybe s) -> v
(List s) -> v
(List1 s) -> text "Just" <+> v
(Tuple ss) -> text "Just" <+> v
(OneOf ss) -> text "Just" <+> v
(String) -> text "Just" <+> v
(Any) -> text "Just" <+> v
(Defined m) -> text "Just" <+> v
in parens (hcat (intersperse comma (zipWith sp sts vs++[rest])))
mkToAux :: Bool -> (Name,[StructType]) -> Doc
mkToAux mixattrs (n,sts) =
let vs = nameSupply sts
attrs = if mixattrs then text "as" else empty
in
text "toElem" <+> parens (mkCpat n attrs vs) <+> text "=" <+>
mkToElem sts vs
mkToMult :: Name -> Doc -> Doc -> (Name,[StructType]) -> Doc
mkToMult tag attrpat attrexp (n,sts) =
let vs = nameSupply sts
in
text "toElem" <+> parens (mkCpat n attrpat vs) <+> text "=" <+>
text "[CElem (Elem \"" <> ppXName tag <> text "\""<+> attrexp <+>
parens (mkToElem sts vs) <+> text ")]"
| jgoerzen/dtmconv | HaXml-1.12/src/Text/XML/HaXml/DtdToHaskell/Instance.hs | gpl-2.0 | 12,878 | 10 | 31 | 4,917 | 4,280 | 2,088 | 2,192 | 257 | 26 |
module Main where
import V
main = vmain
| vrthra/v | src/Main.hs | gpl-2.0 | 42 | 0 | 4 | 10 | 12 | 8 | 4 | 3 | 1 |
-- file: ch4/exB4.hs
-- A pair of function that take from a list while a predicate is true.
-- Daniel Brice
takeWhileRecursive :: (a -> Bool) -> [a] -> [a]
takeWhileRecursive = loop []
where
loop acc p (x : xs) = if p x
then loop (acc ++ [x]) p xs
else acc
loop acc _ _ = acc
takeWhileFold :: (a -> Bool) -> [a] -> [a]
takeWhileFold p xs = reverse $ foldr step [] xs
where
step x acc = if p x
then acc ++ [x]
else []
| friedbrice/RealWorldHaskell | ch4/exB4.hs | gpl-2.0 | 528 | 1 | 9 | 204 | 183 | 98 | 85 | 11 | 3 |
-- | Module servant a faire l'inférence de type à l'aide des règles de Hindley Milner
module TypeInference.Rules where
import TypeInference.Base
import qualified Data.Set as Set
import qualified Data.Map as Map
import TypeInference.TypeVariable
import LambdaCalculus
import Data.Monoid
type TypedExpr = Expr Monotype
newVariable :: Monad m => InferenceMonad m Monotype
newVariable = fmap TVar newTypeVariable
constantType :: Literal -> Monotype
constantType Unit = TConstant "()"
constantType (LInt _) = TConstant "Int"
constantType (LString _) = TConstant "String"
constantType (LBool _) = TConstant "Bool"
identityType :: Monotype -> Monotype
identityType t = createArrow t t
insert :: String -> Polytype -> TypeEnvironment -> TypeEnvironment
insert key val (TypeEnvironment env) = TypeEnvironment $ Map.insert key val env
-- Ajoute des variables libres au monotype
-- |generalize(Γ, τ ) =def ∀α.τ ~ where α = freevars(τ ) − freevars(Γ)
generalize :: TypeEnvironment -> Monotype -> Polytype
generalize env t = Polytype alpha t
where
alpha = Set.toList $ freeVariables t `Set.difference` freeVariables env
-- | Transforme un type polymorphique en un type normal à l'aide des subtitutions
instanciate :: Monad m => Polytype -> InferenceMonad m Monotype
instanciate (Polytype as monotype) = do
env <- Substitutions . Map.fromList <$> mapM mapToNewVar as
return $ substitute env monotype
where mapToNewVar t =fmap (\v -> (t, v)) newVariable
{-|
Infere le type d'une expression
On suppose que l'ont possède une fonction @fix :: (a -> a) -> a, fix f = f (fix f)@
Nous ne pouvons pas encore exprimer cette fonction car elle est récursive, elle est n'est pas encore dans l'environement
quand nous essayons de déterminer le type
L'idée est que au lieu d'exprimer la récursion comme ça : @product n = if (n < 0) then 1 else n * (product (n - 1))@,
nous l'exprimons comme ça: @fix (\product n -> if (n < 0) then 1 else n * (product (n - 1)))@.
Il suffit simplement de simuler l'application pour avoir le type de la fonction
-}
inferLambdaExpr ::
Monad m =>
TypeEnvironment
-> LambdaExpr Expr ()
-> InferenceMonad m (Substitutions, Monotype, Expr Monotype)
inferLambdaExpr env (Var name) = do
t <- findType (getName name) env
t' <- instanciate t
return (mempty, t', LC $ Var (t'<$ name))
inferLambdaExpr env (Apply expr1 expr2) = do
(s1, t1, e1') <- infer env expr1
(s2, t2, e2' ) <- infer (substitute s1 env) expr2
beta <- newVariable
s3 <- unify (substitute s2 t1) (createArrow t2 beta)
return (s1 <> s2 <> s3, substitute s3 beta, LC $ Apply e1' e2')
inferLambdaExpr env (Lambda x expr) = do
beta <- newVariable
let env' = insert (getName x) (toPolytype beta) env
(s1, t1, expr') <- infer env' expr
let paramType = substitute s1 beta
return (s1, createArrow paramType t1, LC $ Lambda (paramType <$ x) expr')
infer :: Monad m => TypeEnvironment -> NonTypedExpr -> InferenceMonad m (Substitutions, Monotype, TypedExpr)
infer env (LC a) = inferLambdaExpr env a
infer _ (Constant c ()) =
let t = constantType c
in return (mempty, t, (Constant c t))
infer env (Fix n expr) = do
a <- newVariable
let fix = Arrow (identityType a) a
(s1, t1, LC (Lambda _ expr')) <- infer env $ LC $ Lambda (Named n ()) expr
b <- newVariable
s2 <- unify (substitute s1 fix) (createArrow t1 b)
return (s1 <> s2, substitute s2 b, Fix n expr')
infer env (If cond a b) = do
(s1, t1, c') <- infer env cond
(s2, t2, a') <- infer env a
(s3, t3, b') <- infer env b
s4 <- unify t1 $ TConstant "Bool"
s5 <- unify t2 t3
return (s1<>s2<>s3<>s4<>s5, substitute s5 t2, If c' a' b') | bruno-cadorette/Baeta-Compiler | src/TypeInference/Rules.hs | gpl-3.0 | 3,774 | 0 | 12 | 825 | 1,184 | 590 | 594 | 67 | 1 |
import Data.Char
-- main = do
-- contents <- getContents
-- putStr (shortLinesOnly contents)
shortLinesOnly :: String -> String
shortLinesOnly input =
let allLines = lines input
shortLines = filter (\line -> length line < 10) allLines
result = unlines shortLines
in result
-- main = interact $ unlines . filter ((<10) . length) . lines
respondPalindromes contents = unlines (map (\xs ->
if isPalindrome xs then "palindrome" else "not a palindrome")
(lines contents))
where isPalindrome xs = xs == reverse xs
main = interact respondPalindromes
| lamontu/learning_haskell | get_contents.hs | gpl-3.0 | 597 | 0 | 13 | 140 | 143 | 74 | 69 | 12 | 2 |
{-#LANGUAGE FlexibleContexts, FlexibleInstances, MultiParamTypeClasses #-}
module Carnap.Languages.PurePropositional.Logic.Gamut
( GamutMPND(..), gamutMPNDCalc, parseGamutMPND
, GamutIPND(..), gamutIPNDCalc, parseGamutIPND
, GamutPND(..), gamutPNDCalc, parseGamutPND
, GamutPNDPlus(..), gamutPNDPlusCalc, parseGamutPNDPlus
) where
import Text.Parsec
import Data.Char
import Carnap.Core.Data.Types (Form)
import Carnap.Core.Data.Classes
import Carnap.Core.Unification.Unification (applySub,subst,FirstOrder)
import Carnap.Languages.PurePropositional.Syntax
import Carnap.Languages.PurePropositional.Parser
import Carnap.Calculi.NaturalDeduction.Syntax
import Carnap.Calculi.NaturalDeduction.Parser
import Carnap.Calculi.NaturalDeduction.Checker (hoProcessLineFitchMemo, hoProcessLineFitch)
import Carnap.Languages.ClassicalSequent.Syntax
import Carnap.Languages.ClassicalSequent.Parser (parseSeqOver)
import Carnap.Languages.Util.LanguageClasses
import Carnap.Languages.Util.GenericConstructors
import Carnap.Languages.PurePropositional.Logic.Rules
data GamutMPND = InAnd | ElimAndL | ElimAndR
| ElimIf | InIf1 | InIf2
| InNeg1 | InNeg2 | ElimNeg
| ElimOr | InOrL | InOrR
| AS | PR | Rep
deriving Eq
data GamutIPND = MPND GamutMPND | EFSQ
deriving Eq
data GamutPND = IPND GamutIPND | DNE
deriving Eq
data GamutPNDPlus = PND GamutPND
| LEM | LNC | DN1 | DN2
| LCC | LCD | LAC1 | LAC2 | LAD1 | LAD2
| LDD1 | LDD2 | LDC1 | LDC2 | DMOR1 | DMOR2
| DMAND1 | DMAND2 | MT | MTP | NMTP
deriving Eq
instance Show GamutMPND where
show InAnd = "I∧"
show ElimAndL = "E∧"
show ElimAndR = "E∧"
show ElimIf = "E→"
show InIf1 = "I→"
show InIf2 = "I→"
show InNeg1 = "I¬"
show InNeg2 = "I¬"
show ElimNeg = "E¬"
show ElimOr = "E∨"
show InOrL = "I∨"
show InOrR = "I∨"
show AS = "assumption"
show PR = "assumption"
show Rep = "repeat"
instance Show GamutIPND where
show (MPND x) = show x
show EFSQ = "EFSQ"
instance Show GamutPND where
show (IPND x) = show x
show DNE = "¬¬"
instance Show GamutPNDPlus where
show (PND x) = show x
show LEM = "LEM"
show LNC = "LNC"
show DN1 = "DN"
show DN2 = "DN"
show LCC = "LCC"
show LCD = "LCD"
show LAC1 = "LAC"
show LAC2 = "LAC"
show LAD1 = "LAD"
show LAD2 = "LAD"
show LDD1 = "LDD"
show LDD2 = "LDD"
show LDC1 = "LDC"
show LDC2 = "LDC"
show DMOR1 = "DMOR"
show DMOR2 = "DMOR"
show DMAND1 = "DMAND"
show DMAND2 = "DMAND"
show MT = "MT"
show MTP = "PDS"
show NMTP = "NDS"
instance Inference GamutMPND PurePropLexicon (Form Bool) where
ruleOf InAnd = adjunction
ruleOf ElimAndL = simplificationVariations !! 0
ruleOf ElimAndR = simplificationVariations !! 1
ruleOf ElimIf = modusPonens
ruleOf InIf1 = conditionalProofVariations !! 0
ruleOf InIf2 = conditionalProofVariations !! 1
ruleOf InNeg1 = constructiveFalsumReductioVariations !! 0
ruleOf InNeg2 = constructiveFalsumReductioVariations !! 1
ruleOf ElimNeg = falsumIntroduction
ruleOf ElimOr = dilemma
ruleOf Rep = identityRule
ruleOf InOrL = additionVariations !! 0
ruleOf InOrR = additionVariations !! 1
ruleOf AS = axiom
ruleOf PR = axiom
indirectInference x
| x `elem` [InIf1, InIf2, InNeg1, InNeg2] = Just (WithAlternate (ImplicitProof (ProofType 0 1)) (TypedProof (ProofType 0 1)))
| otherwise = Nothing
isAssumption AS = True
isAssumption _ = False
globalRestriction (Left ded) n InIf1 = Just $ fitchAssumptionCheck n ded [([phin 1], [phin 2])]
globalRestriction (Left ded) n InIf2 = Just $ fitchAssumptionCheck n ded [([phin 1], [phin 2])]
globalRestriction (Left ded) n InNeg1 = Just $ fitchAssumptionCheck n ded [([phin 1], [lfalsum])]
globalRestriction (Left ded) n InNeg2 = Just $ fitchAssumptionCheck n ded [([phin 1], [lfalsum])]
globalRestriction _ _ _ = Nothing
instance Inference GamutIPND PurePropLexicon (Form Bool) where
ruleOf (MPND x) = ruleOf x
ruleOf EFSQ = falsumElimination
indirectInference (MPND x) = indirectInference x
indirectInference _ = Nothing
isAssumption (MPND x) = isAssumption x
isAssumption _ = False
globalRestriction (Left ded) n (MPND InIf1) = Just $ fitchAssumptionCheck n ded [([phin 1], [phin 2])]
globalRestriction (Left ded) n (MPND InIf2) = Just $ fitchAssumptionCheck n ded [([phin 1], [phin 2])]
globalRestriction (Left ded) n (MPND InNeg1) = Just $ fitchAssumptionCheck n ded [([phin 1], [lfalsum])]
globalRestriction (Left ded) n (MPND InNeg2) = Just $ fitchAssumptionCheck n ded [([phin 1], [lfalsum])]
globalRestriction _ _ _ = Nothing
instance Inference GamutPND PurePropLexicon (Form Bool) where
ruleOf (IPND x) = ruleOf x
ruleOf DNE = doubleNegationElimination
indirectInference (IPND x) = indirectInference x
indirectInference _ = Nothing
isAssumption (IPND x) = isAssumption x
isAssumption _ = False
globalRestriction (Left ded) n (IPND (MPND InIf1)) = Just $ fitchAssumptionCheck n ded [([phin 1], [phin 2])]
globalRestriction (Left ded) n (IPND (MPND InIf2)) = Just $ fitchAssumptionCheck n ded [([phin 1], [phin 2])]
globalRestriction (Left ded) n (IPND (MPND InNeg1)) = Just $ fitchAssumptionCheck n ded [([phin 1], [lfalsum])]
globalRestriction (Left ded) n (IPND (MPND InNeg2)) = Just $ fitchAssumptionCheck n ded [([phin 1], [lfalsum])]
globalRestriction _ _ _ = Nothing
instance Inference GamutPNDPlus PurePropLexicon (Form Bool) where
ruleOf (PND x) = ruleOf x
ruleOf LEM = [] ∴ Top :|-: SS (phin 1 .\/. (lneg $ phin 1))
ruleOf LNC = [] ∴ Top :|-: SS (lneg (phin 1 ./\. (lneg $ phin 1)))
ruleOf DN1 = doubleNegation !! 0
ruleOf DN2 = doubleNegation !! 1
ruleOf LCC = andCommutativity !! 0
ruleOf LCD = orCommutativity !! 0
ruleOf LAC1 = andAssociativity !! 0
ruleOf LAC2 = andAssociativity !! 1
ruleOf LAD1 = orAssociativity !! 0
ruleOf LAD2 = orAssociativity !! 1
ruleOf LDD1 = orDistributivity !! 0
ruleOf LDD2 = orDistributivity !! 1
ruleOf LDC1 = andDistributivity !! 0
ruleOf LDC2 = andDistributivity !! 1
ruleOf DMOR1 = deMorgansLaws !! 0
ruleOf DMOR2 = deMorgansLaws !! 1
ruleOf DMAND1 = deMorgansLaws !! 2
ruleOf DMAND2 = deMorgansLaws !! 3
ruleOf MT = modusTollens
ruleOf MTP = modusTollendoPonensVariations !! 0
ruleOf NMTP = [ GammaV 1 :|-: SS (phin 1)
, GammaV 2 :|-: SS (lneg $ phin 1 .∧. phin 2)
] ∴ GammaV 1 :+: GammaV 2 :|-: SS (lneg $ phin 2)
indirectInference (PND x) = indirectInference x
indirectInference _ = Nothing
isAssumption (PND x) = isAssumption x
isAssumption _ = False
globalRestriction (Left ded) n (PND (IPND (MPND InIf1))) = Just $ fitchAssumptionCheck n ded [([phin 1], [phin 2])]
globalRestriction (Left ded) n (PND (IPND (MPND InIf2))) = Just $ fitchAssumptionCheck n ded [([phin 1], [phin 2])]
globalRestriction (Left ded) n (PND (IPND (MPND InNeg1))) = Just $ fitchAssumptionCheck n ded [([phin 1], [lfalsum])]
globalRestriction (Left ded) n (PND (IPND (MPND InNeg2))) = Just $ fitchAssumptionCheck n ded [([phin 1], [lfalsum])]
globalRestriction _ _ _ = Nothing
parseGamutMPND rtc = do r <- choice (map (try . string)
[ "I∧" , "I/\\", "I^", "E∧" , "E/\\", "E^"
, "E→" , "E->", "I→" , "I->"
, "I¬" , "I~", "I-", "E¬" , "E~", "E-"
, "E∨" , "E\\/", "Ev", "I∨" , "I\\/", "Iv"
, "repetition", "rep" , "assumption", "as"])
case r of
r | r `elem` ["I∧" , "I/\\", "I^"] -> return [InAnd]
| r `elem` ["E∧" , "E/\\", "E^"] -> return [ElimAndR, ElimAndL]
| r `elem` ["E→" , "E->"] -> return [ElimIf]
| r `elem` ["I→" , "I->"] -> return [InIf1, InIf2]
| r `elem` ["I¬" , "I~", "I-"] -> return [InNeg1, InNeg2]
| r `elem` ["E¬" , "E~", "E-"] -> return [ElimNeg]
| r `elem` ["E∨" , "E\\/", "Ev"] -> return [ElimOr]
| r `elem` ["I∨" , "I\\/", "Iv"] -> return [InOrL, InOrR]
| r `elem` ["repetition", "rep"] -> return [Rep]
| r `elem` ["assumption", "as"] -> return [AS, PR]
parseGamutIPND rtc = (map MPND <$> parseGamutMPND rtc) <|> (try (string "EFSQ") >> return [EFSQ])
parseGamutPND rtc = (map IPND <$> parseGamutIPND rtc)
<|> (choice (map (try . string) ["~~","¬¬","--"]) >> return [DNE])
parseGamutPNDPlus rtc = (map PND <$> parseGamutPND rtc)
<|> parsePlus
where parsePlus = do r <- choice (map (try . string) ["LEM", "LNC", "DN", "LCC", "LCD", "LAC", "LAD", "LDD", "LDC", "DMOR", "DMAND", "MT", "PDS", "NDS"])
return $ case r of
r | r == "LEM" -> [LEM]
| r == "LNC" -> [LNC]
| r == "DN" -> [DN1, DN2]
| r == "LCC" -> [LCC]
| r == "LCD" -> [LCD]
| r == "LAC" -> [LAC1,LAC2]
| r == "LAD" -> [LAD1,LAD2]
| r == "LDD" -> [LDD1,LDD2]
| r == "LDC" -> [LDC1,LDC2]
| r == "DMOR" -> [DMOR1,DMOR2]
| r == "DMAND" -> [DMAND1,DMAND2]
| r == "MT" -> [MT]
| r == "PDS" -> [MTP]
| r == "NDS" -> [NMTP]
parseGamutMPNDProof :: RuntimeNaturalDeductionConfig PurePropLexicon (Form Bool) -> String -> [DeductionLine GamutMPND PurePropLexicon (Form Bool)]
parseGamutMPNDProof rtc = toDeductionFitch (parseGamutMPND rtc) (purePropFormulaParser gamutOpts)
parseGamutIPNDProof :: RuntimeNaturalDeductionConfig PurePropLexicon (Form Bool) -> String -> [DeductionLine GamutIPND PurePropLexicon (Form Bool)]
parseGamutIPNDProof rtc = toDeductionFitch (parseGamutIPND rtc) (purePropFormulaParser gamutOpts)
parseGamutPNDProof :: RuntimeNaturalDeductionConfig PurePropLexicon (Form Bool) -> String -> [DeductionLine GamutPND PurePropLexicon (Form Bool)]
parseGamutPNDProof rtc = toDeductionFitch (parseGamutPND rtc) (purePropFormulaParser gamutOpts)
parseGamutPNDPlusProof :: RuntimeNaturalDeductionConfig PurePropLexicon (Form Bool) -> String -> [DeductionLine GamutPNDPlus PurePropLexicon (Form Bool)]
parseGamutPNDPlusProof rtc = toDeductionFitch (parseGamutPNDPlus rtc) (purePropFormulaParser gamutOpts)
gamutNotation :: String -> String
gamutNotation (x:xs) | isUpper x = toLower x : gamutNotation xs
| otherwise = x : gamutNotation xs
gamutNotation [] = []
gamutMPNDCalc = mkNDCalc
{ ndRenderer = NoRender
, ndParseProof = parseGamutMPNDProof
, ndProcessLine = hoProcessLineFitch
, ndProcessLineMemo = Just hoProcessLineFitchMemo
, ndParseSeq = parseSeqOver (purePropFormulaParser gamutOpts)
, ndParseForm = purePropFormulaParser gamutOpts
, ndNotation = gamutNotation
}
gamutIPNDCalc = mkNDCalc
{ ndRenderer = NoRender
, ndParseProof = parseGamutIPNDProof
, ndProcessLine = hoProcessLineFitch
, ndProcessLineMemo = Just hoProcessLineFitchMemo
, ndParseSeq = parseSeqOver (purePropFormulaParser gamutOpts)
, ndParseForm = purePropFormulaParser gamutOpts
, ndNotation = gamutNotation
}
gamutPNDCalc = mkNDCalc
{ ndRenderer = NoRender
, ndParseProof = parseGamutPNDProof
, ndProcessLine = hoProcessLineFitch
, ndProcessLineMemo = Just hoProcessLineFitchMemo
, ndParseSeq = parseSeqOver (purePropFormulaParser gamutOpts)
, ndParseForm = purePropFormulaParser gamutOpts
, ndNotation = gamutNotation
}
gamutPNDPlusCalc = mkNDCalc
{ ndRenderer = NoRender
, ndParseProof = parseGamutPNDPlusProof
, ndProcessLine = hoProcessLineFitch
, ndProcessLineMemo = Just hoProcessLineFitchMemo
, ndParseSeq = parseSeqOver (purePropFormulaParser gamutOpts)
, ndParseForm = purePropFormulaParser gamutOpts
, ndNotation = gamutNotation
}
| gleachkr/Carnap | Carnap/src/Carnap/Languages/PurePropositional/Logic/Gamut.hs | gpl-3.0 | 13,337 | 0 | 16 | 4,109 | 4,113 | 2,189 | 1,924 | 248 | 1 |
module Ordinals where
import Hip.Prelude
import qualified Prelude as P
data Nat = Z | S Nat deriving (P.Show)
Z + y = y
(S x) + y = S (x + y)
Z * _ = Z
(S x) * y = y + (x * y)
data Ord = Zero | Suc Ord | Lim (Nat -> Ord)
(%+) :: Ord -> Ord -> Ord
Zero %+ y = y
Suc x %+ y = Suc (x %+ y)
Lim f %+ y = Lim (\n -> f n %+ y)
(%*) :: Ord -> Ord -> Ord
Zero %* y = Zero
Suc x %* y = y %+ (x %* y)
Lim f %* y = Lim (\n -> f n %* y)
prop_assoc_plus :: Ord -> Ord -> Ord -> Prop Ord
prop_assoc_plus x y z = x %+ (y %+ z) =:= (x %+ y) %+ z
prop_assoc_mul :: Ord -> Ord -> Ord -> Prop Ord
prop_assoc_mul x y z = x %* (y %* z) =:= (x %* y) %* z
prop_right_identity_plus :: Ord -> Prop Ord
prop_right_identity_plus x = x %+ Zero =:= x
prop_left_identity_plus :: Ord -> Prop Ord
prop_left_identity_plus x = Zero %+ x =:= x
prop_right_identity_mul :: Ord -> Prop Ord
prop_right_identity_mul x = x %* Suc Zero =:= x
prop_left_identity_mul :: Ord -> Prop Ord
prop_left_identity_mul x = Suc Zero %* x =:= x
{-
finite :: Nat -> Ord
finite Z = Zero
finite (S n) = Suc (finite n)
omega :: Ord
omega = Lim finite
instance Show Ord where
show Zero = "Zero"
show (Suc n) = "Succ (" P.%+ show n P.%+ ")"
show (Lim f) = "Lim (" P.%+ P.unwords
[ show (f n)
| n <- [Z, S Z, S (S Z), S (S (S Z))]
] P.%+ ")"
-} | danr/hipspec | examples/old-examples/hip/Ordinals.hs | gpl-3.0 | 1,382 | 0 | 9 | 409 | 537 | 274 | 263 | 29 | 1 |
{-# OPTIONS_GHC -fno-implicit-prelude #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Maybe
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : stable
-- Portability : portable
--
-- The Maybe type, and associated operations.
--
-----------------------------------------------------------------------------
module Data.Maybe
(
Maybe(Nothing,Just)-- instance of: Eq, Ord, Show, Read,
-- Functor, Monad, MonadPlus
, maybe -- :: b -> (a -> b) -> Maybe a -> b
, isJust -- :: Maybe a -> Bool
, isNothing -- :: Maybe a -> Bool
, fromJust -- :: Maybe a -> a
, fromMaybe -- :: a -> Maybe a -> a
, listToMaybe -- :: [a] -> Maybe a
, maybeToList -- :: Maybe a -> [a]
, catMaybes -- :: [Maybe a] -> [a]
, mapMaybe -- :: (a -> Maybe b) -> [a] -> [b]
) where
-- | The 'isJust' function returns 'True' iff its argument is of the
-- form @Just _@.
isJust :: Maybe a -> Bool
isJust Nothing = False
isJust _ = True
-- | The 'isNothing' function returns 'True' iff its argument is 'Nothing'.
isNothing :: Maybe a -> Bool
isNothing Nothing = True
isNothing _ = False
-- | The 'fromJust' function extracts the element out of a 'Just' and
-- throws an error if its argument is 'Nothing'.
fromJust :: Maybe a -> a
fromJust Nothing = error "Maybe.fromJust: Nothing" -- yuck
fromJust (Just x) = x
-- | The 'fromMaybe' function takes a default value and and 'Maybe'
-- value. If the 'Maybe' is 'Nothing', it returns the default values;
-- otherwise, it returns the value contained in the 'Maybe'.
fromMaybe :: a -> Maybe a -> a
fromMaybe d x = case x of {Nothing -> d;Just v -> v}
-- | The 'maybeToList' function returns an empty list when given
-- 'Nothing' or a singleton list when not given 'Nothing'.
maybeToList :: Maybe a -> [a]
maybeToList Nothing = []
maybeToList (Just x) = [x]
-- | The 'listToMaybe' function returns 'Nothing' on an empty list
-- or @'Just' a@ where @a@ is the first element of the list.
listToMaybe :: [a] -> Maybe a
listToMaybe [] = Nothing
listToMaybe (a:_) = Just a
-- | The 'catMaybes' function takes a list of 'Maybe's and returns
-- a list of all the 'Just' values.
catMaybes :: [Maybe a] -> [a]
catMaybes ls = [x | Just x <- ls]
-- | The 'mapMaybe' function is a version of 'map' which can throw
-- out elements. In particular, the functional argument returns
-- something of type @'Maybe' b@. If this is 'Nothing', no element
-- is added on to the result list. If it just @'Just' b@, then @b@ is
-- included in the result list.
mapMaybe :: (a -> Maybe b) -> [a] -> [b]
mapMaybe _ [] = []
mapMaybe f (x:xs) =
let rs = mapMaybe f xs in
case f x of
Nothing -> rs
Just r -> r:rs
| kaoskorobase/mescaline | resources/hugs/packages/base/Data/Maybe.hs | gpl-3.0 | 3,030 | 0 | 10 | 780 | 457 | 262 | 195 | 42 | 2 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE Arrows #-}
-- | Interface for the NCBI Entrez REST webservice.
--
-- The entrezHTTP function provides a interface to the NCBI Entrez REST service.
--
-- A series of different eutilites and databases are provided by the REST interface.
-- Response depends on the combination of eutil and database, as well requested returntype.
-- Specific combinations have wrapper functions with corresponding parsing functions included (see Usage example).
--
-- If you use this libary in a tool, please read <http://www.ncbi.nlm.nih.gov/books/NBK25497/ A General Introduction to the E-utilities> carefully and register your tool at eutilities@ncbi.nlm.nih.gov. You can append your registration info generated
-- with the included buildRegistration function to your query.
--
-- == Usage example:
--
-- Retrieve a nucleotide sequence for Escherichia coli
--
-- > nucleotideFasta <- fetchNucleotideString "NC_000913.3" 50 1000 "+" Nothing
module Biobase.Entrez.HTTP (-- * Datatypes
module Biobase.Entrez.HTTPData,
-- * Retrieval function
entrezHTTP,
retrieveGeneSymbolFasta,
fetchNucleotideString,
retrieveElementsEntrez,
portionListElements,
-- * Parsing functions
readEntrezTaxonSet,
readEntrezSimpleTaxons,
readEntrezParentIds,
readEntrezSummaries,
readEntrezSearch,
-- * auxiliary functions
buildRegistration,
maybeBuildRegistration,
setStrand,
convertCoordinatesToStrand
) where
import Network.HTTP.Client
import qualified Data.ByteString.Lazy.Char8 as L8
import qualified Data.ByteString.Char8 as B
import Text.XML.HXT.Core
import Network.Socket
import Data.Maybe
import Biobase.Entrez.HTTPData
import Biobase.Taxonomy.Types
import Network.HTTP.Base
import qualified Data.Text.Lazy as TL
-- | Send query and parse return XML
startSession :: String -> String -> String -> IO String
startSession program' database' query' = do
--requestXml <- withSocketsDo
-- $ sendQuery program' database' query'
let settings = managerSetProxy
(proxyEnvironment Nothing)
defaultManagerSettings
man <- newManager settings
request <- parseRequest ("https://eutils.ncbi.nlm.nih.gov/entrez/eutils/"++ program' ++ ".fcgi?" ++ "db=" ++ database' ++ "&" ++ query')
response <- httpLbs request man
let rbody = responseBody response
let requestXMLString = L8.unpack rbody
return requestXMLString
-- | Send query and return response XML
sendQuery :: String -> String -> String -> IO L8.ByteString
sendQuery program' database' query' = do
--sendQuery program' database' query' = simpleHttp ("https://eutils.ncbi.nlm.nih.gov/entrez/eutils/"++ program' ++ ".fcgi?" ++ "db=" ++ database' ++ "&" ++ query')
let settings = managerSetProxy
(proxyEnvironment Nothing)
defaultManagerSettings
man <- newManager settings
request <- parseRequest ("https://eutils.ncbi.nlm.nih.gov/entrez/eutils/"++ program' ++ ".fcgi?" ++ "db=" ++ database' ++ "&" ++ query')
response <- httpLbs request man
let rbody = responseBody response
return rbody
-- | Function for querying the NCBI entrez REST interface. Input EntrezHTTPQuery datatype is used to select database, program of interest and contains the query string.
-- Please note that query strings containing whitespace or special characters need to be urlencoded. The response format and content depends on the query type, the output
-- therefore provided as String.
entrezHTTP :: EntrezHTTPQuery -> IO String
entrezHTTP (EntrezHTTPQuery program' database' query') = do
let defaultProgram = "summary"
let defaultDatabase = "nucleotide"
let selectedProgram = fromMaybe defaultProgram program'
let selectedDatabase = fromMaybe defaultDatabase database'
startSession selectedProgram selectedDatabase query'
-- | Wrapper function for eutils that accept a list of querys (e.g. a list of gene ids) that ensures that only chunks of 20 queries are sent per request. Sending to long queries otherwise results in a serverside exception.
retrieveElementsEntrez :: [a] -> ([a] -> IO b) -> IO [b]
retrieveElementsEntrez listElements retrievalfunction = do
let splits = portionListElements listElements 20
mapM retrievalfunction splits
-- Auxiliary function for retrieveElementsEntrez
portionListElements :: [a] -> Int -> [[a]]
portionListElements listElements elementsPerSplit
| not (null listElements) = filter (not . null) result
| otherwise = []
where (heads,xs) = splitAt elementsPerSplit listElements
result = heads:portionListElements xs elementsPerSplit
---------------------------------------
-- Parsing functions
-- | Read entrez fetch for taxonomy database into a simplyfied datatype
-- Result of e.g: http://eutils.ncbi.nlm.nih.
readEntrezTaxonSet :: String -> [Taxon]
readEntrezTaxonSet = runLA (xreadDoc >>> parseEntrezTaxonSet)
parseEntrezTaxonSet :: ArrowXml a => a XmlTree Taxon
parseEntrezTaxonSet = atTag "TaxaSet" >>> getChildren >>>
proc entrezTaxons -> do
_taxons <- parseEntrezTaxon -< entrezTaxons
returnA -< _taxons
parseEntrezTaxon :: ArrowXml a => a XmlTree Taxon
parseEntrezTaxon = (isElem >>> hasName "Taxon") >>>
proc entrezTaxon -> do
_taxonomyId <- getChildren >>> (isElem >>> hasName "TaxId") >>> getChildren >>> getText -< entrezTaxon
_scientificName <- getChildren >>> (isElem >>> hasName "ScientificName") >>> getChildren >>> getText -< entrezTaxon
_parentTaxonomyId <- getChildren >>> (isElem >>> hasName "ParentTaxId") >>> getChildren >>> getText -< entrezTaxon
_rank <- getChildren >>> (isElem >>> hasName "Rank") >>> getChildren >>> getText -< entrezTaxon
_divison <- getChildren >>> (isElem >>> hasName "Division") >>> getChildren >>> getText -< entrezTaxon
_geneticCode <- parseTaxonGeneticCode -< entrezTaxon
_mitoGeneticCode <- parseTaxonMitoGeneticCode -< entrezTaxon
_lineage <- getChildren >>> atTag "Lineage" >>> getChildren >>> getText -< entrezTaxon
_lineageEx <- parseTaxonLineageEx -< entrezTaxon
_createDate <- getChildren >>> (isElem >>> hasName "CreateDate") >>> getChildren >>> getText -< entrezTaxon
_updateDate <- getChildren >>> (isElem >>> hasName "UpdateDate") >>> getChildren >>> getText -< entrezTaxon
_pubDate <- getChildren >>> (isElem >>> hasName "PubDate") >>> getChildren >>> getText -< entrezTaxon
returnA -< Taxon {
taxonTaxId = read _taxonomyId :: Int,
taxonScientificName = (B.pack _scientificName),
taxonParentTaxId = read _parentTaxonomyId :: Int,
taxonRank = read _rank :: Rank,
division = (B.pack _divison),
geneticCode = _geneticCode,
mitoGeneticCode = _mitoGeneticCode,
lineage = (B.pack _lineage),
lineageEx = _lineageEx,
createDate = (B.pack _createDate),
updateDate = (B.pack _updateDate),
pubDate = (B.pack _pubDate)
}
parseTaxonGeneticCode :: ArrowXml a => a XmlTree TaxGenCode
parseTaxonGeneticCode = getChildren >>> atTag "GeneticCode" >>>
proc geneticcode -> do
_gcId <- atTag "GCId" >>> getChildren >>> getText -< geneticcode
_gcName <- atTag "GCName" >>> getChildren >>> getText -< geneticcode
returnA -< TaxGenCode {
geneticCodeId = read _gcId :: Int,
abbreviation = B.empty,
geneCodeName = (B.pack _gcName),
cde = B.empty,
starts = B.empty
}
parseTaxonMitoGeneticCode :: ArrowXml a => a XmlTree TaxGenCode
parseTaxonMitoGeneticCode = getChildren >>> atTag "MitoGeneticCode" >>>
proc mitogeneticcode -> do
_mgcId <- atTag "MGCId" >>> getChildren >>> getText -< mitogeneticcode
_mgcName <- atTag "MGCName" >>> getChildren >>> getText -< mitogeneticcode
returnA -< TaxGenCode {
geneticCodeId = read _mgcId :: Int,
abbreviation = B.empty,
geneCodeName = B.pack _mgcName,
cde = B.empty,
starts = B.empty
}
parseTaxonLineageEx :: ArrowXml a => a XmlTree [LineageTaxon]
parseTaxonLineageEx = getChildren >>> atTag "LineageEx" >>>
proc taxonLineageEx -> do
_lineageEx <- listA parseLineageTaxon -< taxonLineageEx
returnA -< _lineageEx
parseLineageTaxon :: ArrowXml a => a XmlTree LineageTaxon
parseLineageTaxon = getChildren >>> atTag "Taxon" >>>
proc lineageTaxon -> do
_lineageTaxId <- atTag "TaxId" >>> getChildren >>> getText -< lineageTaxon
_lineageScienticName <- atTag "ScientificName" >>> getChildren >>> getText -< lineageTaxon
_lineageRank <- atTag "Rank" >>> getChildren >>> getText -< lineageTaxon
returnA -< LineageTaxon {
lineageTaxId = read _lineageTaxId :: Int,
lineageScienticName = (B.pack _lineageScienticName),
lineageRank = read _lineageRank :: Rank
}
-- | Read entrez fetch for taxonomy database into a simplyfied datatype
-- Result of e.g: http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=taxonomy&id=1406860
readEntrezSimpleTaxons :: String -> [SimpleTaxon]
readEntrezSimpleTaxons = runLA (xreadDoc >>> parseEntrezSimpleTaxons)
parseEntrezSimpleTaxons :: ArrowXml a => a XmlTree SimpleTaxon
parseEntrezSimpleTaxons = getChildren >>> atTag "Taxon" >>>
proc entrezSimpleTaxon -> do
simple_TaxId <- atTag "TaxId" >>> getChildren >>> getText -< entrezSimpleTaxon
simple_ScientificName <- atTag "ScientificName" >>> getChildren >>> getText -< entrezSimpleTaxon
simple_ParentTaxId <- atTag "ParentTaxId" >>> getChildren >>> getText -< entrezSimpleTaxon
simple_Rank <- atTag "Rank" >>> getChildren >>> getText -< entrezSimpleTaxon
returnA -< SimpleTaxon {
simpleTaxId = read simple_TaxId :: Int,
simpleScientificName = TL.pack simple_ScientificName,
simpleParentTaxId = read simple_ParentTaxId :: Int,
simpleRank = read simple_Rank :: Rank
}
readEntrezParentIds :: String -> [Int]
readEntrezParentIds = runLA (xreadDoc >>> parseEntrezParentTaxIds)
parseEntrezParentTaxIds :: ArrowXml a => a XmlTree Int
parseEntrezParentTaxIds = getChildren >>> atTag "Taxon" >>>
proc entrezSimpleTaxon -> do
simple_ParentTaxId <- atTag "ParentTaxId" >>> getChildren >>> getText -< entrezSimpleTaxon
returnA -< read simple_ParentTaxId :: Int
-- | Read entrez summary from internal haskell string
readEntrezSummaries :: String -> [EntrezSummary]
readEntrezSummaries = runLA (xreadDoc >>> parseEntrezSummaries)
-- | Parse entrez summary result
parseEntrezSummaries :: ArrowXml a => a XmlTree EntrezSummary
parseEntrezSummaries = atTag "eSummaryResult" >>>
proc entrezSummary -> do
document_Summaries <- listA parseEntrezDocSums -< entrezSummary
returnA -< EntrezSummary {
documentSummaries = document_Summaries
}
-- |
parseEntrezDocSums :: ArrowXml a => a XmlTree EntrezDocSum
parseEntrezDocSums = atTag "DocSum" >>>
proc entrezDocSum -> do
summary_Id <- atTag "Id" >>> getChildren >>> getText -< entrezDocSum
summary_Items <- listA parseSummaryItems -< entrezDocSum
returnA -< EntrezDocSum {
summaryId = summary_Id,
summaryItems = summary_Items
}
-- |
parseSummaryItems :: ArrowXml a => a XmlTree SummaryItem
parseSummaryItems = atTag "Item" >>>
proc summaryItem -> do
item_Name <- getAttrValue "Name" -< summaryItem
item_Type <- getAttrValue "Type" -< summaryItem
item_Content <- getText <<< getChildren -< summaryItem
returnA -< SummaryItem {
itemName = item_Name,
itemType = item_Type,
itemContent = item_Content
}
-- | Read entrez summary from internal haskell string
readEntrezSearch :: String -> [EntrezSearch]
readEntrezSearch = runLA (xreadDoc >>> parseEntrezSearch)
-- | Parse entrez search result
parseEntrezSearch :: ArrowXml a => a XmlTree EntrezSearch
parseEntrezSearch = atTag "eSearchResult" >>>
proc entrezSearch -> do
_count <- atTag "Count" >>> getChildren >>> getText -< entrezSearch
_retMax <- atTag "RetMax" >>> getChildren >>> getText -< entrezSearch
_retStart <- atTag "RetStart" >>> getChildren >>> getText -< entrezSearch
_searchIds <- atTag "IdList" >>> listA parseSearchId -< entrezSearch
_translationStack <- listA parseTranslationStack -< entrezSearch
_queryTranslation <- atTag "QueryTranslation" >>> getChildren >>> getText -< entrezSearch
returnA -< EntrezSearch {
count = readInt _count,
retMax = readInt _retMax,
retStart = readInt _retStart,
searchIds = _searchIds,
translationStack = _translationStack,
queryTranslation = _queryTranslation
}
-- | Parse entrez TranslationStack
parseSearchId :: ArrowXml a => a XmlTree Int
parseSearchId = atTag "Id" >>>
proc entrezSearchId -> do
searchId <- getChildren >>> getText -< entrezSearchId
returnA -< (readInt searchId)
-- | Parse entrez TranslationStack
parseTranslationStack :: ArrowXml a => a XmlTree TranslationStack
parseTranslationStack = atTag "TranslationStack" >>>
proc entrezTranslationStack -> do
_termSets <- listA parseTermSet -< entrezTranslationStack
_operation <- atTag "OP" >>> getChildren >>> getText -< entrezTranslationStack
returnA -< TranslationStack {
termSets = _termSets,
operation = _operation
}
-- | Parse entrez TermSet
parseTermSet :: ArrowXml a => a XmlTree TermSet
parseTermSet = atTag "TermSet" >>>
proc entrezTermSet -> do
_term <- atTag "Term" >>> getChildren >>> getText -< entrezTermSet
_field <- atTag "Field" >>> getChildren >>> getText -< entrezTermSet
_termCount <- atTag "Count" >>> getChildren >>> getText -< entrezTermSet
_explode <- atTag "Explode" >>> getChildren >>> getText -< entrezTermSet
returnA -< TermSet {
term = _term,
field = _field,
termCount = readInt _termCount,
explode = _explode
}
-- | Read entrez summary from internal haskell string
readEntrezGeneSummaries :: String -> [EntrezGeneSummary]
readEntrezGeneSummaries = runLA (xreadDoc >>> parseEntrezGeneSummaries)
-- | Parse entrez summary result
parseEntrezGeneSummaries :: ArrowXml a => a XmlTree EntrezGeneSummary
parseEntrezGeneSummaries = atTag "eSummaryResult" >>> getChildren >>> atTag "DocumentSummarySet" >>>
proc entrezSummary -> do
_geneSummaries <- listA parseEntrezGeneDocSums -< entrezSummary
returnA -< EntrezGeneSummary {
geneSummaries = _geneSummaries
}
-- |
parseEntrezGeneDocSums :: ArrowXml a => a XmlTree EntrezGeneDocSummary
parseEntrezGeneDocSums = atTag "DocumentSummary" >>>
proc entrezDocSum -> do
_geneId <- atTag "Name" >>> getChildren >>> getText -< entrezDocSum
_geneName <- atTag "Description" >>> getChildren >>> getText -< entrezDocSum
_geneStatus <- atTag "Status" >>> getChildren >>> getText -< entrezDocSum
_geneCurrentID <- atTag "CurrentID" >>> getChildren >>> getText -< entrezDocSum
_geneGeneticSource <- atTag "GeneticSource" >>> getChildren >>> getText -< entrezDocSum
_geneOtherAliases <- atTag "OtherAliases" >>> getChildren >>> getText -< entrezDocSum
_geneGenomicInfo <- parseEntrezGenomicInfo -< entrezDocSum
returnA -< EntrezGeneDocSummary {
geneId = _geneId,
geneName = _geneName,
geneStatus = _geneStatus,
geneCurrentID = _geneCurrentID,
geneGeneticSource = _geneGeneticSource,
geneOtherAliases = _geneOtherAliases,
geneGenomicInfo = _geneGenomicInfo
}
parseEntrezGenomicInfo :: ArrowXml a => a XmlTree EntrezGenomicInfo
parseEntrezGenomicInfo = atTag "GenomicInfo" >>> getChildren >>> atTag "GenomicInfoType" >>>
proc entrezGenomicInfo -> do
_chrAccVer <- atTag "ChrAccVer" >>> getChildren >>> getText -< entrezGenomicInfo
_chrStart <- atTag "ChrStart" >>> getChildren >>> getText -< entrezGenomicInfo
_chrStop <- atTag "ChrStop" >>> getChildren >>> getText -< entrezGenomicInfo
_exonCount <- atTag "ExonCount" >>> getChildren >>> getText -< entrezGenomicInfo
returnA -< EntrezGenomicInfo {
chrAccVer = _chrAccVer,
chrStart = readInt _chrStart,
chrStop = readInt _chrStop,
exonCount = readInt _exonCount
}
-- | gets all subtrees with the specified tag name
atTag :: ArrowXml a => String -> a XmlTree XmlTree
atTag tag = deep (isElem >>> hasName tag)
---------------------------------------
-- Retrieval functions
-- | Retrieve sequence for gene symbol (e.g. yhfA) from accession number (e.g. NC_000913.3) and if available entrez registration (toolname,devemail)
retrieveGeneSymbolFasta :: String -> String -> Maybe (String,String) -> IO String
retrieveGeneSymbolFasta genesymbol accession registrationInfo = do
let query1 = EntrezHTTPQuery (Just "esearch") (Just "gene") ("term=" ++ genesymbol ++ urlEncode ("[Gene Name] AND " ++ accession ++ "[Nucleotide Accession]"))
--print query1
uniqueidresponse <- entrezHTTP query1
--print uniqueidresponse
let uniqueid = head (searchIds (head (readEntrezSearch uniqueidresponse)))
let query2 = EntrezHTTPQuery (Just "esummary") (Just "gene") ("id=" ++ show uniqueid)
summaryresponse <- entrezHTTP query2
--print summaryresponse
let parsedSummary = head (geneSummaries (head (readEntrezGeneSummaries summaryresponse)))
let accessionVersion = chrAccVer (geneGenomicInfo parsedSummary)
let seqStart = chrStart (geneGenomicInfo parsedSummary)
let seqStop = chrStop (geneGenomicInfo parsedSummary)
let strand = convertCoordinatesToStrand seqStart seqStop
fetchNucleotideString accessionVersion seqStart seqStop strand registrationInfo
-- | Fetches sequence strings from the nucleotide database. nucleotideId can be a NCBI accession number or gene id.
-- Strand is 1 in case of plus strand (forward) or 2 minus (reverse) strand, the setStrand function can be used for conversion.
fetchNucleotideString :: String -> Int -> Int -> Int -> Maybe (String,String) -> IO String
fetchNucleotideString nucleotideId seqStart seqStop strand maybeRegistrationInfo = do
let registrationInfo = maybeBuildRegistration maybeRegistrationInfo
let program' = Just "efetch"
let database' = Just "nucleotide"
let query' = "id=" ++ nucleotideId ++ "&seq_start=" ++ show seqStart ++ "&seq_stop=" ++ show seqStop ++ "&rettype=fasta" ++ "&strand=" ++ show strand ++ registrationInfo
let entrezQuery = EntrezHTTPQuery program' database' query'
entrezHTTP entrezQuery
convertCoordinatesToStrand :: Int -> Int -> Int
convertCoordinatesToStrand start end
| start <= end = 1
| otherwise = 2
setStrand :: String -> Int
setStrand strandString
| strandString == "+" = 1
| strandString == "-" = 2
| strandString == "forward" = 1
| strandString == "reverse" = 2
| strandString == "Forward" = 1
| strandString == "Reverse" = 2
| strandString == "plus" = 1
| strandString == "false" = 2
| strandString == "Plus" = 1
| strandString == "False" = 2
| otherwise = 1
readInt :: String -> Int
readInt = read
-- | Builds Entrez registration String if present
maybeBuildRegistration :: Maybe (String,String) -> String
maybeBuildRegistration maybeRegistration
| isJust maybeRegistration = buildRegistration toolname developeremail
| otherwise = ""
where registration = fromJust maybeRegistration
toolname = fst registration
developeremail = snd registration
-- | Builds Entrez registration String that has to be appended to query key
buildRegistration :: String -> String -> String
buildRegistration toolname developeremail = "&tool=" ++ toolname ++ "&email=" ++ developeremail
| eggzilla/EntrezHTTP | Biobase/Entrez/HTTP.hs | gpl-3.0 | 19,474 | 18 | 18 | 3,605 | 4,307 | 2,155 | 2,152 | 317 | 1 |
-- grid is a game written in Haskell
-- Copyright (C) 2018 karamellpelle@hotmail.com
--
-- This file is part of grid.
--
-- grid 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.
--
-- grid 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 grid. If not, see <http://www.gnu.org/licenses/>.
--
module Game.Helpers.Prewarm.Plain
(
) where
import MyPrelude
#ifdef GRID_PLATFORM_IOS
#endif
| karamellpelle/grid | source/Game/Helpers/Prewarm/Plain.hs | gpl-3.0 | 850 | 0 | 3 | 154 | 34 | 30 | 4 | 3 | 0 |
{-# LANGUAGE NamedFieldPuns #-}
module Pudding.Observables.SimpleObservable
( SimpleObservable
, liftSimple
) where
import qualified Data.Vector.Unboxed as U
import Pudding.Observables.Observable
import Pudding.Observables.Separate
import Pudding.Types.Configuration (Configuration)
type SimpleObservable a = Configuration -> a
liftSimple :: (Separate a, U.Unbox a) => Estimator a -> SimpleObservable a -> Observable a
liftSimple est obs = \samples ->
est . U.fromList $ map obs samples
| jfulseca/Pudding | src/Pudding/Observables/SimpleObservable.hs | gpl-3.0 | 494 | 0 | 8 | 66 | 128 | 74 | 54 | 12 | 1 |
-- | Settings are centralized, as much as possible, into this file. This
-- includes database connection settings, static file locations, etc.
-- In addition, you can configure a number of different aspects of Yesod
-- by overriding methods in the Yesod typeclass. That instance is
-- declared in the Foundation.hs file.
module Settings where
import ClassyPrelude.Yesod
import Control.Arrow ((>>>))
import Control.Exception (throw)
import Data.Aeson (Result (..), fromJSON, withObject, (.!=),
(.:?))
import Data.FileEmbed (embedFile)
import Data.Yaml (decodeEither')
import Database.Persist.Postgresql (PostgresConf)
import Language.Haskell.TH.Syntax (Exp, Name, Q)
import Network.Wai.Handler.Warp (HostPreference)
import Yesod.Default.Config2 (applyEnvValue, configSettingsYml)
import Yesod.Default.Util (WidgetFileSettings, widgetFileNoReload,
widgetFileReload)
import Network.Mail.Mime (Address (..))
-- | Runtime settings to configure this application. These settings can be
-- loaded from various sources: defaults, environment variables, config files,
-- theoretically even a database.
data AppSettings = AppSettings
{ appStaticDir :: String
-- ^ Directory from which to serve static files.
, appDatabaseConf :: PostgresConf
-- ^ Configuration settings for accessing the database.
, appRoot :: Text
-- ^ Base for all generated URLs.
, appHost :: HostPreference
-- ^ Host/interface the server should bind to.
, appPort :: Int
-- ^ Port to listen on
, appIpFromHeader :: Bool
-- ^ Get the IP address from the header when logging. Useful when sitting
-- behind a reverse proxy.
, appDetailedRequestLogging :: Bool
-- ^ Use detailed request logging system
, appShouldLogAll :: Bool
-- ^ Should all log messages be displayed?
, appReloadTemplates :: Bool
-- ^ Use the reload version of templates
, appMutableStatic :: Bool
-- ^ Assume that files in the static dir may change after compilation
, appSkipCombining :: Bool
-- ^ Perform no stylesheet/script combining
-- Example app-specific configuration values.
, appCopyright :: Text
-- ^ Copyright text to appear in the footer of the page
, appAnalytics :: Maybe Text
-- ^ Google Analytics code
, appNotifyDelay :: Int
, appMailHost :: Text
, appMailFromName :: Maybe Text
, appMailFromAddress :: Text
, appMailListIdSuffix :: Text
}
mailHost :: AppSettings -> String
mailHost = unpack . appMailHost
mailSenderAddress :: AppSettings -> Address
mailSenderAddress = (appMailFromName &&& appMailFromAddress) >>> uncurry Address
instance FromJSON AppSettings where
parseJSON = withObject "AppSettings" $ \o -> do
let defaultDev =
#if DEVELOPMENT
True
#else
False
#endif
appStaticDir <- o .: "static-dir"
appDatabaseConf <- o .: "database"
appRoot <- o .: "approot"
appHost <- fromString <$> o .: "host"
appPort <- o .: "port"
appIpFromHeader <- o .: "ip-from-header"
appDetailedRequestLogging <- o .:? "detailed-logging" .!= defaultDev
appShouldLogAll <- o .:? "should-log-all" .!= defaultDev
appReloadTemplates <- o .:? "reload-templates" .!= defaultDev
appMutableStatic <- o .:? "mutable-static" .!= defaultDev
appSkipCombining <- o .:? "skip-combining" .!= defaultDev
appCopyright <- o .: "copyright"
appAnalytics <- o .:? "analytics"
appNotifyDelay <- o .:? "notifyDelay" .!= 10000000
appMailHost <- o .: "mailHost"
appMailFromName <- o .:? "mailFromName"
appMailFromAddress <- o .: "mailFromAddress"
appMailListIdSuffix <- o .: "mailListIdSuffix"
return AppSettings {..}
-- | Settings for 'widgetFile', such as which template languages to support and
-- default Hamlet settings.
--
-- For more information on modifying behavior, see:
--
-- https://github.com/yesodweb/yesod/wiki/Overriding-widgetFile
widgetFileSettings :: WidgetFileSettings
widgetFileSettings = def
-- | How static files should be combined.
combineSettings :: CombineSettings
combineSettings = def
-- The rest of this file contains settings which rarely need changing by a
-- user.
widgetFile :: String -> Q Exp
widgetFile = (if appReloadTemplates compileTimeAppSettings
then widgetFileReload
else widgetFileNoReload)
widgetFileSettings
-- | Raw bytes at compile time of @config/settings.yml@
configSettingsYmlBS :: ByteString
configSettingsYmlBS = $(embedFile configSettingsYml)
-- | @config/settings.yml@, parsed to a @Value@.
configSettingsYmlValue :: Value
configSettingsYmlValue = either throw id $ decodeEither' configSettingsYmlBS
-- | A version of @AppSettings@ parsed at compile time from @config/settings.yml@.
compileTimeAppSettings :: AppSettings
compileTimeAppSettings =
case fromJSON $ applyEnvValue False mempty configSettingsYmlValue of
Error e -> error e
Success settings -> settings
-- The following two functions can be used to combine multiple CSS or JS files
-- at compile time to decrease the number of http requests.
-- Sample usage (inside a Widget):
--
-- > $(combineStylesheets 'StaticR [style1_css, style2_css])
combineStylesheets :: Name -> [Route Static] -> Q Exp
combineStylesheets = combineStylesheets'
(appSkipCombining compileTimeAppSettings)
combineSettings
combineScripts :: Name -> [Route Static] -> Q Exp
combineScripts = combineScripts'
(appSkipCombining compileTimeAppSettings)
combineSettings
| mmarx/minitrue | Settings.hs | gpl-3.0 | 6,154 | 0 | 12 | 1,698 | 866 | 493 | 373 | -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.DLP.Organizations.Locations.InspectTemplates.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Lists InspectTemplates. See
-- https:\/\/cloud.google.com\/dlp\/docs\/creating-templates to learn more.
--
-- /See:/ <https://cloud.google.com/dlp/docs/ Cloud Data Loss Prevention (DLP) API Reference> for @dlp.organizations.locations.inspectTemplates.list@.
module Network.Google.Resource.DLP.Organizations.Locations.InspectTemplates.List
(
-- * REST Resource
OrganizationsLocationsInspectTemplatesListResource
-- * Creating a Request
, organizationsLocationsInspectTemplatesList
, OrganizationsLocationsInspectTemplatesList
-- * Request Lenses
, olitlParent
, olitlXgafv
, olitlUploadProtocol
, olitlOrderBy
, olitlAccessToken
, olitlUploadType
, olitlPageToken
, olitlLocationId
, olitlPageSize
, olitlCallback
) where
import Network.Google.DLP.Types
import Network.Google.Prelude
-- | A resource alias for @dlp.organizations.locations.inspectTemplates.list@ method which the
-- 'OrganizationsLocationsInspectTemplatesList' request conforms to.
type OrganizationsLocationsInspectTemplatesListResource
=
"v2" :>
Capture "parent" Text :>
"inspectTemplates" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "orderBy" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "pageToken" Text :>
QueryParam "locationId" Text :>
QueryParam "pageSize" (Textual Int32) :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON]
GooglePrivacyDlpV2ListInspectTemplatesResponse
-- | Lists InspectTemplates. See
-- https:\/\/cloud.google.com\/dlp\/docs\/creating-templates to learn more.
--
-- /See:/ 'organizationsLocationsInspectTemplatesList' smart constructor.
data OrganizationsLocationsInspectTemplatesList =
OrganizationsLocationsInspectTemplatesList'
{ _olitlParent :: !Text
, _olitlXgafv :: !(Maybe Xgafv)
, _olitlUploadProtocol :: !(Maybe Text)
, _olitlOrderBy :: !(Maybe Text)
, _olitlAccessToken :: !(Maybe Text)
, _olitlUploadType :: !(Maybe Text)
, _olitlPageToken :: !(Maybe Text)
, _olitlLocationId :: !(Maybe Text)
, _olitlPageSize :: !(Maybe (Textual Int32))
, _olitlCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'OrganizationsLocationsInspectTemplatesList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'olitlParent'
--
-- * 'olitlXgafv'
--
-- * 'olitlUploadProtocol'
--
-- * 'olitlOrderBy'
--
-- * 'olitlAccessToken'
--
-- * 'olitlUploadType'
--
-- * 'olitlPageToken'
--
-- * 'olitlLocationId'
--
-- * 'olitlPageSize'
--
-- * 'olitlCallback'
organizationsLocationsInspectTemplatesList
:: Text -- ^ 'olitlParent'
-> OrganizationsLocationsInspectTemplatesList
organizationsLocationsInspectTemplatesList pOlitlParent_ =
OrganizationsLocationsInspectTemplatesList'
{ _olitlParent = pOlitlParent_
, _olitlXgafv = Nothing
, _olitlUploadProtocol = Nothing
, _olitlOrderBy = Nothing
, _olitlAccessToken = Nothing
, _olitlUploadType = Nothing
, _olitlPageToken = Nothing
, _olitlLocationId = Nothing
, _olitlPageSize = Nothing
, _olitlCallback = Nothing
}
-- | Required. Parent resource name. The format of this value varies
-- depending on the scope of the request (project or organization) and
-- whether you have [specified a processing
-- location](https:\/\/cloud.google.com\/dlp\/docs\/specifying-location): +
-- Projects scope, location specified:
-- \`projects\/\`PROJECT_ID\`\/locations\/\`LOCATION_ID + Projects scope,
-- no location specified (defaults to global): \`projects\/\`PROJECT_ID +
-- Organizations scope, location specified:
-- \`organizations\/\`ORG_ID\`\/locations\/\`LOCATION_ID + Organizations
-- scope, no location specified (defaults to global):
-- \`organizations\/\`ORG_ID The following example \`parent\` string
-- specifies a parent project with the identifier \`example-project\`, and
-- specifies the \`europe-west3\` location for processing data:
-- parent=projects\/example-project\/locations\/europe-west3
olitlParent :: Lens' OrganizationsLocationsInspectTemplatesList Text
olitlParent
= lens _olitlParent (\ s a -> s{_olitlParent = a})
-- | V1 error format.
olitlXgafv :: Lens' OrganizationsLocationsInspectTemplatesList (Maybe Xgafv)
olitlXgafv
= lens _olitlXgafv (\ s a -> s{_olitlXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
olitlUploadProtocol :: Lens' OrganizationsLocationsInspectTemplatesList (Maybe Text)
olitlUploadProtocol
= lens _olitlUploadProtocol
(\ s a -> s{_olitlUploadProtocol = a})
-- | Comma separated list of fields to order by, followed by \`asc\` or
-- \`desc\` postfix. This list is case-insensitive, default sorting order
-- is ascending, redundant space characters are insignificant. Example:
-- \`name asc,update_time, create_time desc\` Supported fields are: -
-- \`create_time\`: corresponds to time the template was created. -
-- \`update_time\`: corresponds to time the template was last updated. -
-- \`name\`: corresponds to template\'s name. - \`display_name\`:
-- corresponds to template\'s display name.
olitlOrderBy :: Lens' OrganizationsLocationsInspectTemplatesList (Maybe Text)
olitlOrderBy
= lens _olitlOrderBy (\ s a -> s{_olitlOrderBy = a})
-- | OAuth access token.
olitlAccessToken :: Lens' OrganizationsLocationsInspectTemplatesList (Maybe Text)
olitlAccessToken
= lens _olitlAccessToken
(\ s a -> s{_olitlAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
olitlUploadType :: Lens' OrganizationsLocationsInspectTemplatesList (Maybe Text)
olitlUploadType
= lens _olitlUploadType
(\ s a -> s{_olitlUploadType = a})
-- | Page token to continue retrieval. Comes from previous call to
-- \`ListInspectTemplates\`.
olitlPageToken :: Lens' OrganizationsLocationsInspectTemplatesList (Maybe Text)
olitlPageToken
= lens _olitlPageToken
(\ s a -> s{_olitlPageToken = a})
-- | Deprecated. This field has no effect.
olitlLocationId :: Lens' OrganizationsLocationsInspectTemplatesList (Maybe Text)
olitlLocationId
= lens _olitlLocationId
(\ s a -> s{_olitlLocationId = a})
-- | Size of the page, can be limited by server. If zero server returns a
-- page of max size 100.
olitlPageSize :: Lens' OrganizationsLocationsInspectTemplatesList (Maybe Int32)
olitlPageSize
= lens _olitlPageSize
(\ s a -> s{_olitlPageSize = a})
. mapping _Coerce
-- | JSONP
olitlCallback :: Lens' OrganizationsLocationsInspectTemplatesList (Maybe Text)
olitlCallback
= lens _olitlCallback
(\ s a -> s{_olitlCallback = a})
instance GoogleRequest
OrganizationsLocationsInspectTemplatesList
where
type Rs OrganizationsLocationsInspectTemplatesList =
GooglePrivacyDlpV2ListInspectTemplatesResponse
type Scopes
OrganizationsLocationsInspectTemplatesList
= '["https://www.googleapis.com/auth/cloud-platform"]
requestClient
OrganizationsLocationsInspectTemplatesList'{..}
= go _olitlParent _olitlXgafv _olitlUploadProtocol
_olitlOrderBy
_olitlAccessToken
_olitlUploadType
_olitlPageToken
_olitlLocationId
_olitlPageSize
_olitlCallback
(Just AltJSON)
dLPService
where go
= buildClient
(Proxy ::
Proxy
OrganizationsLocationsInspectTemplatesListResource)
mempty
| brendanhay/gogol | gogol-dlp/gen/Network/Google/Resource/DLP/Organizations/Locations/InspectTemplates/List.hs | mpl-2.0 | 8,784 | 0 | 20 | 1,850 | 1,063 | 622 | 441 | 156 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.QPXExpress.Types.Product
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
module Network.Google.QPXExpress.Types.Product where
import Network.Google.Prelude
import Network.Google.QPXExpress.Types.Sum
-- | A QPX Express search response.
--
-- /See:/ 'tripOptionsResponse' smart constructor.
data TripOptionsResponse =
TripOptionsResponse'
{ _torRequestId :: !(Maybe Text)
, _torKind :: !Text
, _torData :: !(Maybe Data')
, _torTripOption :: !(Maybe [TripOption])
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'TripOptionsResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'torRequestId'
--
-- * 'torKind'
--
-- * 'torData'
--
-- * 'torTripOption'
tripOptionsResponse
:: TripOptionsResponse
tripOptionsResponse =
TripOptionsResponse'
{ _torRequestId = Nothing
, _torKind = "qpxexpress#tripOptions"
, _torData = Nothing
, _torTripOption = Nothing
}
-- | An identifier uniquely identifying this response.
torRequestId :: Lens' TripOptionsResponse (Maybe Text)
torRequestId
= lens _torRequestId (\ s a -> s{_torRequestId = a})
-- | Identifies this as a QPX Express trip response object, which consists of
-- zero or more solutions. Value: the fixed string qpxexpress#tripOptions.
torKind :: Lens' TripOptionsResponse Text
torKind = lens _torKind (\ s a -> s{_torKind = a})
-- | Informational data global to list of solutions.
torData :: Lens' TripOptionsResponse (Maybe Data')
torData = lens _torData (\ s a -> s{_torData = a})
-- | A list of priced itinerary solutions to the QPX Express query.
torTripOption :: Lens' TripOptionsResponse [TripOption]
torTripOption
= lens _torTripOption
(\ s a -> s{_torTripOption = a})
. _Default
. _Coerce
instance FromJSON TripOptionsResponse where
parseJSON
= withObject "TripOptionsResponse"
(\ o ->
TripOptionsResponse' <$>
(o .:? "requestId") <*>
(o .:? "kind" .!= "qpxexpress#tripOptions")
<*> (o .:? "data")
<*> (o .:? "tripOption" .!= mempty))
instance ToJSON TripOptionsResponse where
toJSON TripOptionsResponse'{..}
= object
(catMaybes
[("requestId" .=) <$> _torRequestId,
Just ("kind" .= _torKind), ("data" .=) <$> _torData,
("tripOption" .=) <$> _torTripOption])
-- | Information about a carrier (ie. an airline, bus line, railroad, etc)
-- that might be useful to display to an end-user.
--
-- /See:/ 'carrierData' smart constructor.
data CarrierData =
CarrierData'
{ _cdKind :: !Text
, _cdName :: !(Maybe Text)
, _cdCode :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'CarrierData' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cdKind'
--
-- * 'cdName'
--
-- * 'cdCode'
carrierData
:: CarrierData
carrierData =
CarrierData'
{_cdKind = "qpxexpress#carrierData", _cdName = Nothing, _cdCode = Nothing}
-- | Identifies this as a kind of carrier (ie. an airline, bus line,
-- railroad, etc). Value: the fixed string qpxexpress#carrierData.
cdKind :: Lens' CarrierData Text
cdKind = lens _cdKind (\ s a -> s{_cdKind = a})
-- | The long, full name of a carrier. For example: American Airlines.
cdName :: Lens' CarrierData (Maybe Text)
cdName = lens _cdName (\ s a -> s{_cdName = a})
-- | The IATA designator of a carrier (airline, etc). For example, for
-- American Airlines, the code is AA.
cdCode :: Lens' CarrierData (Maybe Text)
cdCode = lens _cdCode (\ s a -> s{_cdCode = a})
instance FromJSON CarrierData where
parseJSON
= withObject "CarrierData"
(\ o ->
CarrierData' <$>
(o .:? "kind" .!= "qpxexpress#carrierData") <*>
(o .:? "name")
<*> (o .:? "code"))
instance ToJSON CarrierData where
toJSON CarrierData'{..}
= object
(catMaybes
[Just ("kind" .= _cdKind), ("name" .=) <$> _cdName,
("code" .=) <$> _cdCode])
-- | Information about free baggage allowed on one segment of a trip.
--
-- /See:/ 'freeBaggageAllowance' smart constructor.
data FreeBaggageAllowance =
FreeBaggageAllowance'
{ _fbaKind :: !Text
, _fbaPounds :: !(Maybe (Textual Int32))
, _fbaBagDescriptor :: !(Maybe [BagDescriptor])
, _fbaKilosPerPiece :: !(Maybe (Textual Int32))
, _fbaKilos :: !(Maybe (Textual Int32))
, _fbaPieces :: !(Maybe (Textual Int32))
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'FreeBaggageAllowance' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'fbaKind'
--
-- * 'fbaPounds'
--
-- * 'fbaBagDescriptor'
--
-- * 'fbaKilosPerPiece'
--
-- * 'fbaKilos'
--
-- * 'fbaPieces'
freeBaggageAllowance
:: FreeBaggageAllowance
freeBaggageAllowance =
FreeBaggageAllowance'
{ _fbaKind = "qpxexpress#freeBaggageAllowance"
, _fbaPounds = Nothing
, _fbaBagDescriptor = Nothing
, _fbaKilosPerPiece = Nothing
, _fbaKilos = Nothing
, _fbaPieces = Nothing
}
-- | Identifies this as free baggage object, allowed on one segment of a
-- trip. Value: the fixed string qpxexpress#freeBaggageAllowance.
fbaKind :: Lens' FreeBaggageAllowance Text
fbaKind = lens _fbaKind (\ s a -> s{_fbaKind = a})
-- | The number of pounds of free baggage allowed.
fbaPounds :: Lens' FreeBaggageAllowance (Maybe Int32)
fbaPounds
= lens _fbaPounds (\ s a -> s{_fbaPounds = a}) .
mapping _Coerce
-- | A representation of a type of bag, such as an ATPCo subcode, Commercial
-- Name, or other description.
fbaBagDescriptor :: Lens' FreeBaggageAllowance [BagDescriptor]
fbaBagDescriptor
= lens _fbaBagDescriptor
(\ s a -> s{_fbaBagDescriptor = a})
. _Default
. _Coerce
-- | The maximum number of kilos any one piece of baggage may weigh.
fbaKilosPerPiece :: Lens' FreeBaggageAllowance (Maybe Int32)
fbaKilosPerPiece
= lens _fbaKilosPerPiece
(\ s a -> s{_fbaKilosPerPiece = a})
. mapping _Coerce
-- | The maximum number of kilos all the free baggage together may weigh.
fbaKilos :: Lens' FreeBaggageAllowance (Maybe Int32)
fbaKilos
= lens _fbaKilos (\ s a -> s{_fbaKilos = a}) .
mapping _Coerce
-- | The number of free pieces of baggage allowed.
fbaPieces :: Lens' FreeBaggageAllowance (Maybe Int32)
fbaPieces
= lens _fbaPieces (\ s a -> s{_fbaPieces = a}) .
mapping _Coerce
instance FromJSON FreeBaggageAllowance where
parseJSON
= withObject "FreeBaggageAllowance"
(\ o ->
FreeBaggageAllowance' <$>
(o .:? "kind" .!= "qpxexpress#freeBaggageAllowance")
<*> (o .:? "pounds")
<*> (o .:? "bagDescriptor" .!= mempty)
<*> (o .:? "kilosPerPiece")
<*> (o .:? "kilos")
<*> (o .:? "pieces"))
instance ToJSON FreeBaggageAllowance where
toJSON FreeBaggageAllowance'{..}
= object
(catMaybes
[Just ("kind" .= _fbaKind),
("pounds" .=) <$> _fbaPounds,
("bagDescriptor" .=) <$> _fbaBagDescriptor,
("kilosPerPiece" .=) <$> _fbaKilosPerPiece,
("kilos" .=) <$> _fbaKilos,
("pieces" .=) <$> _fbaPieces])
-- | Two times in a single day defining a time range.
--
-- /See:/ 'timeOfDayRange' smart constructor.
data TimeOfDayRange =
TimeOfDayRange'
{ _todrKind :: !Text
, _todrLatestTime :: !(Maybe Text)
, _todrEarliestTime :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'TimeOfDayRange' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'todrKind'
--
-- * 'todrLatestTime'
--
-- * 'todrEarliestTime'
timeOfDayRange
:: TimeOfDayRange
timeOfDayRange =
TimeOfDayRange'
{ _todrKind = "qpxexpress#timeOfDayRange"
, _todrLatestTime = Nothing
, _todrEarliestTime = Nothing
}
-- | Identifies this as a time of day range object, representing two times in
-- a single day defining a time range. Value: the fixed string
-- qpxexpress#timeOfDayRange.
todrKind :: Lens' TimeOfDayRange Text
todrKind = lens _todrKind (\ s a -> s{_todrKind = a})
-- | The latest time of day in HH:MM format.
todrLatestTime :: Lens' TimeOfDayRange (Maybe Text)
todrLatestTime
= lens _todrLatestTime
(\ s a -> s{_todrLatestTime = a})
-- | The earliest time of day in HH:MM format.
todrEarliestTime :: Lens' TimeOfDayRange (Maybe Text)
todrEarliestTime
= lens _todrEarliestTime
(\ s a -> s{_todrEarliestTime = a})
instance FromJSON TimeOfDayRange where
parseJSON
= withObject "TimeOfDayRange"
(\ o ->
TimeOfDayRange' <$>
(o .:? "kind" .!= "qpxexpress#timeOfDayRange") <*>
(o .:? "latestTime")
<*> (o .:? "earliestTime"))
instance ToJSON TimeOfDayRange where
toJSON TimeOfDayRange'{..}
= object
(catMaybes
[Just ("kind" .= _todrKind),
("latestTime" .=) <$> _todrLatestTime,
("earliestTime" .=) <$> _todrEarliestTime])
-- | Detailed information about components found in the solutions of this
-- response, including a trip\'s airport, city, taxes, airline, and
-- aircraft.
--
-- /See:/ 'data'' smart constructor.
data Data' =
Data''
{ _dCarrier :: !(Maybe [CarrierData])
, _dKind :: !Text
, _dAircraft :: !(Maybe [AircraftData])
, _dAirport :: !(Maybe [AirportData])
, _dCity :: !(Maybe [CityData])
, _dTax :: !(Maybe [TaxData])
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Data' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'dCarrier'
--
-- * 'dKind'
--
-- * 'dAircraft'
--
-- * 'dAirport'
--
-- * 'dCity'
--
-- * 'dTax'
data'
:: Data'
data' =
Data''
{ _dCarrier = Nothing
, _dKind = "qpxexpress#data"
, _dAircraft = Nothing
, _dAirport = Nothing
, _dCity = Nothing
, _dTax = Nothing
}
-- | The airline carrier of the aircraft flying between an origin and
-- destination. Allowed values are IATA carrier codes.
dCarrier :: Lens' Data' [CarrierData]
dCarrier
= lens _dCarrier (\ s a -> s{_dCarrier = a}) .
_Default
. _Coerce
-- | Identifies this as QPX Express response resource, including a trip\'s
-- airport, city, taxes, airline, and aircraft. Value: the fixed string
-- qpxexpress#data.
dKind :: Lens' Data' Text
dKind = lens _dKind (\ s a -> s{_dKind = a})
-- | The aircraft that is flying between an origin and destination.
dAircraft :: Lens' Data' [AircraftData]
dAircraft
= lens _dAircraft (\ s a -> s{_dAircraft = a}) .
_Default
. _Coerce
-- | The airport of an origin or destination.
dAirport :: Lens' Data' [AirportData]
dAirport
= lens _dAirport (\ s a -> s{_dAirport = a}) .
_Default
. _Coerce
-- | The city that is either the origin or destination of part of a trip.
dCity :: Lens' Data' [CityData]
dCity
= lens _dCity (\ s a -> s{_dCity = a}) . _Default .
_Coerce
-- | The taxes due for flying between an origin and a destination.
dTax :: Lens' Data' [TaxData]
dTax
= lens _dTax (\ s a -> s{_dTax = a}) . _Default .
_Coerce
instance FromJSON Data' where
parseJSON
= withObject "Data"
(\ o ->
Data'' <$>
(o .:? "carrier" .!= mempty) <*>
(o .:? "kind" .!= "qpxexpress#data")
<*> (o .:? "aircraft" .!= mempty)
<*> (o .:? "airport" .!= mempty)
<*> (o .:? "city" .!= mempty)
<*> (o .:? "tax" .!= mempty))
instance ToJSON Data' where
toJSON Data''{..}
= object
(catMaybes
[("carrier" .=) <$> _dCarrier,
Just ("kind" .= _dKind),
("aircraft" .=) <$> _dAircraft,
("airport" .=) <$> _dAirport, ("city" .=) <$> _dCity,
("tax" .=) <$> _dTax])
-- | The make, model, and type of an aircraft.
--
-- /See:/ 'aircraftData' smart constructor.
data AircraftData =
AircraftData'
{ _adKind :: !Text
, _adName :: !(Maybe Text)
, _adCode :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'AircraftData' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'adKind'
--
-- * 'adName'
--
-- * 'adCode'
aircraftData
:: AircraftData
aircraftData =
AircraftData'
{_adKind = "qpxexpress#aircraftData", _adName = Nothing, _adCode = Nothing}
-- | Identifies this as an aircraftData object. Value: the fixed string
-- qpxexpress#aircraftData
adKind :: Lens' AircraftData Text
adKind = lens _adKind (\ s a -> s{_adKind = a})
-- | The name of an aircraft, for example Boeing 777.
adName :: Lens' AircraftData (Maybe Text)
adName = lens _adName (\ s a -> s{_adName = a})
-- | The aircraft code. For example, for a Boeing 777 the code would be 777.
adCode :: Lens' AircraftData (Maybe Text)
adCode = lens _adCode (\ s a -> s{_adCode = a})
instance FromJSON AircraftData where
parseJSON
= withObject "AircraftData"
(\ o ->
AircraftData' <$>
(o .:? "kind" .!= "qpxexpress#aircraftData") <*>
(o .:? "name")
<*> (o .:? "code"))
instance ToJSON AircraftData where
toJSON AircraftData'{..}
= object
(catMaybes
[Just ("kind" .= _adKind), ("name" .=) <$> _adName,
("code" .=) <$> _adCode])
-- | Information about a leg. (A leg is the smallest unit of travel, in the
-- case of a flight a takeoff immediately followed by a landing at two set
-- points on a particular carrier with a particular flight number.)
--
-- /See:/ 'legInfo' smart constructor.
data LegInfo =
LegInfo'
{ _liDestination :: !(Maybe Text)
, _liOrigin :: !(Maybe Text)
, _liSecure :: !(Maybe Bool)
, _liKind :: !Text
, _liAircraft :: !(Maybe Text)
, _liArrivalTime :: !(Maybe Text)
, _liOnTimePerformance :: !(Maybe (Textual Int32))
, _liOperatingDisclosure :: !(Maybe Text)
, _liMeal :: !(Maybe Text)
, _liId :: !(Maybe Text)
, _liOriginTerminal :: !(Maybe Text)
, _liChangePlane :: !(Maybe Bool)
, _liDestinationTerminal :: !(Maybe Text)
, _liConnectionDuration :: !(Maybe (Textual Int32))
, _liDuration :: !(Maybe (Textual Int32))
, _liMileage :: !(Maybe (Textual Int32))
, _liDePartureTime :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'LegInfo' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'liDestination'
--
-- * 'liOrigin'
--
-- * 'liSecure'
--
-- * 'liKind'
--
-- * 'liAircraft'
--
-- * 'liArrivalTime'
--
-- * 'liOnTimePerformance'
--
-- * 'liOperatingDisclosure'
--
-- * 'liMeal'
--
-- * 'liId'
--
-- * 'liOriginTerminal'
--
-- * 'liChangePlane'
--
-- * 'liDestinationTerminal'
--
-- * 'liConnectionDuration'
--
-- * 'liDuration'
--
-- * 'liMileage'
--
-- * 'liDePartureTime'
legInfo
:: LegInfo
legInfo =
LegInfo'
{ _liDestination = Nothing
, _liOrigin = Nothing
, _liSecure = Nothing
, _liKind = "qpxexpress#legInfo"
, _liAircraft = Nothing
, _liArrivalTime = Nothing
, _liOnTimePerformance = Nothing
, _liOperatingDisclosure = Nothing
, _liMeal = Nothing
, _liId = Nothing
, _liOriginTerminal = Nothing
, _liChangePlane = Nothing
, _liDestinationTerminal = Nothing
, _liConnectionDuration = Nothing
, _liDuration = Nothing
, _liMileage = Nothing
, _liDePartureTime = Nothing
}
-- | The leg destination as a city and airport.
liDestination :: Lens' LegInfo (Maybe Text)
liDestination
= lens _liDestination
(\ s a -> s{_liDestination = a})
-- | The leg origin as a city and airport.
liOrigin :: Lens' LegInfo (Maybe Text)
liOrigin = lens _liOrigin (\ s a -> s{_liOrigin = a})
-- | Whether passenger information must be furnished to the United States
-- Transportation Security Administration (TSA) prior to departure.
liSecure :: Lens' LegInfo (Maybe Bool)
liSecure = lens _liSecure (\ s a -> s{_liSecure = a})
-- | Identifies this as a leg object. A leg is the smallest unit of travel,
-- in the case of a flight a takeoff immediately followed by a landing at
-- two set points on a particular carrier with a particular flight number.
-- Value: the fixed string qpxexpress#legInfo.
liKind :: Lens' LegInfo Text
liKind = lens _liKind (\ s a -> s{_liKind = a})
-- | The aircraft (or bus, ferry, railcar, etc) travelling between the two
-- points of this leg.
liAircraft :: Lens' LegInfo (Maybe Text)
liAircraft
= lens _liAircraft (\ s a -> s{_liAircraft = a})
-- | The scheduled time of arrival at the destination of the leg, local to
-- the point of arrival.
liArrivalTime :: Lens' LegInfo (Maybe Text)
liArrivalTime
= lens _liArrivalTime
(\ s a -> s{_liArrivalTime = a})
-- | In percent, the published on time performance on this leg.
liOnTimePerformance :: Lens' LegInfo (Maybe Int32)
liOnTimePerformance
= lens _liOnTimePerformance
(\ s a -> s{_liOnTimePerformance = a})
. mapping _Coerce
-- | Department of Transportation disclosure information on the actual
-- operator of a flight in a code share. (A code share refers to a
-- marketing agreement between two carriers, where one carrier will list in
-- its schedules (and take bookings for) flights that are actually operated
-- by another carrier.)
liOperatingDisclosure :: Lens' LegInfo (Maybe Text)
liOperatingDisclosure
= lens _liOperatingDisclosure
(\ s a -> s{_liOperatingDisclosure = a})
-- | A simple, general description of the meal(s) served on the flight, for
-- example: \"Hot meal\".
liMeal :: Lens' LegInfo (Maybe Text)
liMeal = lens _liMeal (\ s a -> s{_liMeal = a})
-- | An identifier that uniquely identifies this leg in the solution.
liId :: Lens' LegInfo (Maybe Text)
liId = lens _liId (\ s a -> s{_liId = a})
-- | The terminal the flight is scheduled to depart from.
liOriginTerminal :: Lens' LegInfo (Maybe Text)
liOriginTerminal
= lens _liOriginTerminal
(\ s a -> s{_liOriginTerminal = a})
-- | Whether you have to change planes following this leg. Only applies to
-- the next leg.
liChangePlane :: Lens' LegInfo (Maybe Bool)
liChangePlane
= lens _liChangePlane
(\ s a -> s{_liChangePlane = a})
-- | The terminal the flight is scheduled to arrive at.
liDestinationTerminal :: Lens' LegInfo (Maybe Text)
liDestinationTerminal
= lens _liDestinationTerminal
(\ s a -> s{_liDestinationTerminal = a})
-- | Duration of a connection following this leg, in minutes.
liConnectionDuration :: Lens' LegInfo (Maybe Int32)
liConnectionDuration
= lens _liConnectionDuration
(\ s a -> s{_liConnectionDuration = a})
. mapping _Coerce
-- | The scheduled travelling time from the origin to the destination.
liDuration :: Lens' LegInfo (Maybe Int32)
liDuration
= lens _liDuration (\ s a -> s{_liDuration = a}) .
mapping _Coerce
-- | The number of miles in this leg.
liMileage :: Lens' LegInfo (Maybe Int32)
liMileage
= lens _liMileage (\ s a -> s{_liMileage = a}) .
mapping _Coerce
-- | The scheduled departure time of the leg, local to the point of
-- departure.
liDePartureTime :: Lens' LegInfo (Maybe Text)
liDePartureTime
= lens _liDePartureTime
(\ s a -> s{_liDePartureTime = a})
instance FromJSON LegInfo where
parseJSON
= withObject "LegInfo"
(\ o ->
LegInfo' <$>
(o .:? "destination") <*> (o .:? "origin") <*>
(o .:? "secure")
<*> (o .:? "kind" .!= "qpxexpress#legInfo")
<*> (o .:? "aircraft")
<*> (o .:? "arrivalTime")
<*> (o .:? "onTimePerformance")
<*> (o .:? "operatingDisclosure")
<*> (o .:? "meal")
<*> (o .:? "id")
<*> (o .:? "originTerminal")
<*> (o .:? "changePlane")
<*> (o .:? "destinationTerminal")
<*> (o .:? "connectionDuration")
<*> (o .:? "duration")
<*> (o .:? "mileage")
<*> (o .:? "departureTime"))
instance ToJSON LegInfo where
toJSON LegInfo'{..}
= object
(catMaybes
[("destination" .=) <$> _liDestination,
("origin" .=) <$> _liOrigin,
("secure" .=) <$> _liSecure,
Just ("kind" .= _liKind),
("aircraft" .=) <$> _liAircraft,
("arrivalTime" .=) <$> _liArrivalTime,
("onTimePerformance" .=) <$> _liOnTimePerformance,
("operatingDisclosure" .=) <$>
_liOperatingDisclosure,
("meal" .=) <$> _liMeal, ("id" .=) <$> _liId,
("originTerminal" .=) <$> _liOriginTerminal,
("changePlane" .=) <$> _liChangePlane,
("destinationTerminal" .=) <$>
_liDestinationTerminal,
("connectionDuration" .=) <$> _liConnectionDuration,
("duration" .=) <$> _liDuration,
("mileage" .=) <$> _liMileage,
("departureTime" .=) <$> _liDePartureTime])
-- | An airport.
--
-- /See:/ 'airportData' smart constructor.
data AirportData =
AirportData'
{ _aKind :: !Text
, _aName :: !(Maybe Text)
, _aCity :: !(Maybe Text)
, _aCode :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'AirportData' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'aKind'
--
-- * 'aName'
--
-- * 'aCity'
--
-- * 'aCode'
airportData
:: AirportData
airportData =
AirportData'
{ _aKind = "qpxexpress#airportData"
, _aName = Nothing
, _aCity = Nothing
, _aCode = Nothing
}
-- | Identifies this as an airport object. Value: the fixed string
-- qpxexpress#airportData.
aKind :: Lens' AirportData Text
aKind = lens _aKind (\ s a -> s{_aKind = a})
-- | The name of an airport. For example, for airport BOS the name is
-- \"Boston Logan International\".
aName :: Lens' AirportData (Maybe Text)
aName = lens _aName (\ s a -> s{_aName = a})
-- | The city code an airport is located in. For example, for JFK airport,
-- this is NYC.
aCity :: Lens' AirportData (Maybe Text)
aCity = lens _aCity (\ s a -> s{_aCity = a})
-- | An airport\'s code. For example, for Boston Logan airport, this is BOS.
aCode :: Lens' AirportData (Maybe Text)
aCode = lens _aCode (\ s a -> s{_aCode = a})
instance FromJSON AirportData where
parseJSON
= withObject "AirportData"
(\ o ->
AirportData' <$>
(o .:? "kind" .!= "qpxexpress#airportData") <*>
(o .:? "name")
<*> (o .:? "city")
<*> (o .:? "code"))
instance ToJSON AirportData where
toJSON AirportData'{..}
= object
(catMaybes
[Just ("kind" .= _aKind), ("name" .=) <$> _aName,
("city" .=) <$> _aCity, ("code" .=) <$> _aCode])
-- | The price of this segment.
--
-- /See:/ 'segmentPricing' smart constructor.
data SegmentPricing =
SegmentPricing'
{ _spFreeBaggageOption :: !(Maybe [FreeBaggageAllowance])
, _spKind :: !Text
, _spFareId :: !(Maybe Text)
, _spSegmentId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'SegmentPricing' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'spFreeBaggageOption'
--
-- * 'spKind'
--
-- * 'spFareId'
--
-- * 'spSegmentId'
segmentPricing
:: SegmentPricing
segmentPricing =
SegmentPricing'
{ _spFreeBaggageOption = Nothing
, _spKind = "qpxexpress#segmentPricing"
, _spFareId = Nothing
, _spSegmentId = Nothing
}
-- | Details of the free baggage allowance on this segment.
spFreeBaggageOption :: Lens' SegmentPricing [FreeBaggageAllowance]
spFreeBaggageOption
= lens _spFreeBaggageOption
(\ s a -> s{_spFreeBaggageOption = a})
. _Default
. _Coerce
-- | Identifies this as a segment pricing object, representing the price of
-- this segment. Value: the fixed string qpxexpress#segmentPricing.
spKind :: Lens' SegmentPricing Text
spKind = lens _spKind (\ s a -> s{_spKind = a})
-- | A segment identifier unique within a single solution. It is used to
-- refer to different parts of the same solution.
spFareId :: Lens' SegmentPricing (Maybe Text)
spFareId = lens _spFareId (\ s a -> s{_spFareId = a})
-- | Unique identifier in the response of this segment.
spSegmentId :: Lens' SegmentPricing (Maybe Text)
spSegmentId
= lens _spSegmentId (\ s a -> s{_spSegmentId = a})
instance FromJSON SegmentPricing where
parseJSON
= withObject "SegmentPricing"
(\ o ->
SegmentPricing' <$>
(o .:? "freeBaggageOption" .!= mempty) <*>
(o .:? "kind" .!= "qpxexpress#segmentPricing")
<*> (o .:? "fareId")
<*> (o .:? "segmentId"))
instance ToJSON SegmentPricing where
toJSON SegmentPricing'{..}
= object
(catMaybes
[("freeBaggageOption" .=) <$> _spFreeBaggageOption,
Just ("kind" .= _spKind),
("fareId" .=) <$> _spFareId,
("segmentId" .=) <$> _spSegmentId])
-- | Information about a slice. A slice represents a traveller\'s intent, the
-- portion of a low-fare search corresponding to a traveler\'s request to
-- get between two points. One-way journeys are generally expressed using 1
-- slice, round-trips using 2. For example, if a traveler specifies the
-- following trip in a user interface: | Origin | Destination | Departure
-- Date | | BOS | LAX | March 10, 2007 | | LAX | SYD | March 17, 2007 | |
-- SYD | BOS | March 22, 2007 | then this is a three slice trip.
--
-- /See:/ 'sliceInfo' smart constructor.
data SliceInfo =
SliceInfo'
{ _siKind :: !Text
, _siSegment :: !(Maybe [SegmentInfo])
, _siDuration :: !(Maybe (Textual Int32))
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'SliceInfo' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'siKind'
--
-- * 'siSegment'
--
-- * 'siDuration'
sliceInfo
:: SliceInfo
sliceInfo =
SliceInfo'
{ _siKind = "qpxexpress#sliceInfo"
, _siSegment = Nothing
, _siDuration = Nothing
}
-- | Identifies this as a slice object. A slice represents a traveller\'s
-- intent, the portion of a low-fare search corresponding to a traveler\'s
-- request to get between two points. One-way journeys are generally
-- expressed using 1 slice, round-trips using 2. Value: the fixed string
-- qpxexpress#sliceInfo.
siKind :: Lens' SliceInfo Text
siKind = lens _siKind (\ s a -> s{_siKind = a})
-- | The segment(s) constituting the slice.
siSegment :: Lens' SliceInfo [SegmentInfo]
siSegment
= lens _siSegment (\ s a -> s{_siSegment = a}) .
_Default
. _Coerce
-- | The duration of the slice in minutes.
siDuration :: Lens' SliceInfo (Maybe Int32)
siDuration
= lens _siDuration (\ s a -> s{_siDuration = a}) .
mapping _Coerce
instance FromJSON SliceInfo where
parseJSON
= withObject "SliceInfo"
(\ o ->
SliceInfo' <$>
(o .:? "kind" .!= "qpxexpress#sliceInfo") <*>
(o .:? "segment" .!= mempty)
<*> (o .:? "duration"))
instance ToJSON SliceInfo where
toJSON SliceInfo'{..}
= object
(catMaybes
[Just ("kind" .= _siKind),
("segment" .=) <$> _siSegment,
("duration" .=) <$> _siDuration])
-- | A QPX Express search response.
--
-- /See:/ 'tripsSearchResponse' smart constructor.
data TripsSearchResponse =
TripsSearchResponse'
{ _tsrTrips :: !(Maybe TripOptionsResponse)
, _tsrKind :: !Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'TripsSearchResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tsrTrips'
--
-- * 'tsrKind'
tripsSearchResponse
:: TripsSearchResponse
tripsSearchResponse =
TripsSearchResponse'
{_tsrTrips = Nothing, _tsrKind = "qpxExpress#tripsSearch"}
-- | All possible solutions to the QPX Express search request.
tsrTrips :: Lens' TripsSearchResponse (Maybe TripOptionsResponse)
tsrTrips = lens _tsrTrips (\ s a -> s{_tsrTrips = a})
-- | Identifies this as a QPX Express API search response resource. Value:
-- the fixed string qpxExpress#tripsSearch.
tsrKind :: Lens' TripsSearchResponse Text
tsrKind = lens _tsrKind (\ s a -> s{_tsrKind = a})
instance FromJSON TripsSearchResponse where
parseJSON
= withObject "TripsSearchResponse"
(\ o ->
TripsSearchResponse' <$>
(o .:? "trips") <*>
(o .:? "kind" .!= "qpxExpress#tripsSearch"))
instance ToJSON TripsSearchResponse where
toJSON TripsSearchResponse'{..}
= object
(catMaybes
[("trips" .=) <$> _tsrTrips,
Just ("kind" .= _tsrKind)])
-- | Trip information.
--
-- /See:/ 'tripOption' smart constructor.
data TripOption =
TripOption'
{ _toPricing :: !(Maybe [PricingInfo])
, _toKind :: !Text
, _toId :: !(Maybe Text)
, _toSlice :: !(Maybe [SliceInfo])
, _toSaleTotal :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'TripOption' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'toPricing'
--
-- * 'toKind'
--
-- * 'toId'
--
-- * 'toSlice'
--
-- * 'toSaleTotal'
tripOption
:: TripOption
tripOption =
TripOption'
{ _toPricing = Nothing
, _toKind = "qpxexpress#tripOption"
, _toId = Nothing
, _toSlice = Nothing
, _toSaleTotal = Nothing
}
-- | Per passenger pricing information.
toPricing :: Lens' TripOption [PricingInfo]
toPricing
= lens _toPricing (\ s a -> s{_toPricing = a}) .
_Default
. _Coerce
-- | Identifies this as a trip information object. Value: the fixed string
-- qpxexpress#tripOption.
toKind :: Lens' TripOption Text
toKind = lens _toKind (\ s a -> s{_toKind = a})
-- | Identifier uniquely identifying this trip in a response.
toId :: Lens' TripOption (Maybe Text)
toId = lens _toId (\ s a -> s{_toId = a})
-- | The slices that make up this trip\'s itinerary.
toSlice :: Lens' TripOption [SliceInfo]
toSlice
= lens _toSlice (\ s a -> s{_toSlice = a}) . _Default
. _Coerce
-- | The total price for all passengers on the trip, in the form of a
-- currency followed by an amount, e.g. USD253.35.
toSaleTotal :: Lens' TripOption (Maybe Text)
toSaleTotal
= lens _toSaleTotal (\ s a -> s{_toSaleTotal = a})
instance FromJSON TripOption where
parseJSON
= withObject "TripOption"
(\ o ->
TripOption' <$>
(o .:? "pricing" .!= mempty) <*>
(o .:? "kind" .!= "qpxexpress#tripOption")
<*> (o .:? "id")
<*> (o .:? "slice" .!= mempty)
<*> (o .:? "saleTotal"))
instance ToJSON TripOption where
toJSON TripOption'{..}
= object
(catMaybes
[("pricing" .=) <$> _toPricing,
Just ("kind" .= _toKind), ("id" .=) <$> _toId,
("slice" .=) <$> _toSlice,
("saleTotal" .=) <$> _toSaleTotal])
-- | Information about an item of baggage.
--
-- /See:/ 'bagDescriptor' smart constructor.
data BagDescriptor =
BagDescriptor'
{ _bdKind :: !Text
, _bdCommercialName :: !(Maybe Text)
, _bdCount :: !(Maybe (Textual Int32))
, _bdDescription :: !(Maybe [Text])
, _bdSubcode :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'BagDescriptor' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'bdKind'
--
-- * 'bdCommercialName'
--
-- * 'bdCount'
--
-- * 'bdDescription'
--
-- * 'bdSubcode'
bagDescriptor
:: BagDescriptor
bagDescriptor =
BagDescriptor'
{ _bdKind = "qpxexpress#bagDescriptor"
, _bdCommercialName = Nothing
, _bdCount = Nothing
, _bdDescription = Nothing
, _bdSubcode = Nothing
}
-- | Identifies this as a baggage object. Value: the fixed string
-- qpxexpress#bagDescriptor.
bdKind :: Lens' BagDescriptor Text
bdKind = lens _bdKind (\ s a -> s{_bdKind = a})
-- | Provides the commercial name for an optional service.
bdCommercialName :: Lens' BagDescriptor (Maybe Text)
bdCommercialName
= lens _bdCommercialName
(\ s a -> s{_bdCommercialName = a})
-- | How many of this type of bag will be checked on this flight.
bdCount :: Lens' BagDescriptor (Maybe Int32)
bdCount
= lens _bdCount (\ s a -> s{_bdCount = a}) .
mapping _Coerce
-- | A description of the baggage.
bdDescription :: Lens' BagDescriptor [Text]
bdDescription
= lens _bdDescription
(\ s a -> s{_bdDescription = a})
. _Default
. _Coerce
-- | The standard IATA subcode used to identify this optional service.
bdSubcode :: Lens' BagDescriptor (Maybe Text)
bdSubcode
= lens _bdSubcode (\ s a -> s{_bdSubcode = a})
instance FromJSON BagDescriptor where
parseJSON
= withObject "BagDescriptor"
(\ o ->
BagDescriptor' <$>
(o .:? "kind" .!= "qpxexpress#bagDescriptor") <*>
(o .:? "commercialName")
<*> (o .:? "count")
<*> (o .:? "description" .!= mempty)
<*> (o .:? "subcode"))
instance ToJSON BagDescriptor where
toJSON BagDescriptor'{..}
= object
(catMaybes
[Just ("kind" .= _bdKind),
("commercialName" .=) <$> _bdCommercialName,
("count" .=) <$> _bdCount,
("description" .=) <$> _bdDescription,
("subcode" .=) <$> _bdSubcode])
-- | Information about a city that might be useful to an end-user; typically
-- the city of an airport.
--
-- /See:/ 'cityData' smart constructor.
data CityData =
CityData'
{ _cCountry :: !(Maybe Text)
, _cKind :: !Text
, _cName :: !(Maybe Text)
, _cCode :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'CityData' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cCountry'
--
-- * 'cKind'
--
-- * 'cName'
--
-- * 'cCode'
cityData
:: CityData
cityData =
CityData'
{ _cCountry = Nothing
, _cKind = "qpxexpress#cityData"
, _cName = Nothing
, _cCode = Nothing
}
-- | The two-character country code of the country the city is located in.
-- For example, US for the United States of America.
cCountry :: Lens' CityData (Maybe Text)
cCountry = lens _cCountry (\ s a -> s{_cCountry = a})
-- | Identifies this as a city, typically with one or more airports. Value:
-- the fixed string qpxexpress#cityData.
cKind :: Lens' CityData Text
cKind = lens _cKind (\ s a -> s{_cKind = a})
-- | The full name of a city. An example would be: New York.
cName :: Lens' CityData (Maybe Text)
cName = lens _cName (\ s a -> s{_cName = a})
-- | The IATA character ID of a city. For example, for Boston this is BOS.
cCode :: Lens' CityData (Maybe Text)
cCode = lens _cCode (\ s a -> s{_cCode = a})
instance FromJSON CityData where
parseJSON
= withObject "CityData"
(\ o ->
CityData' <$>
(o .:? "country") <*>
(o .:? "kind" .!= "qpxexpress#cityData")
<*> (o .:? "name")
<*> (o .:? "code"))
instance ToJSON CityData where
toJSON CityData'{..}
= object
(catMaybes
[("country" .=) <$> _cCountry,
Just ("kind" .= _cKind), ("name" .=) <$> _cName,
("code" .=) <$> _cCode])
-- | The number and type of passengers. Unfortunately the definition of an
-- infant, child, adult, and senior citizen varies across carriers and
-- reservation systems.
--
-- /See:/ 'passengerCounts' smart constructor.
data PassengerCounts =
PassengerCounts'
{ _pcSeniorCount :: !(Maybe (Textual Int32))
, _pcKind :: !Text
, _pcInfantInLapCount :: !(Maybe (Textual Int32))
, _pcChildCount :: !(Maybe (Textual Int32))
, _pcInfantInSeatCount :: !(Maybe (Textual Int32))
, _pcAdultCount :: !(Maybe (Textual Int32))
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'PassengerCounts' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pcSeniorCount'
--
-- * 'pcKind'
--
-- * 'pcInfantInLapCount'
--
-- * 'pcChildCount'
--
-- * 'pcInfantInSeatCount'
--
-- * 'pcAdultCount'
passengerCounts
:: PassengerCounts
passengerCounts =
PassengerCounts'
{ _pcSeniorCount = Nothing
, _pcKind = "qpxexpress#passengerCounts"
, _pcInfantInLapCount = Nothing
, _pcChildCount = Nothing
, _pcInfantInSeatCount = Nothing
, _pcAdultCount = Nothing
}
-- | The number of passengers that are senior citizens.
pcSeniorCount :: Lens' PassengerCounts (Maybe Int32)
pcSeniorCount
= lens _pcSeniorCount
(\ s a -> s{_pcSeniorCount = a})
. mapping _Coerce
-- | Identifies this as a passenger count object, representing the number of
-- passengers. Value: the fixed string qpxexpress#passengerCounts.
pcKind :: Lens' PassengerCounts Text
pcKind = lens _pcKind (\ s a -> s{_pcKind = a})
-- | The number of passengers that are infants travelling in the lap of an
-- adult.
pcInfantInLapCount :: Lens' PassengerCounts (Maybe Int32)
pcInfantInLapCount
= lens _pcInfantInLapCount
(\ s a -> s{_pcInfantInLapCount = a})
. mapping _Coerce
-- | The number of passengers that are children.
pcChildCount :: Lens' PassengerCounts (Maybe Int32)
pcChildCount
= lens _pcChildCount (\ s a -> s{_pcChildCount = a})
. mapping _Coerce
-- | The number of passengers that are infants each assigned a seat.
pcInfantInSeatCount :: Lens' PassengerCounts (Maybe Int32)
pcInfantInSeatCount
= lens _pcInfantInSeatCount
(\ s a -> s{_pcInfantInSeatCount = a})
. mapping _Coerce
-- | The number of passengers that are adults.
pcAdultCount :: Lens' PassengerCounts (Maybe Int32)
pcAdultCount
= lens _pcAdultCount (\ s a -> s{_pcAdultCount = a})
. mapping _Coerce
instance FromJSON PassengerCounts where
parseJSON
= withObject "PassengerCounts"
(\ o ->
PassengerCounts' <$>
(o .:? "seniorCount") <*>
(o .:? "kind" .!= "qpxexpress#passengerCounts")
<*> (o .:? "infantInLapCount")
<*> (o .:? "childCount")
<*> (o .:? "infantInSeatCount")
<*> (o .:? "adultCount"))
instance ToJSON PassengerCounts where
toJSON PassengerCounts'{..}
= object
(catMaybes
[("seniorCount" .=) <$> _pcSeniorCount,
Just ("kind" .= _pcKind),
("infantInLapCount" .=) <$> _pcInfantInLapCount,
("childCount" .=) <$> _pcChildCount,
("infantInSeatCount" .=) <$> _pcInfantInSeatCount,
("adultCount" .=) <$> _pcAdultCount])
-- | Details of a segment of a flight; a segment is one or more consecutive
-- legs on the same flight. For example a hypothetical flight ZZ001, from
-- DFW to OGG, would have one segment with two legs: DFW to HNL (leg 1),
-- HNL to OGG (leg 2), and DFW to OGG (legs 1 and 2).
--
-- /See:/ 'segmentInfo' smart constructor.
data SegmentInfo =
SegmentInfo'
{ _sBookingCode :: !(Maybe Text)
, _sCabin :: !(Maybe Text)
, _sBookingCodeCount :: !(Maybe (Textual Int32))
, _sSubjectToGovernmentApproval :: !(Maybe Bool)
, _sKind :: !Text
, _sFlight :: !(Maybe FlightInfo)
, _sId :: !(Maybe Text)
, _sMarriedSegmentGroup :: !(Maybe Text)
, _sConnectionDuration :: !(Maybe (Textual Int32))
, _sDuration :: !(Maybe (Textual Int32))
, _sLeg :: !(Maybe [LegInfo])
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'SegmentInfo' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'sBookingCode'
--
-- * 'sCabin'
--
-- * 'sBookingCodeCount'
--
-- * 'sSubjectToGovernmentApproval'
--
-- * 'sKind'
--
-- * 'sFlight'
--
-- * 'sId'
--
-- * 'sMarriedSegmentGroup'
--
-- * 'sConnectionDuration'
--
-- * 'sDuration'
--
-- * 'sLeg'
segmentInfo
:: SegmentInfo
segmentInfo =
SegmentInfo'
{ _sBookingCode = Nothing
, _sCabin = Nothing
, _sBookingCodeCount = Nothing
, _sSubjectToGovernmentApproval = Nothing
, _sKind = "qpxexpress#segmentInfo"
, _sFlight = Nothing
, _sId = Nothing
, _sMarriedSegmentGroup = Nothing
, _sConnectionDuration = Nothing
, _sDuration = Nothing
, _sLeg = Nothing
}
-- | The booking code or class for this segment.
sBookingCode :: Lens' SegmentInfo (Maybe Text)
sBookingCode
= lens _sBookingCode (\ s a -> s{_sBookingCode = a})
-- | The cabin booked for this segment.
sCabin :: Lens' SegmentInfo (Maybe Text)
sCabin = lens _sCabin (\ s a -> s{_sCabin = a})
-- | The number of seats available in this booking code on this segment.
sBookingCodeCount :: Lens' SegmentInfo (Maybe Int32)
sBookingCodeCount
= lens _sBookingCodeCount
(\ s a -> s{_sBookingCodeCount = a})
. mapping _Coerce
-- | Whether the operation of this segment remains subject to government
-- approval.
sSubjectToGovernmentApproval :: Lens' SegmentInfo (Maybe Bool)
sSubjectToGovernmentApproval
= lens _sSubjectToGovernmentApproval
(\ s a -> s{_sSubjectToGovernmentApproval = a})
-- | Identifies this as a segment object. A segment is one or more
-- consecutive legs on the same flight. For example a hypothetical flight
-- ZZ001, from DFW to OGG, could have one segment with two legs: DFW to HNL
-- (leg 1), HNL to OGG (leg 2). Value: the fixed string
-- qpxexpress#segmentInfo.
sKind :: Lens' SegmentInfo Text
sKind = lens _sKind (\ s a -> s{_sKind = a})
-- | The flight this is a segment of.
sFlight :: Lens' SegmentInfo (Maybe FlightInfo)
sFlight = lens _sFlight (\ s a -> s{_sFlight = a})
-- | An id uniquely identifying the segment in the solution.
sId :: Lens' SegmentInfo (Maybe Text)
sId = lens _sId (\ s a -> s{_sId = a})
-- | The solution-based index of a segment in a married segment group.
-- Married segments can only be booked together. For example, an airline
-- might report a certain booking code as sold out from Boston to
-- Pittsburgh, but as available as part of two married segments Boston to
-- Chicago connecting through Pittsburgh. For example content of this
-- field, consider the round-trip flight ZZ1 PHX-PHL ZZ2 PHL-CLT ZZ3
-- CLT-PHX. This has three segments, with the two outbound ones (ZZ1 ZZ2)
-- married. In this case, the two outbound segments belong to married
-- segment group 0, and the return segment belongs to married segment group
-- 1.
sMarriedSegmentGroup :: Lens' SegmentInfo (Maybe Text)
sMarriedSegmentGroup
= lens _sMarriedSegmentGroup
(\ s a -> s{_sMarriedSegmentGroup = a})
-- | In minutes, the duration of the connection following this segment.
sConnectionDuration :: Lens' SegmentInfo (Maybe Int32)
sConnectionDuration
= lens _sConnectionDuration
(\ s a -> s{_sConnectionDuration = a})
. mapping _Coerce
-- | The duration of the flight segment in minutes.
sDuration :: Lens' SegmentInfo (Maybe Int32)
sDuration
= lens _sDuration (\ s a -> s{_sDuration = a}) .
mapping _Coerce
-- | The legs composing this segment.
sLeg :: Lens' SegmentInfo [LegInfo]
sLeg
= lens _sLeg (\ s a -> s{_sLeg = a}) . _Default .
_Coerce
instance FromJSON SegmentInfo where
parseJSON
= withObject "SegmentInfo"
(\ o ->
SegmentInfo' <$>
(o .:? "bookingCode") <*> (o .:? "cabin") <*>
(o .:? "bookingCodeCount")
<*> (o .:? "subjectToGovernmentApproval")
<*> (o .:? "kind" .!= "qpxexpress#segmentInfo")
<*> (o .:? "flight")
<*> (o .:? "id")
<*> (o .:? "marriedSegmentGroup")
<*> (o .:? "connectionDuration")
<*> (o .:? "duration")
<*> (o .:? "leg" .!= mempty))
instance ToJSON SegmentInfo where
toJSON SegmentInfo'{..}
= object
(catMaybes
[("bookingCode" .=) <$> _sBookingCode,
("cabin" .=) <$> _sCabin,
("bookingCodeCount" .=) <$> _sBookingCodeCount,
("subjectToGovernmentApproval" .=) <$>
_sSubjectToGovernmentApproval,
Just ("kind" .= _sKind), ("flight" .=) <$> _sFlight,
("id" .=) <$> _sId,
("marriedSegmentGroup" .=) <$> _sMarriedSegmentGroup,
("connectionDuration" .=) <$> _sConnectionDuration,
("duration" .=) <$> _sDuration,
("leg" .=) <$> _sLeg])
-- | Tax data.
--
-- /See:/ 'taxData' smart constructor.
data TaxData =
TaxData'
{ _tdKind :: !Text
, _tdName :: !(Maybe Text)
, _tdId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'TaxData' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tdKind'
--
-- * 'tdName'
--
-- * 'tdId'
taxData
:: TaxData
taxData =
TaxData' {_tdKind = "qpxexpress#taxData", _tdName = Nothing, _tdId = Nothing}
-- | Identifies this as a tax data object, representing some tax. Value: the
-- fixed string qpxexpress#taxData.
tdKind :: Lens' TaxData Text
tdKind = lens _tdKind (\ s a -> s{_tdKind = a})
-- | The name of a tax.
tdName :: Lens' TaxData (Maybe Text)
tdName = lens _tdName (\ s a -> s{_tdName = a})
-- | An identifier uniquely identifying a tax in a response.
tdId :: Lens' TaxData (Maybe Text)
tdId = lens _tdId (\ s a -> s{_tdId = a})
instance FromJSON TaxData where
parseJSON
= withObject "TaxData"
(\ o ->
TaxData' <$>
(o .:? "kind" .!= "qpxexpress#taxData") <*>
(o .:? "name")
<*> (o .:? "id"))
instance ToJSON TaxData where
toJSON TaxData'{..}
= object
(catMaybes
[Just ("kind" .= _tdKind), ("name" .=) <$> _tdName,
("id" .=) <$> _tdId])
-- | A QPX Express search request.
--
-- /See:/ 'tripsSearchRequest' smart constructor.
newtype TripsSearchRequest =
TripsSearchRequest'
{ _tsrRequest :: Maybe TripOptionsRequest
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'TripsSearchRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tsrRequest'
tripsSearchRequest
:: TripsSearchRequest
tripsSearchRequest = TripsSearchRequest' {_tsrRequest = Nothing}
-- | A QPX Express search request. Required values are at least one adult or
-- senior passenger, an origin, a destination, and a date.
tsrRequest :: Lens' TripsSearchRequest (Maybe TripOptionsRequest)
tsrRequest
= lens _tsrRequest (\ s a -> s{_tsrRequest = a})
instance FromJSON TripsSearchRequest where
parseJSON
= withObject "TripsSearchRequest"
(\ o -> TripsSearchRequest' <$> (o .:? "request"))
instance ToJSON TripsSearchRequest where
toJSON TripsSearchRequest'{..}
= object (catMaybes [("request" .=) <$> _tsrRequest])
-- | Tax information.
--
-- /See:/ 'taxInfo' smart constructor.
data TaxInfo =
TaxInfo'
{ _tiChargeType :: !(Maybe Text)
, _tiCountry :: !(Maybe Text)
, _tiKind :: !Text
, _tiSalePrice :: !(Maybe Text)
, _tiCode :: !(Maybe Text)
, _tiId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'TaxInfo' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tiChargeType'
--
-- * 'tiCountry'
--
-- * 'tiKind'
--
-- * 'tiSalePrice'
--
-- * 'tiCode'
--
-- * 'tiId'
taxInfo
:: TaxInfo
taxInfo =
TaxInfo'
{ _tiChargeType = Nothing
, _tiCountry = Nothing
, _tiKind = "qpxexpress#taxInfo"
, _tiSalePrice = Nothing
, _tiCode = Nothing
, _tiId = Nothing
}
-- | Whether this is a government charge or a carrier surcharge.
tiChargeType :: Lens' TaxInfo (Maybe Text)
tiChargeType
= lens _tiChargeType (\ s a -> s{_tiChargeType = a})
-- | For government charges, the country levying the charge.
tiCountry :: Lens' TaxInfo (Maybe Text)
tiCountry
= lens _tiCountry (\ s a -> s{_tiCountry = a})
-- | Identifies this as a tax information object. Value: the fixed string
-- qpxexpress#taxInfo.
tiKind :: Lens' TaxInfo Text
tiKind = lens _tiKind (\ s a -> s{_tiKind = a})
-- | The price of the tax in the sales or equivalent currency.
tiSalePrice :: Lens' TaxInfo (Maybe Text)
tiSalePrice
= lens _tiSalePrice (\ s a -> s{_tiSalePrice = a})
-- | The code to enter in the ticket\'s tax box.
tiCode :: Lens' TaxInfo (Maybe Text)
tiCode = lens _tiCode (\ s a -> s{_tiCode = a})
-- | Identifier uniquely identifying this tax in a response. Not present for
-- unnamed carrier surcharges.
tiId :: Lens' TaxInfo (Maybe Text)
tiId = lens _tiId (\ s a -> s{_tiId = a})
instance FromJSON TaxInfo where
parseJSON
= withObject "TaxInfo"
(\ o ->
TaxInfo' <$>
(o .:? "chargeType") <*> (o .:? "country") <*>
(o .:? "kind" .!= "qpxexpress#taxInfo")
<*> (o .:? "salePrice")
<*> (o .:? "code")
<*> (o .:? "id"))
instance ToJSON TaxInfo where
toJSON TaxInfo'{..}
= object
(catMaybes
[("chargeType" .=) <$> _tiChargeType,
("country" .=) <$> _tiCountry,
Just ("kind" .= _tiKind),
("salePrice" .=) <$> _tiSalePrice,
("code" .=) <$> _tiCode, ("id" .=) <$> _tiId])
-- | The price of one or more travel segments. The currency used to purchase
-- tickets is usually determined by the sale\/ticketing city or the
-- sale\/ticketing country, unless none are specified, in which case it
-- defaults to that of the journey origin country.
--
-- /See:/ 'pricingInfo' smart constructor.
data PricingInfo =
PricingInfo'
{ _piSaleTaxTotal :: !(Maybe Text)
, _piRefundable :: !(Maybe Bool)
, _piPtc :: !(Maybe Text)
, _piBaseFareTotal :: !(Maybe Text)
, _piFare :: !(Maybe [FareInfo])
, _piKind :: !Text
, _piSegmentPricing :: !(Maybe [SegmentPricing])
, _piPassengers :: !(Maybe PassengerCounts)
, _piFareCalculation :: !(Maybe Text)
, _piLatestTicketingTime :: !(Maybe Text)
, _piTax :: !(Maybe [TaxInfo])
, _piSaleTotal :: !(Maybe Text)
, _piSaleFareTotal :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'PricingInfo' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'piSaleTaxTotal'
--
-- * 'piRefundable'
--
-- * 'piPtc'
--
-- * 'piBaseFareTotal'
--
-- * 'piFare'
--
-- * 'piKind'
--
-- * 'piSegmentPricing'
--
-- * 'piPassengers'
--
-- * 'piFareCalculation'
--
-- * 'piLatestTicketingTime'
--
-- * 'piTax'
--
-- * 'piSaleTotal'
--
-- * 'piSaleFareTotal'
pricingInfo
:: PricingInfo
pricingInfo =
PricingInfo'
{ _piSaleTaxTotal = Nothing
, _piRefundable = Nothing
, _piPtc = Nothing
, _piBaseFareTotal = Nothing
, _piFare = Nothing
, _piKind = "qpxexpress#pricingInfo"
, _piSegmentPricing = Nothing
, _piPassengers = Nothing
, _piFareCalculation = Nothing
, _piLatestTicketingTime = Nothing
, _piTax = Nothing
, _piSaleTotal = Nothing
, _piSaleFareTotal = Nothing
}
-- | The taxes in the sale or equivalent currency.
piSaleTaxTotal :: Lens' PricingInfo (Maybe Text)
piSaleTaxTotal
= lens _piSaleTaxTotal
(\ s a -> s{_piSaleTaxTotal = a})
-- | Whether the fares on this pricing are refundable.
piRefundable :: Lens' PricingInfo (Maybe Bool)
piRefundable
= lens _piRefundable (\ s a -> s{_piRefundable = a})
-- | The passenger type code for this pricing. An alphanumeric code used by a
-- carrier to restrict fares to certain categories of passenger. For
-- instance, a fare might be valid only for senior citizens.
piPtc :: Lens' PricingInfo (Maybe Text)
piPtc = lens _piPtc (\ s a -> s{_piPtc = a})
-- | The total fare in the base fare currency (the currency of the country of
-- origin). This element is only present when the sales currency and the
-- currency of the country of commencement are different.
piBaseFareTotal :: Lens' PricingInfo (Maybe Text)
piBaseFareTotal
= lens _piBaseFareTotal
(\ s a -> s{_piBaseFareTotal = a})
-- | The fare used to price one or more segments.
piFare :: Lens' PricingInfo [FareInfo]
piFare
= lens _piFare (\ s a -> s{_piFare = a}) . _Default .
_Coerce
-- | Identifies this as a pricing object, representing the price of one or
-- more travel segments. Value: the fixed string qpxexpress#pricingInfo.
piKind :: Lens' PricingInfo Text
piKind = lens _piKind (\ s a -> s{_piKind = a})
-- | The per-segment price and baggage information.
piSegmentPricing :: Lens' PricingInfo [SegmentPricing]
piSegmentPricing
= lens _piSegmentPricing
(\ s a -> s{_piSegmentPricing = a})
. _Default
. _Coerce
-- | The number of passengers to which this price applies.
piPassengers :: Lens' PricingInfo (Maybe PassengerCounts)
piPassengers
= lens _piPassengers (\ s a -> s{_piPassengers = a})
-- | The horizontal fare calculation. This is a field on a ticket that
-- displays all of the relevant items that go into the calculation of the
-- fare.
piFareCalculation :: Lens' PricingInfo (Maybe Text)
piFareCalculation
= lens _piFareCalculation
(\ s a -> s{_piFareCalculation = a})
-- | The latest ticketing time for this pricing assuming the reservation
-- occurs at ticketing time and there is no change in fares\/rules. The
-- time is local to the point of sale (POS).
piLatestTicketingTime :: Lens' PricingInfo (Maybe Text)
piLatestTicketingTime
= lens _piLatestTicketingTime
(\ s a -> s{_piLatestTicketingTime = a})
-- | The taxes used to calculate the tax total per ticket.
piTax :: Lens' PricingInfo [TaxInfo]
piTax
= lens _piTax (\ s a -> s{_piTax = a}) . _Default .
_Coerce
-- | Total per-passenger price (fare and tax) in the sale or equivalent
-- currency.
piSaleTotal :: Lens' PricingInfo (Maybe Text)
piSaleTotal
= lens _piSaleTotal (\ s a -> s{_piSaleTotal = a})
-- | The total fare in the sale or equivalent currency.
piSaleFareTotal :: Lens' PricingInfo (Maybe Text)
piSaleFareTotal
= lens _piSaleFareTotal
(\ s a -> s{_piSaleFareTotal = a})
instance FromJSON PricingInfo where
parseJSON
= withObject "PricingInfo"
(\ o ->
PricingInfo' <$>
(o .:? "saleTaxTotal") <*> (o .:? "refundable") <*>
(o .:? "ptc")
<*> (o .:? "baseFareTotal")
<*> (o .:? "fare" .!= mempty)
<*> (o .:? "kind" .!= "qpxexpress#pricingInfo")
<*> (o .:? "segmentPricing" .!= mempty)
<*> (o .:? "passengers")
<*> (o .:? "fareCalculation")
<*> (o .:? "latestTicketingTime")
<*> (o .:? "tax" .!= mempty)
<*> (o .:? "saleTotal")
<*> (o .:? "saleFareTotal"))
instance ToJSON PricingInfo where
toJSON PricingInfo'{..}
= object
(catMaybes
[("saleTaxTotal" .=) <$> _piSaleTaxTotal,
("refundable" .=) <$> _piRefundable,
("ptc" .=) <$> _piPtc,
("baseFareTotal" .=) <$> _piBaseFareTotal,
("fare" .=) <$> _piFare, Just ("kind" .= _piKind),
("segmentPricing" .=) <$> _piSegmentPricing,
("passengers" .=) <$> _piPassengers,
("fareCalculation" .=) <$> _piFareCalculation,
("latestTicketingTime" .=) <$>
_piLatestTicketingTime,
("tax" .=) <$> _piTax,
("saleTotal" .=) <$> _piSaleTotal,
("saleFareTotal" .=) <$> _piSaleFareTotal])
-- | A flight is a sequence of legs with the same airline carrier and flight
-- number. (A leg is the smallest unit of travel, in the case of a flight a
-- takeoff immediately followed by a landing at two set points on a
-- particular carrier with a particular flight number.) The naive view is
-- that a flight is scheduled travel of an aircraft between two points,
-- with possibly intermediate stops, but carriers will frequently list
-- flights that require a change of aircraft between legs.
--
-- /See:/ 'flightInfo' smart constructor.
data FlightInfo =
FlightInfo'
{ _fiCarrier :: !(Maybe Text)
, _fiNumber :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'FlightInfo' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'fiCarrier'
--
-- * 'fiNumber'
flightInfo
:: FlightInfo
flightInfo = FlightInfo' {_fiCarrier = Nothing, _fiNumber = Nothing}
fiCarrier :: Lens' FlightInfo (Maybe Text)
fiCarrier
= lens _fiCarrier (\ s a -> s{_fiCarrier = a})
-- | The flight number.
fiNumber :: Lens' FlightInfo (Maybe Text)
fiNumber = lens _fiNumber (\ s a -> s{_fiNumber = a})
instance FromJSON FlightInfo where
parseJSON
= withObject "FlightInfo"
(\ o ->
FlightInfo' <$>
(o .:? "carrier") <*> (o .:? "number"))
instance ToJSON FlightInfo where
toJSON FlightInfo'{..}
= object
(catMaybes
[("carrier" .=) <$> _fiCarrier,
("number" .=) <$> _fiNumber])
-- | Complete information about a fare used in the solution to a low-fare
-- search query. In the airline industry a fare is a price an airline
-- charges for one-way travel between two points. A fare typically contains
-- a carrier code, two city codes, a price, and a fare basis. (A fare basis
-- is a one-to-eight character alphanumeric code used to identify a fare.)
--
-- /See:/ 'fareInfo' smart constructor.
data FareInfo =
FareInfo'
{ _fCarrier :: !(Maybe Text)
, _fDestination :: !(Maybe Text)
, _fOrigin :: !(Maybe Text)
, _fPrivate :: !(Maybe Bool)
, _fKind :: !Text
, _fBasisCode :: !(Maybe Text)
, _fId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'FareInfo' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'fCarrier'
--
-- * 'fDestination'
--
-- * 'fOrigin'
--
-- * 'fPrivate'
--
-- * 'fKind'
--
-- * 'fBasisCode'
--
-- * 'fId'
fareInfo
:: FareInfo
fareInfo =
FareInfo'
{ _fCarrier = Nothing
, _fDestination = Nothing
, _fOrigin = Nothing
, _fPrivate = Nothing
, _fKind = "qpxexpress#fareInfo"
, _fBasisCode = Nothing
, _fId = Nothing
}
-- | The carrier of the aircraft or other vehicle commuting between two
-- points.
fCarrier :: Lens' FareInfo (Maybe Text)
fCarrier = lens _fCarrier (\ s a -> s{_fCarrier = a})
-- | The city code of the city the trip ends at.
fDestination :: Lens' FareInfo (Maybe Text)
fDestination
= lens _fDestination (\ s a -> s{_fDestination = a})
-- | The city code of the city the trip begins at.
fOrigin :: Lens' FareInfo (Maybe Text)
fOrigin = lens _fOrigin (\ s a -> s{_fOrigin = a})
-- | Whether this is a private fare, for example one offered only to select
-- customers rather than the general public.
fPrivate :: Lens' FareInfo (Maybe Bool)
fPrivate = lens _fPrivate (\ s a -> s{_fPrivate = a})
-- | Identifies this as a fare object. Value: the fixed string
-- qpxexpress#fareInfo.
fKind :: Lens' FareInfo Text
fKind = lens _fKind (\ s a -> s{_fKind = a})
fBasisCode :: Lens' FareInfo (Maybe Text)
fBasisCode
= lens _fBasisCode (\ s a -> s{_fBasisCode = a})
-- | A unique identifier of the fare.
fId :: Lens' FareInfo (Maybe Text)
fId = lens _fId (\ s a -> s{_fId = a})
instance FromJSON FareInfo where
parseJSON
= withObject "FareInfo"
(\ o ->
FareInfo' <$>
(o .:? "carrier") <*> (o .:? "destination") <*>
(o .:? "origin")
<*> (o .:? "private")
<*> (o .:? "kind" .!= "qpxexpress#fareInfo")
<*> (o .:? "basisCode")
<*> (o .:? "id"))
instance ToJSON FareInfo where
toJSON FareInfo'{..}
= object
(catMaybes
[("carrier" .=) <$> _fCarrier,
("destination" .=) <$> _fDestination,
("origin" .=) <$> _fOrigin,
("private" .=) <$> _fPrivate,
Just ("kind" .= _fKind),
("basisCode" .=) <$> _fBasisCode,
("id" .=) <$> _fId])
-- | A QPX Express search request, which will yield one or more solutions.
--
-- /See:/ 'tripOptionsRequest' smart constructor.
data TripOptionsRequest =
TripOptionsRequest'
{ _torRefundable :: !(Maybe Bool)
, _torSaleCountry :: !(Maybe Text)
, _torPassengers :: !(Maybe PassengerCounts)
, _torTicketingCountry :: !(Maybe Text)
, _torSolutions :: !(Maybe (Textual Int32))
, _torSlice :: !(Maybe [SliceInput])
, _torMaxPrice :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'TripOptionsRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'torRefundable'
--
-- * 'torSaleCountry'
--
-- * 'torPassengers'
--
-- * 'torTicketingCountry'
--
-- * 'torSolutions'
--
-- * 'torSlice'
--
-- * 'torMaxPrice'
tripOptionsRequest
:: TripOptionsRequest
tripOptionsRequest =
TripOptionsRequest'
{ _torRefundable = Nothing
, _torSaleCountry = Nothing
, _torPassengers = Nothing
, _torTicketingCountry = Nothing
, _torSolutions = Nothing
, _torSlice = Nothing
, _torMaxPrice = Nothing
}
-- | Return only solutions with refundable fares.
torRefundable :: Lens' TripOptionsRequest (Maybe Bool)
torRefundable
= lens _torRefundable
(\ s a -> s{_torRefundable = a})
-- | IATA country code representing the point of sale. This determines the
-- \"equivalent amount paid\" currency for the ticket.
torSaleCountry :: Lens' TripOptionsRequest (Maybe Text)
torSaleCountry
= lens _torSaleCountry
(\ s a -> s{_torSaleCountry = a})
-- | Counts for each passenger type in the request.
torPassengers :: Lens' TripOptionsRequest (Maybe PassengerCounts)
torPassengers
= lens _torPassengers
(\ s a -> s{_torPassengers = a})
-- | IATA country code representing the point of ticketing.
torTicketingCountry :: Lens' TripOptionsRequest (Maybe Text)
torTicketingCountry
= lens _torTicketingCountry
(\ s a -> s{_torTicketingCountry = a})
-- | The number of solutions to return, maximum 500.
torSolutions :: Lens' TripOptionsRequest (Maybe Int32)
torSolutions
= lens _torSolutions (\ s a -> s{_torSolutions = a})
. mapping _Coerce
-- | The slices that make up the itinerary of this trip. A slice represents a
-- traveler\'s intent, the portion of a low-fare search corresponding to a
-- traveler\'s request to get between two points. One-way journeys are
-- generally expressed using one slice, round-trips using two. An example
-- of a one slice trip with three segments might be BOS-SYD, SYD-LAX,
-- LAX-BOS if the traveler only stopped in SYD and LAX just long enough to
-- change planes.
torSlice :: Lens' TripOptionsRequest [SliceInput]
torSlice
= lens _torSlice (\ s a -> s{_torSlice = a}) .
_Default
. _Coerce
-- | Do not return solutions that cost more than this price. The alphabetical
-- part of the price is in ISO 4217. The format, in regex, is
-- [A-Z]{3}\\d+(\\.\\d+)? Example: $102.07
torMaxPrice :: Lens' TripOptionsRequest (Maybe Text)
torMaxPrice
= lens _torMaxPrice (\ s a -> s{_torMaxPrice = a})
instance FromJSON TripOptionsRequest where
parseJSON
= withObject "TripOptionsRequest"
(\ o ->
TripOptionsRequest' <$>
(o .:? "refundable") <*> (o .:? "saleCountry") <*>
(o .:? "passengers")
<*> (o .:? "ticketingCountry")
<*> (o .:? "solutions")
<*> (o .:? "slice" .!= mempty)
<*> (o .:? "maxPrice"))
instance ToJSON TripOptionsRequest where
toJSON TripOptionsRequest'{..}
= object
(catMaybes
[("refundable" .=) <$> _torRefundable,
("saleCountry" .=) <$> _torSaleCountry,
("passengers" .=) <$> _torPassengers,
("ticketingCountry" .=) <$> _torTicketingCountry,
("solutions" .=) <$> _torSolutions,
("slice" .=) <$> _torSlice,
("maxPrice" .=) <$> _torMaxPrice])
-- | Criteria a desired slice must satisfy.
--
-- /See:/ 'sliceInput' smart constructor.
data SliceInput =
SliceInput'
{ _sliDestination :: !(Maybe Text)
, _sliOrigin :: !(Maybe Text)
, _sliMaxStops :: !(Maybe (Textual Int32))
, _sliKind :: !Text
, _sliProhibitedCarrier :: !(Maybe [Text])
, _sliDate :: !(Maybe Text)
, _sliMaxConnectionDuration :: !(Maybe (Textual Int32))
, _sliPreferredCabin :: !(Maybe Text)
, _sliPermittedDePartureTime :: !(Maybe TimeOfDayRange)
, _sliPermittedCarrier :: !(Maybe [Text])
, _sliAlliance :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'SliceInput' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'sliDestination'
--
-- * 'sliOrigin'
--
-- * 'sliMaxStops'
--
-- * 'sliKind'
--
-- * 'sliProhibitedCarrier'
--
-- * 'sliDate'
--
-- * 'sliMaxConnectionDuration'
--
-- * 'sliPreferredCabin'
--
-- * 'sliPermittedDePartureTime'
--
-- * 'sliPermittedCarrier'
--
-- * 'sliAlliance'
sliceInput
:: SliceInput
sliceInput =
SliceInput'
{ _sliDestination = Nothing
, _sliOrigin = Nothing
, _sliMaxStops = Nothing
, _sliKind = "qpxexpress#sliceInput"
, _sliProhibitedCarrier = Nothing
, _sliDate = Nothing
, _sliMaxConnectionDuration = Nothing
, _sliPreferredCabin = Nothing
, _sliPermittedDePartureTime = Nothing
, _sliPermittedCarrier = Nothing
, _sliAlliance = Nothing
}
-- | Airport or city IATA designator of the destination.
sliDestination :: Lens' SliceInput (Maybe Text)
sliDestination
= lens _sliDestination
(\ s a -> s{_sliDestination = a})
-- | Airport or city IATA designator of the origin.
sliOrigin :: Lens' SliceInput (Maybe Text)
sliOrigin
= lens _sliOrigin (\ s a -> s{_sliOrigin = a})
-- | The maximum number of stops you are willing to accept in this slice.
sliMaxStops :: Lens' SliceInput (Maybe Int32)
sliMaxStops
= lens _sliMaxStops (\ s a -> s{_sliMaxStops = a}) .
mapping _Coerce
-- | Identifies this as a slice input object, representing the criteria a
-- desired slice must satisfy. Value: the fixed string
-- qpxexpress#sliceInput.
sliKind :: Lens' SliceInput Text
sliKind = lens _sliKind (\ s a -> s{_sliKind = a})
-- | A list of 2-letter IATA airline designators. Exclude slices that use
-- these carriers.
sliProhibitedCarrier :: Lens' SliceInput [Text]
sliProhibitedCarrier
= lens _sliProhibitedCarrier
(\ s a -> s{_sliProhibitedCarrier = a})
. _Default
. _Coerce
-- | Departure date in YYYY-MM-DD format.
sliDate :: Lens' SliceInput (Maybe Text)
sliDate = lens _sliDate (\ s a -> s{_sliDate = a})
-- | The longest connection between two legs, in minutes, you are willing to
-- accept.
sliMaxConnectionDuration :: Lens' SliceInput (Maybe Int32)
sliMaxConnectionDuration
= lens _sliMaxConnectionDuration
(\ s a -> s{_sliMaxConnectionDuration = a})
. mapping _Coerce
-- | Prefer solutions that book in this cabin for this slice. Allowed values
-- are COACH, PREMIUM_COACH, BUSINESS, and FIRST.
sliPreferredCabin :: Lens' SliceInput (Maybe Text)
sliPreferredCabin
= lens _sliPreferredCabin
(\ s a -> s{_sliPreferredCabin = a})
-- | Slices must depart in this time of day range, local to the point of
-- departure.
sliPermittedDePartureTime :: Lens' SliceInput (Maybe TimeOfDayRange)
sliPermittedDePartureTime
= lens _sliPermittedDePartureTime
(\ s a -> s{_sliPermittedDePartureTime = a})
-- | A list of 2-letter IATA airline designators. Slices with only these
-- carriers should be returned.
sliPermittedCarrier :: Lens' SliceInput [Text]
sliPermittedCarrier
= lens _sliPermittedCarrier
(\ s a -> s{_sliPermittedCarrier = a})
. _Default
. _Coerce
-- | Slices with only the carriers in this alliance should be returned; do
-- not use this field with permittedCarrier. Allowed values are ONEWORLD,
-- SKYTEAM, and STAR.
sliAlliance :: Lens' SliceInput (Maybe Text)
sliAlliance
= lens _sliAlliance (\ s a -> s{_sliAlliance = a})
instance FromJSON SliceInput where
parseJSON
= withObject "SliceInput"
(\ o ->
SliceInput' <$>
(o .:? "destination") <*> (o .:? "origin") <*>
(o .:? "maxStops")
<*> (o .:? "kind" .!= "qpxexpress#sliceInput")
<*> (o .:? "prohibitedCarrier" .!= mempty)
<*> (o .:? "date")
<*> (o .:? "maxConnectionDuration")
<*> (o .:? "preferredCabin")
<*> (o .:? "permittedDepartureTime")
<*> (o .:? "permittedCarrier" .!= mempty)
<*> (o .:? "alliance"))
instance ToJSON SliceInput where
toJSON SliceInput'{..}
= object
(catMaybes
[("destination" .=) <$> _sliDestination,
("origin" .=) <$> _sliOrigin,
("maxStops" .=) <$> _sliMaxStops,
Just ("kind" .= _sliKind),
("prohibitedCarrier" .=) <$> _sliProhibitedCarrier,
("date" .=) <$> _sliDate,
("maxConnectionDuration" .=) <$>
_sliMaxConnectionDuration,
("preferredCabin" .=) <$> _sliPreferredCabin,
("permittedDepartureTime" .=) <$>
_sliPermittedDePartureTime,
("permittedCarrier" .=) <$> _sliPermittedCarrier,
("alliance" .=) <$> _sliAlliance])
| brendanhay/gogol | gogol-qpxexpress/gen/Network/Google/QPXExpress/Types/Product.hs | mpl-2.0 | 73,669 | 0 | 27 | 19,409 | 15,061 | 8,675 | 6,386 | 1,624 | 1 |
module Data.GI.CodeGen.JNI.Types where
import qualified Data.Map as M
import qualified Data.Text as T
import qualified Data.GI.CodeGen.API as GI
-- | Lists component of the package (like ["org", "freedesktop"])
type Package = [String]
-- | Unqualified class name
type Class = String
-- | Fully qualified class consisting of the package and class name
type FQClass = (Package, Class)
-- | Information used during generation, based on Data.GI.CodeGen.API.GIRInfo
data Info = Info {
infoPkgPrefix :: Package, -- ^ Top level Java package prefix
infoAPI :: M.Map GI.Name GI.API, -- ^ The main API
infoDeps :: M.Map GI.Name GI.API, -- ^ The dependent APIs
infoCTypes :: M.Map GI.Name T.Text -- ^ A map from GI types to the corresponding C type
}
| ford-prefect/gir2jni | src/Data/GI/CodeGen/JNI/Types.hs | lgpl-2.1 | 782 | 0 | 10 | 162 | 136 | 89 | 47 | 12 | 0 |
head' :: [a] -> a
head' xs = case xs of [] -> error "No head for empty lists!"
(x:_) -> x
| Physwf/physwf-haskell-lab | head.hs | apache-2.0 | 117 | 0 | 9 | 49 | 49 | 25 | 24 | 3 | 2 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TemplateHaskell #-}
{-
- Copyright (c) 2015, Peter Lebbing <peter@digitalbrains.com>
- All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- POSSIBILITY OF SUCH DAMAGE.
-}
module LT24.InitSteps where
import CLaSH.Prelude
import Language.Haskell.TH
import qualified LT24.LT24 as LT24
import LT24.Commands
import qualified Toolbox.ClockScale as CS
import Toolbox.Misc
import Toolbox.FClk
type IlSIndex = $(uToFit $ max (CS.ticksMinPeriod fClk 120e-3) (320*240))
data IlStep = IlL LT24.Action (Unsigned 16) | IlDoPalette5b | IlDoPalette6b
| IlWait IlSIndex | IlWipeFb
{-
- These are the steps necessary to initialize the LT24's controller.
-
- It is initialized in a 16bpp mode with a direct colour mapping. The
- coordinates are chosen such that if you have the LT24 module oriented with
- the silkscreen text "terasIC LT24" upright, then the coordinates (x,y) are
- (0,0) top-left, (319,0) top-right, (0,239) bottom-left and (319,239)
- bottom-right.
-}
initSteps = IlL LT24.Reset 0
:> IlL LT24.Command cMADCTL
:> IlL LT24.Write 232 -- Alternate row address order,
-- alternate column address order,
-- row / column exchange,
-- BGR subpixel order
:> IlL LT24.Command cCOLMOD
:> IlL LT24.Write 5 -- 16bpp MCU interface
:> IlL LT24.Command cRGBSET
:> IlDoPalette5b -- Red
:> IlDoPalette6b -- Green
:> IlDoPalette5b -- Blue
:> IlL LT24.Command cCASET -- Since we exchanged rows and
:> IlL LT24.Write 0 -- columns, we need to set the
:> IlL LT24.Write 0 -- end addresses correctly
:> IlL LT24.Write 1
:> IlL LT24.Write 0x3F
:> IlL LT24.Command cPASET
:> IlL LT24.Write 0
:> IlL LT24.Write 0
:> IlL LT24.Write 0
:> IlL LT24.Write 0xEF
:> IlL LT24.Command cRAMWR -- Clear the framebuffer
:> IlWipeFb
:> IlL LT24.Command cSLPOUT
:> IlWait $(CS.ticksMinPeriodTH fClk 120e-3)
:> IlL LT24.Command cDISPON
:> Nil
| DigitalBrains1/clash-lt24 | LT24/InitSteps.hs | bsd-2-clause | 3,615 | 0 | 30 | 1,041 | 381 | 200 | 181 | 38 | 1 |
module Application.DocManager.Job where
import Application.DocManager.Config
import Application.DocManager.Type
import Application.DocManager.Data.Document
import Application.DocManager.Xournal
import Application.DocManager.Xelatex
import Control.Monad
import Data.List
import Data.Char
import System.FilePath
import System.Directory
import System.Process
startJob :: DocManagerConfig -> IO ()
startJob dmc = do
putStrLn "job started"
putStrLn $ show dmc
let texfilelist = filter (\x->doctype x == TeX) doclist
xojfilelist = filter (\x->doctype x == Xoj) doclist
mapM_ (runXelatex dmc) texfilelist
mapM_ (runHXournal dmc) xojfilelist
startIndividualJob :: DocManagerConfig -> String -> IO ()
startIndividualJob dmc fname = do
putStrLn "individual job started"
putStrLn $ show dmc
let (fnamebdy,fnameext) = splitExtension fname
let (p,f') = span isAlpha fnamebdy
(sn,vn) = span isDigit f'
case fnameext of
".tex" -> do putStrLn "tex file"
let doc = Document p sn vn TeX
putStrLn $ show doc
cpPics dmc
runXelatex dmc doc
".xoj" -> do putStrLn "xoj file"
let doc = Document p sn vn Xoj
putStrLn $ show doc
runHXournal dmc doc
{-
mapM_ (runXelatex dmc) texfilelist
mapM_ (runHXournal dmc) xojfilelist
-}
| wavewave/docmanager | lib/Application/DocManager/Job.hs | bsd-2-clause | 1,413 | 0 | 15 | 374 | 399 | 194 | 205 | 37 | 2 |
{-# LANGUAGE Trustworthy #-}
-----------------------------------------------------------------------------
-- |
-- Copyright : (C) 2015 Edward Kmett and Ted Cooper
-- License : BSD-style (see the file LICENSE)
-- Maintainer : Edward Kmett <ekmett@gmail.com>
-- Ted Cooper <anthezium@gmail.com>
-- Stability : experimental
-- Portability : non-portable
--
-----------------------------------------------------------------------------
module Control.Concurrent.RCU.QSBR
( SRef
, RCU, runRCU
, MonadNew(..)
, MonadReading(..)
, MonadWriting(..)
, MonadRCU(..)
-- * Implementation Details
, ReadingRCU
, WritingRCU
, RCUThread(rcuThreadId)
) where
import Control.Concurrent.RCU.Class
import Control.Concurrent.RCU.QSBR.Internal
| anthezium/rcu | src/Control/Concurrent/RCU/QSBR.hs | bsd-2-clause | 776 | 0 | 5 | 128 | 87 | 65 | 22 | 16 | 0 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Main where
import Ivory.Tower
import Ivory.Language
import Tower.AADL
import Ivory.Tower.Config
simpleTower :: Tower e ()
simpleTower = do
towerModule towerDepModule
towerDepends towerDepModule
(c1in, c1out) <- channel
(chtx, chrx) <- channel
per <- period (Microseconds 1000)
monitor "periodicM" $ do
s <- state "local_st"
handler per "send" $ do
e <- emitter c1in 1
callback $ \_ -> do
emit e (constRef (s :: Ref 'Global ('Stored Uint8)))
handler chrx "rcv" $ callback $ \msg -> do
n' <- deref msg
store s (n' + 1)
call_ printf "received: %u\n" n'
{-
monitor "withsharedM" $ do
s <- state "last_m2_chan1_message"
handler c1out "fromActiveh" $ do
e <- emitter chtx 1
callback $ \m -> do
refCopy s m
emitV e true
handler chrx "readStateh" $ do
callback $ \_m -> do
s' <- deref s
call_ printf "rsh: %u\n" s'
-}
ext_chan1 <- channel
ext_chan2 <- channel
externalMonitor "extMon" $ do
handler c1out "send_ext" $ do
e <- emitter (fst ext_chan1) 1
callback $ \msg -> emit e msg
handler (snd ext_chan2) "rcv_ext" $ do
e <- emitter chtx 1
callback $ \msg -> emit e msg
main :: IO ()
main = compileTowerAADL id p simpleTower
where
p topts = getConfig topts $ aadlConfigParser defaultAADLConfig
[ivory|
import (stdio.h, printf) void printf(string x, uint8_t y)
|]
towerDepModule :: Module
towerDepModule = package "towerDeps" $ do
incl printf
| GaloisInc/tower | tower-aadl/test/External.hs | bsd-3-clause | 1,800 | 0 | 24 | 455 | 442 | 213 | 229 | 46 | 1 |
{-# LANGUAGE OverloadedStrings, RankNTypes #-}
module Qualys.Internal.ParseWasCommon
( parseProfile
, parseTag
, parseProxy
, parseUser
, parseScanAppl
, parseComment
, parseV3List
) where
import Control.Applicative hiding (many)
import Control.Monad (join)
import Control.Monad.Catch (MonadThrow)
import Control.Monad.IO.Class (MonadIO)
import Data.Conduit (ConduitM, Consumer)
import Data.XML.Types
import Text.XML.Stream.Parse
import Qualys.Internal
import Qualys.Types.Was
parseProfile :: (MonadIO m, MonadThrow m) => ConduitM Event o m WsScanProfile
parseProfile = WsScanProfile
<$> optionalWith parseUInt (tagNoAttr "id" content)
<*> tagNoAttr "name" content
parseTag :: (MonadIO m, MonadThrow m) => ConduitM Event o m (Maybe WsTag)
parseTag = tagNoAttr "Tag" $ WsTag
<$> requireWith parseUInt (tagNoAttr "id" content)
<*> tagNoAttr "name" content
parseProxy :: (MonadIO m, MonadThrow m) => ConduitM Event o m WsProxy
parseProxy = WsProxy
<$> optionalWith parseUInt (tagNoAttr "id" content)
<*> tagNoAttr "name" content
<*> tagNoAttr "url" content
parseUser :: (MonadIO m, MonadThrow m) => ConduitM Event o m WsUser
parseUser = WsUser
<$> optionalWith parseUInt (tagNoAttr "id" content)
<*> tagNoAttr "username" content
<*> tagNoAttr "firstName" content
<*> tagNoAttr "lastName" content
parseScanAppl :: (MonadIO m, MonadThrow m) => ConduitM Event o m ScanAppl
parseScanAppl = ScanAppl
<$> requireTagNoAttr "type" content
<*> tagNoAttr "friendlyName" content
parseComment :: (MonadThrow m, MonadIO m) => ConduitM Event o m Comment
parseComment = Comment
<$> requireTagNoAttr "contents" content
<*> tagNoAttr "author" parseUser
<*> optionalWith parseDate (tagNoAttr "createdDate" content)
parseV3List :: (MonadIO m, MonadThrow m)
=> Name -- ^ Name of the list
-> Consumer Event m (Maybe a) -- ^ function to parse list items
-> ConduitM Event o m (Maybe [a])
parseV3List x f = do
xs <- tagNoAttr x $ do
parseDiscard "count"
tagNoAttr "list" (many f)
return $ join xs
| ahodgen/qualys | Qualys/Internal/ParseWasCommon.hs | bsd-3-clause | 2,226 | 0 | 13 | 526 | 628 | 326 | 302 | 55 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
module Haskcord.Resource.GuildChannel
where
import Control.Lens
import Data.Aeson
import qualified Data.Text as T
import Haskcord.Resource.Base
import Haskcord.Resource.Id
import Haskcord.Permissions
-- TODO we need to "thread in" guild_id somehow.
data GuildChannelResource = GuildChannelResource {
_guildChannelResourceId :: GuildChannelId
--, _guildChannelResourceGuildId :: GuildId
, _guildChannelResourceName :: T.Text
, _guildChannelResourceType :: T.Text
, _guildChannelResourcePosition :: Int
, _guildChannelResourcePermissionOverwrites :: [Overwrite]
, _guildChannelResourceTopic :: Maybe T.Text
, _guildChannelResourceLastMessageId :: Maybe MessageId
, _guildChannelResourceBitrate :: Maybe Int
, _guildChannelResourceUserLimit :: Maybe Int
}
deriving (Show, Eq, Read)
makeLenses ''GuildChannelResource
instance FromJSON GuildChannelResource where
parseJSON = withObject "guildchannel" $ \v -> GuildChannelResource
<$> v .: "id"
-- <*> v .: "guild_id"
<*> v .: "name"
<*> v .: "type"
<*> v .: "position"
<*> v .: "permission_overwrites"
<*> v .:? "topic"
<*> v .:? "last_message_id"
<*> v .:? "bitrate"
<*> v .:? "user_limit"
instance Resource GuildChannelResource where
syncResource = error "unimplemented lol" | swagcod/haskcord | src/Haskcord/Resource/GuildChannel.hs | bsd-3-clause | 1,433 | 0 | 25 | 295 | 267 | 151 | 116 | 34 | 0 |
module Job.Description where
import Text.Regex.Posix
data JobDescription = JobDescription
{ jobId :: String
, name :: String
, args :: [String]
, matchExpr :: String
}
filterJobsMatching :: [JobDescription] -> FilePath -> [JobDescription]
filterJobsMatching jobDescriptions fileChanged = filter isMatch jobDescriptions
where
isMatch job = fileChanged =~ matchExpr job
fullName :: JobDescription -> String
fullName (JobDescription { name = name, args = args }) = name ++ " " ++ unwords args
| rickardlindberg/codemonitor | src/Job/Description.hs | bsd-3-clause | 540 | 0 | 9 | 121 | 145 | 82 | 63 | 12 | 1 |
module Test.Network.BitTorrent.Whiteout (theTests) where
import Control.Applicative
import Control.Concurrent.STM
import Data.Array.IArray
import Data.Maybe
import Test.Framework
import Test.Framework.Providers.HUnit
import Test.HUnit
import Network.BitTorrent.Whiteout
theTests :: Test.Framework.Test
theTests =
testGroup "Network.Whiteout" [
testGroup "verify" [
testCase "singleFileShouldSucceed" verifySingleFileShouldSucceed,
testCase "singleFileShouldFail" verifySingleFileShouldFail,
testCase "multiFileShouldSucceed" verifyMultiFileShouldSucceed,
testCase "multiFileShouldFail" verifyMultiFileShouldFail
]
]
verifyGeneric :: FilePath -> FilePath -> Bool -> Assertion
verifyGeneric torpath datapath expectedResult = do
sess <- initialize Nothing Nothing Nothing
tor <- loadTorrentFromFile torpath
torst <- addTorrent sess tor datapath
beginVerifyingTorrent sess torst
atomically $ do
activity <- getActivity torst
case activity of
Verifying -> retry
Stopped -> return ()
Running -> error "Ghost started torrent."
Stopping -> error
"Ghost started torrent, then stopped it again. Spooooooky."
let (0, maxPieceNum) = bounds $ tPieceHashes tor
allExpected <- and <$> atomically
(mapM
(\i -> (==expectedResult) <$> isPieceComplete torst i)
[0..maxPieceNum]
)
assertBool "Some pieces were not verified as expected" allExpected
close sess
verifySingleFileShouldSucceed :: Assertion
verifySingleFileShouldSucceed = verifyGeneric
"test-data/01_-_Brad_Sucks_-_Dropping_out_of_School.mp3.torrent"
"test-data/01_-_Brad_Sucks_-_Dropping_out_of_School.mp3"
True
verifySingleFileShouldFail :: Assertion
verifySingleFileShouldFail = verifyGeneric
"test-data/01_-_Brad_Sucks_-_Dropping_out_of_School.mp3.torrent"
"test-data/01_-_Brad_Sucks_-_Dropping_out_of_School.mp3.zeroes"
False
verifyMultiFileShouldSucceed :: Assertion
verifyMultiFileShouldSucceed = verifyGeneric
"test-data/larry lessig - code v2.torrent"
"test-data/Larry Lessig - Code V2"
True
verifyMultiFileShouldFail :: Assertion
verifyMultiFileShouldFail = verifyGeneric
"test-data/larry lessig - code v2.torrent"
"test-data/Larry Lessig - Code V2.zeroes"
False
| enolan/whiteout | src/Test/Network/BitTorrent/Whiteout.hs | bsd-3-clause | 2,399 | 0 | 15 | 483 | 403 | 205 | 198 | 58 | 4 |
module Handler.CampaignDel where
import Import
getCampaignDelR :: CampaignId -> Handler Html
getCampaignDelR cid = do
user <- requireAuthId
camp <- runDB $ get404 cid
if user /= campaignOwnerId camp
then do
setMessage "Permission denied."
defaultLayout $ $(widgetFile "error")
else do
runDB $ deleteWhere [EntryCampaignId ==. cid]
runDB $ delete cid
setMessage . toHtml $ campaignName camp <> " deleted."
redirect HomeR
| sulami/hGM | Handler/CampaignDel.hs | bsd-3-clause | 473 | 0 | 14 | 114 | 140 | 64 | 76 | -1 | -1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
-----------------------------------------------------------------------------
--
-- (c) The University of Glasgow 2004-2009.
--
-- Package management tool
--
-----------------------------------------------------------------------------
module Main (main) where
import Version ( version, targetOS, targetARCH )
import qualified GHC.PackageDb as GhcPkg
import GHC.PackageDb (BinaryStringRep(..))
import qualified Distribution.Simple.PackageIndex as PackageIndex
import qualified Data.Graph as Graph
import qualified Distribution.ModuleName as ModuleName
import Distribution.ModuleName (ModuleName)
import Distribution.InstalledPackageInfo as Cabal
import Distribution.Compat.ReadP hiding (get)
import Distribution.ParseUtils
import Distribution.Package hiding (installedUnitId)
import Distribution.Text
import Distribution.Version
import Distribution.Backpack
import Distribution.Simple.Utils (fromUTF8, toUTF8, writeUTF8File, readUTF8File)
import qualified Data.Version as Version
import System.FilePath as FilePath
import qualified System.FilePath.Posix as FilePath.Posix
import System.Directory ( getAppUserDataDirectory, createDirectoryIfMissing,
getModificationTime )
import Text.Printf
import Prelude
import System.Console.GetOpt
import qualified Control.Exception as Exception
import Data.Maybe
import Data.Char ( isSpace, toLower )
import Control.Monad
import System.Directory ( doesDirectoryExist, getDirectoryContents,
doesFileExist, removeFile,
getCurrentDirectory )
import System.Exit ( exitWith, ExitCode(..) )
import System.Environment ( getArgs, getProgName, getEnv )
import System.IO
import System.IO.Error
import GHC.IO.Exception (IOErrorType(InappropriateType))
import Data.List
import Control.Concurrent
import qualified Data.Set as Set
import qualified Data.Map as Map
import qualified Data.ByteString.Char8 as BS
#if defined(mingw32_HOST_OS)
-- mingw32 needs these for getExecDir
import Foreign
import Foreign.C
#endif
#ifdef mingw32_HOST_OS
import GHC.ConsoleHandler
#else
import System.Posix hiding (fdToHandle)
#endif
#if defined(GLOB)
import qualified System.Info(os)
#endif
#if !defined(mingw32_HOST_OS) && !defined(BOOTSTRAPPING)
import System.Console.Terminfo as Terminfo
#endif
#ifdef mingw32_HOST_OS
# if defined(i386_HOST_ARCH)
# define WINDOWS_CCONV stdcall
# elif defined(x86_64_HOST_ARCH)
# define WINDOWS_CCONV ccall
# else
# error Unknown mingw32 arch
# endif
#endif
-- | Short-circuit 'any' with a \"monadic predicate\".
anyM :: (Monad m) => (a -> m Bool) -> [a] -> m Bool
anyM _ [] = return False
anyM p (x:xs) = do
b <- p x
if b
then return True
else anyM p xs
-- -----------------------------------------------------------------------------
-- Entry point
main :: IO ()
main = do
args <- getArgs
case getOpt Permute (flags ++ deprecFlags) args of
(cli,_,[]) | FlagHelp `elem` cli -> do
prog <- getProgramName
bye (usageInfo (usageHeader prog) flags)
(cli,_,[]) | FlagVersion `elem` cli ->
bye ourCopyright
(cli,nonopts,[]) ->
case getVerbosity Normal cli of
Right v -> runit v cli nonopts
Left err -> die err
(_,_,errors) -> do
prog <- getProgramName
die (concat errors ++ shortUsage prog)
-- -----------------------------------------------------------------------------
-- Command-line syntax
data Flag
= FlagUser
| FlagGlobal
| FlagHelp
| FlagVersion
| FlagConfig FilePath
| FlagGlobalConfig FilePath
| FlagUserConfig FilePath
| FlagForce
| FlagForceFiles
| FlagMultiInstance
| FlagExpandEnvVars
| FlagExpandPkgroot
| FlagNoExpandPkgroot
| FlagSimpleOutput
| FlagNamesOnly
| FlagIgnoreCase
| FlagNoUserDb
| FlagVerbosity (Maybe String)
| FlagUnitId
deriving Eq
flags :: [OptDescr Flag]
flags = [
Option [] ["user"] (NoArg FlagUser)
"use the current user's package database",
Option [] ["global"] (NoArg FlagGlobal)
"use the global package database",
Option ['f'] ["package-db"] (ReqArg FlagConfig "FILE/DIR")
"use the specified package database",
Option [] ["package-conf"] (ReqArg FlagConfig "FILE/DIR")
"use the specified package database (DEPRECATED)",
Option [] ["global-package-db"] (ReqArg FlagGlobalConfig "DIR")
"location of the global package database",
Option [] ["no-user-package-db"] (NoArg FlagNoUserDb)
"never read the user package database",
Option [] ["user-package-db"] (ReqArg FlagUserConfig "DIR")
"location of the user package database (use instead of default)",
Option [] ["no-user-package-conf"] (NoArg FlagNoUserDb)
"never read the user package database (DEPRECATED)",
Option [] ["force"] (NoArg FlagForce)
"ignore missing dependencies, directories, and libraries",
Option [] ["force-files"] (NoArg FlagForceFiles)
"ignore missing directories and libraries only",
Option [] ["enable-multi-instance"] (NoArg FlagMultiInstance)
"allow registering multiple instances of the same package version",
Option [] ["expand-env-vars"] (NoArg FlagExpandEnvVars)
"expand environment variables (${name}-style) in input package descriptions",
Option [] ["expand-pkgroot"] (NoArg FlagExpandPkgroot)
"expand ${pkgroot}-relative paths to absolute in output package descriptions",
Option [] ["no-expand-pkgroot"] (NoArg FlagNoExpandPkgroot)
"preserve ${pkgroot}-relative paths in output package descriptions",
Option ['?'] ["help"] (NoArg FlagHelp)
"display this help and exit",
Option ['V'] ["version"] (NoArg FlagVersion)
"output version information and exit",
Option [] ["simple-output"] (NoArg FlagSimpleOutput)
"print output in easy-to-parse format for some commands",
Option [] ["names-only"] (NoArg FlagNamesOnly)
"only print package names, not versions; can only be used with list --simple-output",
Option [] ["ignore-case"] (NoArg FlagIgnoreCase)
"ignore case for substring matching",
Option [] ["ipid", "unit-id"] (NoArg FlagUnitId)
"interpret package arguments as unit IDs (e.g. installed package IDs)",
Option ['v'] ["verbose"] (OptArg FlagVerbosity "Verbosity")
"verbosity level (0-2, default 1)"
]
data Verbosity = Silent | Normal | Verbose
deriving (Show, Eq, Ord)
getVerbosity :: Verbosity -> [Flag] -> Either String Verbosity
getVerbosity v [] = Right v
getVerbosity _ (FlagVerbosity Nothing : fs) = getVerbosity Verbose fs
getVerbosity _ (FlagVerbosity (Just "0") : fs) = getVerbosity Silent fs
getVerbosity _ (FlagVerbosity (Just "1") : fs) = getVerbosity Normal fs
getVerbosity _ (FlagVerbosity (Just "2") : fs) = getVerbosity Verbose fs
getVerbosity _ (FlagVerbosity v : _) = Left ("Bad verbosity: " ++ show v)
getVerbosity v (_ : fs) = getVerbosity v fs
deprecFlags :: [OptDescr Flag]
deprecFlags = [
-- put deprecated flags here
]
ourCopyright :: String
ourCopyright = "GHC package manager version " ++ Version.version ++ "\n"
shortUsage :: String -> String
shortUsage prog = "For usage information see '" ++ prog ++ " --help'."
usageHeader :: String -> String
usageHeader prog = substProg prog $
"Usage:\n" ++
" $p init {path}\n" ++
" Create and initialise a package database at the location {path}.\n" ++
" Packages can be registered in the new database using the register\n" ++
" command with --package-db={path}. To use the new database with GHC,\n" ++
" use GHC's -package-db flag.\n" ++
"\n" ++
" $p register {filename | -}\n" ++
" Register the package using the specified installed package\n" ++
" description. The syntax for the latter is given in the $p\n" ++
" documentation. The input file should be encoded in UTF-8.\n" ++
"\n" ++
" $p update {filename | -}\n" ++
" Register the package, overwriting any other package with the\n" ++
" same name. The input file should be encoded in UTF-8.\n" ++
"\n" ++
" $p unregister [pkg-id] \n" ++
" Unregister the specified packages in the order given.\n" ++
"\n" ++
" $p expose {pkg-id}\n" ++
" Expose the specified package.\n" ++
"\n" ++
" $p hide {pkg-id}\n" ++
" Hide the specified package.\n" ++
"\n" ++
" $p trust {pkg-id}\n" ++
" Trust the specified package.\n" ++
"\n" ++
" $p distrust {pkg-id}\n" ++
" Distrust the specified package.\n" ++
"\n" ++
" $p list [pkg]\n" ++
" List registered packages in the global database, and also the\n" ++
" user database if --user is given. If a package name is given\n" ++
" all the registered versions will be listed in ascending order.\n" ++
" Accepts the --simple-output flag.\n" ++
"\n" ++
" $p dot\n" ++
" Generate a graph of the package dependencies in a form suitable\n" ++
" for input for the graphviz tools. For example, to generate a PDF" ++
" of the dependency graph: ghc-pkg dot | tred | dot -Tpdf >pkgs.pdf" ++
"\n" ++
" $p find-module {module}\n" ++
" List registered packages exposing module {module} in the global\n" ++
" database, and also the user database if --user is given.\n" ++
" All the registered versions will be listed in ascending order.\n" ++
" Accepts the --simple-output flag.\n" ++
"\n" ++
" $p latest {pkg-id}\n" ++
" Prints the highest registered version of a package.\n" ++
"\n" ++
" $p check\n" ++
" Check the consistency of package dependencies and list broken packages.\n" ++
" Accepts the --simple-output flag.\n" ++
"\n" ++
" $p describe {pkg}\n" ++
" Give the registered description for the specified package. The\n" ++
" description is returned in precisely the syntax required by $p\n" ++
" register.\n" ++
"\n" ++
" $p field {pkg} {field}\n" ++
" Extract the specified field of the package description for the\n" ++
" specified package. Accepts comma-separated multiple fields.\n" ++
"\n" ++
" $p dump\n" ++
" Dump the registered description for every package. This is like\n" ++
" \"ghc-pkg describe '*'\", except that it is intended to be used\n" ++
" by tools that parse the results, rather than humans. The output is\n" ++
" always encoded in UTF-8, regardless of the current locale.\n" ++
"\n" ++
" $p recache\n" ++
" Regenerate the package database cache. This command should only be\n" ++
" necessary if you added a package to the database by dropping a file\n" ++
" into the database directory manually. By default, the global DB\n" ++
" is recached; to recache a different DB use --user or --package-db\n" ++
" as appropriate.\n" ++
"\n" ++
" Substring matching is supported for {module} in find-module and\n" ++
" for {pkg} in list, describe, and field, where a '*' indicates\n" ++
" open substring ends (prefix*, *suffix, *infix*). Use --ipid to\n" ++
" match against the installed package ID instead.\n" ++
"\n" ++
" When asked to modify a database (register, unregister, update,\n"++
" hide, expose, and also check), ghc-pkg modifies the global database by\n"++
" default. Specifying --user causes it to act on the user database,\n"++
" or --package-db can be used to act on another database\n"++
" entirely. When multiple of these options are given, the rightmost\n"++
" one is used as the database to act upon.\n"++
"\n"++
" Commands that query the package database (list, tree, latest, describe,\n"++
" field) operate on the list of databases specified by the flags\n"++
" --user, --global, and --package-db. If none of these flags are\n"++
" given, the default is --global --user.\n"++
"\n" ++
" The following optional flags are also accepted:\n"
substProg :: String -> String -> String
substProg _ [] = []
substProg prog ('$':'p':xs) = prog ++ substProg prog xs
substProg prog (c:xs) = c : substProg prog xs
-- -----------------------------------------------------------------------------
-- Do the business
data Force = NoForce | ForceFiles | ForceAll | CannotForce
deriving (Eq,Ord)
-- | Enum flag representing argument type
data AsPackageArg
= AsUnitId
| AsDefault
-- | Represents how a package may be specified by a user on the command line.
data PackageArg
-- | A package identifier foo-0.1, or a glob foo-*
= Id GlobPackageIdentifier
-- | An installed package ID foo-0.1-HASH. This is guaranteed to uniquely
-- match a single entry in the package database.
| IUId UnitId
-- | A glob against the package name. The first string is the literal
-- glob, the second is a function which returns @True@ if the argument
-- matches.
| Substring String (String->Bool)
runit :: Verbosity -> [Flag] -> [String] -> IO ()
runit verbosity cli nonopts = do
installSignalHandlers -- catch ^C and clean up
when (verbosity >= Verbose)
(putStr ourCopyright)
prog <- getProgramName
let
force
| FlagForce `elem` cli = ForceAll
| FlagForceFiles `elem` cli = ForceFiles
| otherwise = NoForce
as_arg | FlagUnitId `elem` cli = AsUnitId
| otherwise = AsDefault
multi_instance = FlagMultiInstance `elem` cli
expand_env_vars= FlagExpandEnvVars `elem` cli
mexpand_pkgroot= foldl' accumExpandPkgroot Nothing cli
where accumExpandPkgroot _ FlagExpandPkgroot = Just True
accumExpandPkgroot _ FlagNoExpandPkgroot = Just False
accumExpandPkgroot x _ = x
splitFields fields = unfoldr splitComma (',':fields)
where splitComma "" = Nothing
splitComma fs = Just $ break (==',') (tail fs)
-- | Parses a glob into a predicate which tests if a string matches
-- the glob. Returns Nothing if the string in question is not a glob.
-- At the moment, we only support globs at the beginning and/or end of
-- strings. This function respects case sensitivity.
--
-- >>> fromJust (substringCheck "*") "anything"
-- True
--
-- >>> fromJust (substringCheck "string") "string"
-- True
--
-- >>> fromJust (substringCheck "*bar") "foobar"
-- True
--
-- >>> fromJust (substringCheck "foo*") "foobar"
-- True
--
-- >>> fromJust (substringCheck "*ooba*") "foobar"
-- True
--
-- >>> fromJust (substringCheck "f*bar") "foobar"
-- False
substringCheck :: String -> Maybe (String -> Bool)
substringCheck "" = Nothing
substringCheck "*" = Just (const True)
substringCheck [_] = Nothing
substringCheck (h:t) =
case (h, init t, last t) of
('*',s,'*') -> Just (isInfixOf (f s) . f)
('*',_, _ ) -> Just (isSuffixOf (f t) . f)
( _ ,s,'*') -> Just (isPrefixOf (f (h:s)) . f)
_ -> Nothing
where f | FlagIgnoreCase `elem` cli = map toLower
| otherwise = id
#if defined(GLOB)
glob x | System.Info.os=="mingw32" = do
-- glob echoes its argument, after win32 filename globbing
(_,o,_,_) <- runInteractiveCommand ("glob "++x)
txt <- hGetContents o
return (read txt)
glob x | otherwise = return [x]
#endif
--
-- first, parse the command
case nonopts of
#if defined(GLOB)
-- dummy command to demonstrate usage and permit testing
-- without messing things up; use glob to selectively enable
-- windows filename globbing for file parameters
-- register, update, FlagGlobalConfig, FlagConfig; others?
["glob", filename] -> do
print filename
glob filename >>= print
#endif
["init", filename] ->
initPackageDB filename verbosity cli
["register", filename] ->
registerPackage filename verbosity cli
multi_instance
expand_env_vars False force
["update", filename] ->
registerPackage filename verbosity cli
multi_instance
expand_env_vars True force
"unregister" : pkgarg_strs@(_:_) -> do
forM_ pkgarg_strs $ \pkgarg_str -> do
pkgarg <- readPackageArg as_arg pkgarg_str
unregisterPackage pkgarg verbosity cli force
["expose", pkgarg_str] -> do
pkgarg <- readPackageArg as_arg pkgarg_str
exposePackage pkgarg verbosity cli force
["hide", pkgarg_str] -> do
pkgarg <- readPackageArg as_arg pkgarg_str
hidePackage pkgarg verbosity cli force
["trust", pkgarg_str] -> do
pkgarg <- readPackageArg as_arg pkgarg_str
trustPackage pkgarg verbosity cli force
["distrust", pkgarg_str] -> do
pkgarg <- readPackageArg as_arg pkgarg_str
distrustPackage pkgarg verbosity cli force
["list"] -> do
listPackages verbosity cli Nothing Nothing
["list", pkgarg_str] ->
case substringCheck pkgarg_str of
Nothing -> do pkgarg <- readPackageArg as_arg pkgarg_str
listPackages verbosity cli (Just pkgarg) Nothing
Just m -> listPackages verbosity cli
(Just (Substring pkgarg_str m)) Nothing
["dot"] -> do
showPackageDot verbosity cli
["find-module", mod_name] -> do
let match = maybe (==mod_name) id (substringCheck mod_name)
listPackages verbosity cli Nothing (Just match)
["latest", pkgid_str] -> do
pkgid <- readGlobPkgId pkgid_str
latestPackage verbosity cli pkgid
["describe", pkgid_str] -> do
pkgarg <- case substringCheck pkgid_str of
Nothing -> readPackageArg as_arg pkgid_str
Just m -> return (Substring pkgid_str m)
describePackage verbosity cli pkgarg (fromMaybe False mexpand_pkgroot)
["field", pkgid_str, fields] -> do
pkgarg <- case substringCheck pkgid_str of
Nothing -> readPackageArg as_arg pkgid_str
Just m -> return (Substring pkgid_str m)
describeField verbosity cli pkgarg
(splitFields fields) (fromMaybe True mexpand_pkgroot)
["check"] -> do
checkConsistency verbosity cli
["dump"] -> do
dumpPackages verbosity cli (fromMaybe False mexpand_pkgroot)
["recache"] -> do
recache verbosity cli
[] -> do
die ("missing command\n" ++ shortUsage prog)
(_cmd:_) -> do
die ("command-line syntax error\n" ++ shortUsage prog)
parseCheck :: ReadP a a -> String -> String -> IO a
parseCheck parser str what =
case [ x | (x,ys) <- readP_to_S parser str, all isSpace ys ] of
[x] -> return x
_ -> die ("cannot parse \'" ++ str ++ "\' as a " ++ what)
-- | Either an exact 'PackageIdentifier', or a glob for all packages
-- matching 'PackageName'.
data GlobPackageIdentifier
= ExactPackageIdentifier PackageIdentifier
| GlobPackageIdentifier PackageName
displayGlobPkgId :: GlobPackageIdentifier -> String
displayGlobPkgId (ExactPackageIdentifier pid) = display pid
displayGlobPkgId (GlobPackageIdentifier pn) = display pn ++ "-*"
readGlobPkgId :: String -> IO GlobPackageIdentifier
readGlobPkgId str = parseCheck parseGlobPackageId str "package identifier"
parseGlobPackageId :: ReadP r GlobPackageIdentifier
parseGlobPackageId =
fmap ExactPackageIdentifier parse
+++
(do n <- parse
_ <- string "-*"
return (GlobPackageIdentifier n))
readPackageArg :: AsPackageArg -> String -> IO PackageArg
readPackageArg AsUnitId str =
parseCheck (IUId `fmap` parse) str "installed package id"
readPackageArg AsDefault str = Id `fmap` readGlobPkgId str
-- -----------------------------------------------------------------------------
-- Package databases
-- Some commands operate on a single database:
-- register, unregister, expose, hide, trust, distrust
-- however these commands also check the union of the available databases
-- in order to check consistency. For example, register will check that
-- dependencies exist before registering a package.
--
-- Some commands operate on multiple databases, with overlapping semantics:
-- list, describe, field
data PackageDB
= PackageDB {
location, locationAbsolute :: !FilePath,
-- We need both possibly-relative and definately-absolute package
-- db locations. This is because the relative location is used as
-- an identifier for the db, so it is important we do not modify it.
-- On the other hand we need the absolute path in a few places
-- particularly in relation to the ${pkgroot} stuff.
packages :: [InstalledPackageInfo]
}
type PackageDBStack = [PackageDB]
-- A stack of package databases. Convention: head is the topmost
-- in the stack.
allPackagesInStack :: PackageDBStack -> [InstalledPackageInfo]
allPackagesInStack = concatMap packages
getPkgDatabases :: Verbosity
-> Bool -- we are modifying, not reading
-> Bool -- use the user db
-> Bool -- read caches, if available
-> Bool -- expand vars, like ${pkgroot} and $topdir
-> [Flag]
-> IO (PackageDBStack,
-- the real package DB stack: [global,user] ++
-- DBs specified on the command line with -f.
Maybe FilePath,
-- which one to modify, if any
PackageDBStack)
-- the package DBs specified on the command
-- line, or [global,user] otherwise. This
-- is used as the list of package DBs for
-- commands that just read the DB, such as 'list'.
getPkgDatabases verbosity modify use_user use_cache expand_vars my_flags = do
-- first we determine the location of the global package config. On Windows,
-- this is found relative to the ghc-pkg.exe binary, whereas on Unix the
-- location is passed to the binary using the --global-package-db flag by the
-- wrapper script.
let err_msg = "missing --global-package-db option, location of global package database unknown\n"
global_conf <-
case [ f | FlagGlobalConfig f <- my_flags ] of
[] -> do mb_dir <- getLibDir
case mb_dir of
Nothing -> die err_msg
Just dir -> do
r <- lookForPackageDBIn dir
case r of
Nothing -> die ("Can't find package database in " ++ dir)
Just path -> return path
fs -> return (last fs)
-- The value of the $topdir variable used in some package descriptions
-- Note that the way we calculate this is slightly different to how it
-- is done in ghc itself. We rely on the convention that the global
-- package db lives in ghc's libdir.
top_dir <- absolutePath (takeDirectory global_conf)
let no_user_db = FlagNoUserDb `elem` my_flags
-- get the location of the user package database, and create it if necessary
-- getAppUserDataDirectory can fail (e.g. if $HOME isn't set)
e_appdir <- tryIO $ getAppUserDataDirectory "ghc"
mb_user_conf <-
case [ f | FlagUserConfig f <- my_flags ] of
_ | no_user_db -> return Nothing
[] -> case e_appdir of
Left _ -> return Nothing
Right appdir -> do
let subdir = targetARCH ++ '-':targetOS ++ '-':Version.version
dir = appdir </> subdir
r <- lookForPackageDBIn dir
case r of
Nothing -> return (Just (dir </> "package.conf.d", False))
Just f -> return (Just (f, True))
fs -> return (Just (last fs, True))
-- If the user database exists, and for "use_user" commands (which includes
-- "ghc-pkg check" and all commands that modify the db) we will attempt to
-- use the user db.
let sys_databases
| Just (user_conf,user_exists) <- mb_user_conf,
use_user || user_exists = [user_conf, global_conf]
| otherwise = [global_conf]
e_pkg_path <- tryIO (System.Environment.getEnv "GHC_PACKAGE_PATH")
let env_stack =
case e_pkg_path of
Left _ -> sys_databases
Right path
| not (null path) && isSearchPathSeparator (last path)
-> splitSearchPath (init path) ++ sys_databases
| otherwise
-> splitSearchPath path
-- The "global" database is always the one at the bottom of the stack.
-- This is the database we modify by default.
virt_global_conf = last env_stack
let db_flags = [ f | Just f <- map is_db_flag my_flags ]
where is_db_flag FlagUser
| Just (user_conf, _user_exists) <- mb_user_conf
= Just user_conf
is_db_flag FlagGlobal = Just virt_global_conf
is_db_flag (FlagConfig f) = Just f
is_db_flag _ = Nothing
let flag_db_names | null db_flags = env_stack
| otherwise = reverse (nub db_flags)
-- For a "modify" command, treat all the databases as
-- a stack, where we are modifying the top one, but it
-- can refer to packages in databases further down the
-- stack.
-- -f flags on the command line add to the database
-- stack, unless any of them are present in the stack
-- already.
let final_stack = filter (`notElem` env_stack)
[ f | FlagConfig f <- reverse my_flags ]
++ env_stack
-- the database we actually modify is the one mentioned
-- rightmost on the command-line.
let to_modify
| not modify = Nothing
| null db_flags = Just virt_global_conf
| otherwise = Just (last db_flags)
db_stack <- sequence
[ do db <- readParseDatabase verbosity mb_user_conf modify use_cache db_path
if expand_vars then return (mungePackageDBPaths top_dir db)
else return db
| db_path <- final_stack ]
let flag_db_stack = [ db | db_name <- flag_db_names,
db <- db_stack, location db == db_name ]
when (verbosity > Normal) $ do
infoLn ("db stack: " ++ show (map location db_stack))
infoLn ("modifying: " ++ show to_modify)
infoLn ("flag db stack: " ++ show (map location flag_db_stack))
return (db_stack, to_modify, flag_db_stack)
lookForPackageDBIn :: FilePath -> IO (Maybe FilePath)
lookForPackageDBIn dir = do
let path_dir = dir </> "package.conf.d"
exists_dir <- doesDirectoryExist path_dir
if exists_dir then return (Just path_dir) else do
let path_file = dir </> "package.conf"
exists_file <- doesFileExist path_file
if exists_file then return (Just path_file) else return Nothing
readParseDatabase :: Verbosity
-> Maybe (FilePath,Bool)
-> Bool -- we will be modifying, not just reading
-> Bool -- use cache
-> FilePath
-> IO PackageDB
readParseDatabase verbosity mb_user_conf modify use_cache path
-- the user database (only) is allowed to be non-existent
| Just (user_conf,False) <- mb_user_conf, path == user_conf
= mkPackageDB []
| otherwise
= do e <- tryIO $ getDirectoryContents path
case e of
Left err
| ioeGetErrorType err == InappropriateType -> do
-- We provide a limited degree of backwards compatibility for
-- old single-file style db:
mdb <- tryReadParseOldFileStyleDatabase verbosity
mb_user_conf modify use_cache path
case mdb of
Just db -> return db
Nothing ->
die $ "ghc no longer supports single-file style package "
++ "databases (" ++ path ++ ") use 'ghc-pkg init'"
++ "to create the database with the correct format."
| otherwise -> ioError err
Right fs
| not use_cache -> ignore_cache (const $ return ())
| otherwise -> do
let cache = path </> cachefilename
tdir <- getModificationTime path
e_tcache <- tryIO $ getModificationTime cache
case e_tcache of
Left ex -> do
whenReportCacheErrors $
if isDoesNotExistError ex
then do
warn ("WARNING: cache does not exist: " ++ cache)
warn ("ghc will fail to read this package db. " ++
recacheAdvice)
else do
warn ("WARNING: cache cannot be read: " ++ show ex)
warn "ghc will fail to read this package db."
ignore_cache (const $ return ())
Right tcache -> do
let compareTimestampToCache file =
when (verbosity >= Verbose) $ do
tFile <- getModificationTime file
compareTimestampToCache' file tFile
compareTimestampToCache' file tFile = do
let rel = case tcache `compare` tFile of
LT -> " (NEWER than cache)"
GT -> " (older than cache)"
EQ -> " (same as cache)"
warn ("Timestamp " ++ show tFile
++ " for " ++ file ++ rel)
when (verbosity >= Verbose) $ do
warn ("Timestamp " ++ show tcache ++ " for " ++ cache)
compareTimestampToCache' path tdir
if tcache >= tdir
then do
when (verbosity > Normal) $
infoLn ("using cache: " ++ cache)
pkgs <- GhcPkg.readPackageDbForGhcPkg cache
mkPackageDB pkgs
else do
whenReportCacheErrors $ do
warn ("WARNING: cache is out of date: " ++ cache)
warn ("ghc will see an old view of this " ++
"package db. " ++ recacheAdvice)
ignore_cache compareTimestampToCache
where
ignore_cache :: (FilePath -> IO ()) -> IO PackageDB
ignore_cache checkTime = do
let confs = filter (".conf" `isSuffixOf`) fs
doFile f = do checkTime f
parseSingletonPackageConf verbosity f
pkgs <- mapM doFile $ map (path </>) confs
mkPackageDB pkgs
-- We normally report cache errors for read-only commands,
-- since modify commands because will usually fix the cache.
whenReportCacheErrors =
when ( verbosity > Normal
|| verbosity >= Normal && not modify)
where
recacheAdvice
| Just (user_conf, True) <- mb_user_conf, path == user_conf
= "Use 'ghc-pkg recache --user' to fix."
| otherwise
= "Use 'ghc-pkg recache' to fix."
mkPackageDB pkgs = do
path_abs <- absolutePath path
return PackageDB {
location = path,
locationAbsolute = path_abs,
packages = pkgs
}
parseSingletonPackageConf :: Verbosity -> FilePath -> IO InstalledPackageInfo
parseSingletonPackageConf verbosity file = do
when (verbosity > Normal) $ infoLn ("reading package config: " ++ file)
readUTF8File file >>= fmap fst . parsePackageInfo
cachefilename :: FilePath
cachefilename = "package.cache"
mungePackageDBPaths :: FilePath -> PackageDB -> PackageDB
mungePackageDBPaths top_dir db@PackageDB { packages = pkgs } =
db { packages = map (mungePackagePaths top_dir pkgroot) pkgs }
where
pkgroot = takeDirectory $ dropTrailingPathSeparator (locationAbsolute db)
-- It so happens that for both styles of package db ("package.conf"
-- files and "package.conf.d" dirs) the pkgroot is the parent directory
-- ${pkgroot}/package.conf or ${pkgroot}/package.conf.d/
-- TODO: This code is duplicated in compiler/main/Packages.lhs
mungePackagePaths :: FilePath -> FilePath
-> InstalledPackageInfo -> InstalledPackageInfo
-- Perform path/URL variable substitution as per the Cabal ${pkgroot} spec
-- (http://www.haskell.org/pipermail/libraries/2009-May/011772.html)
-- Paths/URLs can be relative to ${pkgroot} or ${pkgrooturl}.
-- The "pkgroot" is the directory containing the package database.
--
-- Also perform a similar substitution for the older GHC-specific
-- "$topdir" variable. The "topdir" is the location of the ghc
-- installation (obtained from the -B option).
mungePackagePaths top_dir pkgroot pkg =
pkg {
importDirs = munge_paths (importDirs pkg),
includeDirs = munge_paths (includeDirs pkg),
libraryDirs = munge_paths (libraryDirs pkg),
libraryDynDirs = munge_paths (libraryDynDirs pkg),
frameworkDirs = munge_paths (frameworkDirs pkg),
haddockInterfaces = munge_paths (haddockInterfaces pkg),
-- haddock-html is allowed to be either a URL or a file
haddockHTMLs = munge_paths (munge_urls (haddockHTMLs pkg))
}
where
munge_paths = map munge_path
munge_urls = map munge_url
munge_path p
| Just p' <- stripVarPrefix "${pkgroot}" p = pkgroot ++ p'
| Just p' <- stripVarPrefix "$topdir" p = top_dir ++ p'
| otherwise = p
munge_url p
| Just p' <- stripVarPrefix "${pkgrooturl}" p = toUrlPath pkgroot p'
| Just p' <- stripVarPrefix "$httptopdir" p = toUrlPath top_dir p'
| otherwise = p
toUrlPath r p = "file:///"
-- URLs always use posix style '/' separators:
++ FilePath.Posix.joinPath
(r : -- We need to drop a leading "/" or "\\"
-- if there is one:
dropWhile (all isPathSeparator)
(FilePath.splitDirectories p))
-- We could drop the separator here, and then use </> above. However,
-- by leaving it in and using ++ we keep the same path separator
-- rather than letting FilePath change it to use \ as the separator
stripVarPrefix var path = case stripPrefix var path of
Just [] -> Just []
Just cs@(c : _) | isPathSeparator c -> Just cs
_ -> Nothing
-- -----------------------------------------------------------------------------
-- Workaround for old single-file style package dbs
-- Single-file style package dbs have been deprecated for some time, but
-- it turns out that Cabal was using them in one place. So this code is for a
-- workaround to allow older Cabal versions to use this newer ghc.
-- We check if the file db contains just "[]" and if so, we look for a new
-- dir-style db in path.d/, ie in a dir next to the given file.
-- We cannot just replace the file with a new dir style since Cabal still
-- assumes it's a file and tries to overwrite with 'writeFile'.
-- ghc itself also cooperates in this workaround
tryReadParseOldFileStyleDatabase :: Verbosity -> Maybe (FilePath, Bool)
-> Bool -> Bool -> FilePath
-> IO (Maybe PackageDB)
tryReadParseOldFileStyleDatabase verbosity mb_user_conf modify use_cache path = do
-- assumes we've already established that path exists and is not a dir
content <- readFile path `catchIO` \_ -> return ""
if take 2 content == "[]"
then do
path_abs <- absolutePath path
let path_dir = path <.> "d"
warn $ "Warning: ignoring old file-style db and trying " ++ path_dir
direxists <- doesDirectoryExist path_dir
if direxists
then do db <- readParseDatabase verbosity mb_user_conf
modify use_cache path_dir
-- but pretend it was at the original location
return $ Just db {
location = path,
locationAbsolute = path_abs
}
else return $ Just PackageDB {
location = path,
locationAbsolute = path_abs,
packages = []
}
-- if the path is not a file, or is not an empty db then we fail
else return Nothing
adjustOldFileStylePackageDB :: PackageDB -> IO PackageDB
adjustOldFileStylePackageDB db = do
-- assumes we have not yet established if it's an old style or not
mcontent <- liftM Just (readFile (location db)) `catchIO` \_ -> return Nothing
case fmap (take 2) mcontent of
-- it is an old style and empty db, so look for a dir kind in location.d/
Just "[]" -> return db {
location = location db <.> "d",
locationAbsolute = locationAbsolute db <.> "d"
}
-- it is old style but not empty, we have to bail
Just _ -> die $ "ghc no longer supports single-file style package "
++ "databases (" ++ location db ++ ") use 'ghc-pkg init'"
++ "to create the database with the correct format."
-- probably not old style, carry on as normal
Nothing -> return db
-- -----------------------------------------------------------------------------
-- Creating a new package DB
initPackageDB :: FilePath -> Verbosity -> [Flag] -> IO ()
initPackageDB filename verbosity _flags = do
let eexist = die ("cannot create: " ++ filename ++ " already exists")
b1 <- doesFileExist filename
when b1 eexist
b2 <- doesDirectoryExist filename
when b2 eexist
filename_abs <- absolutePath filename
changeDB verbosity [] PackageDB {
location = filename, locationAbsolute = filename_abs,
packages = []
}
-- -----------------------------------------------------------------------------
-- Registering
registerPackage :: FilePath
-> Verbosity
-> [Flag]
-> Bool -- multi_instance
-> Bool -- expand_env_vars
-> Bool -- update
-> Force
-> IO ()
registerPackage input verbosity my_flags multi_instance
expand_env_vars update force = do
(db_stack, Just to_modify, _flag_dbs) <-
getPkgDatabases verbosity True{-modify-} True{-use user-}
True{-use cache-} False{-expand vars-} my_flags
let
db_to_operate_on = my_head "register" $
filter ((== to_modify).location) db_stack
s <-
case input of
"-" -> do
when (verbosity >= Normal) $
info "Reading package info from stdin ... "
-- fix the encoding to UTF-8, since this is an interchange format
hSetEncoding stdin utf8
getContents
f -> do
when (verbosity >= Normal) $
info ("Reading package info from " ++ show f ++ " ... ")
readUTF8File f
expanded <- if expand_env_vars then expandEnvVars s force
else return s
(pkg, ws) <- parsePackageInfo expanded
when (verbosity >= Normal) $
infoLn "done."
-- report any warnings from the parse phase
_ <- reportValidateErrors verbosity [] ws
(display (sourcePackageId pkg) ++ ": Warning: ") Nothing
-- validate the expanded pkg, but register the unexpanded
pkgroot <- absolutePath (takeDirectory to_modify)
let top_dir = takeDirectory (location (last db_stack))
pkg_expanded = mungePackagePaths top_dir pkgroot pkg
let truncated_stack = dropWhile ((/= to_modify).location) db_stack
-- truncate the stack for validation, because we don't allow
-- packages lower in the stack to refer to those higher up.
validatePackageConfig pkg_expanded verbosity truncated_stack
multi_instance update force
let
-- In the normal mode, we only allow one version of each package, so we
-- remove all instances with the same source package id as the one we're
-- adding. In the multi instance mode we don't do that, thus allowing
-- multiple instances with the same source package id.
removes = [ RemovePackage p
| not multi_instance,
p <- packages db_to_operate_on,
sourcePackageId p == sourcePackageId pkg,
-- Only remove things that were instantiated the same way!
instantiatedWith p == instantiatedWith pkg ]
--
changeDB verbosity (removes ++ [AddPackage pkg]) db_to_operate_on
parsePackageInfo
:: String
-> IO (InstalledPackageInfo, [ValidateWarning])
parsePackageInfo str =
case parseInstalledPackageInfo str of
ParseOk warnings ok -> return (mungePackageInfo ok, ws)
where
ws = [ msg | PWarning msg <- warnings
, not ("Unrecognized field pkgroot" `isPrefixOf` msg) ]
ParseFailed err -> case locatedErrorMsg err of
(Nothing, s) -> die s
(Just l, s) -> die (show l ++ ": " ++ s)
mungePackageInfo :: InstalledPackageInfo -> InstalledPackageInfo
mungePackageInfo ipi = ipi
-- -----------------------------------------------------------------------------
-- Making changes to a package database
data DBOp = RemovePackage InstalledPackageInfo
| AddPackage InstalledPackageInfo
| ModifyPackage InstalledPackageInfo
changeDB :: Verbosity -> [DBOp] -> PackageDB -> IO ()
changeDB verbosity cmds db = do
let db' = updateInternalDB db cmds
db'' <- adjustOldFileStylePackageDB db'
createDirectoryIfMissing True (location db'')
changeDBDir verbosity cmds db''
updateInternalDB :: PackageDB -> [DBOp] -> PackageDB
updateInternalDB db cmds = db{ packages = foldl do_cmd (packages db) cmds }
where
do_cmd pkgs (RemovePackage p) =
filter ((/= installedUnitId p) . installedUnitId) pkgs
do_cmd pkgs (AddPackage p) = p : pkgs
do_cmd pkgs (ModifyPackage p) =
do_cmd (do_cmd pkgs (RemovePackage p)) (AddPackage p)
changeDBDir :: Verbosity -> [DBOp] -> PackageDB -> IO ()
changeDBDir verbosity cmds db = do
mapM_ do_cmd cmds
updateDBCache verbosity db
where
do_cmd (RemovePackage p) = do
let file = location db </> display (installedUnitId p) <.> "conf"
when (verbosity > Normal) $ infoLn ("removing " ++ file)
removeFileSafe file
do_cmd (AddPackage p) = do
let file = location db </> display (installedUnitId p) <.> "conf"
when (verbosity > Normal) $ infoLn ("writing " ++ file)
writeUTF8File file (showInstalledPackageInfo p)
do_cmd (ModifyPackage p) =
do_cmd (AddPackage p)
updateDBCache :: Verbosity -> PackageDB -> IO ()
updateDBCache verbosity db = do
let filename = location db </> cachefilename
pkgsCabalFormat :: [InstalledPackageInfo]
pkgsCabalFormat = packages db
pkgsGhcCacheFormat :: [PackageCacheFormat]
pkgsGhcCacheFormat = map convertPackageInfoToCacheFormat pkgsCabalFormat
when (verbosity > Normal) $
infoLn ("writing cache " ++ filename)
GhcPkg.writePackageDb filename pkgsGhcCacheFormat pkgsCabalFormat
`catchIO` \e ->
if isPermissionError e
then die (filename ++ ": you don't have permission to modify this file")
else ioError e
-- See Note [writeAtomic leaky abstraction]
-- Cross-platform "touch". This only works if filename is not empty, and not
-- open for writing already.
-- TODO. When the Win32 or directory packages have either a touchFile or a
-- setModificationTime function, use one of those.
withBinaryFile filename ReadWriteMode $ \handle -> do
c <- hGetChar handle
hSeek handle AbsoluteSeek 0
hPutChar handle c
type PackageCacheFormat = GhcPkg.InstalledPackageInfo
ComponentId
PackageIdentifier
PackageName
UnitId
OpenUnitId
ModuleName
OpenModule
convertPackageInfoToCacheFormat :: InstalledPackageInfo -> PackageCacheFormat
convertPackageInfoToCacheFormat pkg =
GhcPkg.InstalledPackageInfo {
GhcPkg.unitId = installedUnitId pkg,
GhcPkg.componentId = installedComponentId pkg,
GhcPkg.instantiatedWith = instantiatedWith pkg,
GhcPkg.sourcePackageId = sourcePackageId pkg,
GhcPkg.packageName = packageName pkg,
GhcPkg.packageVersion = Version.Version (versionNumbers (packageVersion pkg)) [],
GhcPkg.depends = depends pkg,
GhcPkg.abiHash = unAbiHash (abiHash pkg),
GhcPkg.importDirs = importDirs pkg,
GhcPkg.hsLibraries = hsLibraries pkg,
GhcPkg.extraLibraries = extraLibraries pkg,
GhcPkg.extraGHCiLibraries = extraGHCiLibraries pkg,
GhcPkg.libraryDirs = libraryDirs pkg,
GhcPkg.libraryDynDirs = libraryDynDirs pkg,
GhcPkg.frameworks = frameworks pkg,
GhcPkg.frameworkDirs = frameworkDirs pkg,
GhcPkg.ldOptions = ldOptions pkg,
GhcPkg.ccOptions = ccOptions pkg,
GhcPkg.includes = includes pkg,
GhcPkg.includeDirs = includeDirs pkg,
GhcPkg.haddockInterfaces = haddockInterfaces pkg,
GhcPkg.haddockHTMLs = haddockHTMLs pkg,
GhcPkg.exposedModules = map convertExposed (exposedModules pkg),
GhcPkg.hiddenModules = hiddenModules pkg,
GhcPkg.indefinite = indefinite pkg,
GhcPkg.exposed = exposed pkg,
GhcPkg.trusted = trusted pkg
}
where convertExposed (ExposedModule n reexport) = (n, reexport)
instance GhcPkg.BinaryStringRep ComponentId where
fromStringRep = mkComponentId . fromStringRep
toStringRep = toStringRep . display
instance GhcPkg.BinaryStringRep PackageName where
fromStringRep = mkPackageName . fromStringRep
toStringRep = toStringRep . display
instance GhcPkg.BinaryStringRep PackageIdentifier where
fromStringRep = fromMaybe (error "BinaryStringRep PackageIdentifier")
. simpleParse . fromStringRep
toStringRep = toStringRep . display
instance GhcPkg.BinaryStringRep ModuleName where
fromStringRep = ModuleName.fromString . fromStringRep
toStringRep = toStringRep . display
instance GhcPkg.BinaryStringRep String where
fromStringRep = fromUTF8 . BS.unpack
toStringRep = BS.pack . toUTF8
instance GhcPkg.BinaryStringRep UnitId where
fromStringRep = mkUnitId . fromStringRep
toStringRep = toStringRep . display
instance GhcPkg.DbUnitIdModuleRep UnitId ComponentId OpenUnitId ModuleName OpenModule where
fromDbModule (GhcPkg.DbModule uid mod_name) = OpenModule uid mod_name
fromDbModule (GhcPkg.DbModuleVar mod_name) = OpenModuleVar mod_name
toDbModule (OpenModule uid mod_name) = GhcPkg.DbModule uid mod_name
toDbModule (OpenModuleVar mod_name) = GhcPkg.DbModuleVar mod_name
fromDbUnitId (GhcPkg.DbUnitId cid insts) = IndefFullUnitId cid (Map.fromList insts)
fromDbUnitId (GhcPkg.DbInstalledUnitId uid)
= DefiniteUnitId (unsafeMkDefUnitId uid)
toDbUnitId (IndefFullUnitId cid insts) = GhcPkg.DbUnitId cid (Map.toList insts)
toDbUnitId (DefiniteUnitId def_uid)
= GhcPkg.DbInstalledUnitId (unDefUnitId def_uid)
-- -----------------------------------------------------------------------------
-- Exposing, Hiding, Trusting, Distrusting, Unregistering are all similar
exposePackage :: PackageArg -> Verbosity -> [Flag] -> Force -> IO ()
exposePackage = modifyPackage (\p -> ModifyPackage p{exposed=True})
hidePackage :: PackageArg -> Verbosity -> [Flag] -> Force -> IO ()
hidePackage = modifyPackage (\p -> ModifyPackage p{exposed=False})
trustPackage :: PackageArg -> Verbosity -> [Flag] -> Force -> IO ()
trustPackage = modifyPackage (\p -> ModifyPackage p{trusted=True})
distrustPackage :: PackageArg -> Verbosity -> [Flag] -> Force -> IO ()
distrustPackage = modifyPackage (\p -> ModifyPackage p{trusted=False})
unregisterPackage :: PackageArg -> Verbosity -> [Flag] -> Force -> IO ()
unregisterPackage = modifyPackage RemovePackage
modifyPackage
:: (InstalledPackageInfo -> DBOp)
-> PackageArg
-> Verbosity
-> [Flag]
-> Force
-> IO ()
modifyPackage fn pkgarg verbosity my_flags force = do
(db_stack, Just _to_modify, flag_dbs) <-
getPkgDatabases verbosity True{-modify-} True{-use user-}
True{-use cache-} False{-expand vars-} my_flags
-- Do the search for the package respecting flags...
(db, ps) <- fmap head $ findPackagesByDB flag_dbs pkgarg
let
db_name = location db
pkgs = packages db
pks = map installedUnitId ps
cmds = [ fn pkg | pkg <- pkgs, installedUnitId pkg `elem` pks ]
new_db = updateInternalDB db cmds
-- ...but do consistency checks with regards to the full stack
old_broken = brokenPackages (allPackagesInStack db_stack)
rest_of_stack = filter ((/= db_name) . location) db_stack
new_stack = new_db : rest_of_stack
new_broken = brokenPackages (allPackagesInStack new_stack)
newly_broken = filter ((`notElem` map installedUnitId old_broken)
. installedUnitId) new_broken
--
let displayQualPkgId pkg
| [_] <- filter ((== pkgid) . sourcePackageId)
(allPackagesInStack db_stack)
= display pkgid
| otherwise = display pkgid ++ "@" ++ display (installedUnitId pkg)
where pkgid = sourcePackageId pkg
when (not (null newly_broken)) $
dieOrForceAll force ("unregistering would break the following packages: "
++ unwords (map displayQualPkgId newly_broken))
changeDB verbosity cmds db
recache :: Verbosity -> [Flag] -> IO ()
recache verbosity my_flags = do
(db_stack, Just to_modify, _flag_dbs) <-
getPkgDatabases verbosity True{-modify-} True{-use user-} False{-no cache-}
False{-expand vars-} my_flags
let
db_to_operate_on = my_head "recache" $
filter ((== to_modify).location) db_stack
--
changeDB verbosity [] db_to_operate_on
-- -----------------------------------------------------------------------------
-- Listing packages
listPackages :: Verbosity -> [Flag] -> Maybe PackageArg
-> Maybe (String->Bool)
-> IO ()
listPackages verbosity my_flags mPackageName mModuleName = do
let simple_output = FlagSimpleOutput `elem` my_flags
(db_stack, _, flag_db_stack) <-
getPkgDatabases verbosity False{-modify-} False{-use user-}
True{-use cache-} False{-expand vars-} my_flags
let db_stack_filtered -- if a package is given, filter out all other packages
| Just this <- mPackageName =
[ db{ packages = filter (this `matchesPkg`) (packages db) }
| db <- flag_db_stack ]
| Just match <- mModuleName = -- packages which expose mModuleName
[ db{ packages = filter (match `exposedInPkg`) (packages db) }
| db <- flag_db_stack ]
| otherwise = flag_db_stack
db_stack_sorted
= [ db{ packages = sort_pkgs (packages db) }
| db <- db_stack_filtered ]
where sort_pkgs = sortBy cmpPkgIds
cmpPkgIds pkg1 pkg2 =
case pkgName p1 `compare` pkgName p2 of
LT -> LT
GT -> GT
EQ -> case pkgVersion p1 `compare` pkgVersion p2 of
LT -> LT
GT -> GT
EQ -> installedUnitId pkg1 `compare` installedUnitId pkg2
where (p1,p2) = (sourcePackageId pkg1, sourcePackageId pkg2)
stack = reverse db_stack_sorted
match `exposedInPkg` pkg = any match (map display $ exposedModules pkg)
pkg_map = allPackagesInStack db_stack
broken = map installedUnitId (brokenPackages pkg_map)
show_normal PackageDB{ location = db_name, packages = pkg_confs } =
do hPutStrLn stdout db_name
if null pkg_confs
then hPutStrLn stdout " (no packages)"
else hPutStrLn stdout $ unlines (map (" " ++) (map pp_pkg pkg_confs))
where
pp_pkg p
| installedUnitId p `elem` broken = printf "{%s}" doc
| exposed p = doc
| otherwise = printf "(%s)" doc
where doc | verbosity >= Verbose = printf "%s (%s)" pkg (display (installedUnitId p))
| otherwise = pkg
where
pkg = display (sourcePackageId p)
show_simple = simplePackageList my_flags . allPackagesInStack
when (not (null broken) && not simple_output && verbosity /= Silent) $ do
prog <- getProgramName
warn ("WARNING: there are broken packages. Run '" ++ prog ++ " check' for more details.")
if simple_output then show_simple stack else do
#if defined(mingw32_HOST_OS) || defined(BOOTSTRAPPING)
mapM_ show_normal stack
#else
let
show_colour withF db@PackageDB{ packages = pkg_confs } =
if null pkg_confs
then termText (location db) <#> termText "\n (no packages)\n"
else
mconcat $ map (<#> termText "\n") $
(termText (location db)
: map (termText " " <#>) (map pp_pkg pkg_confs))
where
pp_pkg p
| installedUnitId p `elem` broken = withF Red doc
| exposed p = doc
| otherwise = withF Blue doc
where doc | verbosity >= Verbose
= termText (printf "%s (%s)" pkg (display (installedUnitId p)))
| otherwise
= termText pkg
where
pkg = display (sourcePackageId p)
is_tty <- hIsTerminalDevice stdout
if not is_tty
then mapM_ show_normal stack
else do tty <- Terminfo.setupTermFromEnv
case Terminfo.getCapability tty withForegroundColor of
Nothing -> mapM_ show_normal stack
Just w -> runTermOutput tty $ mconcat $
map (show_colour w) stack
#endif
simplePackageList :: [Flag] -> [InstalledPackageInfo] -> IO ()
simplePackageList my_flags pkgs = do
let showPkg = if FlagNamesOnly `elem` my_flags then display . pkgName
else display
strs = map showPkg $ map sourcePackageId pkgs
when (not (null pkgs)) $
hPutStrLn stdout $ concat $ intersperse " " strs
showPackageDot :: Verbosity -> [Flag] -> IO ()
showPackageDot verbosity myflags = do
(_, _, flag_db_stack) <-
getPkgDatabases verbosity False{-modify-} False{-use user-}
True{-use cache-} False{-expand vars-} myflags
let all_pkgs = allPackagesInStack flag_db_stack
ipix = PackageIndex.fromList all_pkgs
putStrLn "digraph {"
let quote s = '"':s ++ "\""
mapM_ putStrLn [ quote from ++ " -> " ++ quote to
| p <- all_pkgs,
let from = display (sourcePackageId p),
key <- depends p,
Just dep <- [PackageIndex.lookupUnitId ipix key],
let to = display (sourcePackageId dep)
]
putStrLn "}"
-- -----------------------------------------------------------------------------
-- Prints the highest (hidden or exposed) version of a package
-- ToDo: This is no longer well-defined with unit ids, because the
-- dependencies may be varying versions
latestPackage :: Verbosity -> [Flag] -> GlobPackageIdentifier -> IO ()
latestPackage verbosity my_flags pkgid = do
(_, _, flag_db_stack) <-
getPkgDatabases verbosity False{-modify-} False{-use user-}
True{-use cache-} False{-expand vars-} my_flags
ps <- findPackages flag_db_stack (Id pkgid)
case ps of
[] -> die "no matches"
_ -> show_pkg . maximum . map sourcePackageId $ ps
where
show_pkg pid = hPutStrLn stdout (display pid)
-- -----------------------------------------------------------------------------
-- Describe
describePackage :: Verbosity -> [Flag] -> PackageArg -> Bool -> IO ()
describePackage verbosity my_flags pkgarg expand_pkgroot = do
(_, _, flag_db_stack) <-
getPkgDatabases verbosity False{-modify-} False{-use user-}
True{-use cache-} expand_pkgroot my_flags
dbs <- findPackagesByDB flag_db_stack pkgarg
doDump expand_pkgroot [ (pkg, locationAbsolute db)
| (db, pkgs) <- dbs, pkg <- pkgs ]
dumpPackages :: Verbosity -> [Flag] -> Bool -> IO ()
dumpPackages verbosity my_flags expand_pkgroot = do
(_, _, flag_db_stack) <-
getPkgDatabases verbosity False{-modify-} False{-use user-}
True{-use cache-} expand_pkgroot my_flags
doDump expand_pkgroot [ (pkg, locationAbsolute db)
| db <- flag_db_stack, pkg <- packages db ]
doDump :: Bool -> [(InstalledPackageInfo, FilePath)] -> IO ()
doDump expand_pkgroot pkgs = do
-- fix the encoding to UTF-8, since this is an interchange format
hSetEncoding stdout utf8
putStrLn $
intercalate "---\n"
[ if expand_pkgroot
then showInstalledPackageInfo pkg
else showInstalledPackageInfo pkg ++ pkgrootField
| (pkg, pkgloc) <- pkgs
, let pkgroot = takeDirectory pkgloc
pkgrootField = "pkgroot: " ++ show pkgroot ++ "\n" ]
-- PackageId is can have globVersion for the version
findPackages :: PackageDBStack -> PackageArg -> IO [InstalledPackageInfo]
findPackages db_stack pkgarg
= fmap (concatMap snd) $ findPackagesByDB db_stack pkgarg
findPackagesByDB :: PackageDBStack -> PackageArg
-> IO [(PackageDB, [InstalledPackageInfo])]
findPackagesByDB db_stack pkgarg
= case [ (db, matched)
| db <- db_stack,
let matched = filter (pkgarg `matchesPkg`) (packages db),
not (null matched) ] of
[] -> die ("cannot find package " ++ pkg_msg pkgarg)
ps -> return ps
where
pkg_msg (Id pkgid) = displayGlobPkgId pkgid
pkg_msg (IUId ipid) = display ipid
pkg_msg (Substring pkgpat _) = "matching " ++ pkgpat
matches :: GlobPackageIdentifier -> PackageIdentifier -> Bool
GlobPackageIdentifier pn `matches` pid'
= (pn == pkgName pid')
ExactPackageIdentifier pid `matches` pid'
= pkgName pid == pkgName pid' &&
(pkgVersion pid == pkgVersion pid' || pkgVersion pid == nullVersion)
matchesPkg :: PackageArg -> InstalledPackageInfo -> Bool
(Id pid) `matchesPkg` pkg = pid `matches` sourcePackageId pkg
(IUId ipid) `matchesPkg` pkg = ipid == installedUnitId pkg
(Substring _ m) `matchesPkg` pkg = m (display (sourcePackageId pkg))
-- -----------------------------------------------------------------------------
-- Field
describeField :: Verbosity -> [Flag] -> PackageArg -> [String] -> Bool -> IO ()
describeField verbosity my_flags pkgarg fields expand_pkgroot = do
(_, _, flag_db_stack) <-
getPkgDatabases verbosity False{-modify-} False{-use user-}
True{-use cache-} expand_pkgroot my_flags
fns <- mapM toField fields
ps <- findPackages flag_db_stack pkgarg
mapM_ (selectFields fns) ps
where showFun = if FlagSimpleOutput `elem` my_flags
then showSimpleInstalledPackageInfoField
else showInstalledPackageInfoField
toField f = case showFun f of
Nothing -> die ("unknown field: " ++ f)
Just fn -> return fn
selectFields fns pinfo = mapM_ (\fn->putStrLn (fn pinfo)) fns
-- -----------------------------------------------------------------------------
-- Check: Check consistency of installed packages
checkConsistency :: Verbosity -> [Flag] -> IO ()
checkConsistency verbosity my_flags = do
(db_stack, _, _) <-
getPkgDatabases verbosity False{-modify-} True{-use user-}
True{-use cache-} True{-expand vars-}
my_flags
-- although check is not a modify command, we do need to use the user
-- db, because we may need it to verify package deps.
let simple_output = FlagSimpleOutput `elem` my_flags
let pkgs = allPackagesInStack db_stack
checkPackage p = do
(_,es,ws) <- runValidate $ checkPackageConfig p verbosity db_stack
True True
if null es
then do when (not simple_output) $ do
_ <- reportValidateErrors verbosity [] ws "" Nothing
return ()
return []
else do
when (not simple_output) $ do
reportError ("There are problems in package " ++ display (sourcePackageId p) ++ ":")
_ <- reportValidateErrors verbosity es ws " " Nothing
return ()
return [p]
broken_pkgs <- concat `fmap` mapM checkPackage pkgs
let filterOut pkgs1 pkgs2 = filter not_in pkgs2
where not_in p = sourcePackageId p `notElem` all_ps
all_ps = map sourcePackageId pkgs1
let not_broken_pkgs = filterOut broken_pkgs pkgs
(_, trans_broken_pkgs) = closure [] not_broken_pkgs
all_broken_pkgs = broken_pkgs ++ trans_broken_pkgs
when (not (null all_broken_pkgs)) $ do
if simple_output
then simplePackageList my_flags all_broken_pkgs
else do
reportError ("\nThe following packages are broken, either because they have a problem\n"++
"listed above, or because they depend on a broken package.")
mapM_ (hPutStrLn stderr . display . sourcePackageId) all_broken_pkgs
when (not (null all_broken_pkgs)) $ exitWith (ExitFailure 1)
closure :: [InstalledPackageInfo] -> [InstalledPackageInfo]
-> ([InstalledPackageInfo], [InstalledPackageInfo])
closure pkgs db_stack = go pkgs db_stack
where
go avail not_avail =
case partition (depsAvailable avail) not_avail of
([], not_avail') -> (avail, not_avail')
(new_avail, not_avail') -> go (new_avail ++ avail) not_avail'
depsAvailable :: [InstalledPackageInfo] -> InstalledPackageInfo
-> Bool
depsAvailable pkgs_ok pkg = null dangling
where dangling = filter (`notElem` pids) (depends pkg)
pids = map installedUnitId pkgs_ok
-- we want mutually recursive groups of package to show up
-- as broken. (#1750)
brokenPackages :: [InstalledPackageInfo] -> [InstalledPackageInfo]
brokenPackages pkgs = snd (closure [] pkgs)
-----------------------------------------------------------------------------
-- Sanity-check a new package config, and automatically build GHCi libs
-- if requested.
type ValidateError = (Force,String)
type ValidateWarning = String
newtype Validate a = V { runValidate :: IO (a, [ValidateError],[ValidateWarning]) }
instance Functor Validate where
fmap = liftM
instance Applicative Validate where
pure a = V $ pure (a, [], [])
(<*>) = ap
instance Monad Validate where
m >>= k = V $ do
(a, es, ws) <- runValidate m
(b, es', ws') <- runValidate (k a)
return (b,es++es',ws++ws')
verror :: Force -> String -> Validate ()
verror f s = V (return ((),[(f,s)],[]))
vwarn :: String -> Validate ()
vwarn s = V (return ((),[],["Warning: " ++ s]))
liftIO :: IO a -> Validate a
liftIO k = V (k >>= \a -> return (a,[],[]))
-- returns False if we should die
reportValidateErrors :: Verbosity -> [ValidateError] -> [ValidateWarning]
-> String -> Maybe Force -> IO Bool
reportValidateErrors verbosity es ws prefix mb_force = do
mapM_ (warn . (prefix++)) ws
oks <- mapM report es
return (and oks)
where
report (f,s)
| Just force <- mb_force
= if (force >= f)
then do when (verbosity >= Normal) $
reportError (prefix ++ s ++ " (ignoring)")
return True
else if f < CannotForce
then do reportError (prefix ++ s ++ " (use --force to override)")
return False
else do reportError err
return False
| otherwise = do reportError err
return False
where
err = prefix ++ s
validatePackageConfig :: InstalledPackageInfo
-> Verbosity
-> PackageDBStack
-> Bool -- multi_instance
-> Bool -- update, or check
-> Force
-> IO ()
validatePackageConfig pkg verbosity db_stack
multi_instance update force = do
(_,es,ws) <- runValidate $
checkPackageConfig pkg verbosity db_stack
multi_instance update
ok <- reportValidateErrors verbosity es ws
(display (sourcePackageId pkg) ++ ": ") (Just force)
when (not ok) $ exitWith (ExitFailure 1)
checkPackageConfig :: InstalledPackageInfo
-> Verbosity
-> PackageDBStack
-> Bool -- multi_instance
-> Bool -- update, or check
-> Validate ()
checkPackageConfig pkg verbosity db_stack
multi_instance update = do
checkPackageId pkg
checkUnitId pkg db_stack update
checkDuplicates db_stack pkg multi_instance update
mapM_ (checkDep db_stack) (depends pkg)
checkDuplicateDepends (depends pkg)
mapM_ (checkDir False "import-dirs") (importDirs pkg)
mapM_ (checkDir True "library-dirs") (libraryDirs pkg)
mapM_ (checkDir True "dynamic-library-dirs") (libraryDynDirs pkg)
mapM_ (checkDir True "include-dirs") (includeDirs pkg)
mapM_ (checkDir True "framework-dirs") (frameworkDirs pkg)
mapM_ (checkFile True "haddock-interfaces") (haddockInterfaces pkg)
mapM_ (checkDirURL True "haddock-html") (haddockHTMLs pkg)
checkDuplicateModules pkg
checkExposedModules db_stack pkg
checkOtherModules pkg
let has_code = Set.null (openModuleSubstFreeHoles (Map.fromList (instantiatedWith pkg)))
when has_code $ mapM_ (checkHSLib verbosity (libraryDirs pkg ++ libraryDynDirs pkg)) (hsLibraries pkg)
-- ToDo: check these somehow?
-- extra_libraries :: [String],
-- c_includes :: [String],
-- When the package name and version are put together, sometimes we can
-- end up with a package id that cannot be parsed. This will lead to
-- difficulties when the user wants to refer to the package later, so
-- we check that the package id can be parsed properly here.
checkPackageId :: InstalledPackageInfo -> Validate ()
checkPackageId ipi =
let str = display (sourcePackageId ipi) in
case [ x :: PackageIdentifier | (x,ys) <- readP_to_S parse str, all isSpace ys ] of
[_] -> return ()
[] -> verror CannotForce ("invalid package identifier: " ++ str)
_ -> verror CannotForce ("ambiguous package identifier: " ++ str)
checkUnitId :: InstalledPackageInfo -> PackageDBStack -> Bool
-> Validate ()
checkUnitId ipi db_stack update = do
let uid = installedUnitId ipi
when (null (display uid)) $ verror CannotForce "missing id field"
when (display uid /= compatPackageKey ipi) $
verror CannotForce $ "installed package info from too old version of Cabal "
++ "(key field does not match id field)"
let dups = [ p | p <- allPackagesInStack db_stack,
installedUnitId p == uid ]
when (not update && not (null dups)) $
verror CannotForce $
"package(s) with this id already exist: " ++
unwords (map (display.installedUnitId) dups)
checkDuplicates :: PackageDBStack -> InstalledPackageInfo
-> Bool -> Bool-> Validate ()
checkDuplicates db_stack pkg multi_instance update = do
let
pkgid = sourcePackageId pkg
pkgs = packages (head db_stack)
--
-- Check whether this package id already exists in this DB
--
when (not update && not multi_instance
&& (pkgid `elem` map sourcePackageId pkgs)) $
verror CannotForce $
"package " ++ display pkgid ++ " is already installed"
let
uncasep = map toLower . display
dups = filter ((== uncasep pkgid) . uncasep) (map sourcePackageId pkgs)
when (not update && not multi_instance
&& not (null dups)) $ verror ForceAll $
"Package names may be treated case-insensitively in the future.\n"++
"Package " ++ display pkgid ++
" overlaps with: " ++ unwords (map display dups)
checkDir, checkFile, checkDirURL :: Bool -> String -> FilePath -> Validate ()
checkDir = checkPath False True
checkFile = checkPath False False
checkDirURL = checkPath True True
checkPath :: Bool -> Bool -> Bool -> String -> FilePath -> Validate ()
checkPath url_ok is_dir warn_only thisfield d
| url_ok && ("http://" `isPrefixOf` d
|| "https://" `isPrefixOf` d) = return ()
| url_ok
, Just d' <- stripPrefix "file://" d
= checkPath False is_dir warn_only thisfield d'
-- Note: we don't check for $topdir/${pkgroot} here. We rely on these
-- variables having been expanded already, see mungePackagePaths.
| isRelative d = verror ForceFiles $
thisfield ++ ": " ++ d ++ " is a relative path which "
++ "makes no sense (as there is nothing for it to be "
++ "relative to). You can make paths relative to the "
++ "package database itself by using ${pkgroot}."
-- relative paths don't make any sense; #4134
| otherwise = do
there <- liftIO $ if is_dir then doesDirectoryExist d else doesFileExist d
when (not there) $
let msg = thisfield ++ ": " ++ d ++ " doesn't exist or isn't a "
++ if is_dir then "directory" else "file"
in
if warn_only
then vwarn msg
else verror ForceFiles msg
checkDep :: PackageDBStack -> UnitId -> Validate ()
checkDep db_stack pkgid
| pkgid `elem` pkgids = return ()
| otherwise = verror ForceAll ("dependency \"" ++ display pkgid
++ "\" doesn't exist")
where
all_pkgs = allPackagesInStack db_stack
pkgids = map installedUnitId all_pkgs
checkDuplicateDepends :: [UnitId] -> Validate ()
checkDuplicateDepends deps
| null dups = return ()
| otherwise = verror ForceAll ("package has duplicate dependencies: " ++
unwords (map display dups))
where
dups = [ p | (p:_:_) <- group (sort deps) ]
checkHSLib :: Verbosity -> [String] -> String -> Validate ()
checkHSLib _verbosity dirs lib = do
let filenames = ["lib" ++ lib ++ ".a",
"lib" ++ lib ++ ".p_a",
"lib" ++ lib ++ "-ghc" ++ Version.version ++ ".so",
"lib" ++ lib ++ "-ghc" ++ Version.version ++ ".dylib",
lib ++ "-ghc" ++ Version.version ++ ".dll"]
b <- liftIO $ doesFileExistOnPath filenames dirs
when (not b) $
verror ForceFiles ("cannot find any of " ++ show filenames ++
" on library path")
doesFileExistOnPath :: [FilePath] -> [FilePath] -> IO Bool
doesFileExistOnPath filenames paths = anyM doesFileExist fullFilenames
where fullFilenames = [ path </> filename
| filename <- filenames
, path <- paths ]
-- | Perform validation checks (module file existence checks) on the
-- @hidden-modules@ field.
checkOtherModules :: InstalledPackageInfo -> Validate ()
checkOtherModules pkg = mapM_ (checkModuleFile pkg) (hiddenModules pkg)
-- | Perform validation checks (module file existence checks and module
-- reexport checks) on the @exposed-modules@ field.
checkExposedModules :: PackageDBStack -> InstalledPackageInfo -> Validate ()
checkExposedModules db_stack pkg =
mapM_ checkExposedModule (exposedModules pkg)
where
checkExposedModule (ExposedModule modl reexport) = do
let checkOriginal = checkModuleFile pkg modl
checkReexport = checkModule "module reexport" db_stack pkg
maybe checkOriginal checkReexport reexport
-- | Validates the existence of an appropriate @hi@ file associated with
-- a module. Used for both @hidden-modules@ and @exposed-modules@ which
-- are not reexports.
checkModuleFile :: InstalledPackageInfo -> ModuleName -> Validate ()
checkModuleFile pkg modl =
-- there's no interface file for GHC.Prim
unless (modl == ModuleName.fromString "GHC.Prim") $ do
let files = [ ModuleName.toFilePath modl <.> extension
| extension <- ["hi", "p_hi", "dyn_hi" ] ]
b <- liftIO $ doesFileExistOnPath files (importDirs pkg)
when (not b) $
verror ForceFiles ("cannot find any of " ++ show files)
-- | Validates that @exposed-modules@ and @hidden-modules@ do not have duplicate
-- entries.
-- ToDo: this needs updating for signatures: signatures can validly show up
-- multiple times in the @exposed-modules@ list as long as their backing
-- implementations agree.
checkDuplicateModules :: InstalledPackageInfo -> Validate ()
checkDuplicateModules pkg
| null dups = return ()
| otherwise = verror ForceAll ("package has duplicate modules: " ++
unwords (map display dups))
where
dups = [ m | (m:_:_) <- group (sort mods) ]
mods = map exposedName (exposedModules pkg) ++ hiddenModules pkg
-- | Validates an original module entry, either the origin of a module reexport
-- or the backing implementation of a signature, by checking that it exists,
-- really is an original definition, and is accessible from the dependencies of
-- the package.
-- ToDo: If the original module in question is a backing signature
-- implementation, then we should also check that the original module in
-- question is NOT a signature (however, if it is a reexport, then it's fine
-- for the original module to be a signature.)
checkModule :: String
-> PackageDBStack
-> InstalledPackageInfo
-> OpenModule
-> Validate ()
checkModule _ _ _ (OpenModuleVar _) = error "Impermissible reexport"
checkModule field_name db_stack pkg
(OpenModule (DefiniteUnitId def_uid) definingModule) =
let definingPkgId = unDefUnitId def_uid
mpkg = if definingPkgId == installedUnitId pkg
then Just pkg
else PackageIndex.lookupUnitId ipix definingPkgId
in case mpkg of
Nothing
-> verror ForceAll (field_name ++ " refers to a non-existent " ++
"defining package: " ++
display definingPkgId)
Just definingPkg
| not (isIndirectDependency definingPkgId)
-> verror ForceAll (field_name ++ " refers to a defining " ++
"package that is not a direct (or indirect) " ++
"dependency of this package: " ++
display definingPkgId)
| otherwise
-> case find ((==definingModule).exposedName)
(exposedModules definingPkg) of
Nothing ->
verror ForceAll (field_name ++ " refers to a module " ++
display definingModule ++ " " ++
"that is not exposed in the " ++
"defining package " ++ display definingPkgId)
Just (ExposedModule {exposedReexport = Just _} ) ->
verror ForceAll (field_name ++ " refers to a module " ++
display definingModule ++ " " ++
"that is reexported but not defined in the " ++
"defining package " ++ display definingPkgId)
_ -> return ()
where
all_pkgs = allPackagesInStack db_stack
ipix = PackageIndex.fromList all_pkgs
isIndirectDependency pkgid = fromMaybe False $ do
thispkg <- graphVertex (installedUnitId pkg)
otherpkg <- graphVertex pkgid
return (Graph.path depgraph thispkg otherpkg)
(depgraph, _, graphVertex) =
PackageIndex.dependencyGraph (PackageIndex.insert pkg ipix)
checkModule _ _ _ (OpenModule (IndefFullUnitId _ _) _) =
-- TODO: add some checks here
return ()
-- ---------------------------------------------------------------------------
-- expanding environment variables in the package configuration
expandEnvVars :: String -> Force -> IO String
expandEnvVars str0 force = go str0 ""
where
go "" acc = return $! reverse acc
go ('$':'{':str) acc | (var, '}':rest) <- break close str
= do value <- lookupEnvVar var
go rest (reverse value ++ acc)
where close c = c == '}' || c == '\n' -- don't span newlines
go (c:str) acc
= go str (c:acc)
lookupEnvVar :: String -> IO String
lookupEnvVar "pkgroot" = return "${pkgroot}" -- these two are special,
lookupEnvVar "pkgrooturl" = return "${pkgrooturl}" -- we don't expand them
lookupEnvVar nm =
catchIO (System.Environment.getEnv nm)
(\ _ -> do dieOrForceAll force ("Unable to expand variable " ++
show nm)
return "")
-----------------------------------------------------------------------------
getProgramName :: IO String
getProgramName = liftM (`withoutSuffix` ".bin") getProgName
where str `withoutSuffix` suff
| suff `isSuffixOf` str = take (length str - length suff) str
| otherwise = str
bye :: String -> IO a
bye s = putStr s >> exitWith ExitSuccess
die :: String -> IO a
die = dieWith 1
dieWith :: Int -> String -> IO a
dieWith ec s = do
prog <- getProgramName
reportError (prog ++ ": " ++ s)
exitWith (ExitFailure ec)
dieOrForceAll :: Force -> String -> IO ()
dieOrForceAll ForceAll s = ignoreError s
dieOrForceAll _other s = dieForcible s
warn :: String -> IO ()
warn = reportError
-- send info messages to stdout
infoLn :: String -> IO ()
infoLn = putStrLn
info :: String -> IO ()
info = putStr
ignoreError :: String -> IO ()
ignoreError s = reportError (s ++ " (ignoring)")
reportError :: String -> IO ()
reportError s = do hFlush stdout; hPutStrLn stderr s
dieForcible :: String -> IO ()
dieForcible s = die (s ++ " (use --force to override)")
my_head :: String -> [a] -> a
my_head s [] = error s
my_head _ (x : _) = x
-----------------------------------------
-- Cut and pasted from ghc/compiler/main/SysTools
#if defined(mingw32_HOST_OS)
subst :: Char -> Char -> String -> String
subst a b ls = map (\ x -> if x == a then b else x) ls
unDosifyPath :: FilePath -> FilePath
unDosifyPath xs = subst '\\' '/' xs
getLibDir :: IO (Maybe String)
getLibDir = fmap (fmap (</> "lib")) $ getExecDir "/bin/ghc-pkg.exe"
-- (getExecDir cmd) returns the directory in which the current
-- executable, which should be called 'cmd', is running
-- So if the full path is /a/b/c/d/e, and you pass "d/e" as cmd,
-- you'll get "/a/b/c" back as the result
getExecDir :: String -> IO (Maybe String)
getExecDir cmd =
getExecPath >>= maybe (return Nothing) removeCmdSuffix
where initN n = reverse . drop n . reverse
removeCmdSuffix = return . Just . initN (length cmd) . unDosifyPath
getExecPath :: IO (Maybe String)
getExecPath = try_size 2048 -- plenty, PATH_MAX is 512 under Win32.
where
try_size size = allocaArray (fromIntegral size) $ \buf -> do
ret <- c_GetModuleFileName nullPtr buf size
case ret of
0 -> return Nothing
_ | ret < size -> fmap Just $ peekCWString buf
| otherwise -> try_size (size * 2)
foreign import WINDOWS_CCONV unsafe "windows.h GetModuleFileNameW"
c_GetModuleFileName :: Ptr () -> CWString -> Word32 -> IO Word32
#else
getLibDir :: IO (Maybe String)
getLibDir = return Nothing
#endif
-----------------------------------------
-- Adapted from ghc/compiler/utils/Panic
installSignalHandlers :: IO ()
installSignalHandlers = do
threadid <- myThreadId
let
interrupt = Exception.throwTo threadid
(Exception.ErrorCall "interrupted")
--
#if !defined(mingw32_HOST_OS)
_ <- installHandler sigQUIT (Catch interrupt) Nothing
_ <- installHandler sigINT (Catch interrupt) Nothing
return ()
#else
-- GHC 6.3+ has support for console events on Windows
-- NOTE: running GHCi under a bash shell for some reason requires
-- you to press Ctrl-Break rather than Ctrl-C to provoke
-- an interrupt. Ctrl-C is getting blocked somewhere, I don't know
-- why --SDM 17/12/2004
let sig_handler ControlC = interrupt
sig_handler Break = interrupt
sig_handler _ = return ()
_ <- installHandler (Catch sig_handler)
return ()
#endif
catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a
catchIO = Exception.catch
tryIO :: IO a -> IO (Either Exception.IOException a)
tryIO = Exception.try
-- removeFileSave doesn't throw an exceptions, if the file is already deleted
removeFileSafe :: FilePath -> IO ()
removeFileSafe fn =
removeFile fn `catchIO` \ e ->
when (not $ isDoesNotExistError e) $ ioError e
-- | Turn a path relative to the current directory into a (normalised)
-- absolute path.
absolutePath :: FilePath -> IO FilePath
absolutePath path = return . normalise . (</> path) =<< getCurrentDirectory
{- Note [writeAtomic leaky abstraction]
GhcPkg.writePackageDb calls writeAtomic, which first writes to a temp file,
and then moves the tempfile to its final destination. This all happens in the
same directory (package.conf.d).
Moving a file doesn't change its modification time, but it *does* change the
modification time of the directory it is placed in. Since we compare the
modification time of the cache file to that of the directory it is in to
decide whether the cache is out-of-date, it will be instantly out-of-date
after creation, if the renaming takes longer than the smallest time difference
that the getModificationTime can measure.
The solution we opt for is a "touch" of the cache file right after it is
created. This resets the modification time of the cache file and the directory
to the current time.
Other possible solutions:
* backdate the modification time of the directory to the modification time
of the cachefile. This is what we used to do on posix platforms. An
observer of the directory would see the modification time of the directory
jump back in time. Not nice, although in practice probably not a problem.
Also note that a cross-platform implementation of setModificationTime is
currently not available.
* set the modification time of the cache file to the modification time of
the directory (instead of the curent time). This could also work,
given that we are the only ones writing to this directory. It would also
require a high-precision getModificationTime (lower precision times get
rounded down it seems), or the cache would still be out-of-date.
* change writeAtomic to create the tempfile outside of the target file's
directory.
* create the cachefile outside of the package.conf.d directory in the first
place. But there are tests and there might be tools that currently rely on
the package.conf.d/package.cache format.
-}
| mettekou/ghc | utils/ghc-pkg/Main.hs | bsd-3-clause | 84,915 | 53 | 101 | 24,012 | 17,303 | 8,873 | 8,430 | 1,420 | 32 |
module Data.Arrowee where
| maoe/arrowee | src/Data/Arrowee.hs | bsd-3-clause | 27 | 0 | 3 | 4 | 6 | 4 | 2 | 1 | 0 |
-----------------------------------------------------------------------------
-- |
-- Module : TestSuite.CRC.CCITT
-- Copyright : (c) Levent Erkok
-- License : BSD3
-- Maintainer : erkokl@gmail.com
-- Stability : experimental
--
-- Test suite for Examples.CRC.CCITT
-----------------------------------------------------------------------------
module TestSuite.CRC.CCITT(tests) where
import Data.SBV.Tools.Polynomial
import Utils.SBVTestFramework
-- Test suite
tests :: TestTree
tests = testGroup "CRC.CCITT"
[ goldenVsStringShow "ccitt" crcPgm
]
where crcPgm = runSAT $ forAll_ crcGood >>= output
-- We don't have native support for 48 bits in Data.SBV
-- So, represent as 32 high-bits and 16 low
type SWord48 = (SWord32, SWord16)
extendData :: SWord48 -> SWord64
extendData (h, l) = h # l # 0
mkFrame :: SWord48 -> SWord64
mkFrame msg@(h, l) = h # l # crc_48_16 msg
crc_48_16 :: SWord48 -> SWord16
crc_48_16 msg = res
where msg64, divisor :: SWord64
msg64 = extendData msg
divisor = polynomial [16, 12, 5, 0]
crc64 = pMod msg64 divisor
(_, res) = split (snd (split crc64))
diffCount :: SWord64 -> SWord64 -> SWord8
diffCount x y = count $ zipWith (.==) (blastLE x) (blastLE y)
where count [] = 0
count (b:bs) = let r = count bs in ite b r (1+r)
-- Claim: If there is an undetected corruption, it must be at least at 4 bits; i.e. HD is 4
crcGood :: SWord48 -> SWord48 -> SBool
crcGood sent received =
sent ./= received ==> diffCount frameSent frameReceived .> 3
where frameSent = mkFrame sent
frameReceived = mkFrame received
| josefs/sbv | SBVTestSuite/TestSuite/CRC/CCITT.hs | bsd-3-clause | 1,633 | 0 | 11 | 346 | 411 | 227 | 184 | 28 | 2 |
{-# LANGUAGE ExplicitForAll #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE UndecidableInstances #-}
module Marvin.Internal where
import Control.Exception.Lifted
import Control.Monad.Logger
import Control.Monad.Reader
import Control.Monad.State
import Marvin.Internal.Types
import Marvin.Internal.Values
import Marvin.Interpolate.Text
import qualified Marvin.Util.Config as C
import Util
getSubConfFor :: HasConfigAccess m => ScriptId -> m C.Config
getSubConfFor (ScriptId name) = C.subconfig $(isT "#{scriptConfigKey}.#{name}") =<< getConfigInternal
-- | Get the config part for the currect script
getConfig :: HasConfigAccess m => m C.Config
getConfig = getScriptId >>= getSubConfFor
runBotAction :: ShowT t => ScriptId -> C.Config -> a -> Maybe t -> d -> BotReacting a d () -> RunnerM ()
runBotAction scriptId config adapter trigger data_ action = do
oldLogFn <- askLoggerIO
runScript oldLogFn `catch` onScriptExcept scriptId trigger
where
runScript oldLogFn = liftIO
$ flip runLoggingT (loggingAddSourcePrefix $(isT "#{scriptConfigKey}.#{scriptId}") oldLogFn)
$ runReaderT (runReaction action) actionState
actionState = BotActionState scriptId config adapter data_
onScriptExcept :: ShowT t => ScriptId -> Maybe t -> SomeException -> RunnerM ()
onScriptExcept sid trigger e =
logErrorNS $(isT "#{applicationScriptId}.dispatch") $ case trigger of
Just t -> $(isT "Unhandled exception during execution of script \"#{sid}\" with trigger \"#{t}\": #{e}")
Nothing -> $(isT "Unhandled exception during execution of script \"#{sid}\": #{e}")
runDefinitions :: ScriptId -> ScriptDefinition a () -> a -> C.Config -> RunnerM (Script a)
runDefinitions sid definitions ada cfg = execStateT (runScript definitions) (Script mempty sid cfg ada)
-- | INTERNAL, USE WITH CARE
--
-- Get the configuration for the bot (should be "bot" subconfig)
getAppConfig :: HasConfigAccess m => m C.Config
getAppConfig = getSubConfFor applicationScriptId
-- | INTERNAL, USE WITH CARE
--
-- Get a value from the bot config (should be "bot" subconfig)
getAppConfigVal :: (C.Configured a, HasConfigAccess m) => C.Name -> m (Maybe a)
getAppConfigVal name = getAppConfig >>= liftIO . flip C.lookup name
-- | INTERNAL, USE WITH CARE
--
-- Get a value from the bot config (should be "bot" subconfig)
requireAppConfigVal :: (C.Configured a, HasConfigAccess m) => C.Name -> m a
requireAppConfigVal name = getAppConfig >>= liftIO . flip C.require name
| JustusAdam/marvin | src/Marvin/Internal.hs | bsd-3-clause | 2,697 | 0 | 14 | 544 | 618 | 317 | 301 | -1 | -1 |
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE Strict #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Graphics.Vulkan.Pipeline where
import Graphics.Vulkan.Device( VkDevice(..)
)
import {-# SOURCE #-} Graphics.Vulkan.Pass( VkRenderPass(..)
)
import Data.Word( Word64
, Word32
)
import Foreign.Ptr( Ptr
, plusPtr
)
import Graphics.Vulkan.PipelineCache( VkPipelineCache(..)
)
import Data.Int( Int32
)
import Data.Vector.Fixed.Cont( ToPeano
)
import Data.Bits( Bits
, FiniteBits
)
import Foreign.Storable( Storable(..)
)
import Data.Void( Void
)
import Graphics.Vulkan.Memory( VkInternalAllocationType(..)
, PFN_vkAllocationFunction
, PFN_vkReallocationFunction
, PFN_vkInternalAllocationNotification
, VkAllocationCallbacks(..)
, VkSystemAllocationScope(..)
, PFN_vkFreeFunction
, PFN_vkInternalFreeNotification
)
import Graphics.Vulkan.PipelineLayout( VkPipelineLayout(..)
)
import Graphics.Vulkan.Shader( VkShaderStageFlagBits(..)
, VkShaderModule(..)
)
import Graphics.Vulkan.Sampler( VkSampleCountFlagBits(..)
, VkCompareOp(..)
)
import Data.Vector.Fixed.Storable( Vec
)
import Graphics.Vulkan.Core( VkResult(..)
, VkBool32(..)
, VkExtent2D(..)
, VkFlags(..)
, VkFormat(..)
, VkOffset2D(..)
, VkRect2D(..)
, VkViewport(..)
, VkStructureType(..)
)
import Foreign.C.Types( CSize
, CFloat
, CFloat(..)
, CChar
, CSize(..)
)
data VkPipelineTessellationStateCreateInfo =
VkPipelineTessellationStateCreateInfo{ vkSType :: VkStructureType
, vkPNext :: Ptr Void
, vkFlags :: VkPipelineTessellationStateCreateFlags
, vkPatchControlPoints :: Word32
}
deriving (Eq)
instance Storable VkPipelineTessellationStateCreateInfo where
sizeOf ~_ = 24
alignment ~_ = 8
peek ptr = VkPipelineTessellationStateCreateInfo <$> peek (ptr `plusPtr` 0)
<*> peek (ptr `plusPtr` 8)
<*> peek (ptr `plusPtr` 16)
<*> peek (ptr `plusPtr` 20)
poke ptr poked = poke (ptr `plusPtr` 0) (vkSType (poked :: VkPipelineTessellationStateCreateInfo))
*> poke (ptr `plusPtr` 8) (vkPNext (poked :: VkPipelineTessellationStateCreateInfo))
*> poke (ptr `plusPtr` 16) (vkFlags (poked :: VkPipelineTessellationStateCreateInfo))
*> poke (ptr `plusPtr` 20) (vkPatchControlPoints (poked :: VkPipelineTessellationStateCreateInfo))
data VkVertexInputAttributeDescription =
VkVertexInputAttributeDescription{ vkLocation :: Word32
, vkBinding :: Word32
, vkFormat :: VkFormat
, vkOffset :: Word32
}
deriving (Eq)
instance Storable VkVertexInputAttributeDescription where
sizeOf ~_ = 16
alignment ~_ = 4
peek ptr = VkVertexInputAttributeDescription <$> peek (ptr `plusPtr` 0)
<*> peek (ptr `plusPtr` 4)
<*> peek (ptr `plusPtr` 8)
<*> peek (ptr `plusPtr` 12)
poke ptr poked = poke (ptr `plusPtr` 0) (vkLocation (poked :: VkVertexInputAttributeDescription))
*> poke (ptr `plusPtr` 4) (vkBinding (poked :: VkVertexInputAttributeDescription))
*> poke (ptr `plusPtr` 8) (vkFormat (poked :: VkVertexInputAttributeDescription))
*> poke (ptr `plusPtr` 12) (vkOffset (poked :: VkVertexInputAttributeDescription))
data VkGraphicsPipelineCreateInfo =
VkGraphicsPipelineCreateInfo{ vkSType :: VkStructureType
, vkPNext :: Ptr Void
, vkFlags :: VkPipelineCreateFlags
, vkStageCount :: Word32
, vkPStages :: Ptr VkPipelineShaderStageCreateInfo
, vkPVertexInputState :: Ptr VkPipelineVertexInputStateCreateInfo
, vkPInputAssemblyState :: Ptr VkPipelineInputAssemblyStateCreateInfo
, vkPTessellationState :: Ptr VkPipelineTessellationStateCreateInfo
, vkPViewportState :: Ptr VkPipelineViewportStateCreateInfo
, vkPRasterizationState :: Ptr VkPipelineRasterizationStateCreateInfo
, vkPMultisampleState :: Ptr VkPipelineMultisampleStateCreateInfo
, vkPDepthStencilState :: Ptr VkPipelineDepthStencilStateCreateInfo
, vkPColorBlendState :: Ptr VkPipelineColorBlendStateCreateInfo
, vkPDynamicState :: Ptr VkPipelineDynamicStateCreateInfo
, vkLayout :: VkPipelineLayout
, vkRenderPass :: VkRenderPass
, vkSubpass :: Word32
, vkBasePipelineHandle :: VkPipeline
, vkBasePipelineIndex :: Int32
}
deriving (Eq)
instance Storable VkGraphicsPipelineCreateInfo where
sizeOf ~_ = 144
alignment ~_ = 8
peek ptr = VkGraphicsPipelineCreateInfo <$> peek (ptr `plusPtr` 0)
<*> peek (ptr `plusPtr` 8)
<*> peek (ptr `plusPtr` 16)
<*> peek (ptr `plusPtr` 20)
<*> peek (ptr `plusPtr` 24)
<*> peek (ptr `plusPtr` 32)
<*> peek (ptr `plusPtr` 40)
<*> peek (ptr `plusPtr` 48)
<*> peek (ptr `plusPtr` 56)
<*> peek (ptr `plusPtr` 64)
<*> peek (ptr `plusPtr` 72)
<*> peek (ptr `plusPtr` 80)
<*> peek (ptr `plusPtr` 88)
<*> peek (ptr `plusPtr` 96)
<*> peek (ptr `plusPtr` 104)
<*> peek (ptr `plusPtr` 112)
<*> peek (ptr `plusPtr` 120)
<*> peek (ptr `plusPtr` 128)
<*> peek (ptr `plusPtr` 136)
poke ptr poked = poke (ptr `plusPtr` 0) (vkSType (poked :: VkGraphicsPipelineCreateInfo))
*> poke (ptr `plusPtr` 8) (vkPNext (poked :: VkGraphicsPipelineCreateInfo))
*> poke (ptr `plusPtr` 16) (vkFlags (poked :: VkGraphicsPipelineCreateInfo))
*> poke (ptr `plusPtr` 20) (vkStageCount (poked :: VkGraphicsPipelineCreateInfo))
*> poke (ptr `plusPtr` 24) (vkPStages (poked :: VkGraphicsPipelineCreateInfo))
*> poke (ptr `plusPtr` 32) (vkPVertexInputState (poked :: VkGraphicsPipelineCreateInfo))
*> poke (ptr `plusPtr` 40) (vkPInputAssemblyState (poked :: VkGraphicsPipelineCreateInfo))
*> poke (ptr `plusPtr` 48) (vkPTessellationState (poked :: VkGraphicsPipelineCreateInfo))
*> poke (ptr `plusPtr` 56) (vkPViewportState (poked :: VkGraphicsPipelineCreateInfo))
*> poke (ptr `plusPtr` 64) (vkPRasterizationState (poked :: VkGraphicsPipelineCreateInfo))
*> poke (ptr `plusPtr` 72) (vkPMultisampleState (poked :: VkGraphicsPipelineCreateInfo))
*> poke (ptr `plusPtr` 80) (vkPDepthStencilState (poked :: VkGraphicsPipelineCreateInfo))
*> poke (ptr `plusPtr` 88) (vkPColorBlendState (poked :: VkGraphicsPipelineCreateInfo))
*> poke (ptr `plusPtr` 96) (vkPDynamicState (poked :: VkGraphicsPipelineCreateInfo))
*> poke (ptr `plusPtr` 104) (vkLayout (poked :: VkGraphicsPipelineCreateInfo))
*> poke (ptr `plusPtr` 112) (vkRenderPass (poked :: VkGraphicsPipelineCreateInfo))
*> poke (ptr `plusPtr` 120) (vkSubpass (poked :: VkGraphicsPipelineCreateInfo))
*> poke (ptr `plusPtr` 128) (vkBasePipelineHandle (poked :: VkGraphicsPipelineCreateInfo))
*> poke (ptr `plusPtr` 136) (vkBasePipelineIndex (poked :: VkGraphicsPipelineCreateInfo))
-- ** VkCullModeFlags
newtype VkCullModeFlagBits = VkCullModeFlagBits VkFlags
deriving (Eq, Storable, Bits, FiniteBits)
-- | Alias for VkCullModeFlagBits
type VkCullModeFlags = VkCullModeFlagBits
pattern VK_CULL_MODE_FRONT_BIT = VkCullModeFlagBits 0x1
pattern VK_CULL_MODE_BACK_BIT = VkCullModeFlagBits 0x2
pattern VK_CULL_MODE_NONE = VkCullModeFlagBits 0x0
pattern VK_CULL_MODE_FRONT_AND_BACK = VkCullModeFlagBits 0x3
-- ** VkPipelineDepthStencilStateCreateFlags
-- | Opaque flag
newtype VkPipelineDepthStencilStateCreateFlags = VkPipelineDepthStencilStateCreateFlags VkFlags
deriving (Eq, Storable)
data VkPipelineShaderStageCreateInfo =
VkPipelineShaderStageCreateInfo{ vkSType :: VkStructureType
, vkPNext :: Ptr Void
, vkFlags :: VkPipelineShaderStageCreateFlags
, vkStage :: VkShaderStageFlagBits
, vkModule :: VkShaderModule
, vkPName :: Ptr CChar
, vkPSpecializationInfo :: Ptr VkSpecializationInfo
}
deriving (Eq)
instance Storable VkPipelineShaderStageCreateInfo where
sizeOf ~_ = 48
alignment ~_ = 8
peek ptr = VkPipelineShaderStageCreateInfo <$> peek (ptr `plusPtr` 0)
<*> peek (ptr `plusPtr` 8)
<*> peek (ptr `plusPtr` 16)
<*> peek (ptr `plusPtr` 20)
<*> peek (ptr `plusPtr` 24)
<*> peek (ptr `plusPtr` 32)
<*> peek (ptr `plusPtr` 40)
poke ptr poked = poke (ptr `plusPtr` 0) (vkSType (poked :: VkPipelineShaderStageCreateInfo))
*> poke (ptr `plusPtr` 8) (vkPNext (poked :: VkPipelineShaderStageCreateInfo))
*> poke (ptr `plusPtr` 16) (vkFlags (poked :: VkPipelineShaderStageCreateInfo))
*> poke (ptr `plusPtr` 20) (vkStage (poked :: VkPipelineShaderStageCreateInfo))
*> poke (ptr `plusPtr` 24) (vkModule (poked :: VkPipelineShaderStageCreateInfo))
*> poke (ptr `plusPtr` 32) (vkPName (poked :: VkPipelineShaderStageCreateInfo))
*> poke (ptr `plusPtr` 40) (vkPSpecializationInfo (poked :: VkPipelineShaderStageCreateInfo))
-- ** VkColorComponentFlags
newtype VkColorComponentFlagBits = VkColorComponentFlagBits VkFlags
deriving (Eq, Storable, Bits, FiniteBits)
-- | Alias for VkColorComponentFlagBits
type VkColorComponentFlags = VkColorComponentFlagBits
pattern VK_COLOR_COMPONENT_R_BIT = VkColorComponentFlagBits 0x1
pattern VK_COLOR_COMPONENT_G_BIT = VkColorComponentFlagBits 0x2
pattern VK_COLOR_COMPONENT_B_BIT = VkColorComponentFlagBits 0x4
pattern VK_COLOR_COMPONENT_A_BIT = VkColorComponentFlagBits 0x8
data VkComputePipelineCreateInfo =
VkComputePipelineCreateInfo{ vkSType :: VkStructureType
, vkPNext :: Ptr Void
, vkFlags :: VkPipelineCreateFlags
, vkStage :: VkPipelineShaderStageCreateInfo
, vkLayout :: VkPipelineLayout
, vkBasePipelineHandle :: VkPipeline
, vkBasePipelineIndex :: Int32
}
deriving (Eq)
instance Storable VkComputePipelineCreateInfo where
sizeOf ~_ = 96
alignment ~_ = 8
peek ptr = VkComputePipelineCreateInfo <$> peek (ptr `plusPtr` 0)
<*> peek (ptr `plusPtr` 8)
<*> peek (ptr `plusPtr` 16)
<*> peek (ptr `plusPtr` 24)
<*> peek (ptr `plusPtr` 72)
<*> peek (ptr `plusPtr` 80)
<*> peek (ptr `plusPtr` 88)
poke ptr poked = poke (ptr `plusPtr` 0) (vkSType (poked :: VkComputePipelineCreateInfo))
*> poke (ptr `plusPtr` 8) (vkPNext (poked :: VkComputePipelineCreateInfo))
*> poke (ptr `plusPtr` 16) (vkFlags (poked :: VkComputePipelineCreateInfo))
*> poke (ptr `plusPtr` 24) (vkStage (poked :: VkComputePipelineCreateInfo))
*> poke (ptr `plusPtr` 72) (vkLayout (poked :: VkComputePipelineCreateInfo))
*> poke (ptr `plusPtr` 80) (vkBasePipelineHandle (poked :: VkComputePipelineCreateInfo))
*> poke (ptr `plusPtr` 88) (vkBasePipelineIndex (poked :: VkComputePipelineCreateInfo))
-- ** VkStencilOp
newtype VkStencilOp = VkStencilOp Int32
deriving (Eq, Storable)
pattern VK_STENCIL_OP_KEEP = VkStencilOp 0
pattern VK_STENCIL_OP_ZERO = VkStencilOp 1
pattern VK_STENCIL_OP_REPLACE = VkStencilOp 2
pattern VK_STENCIL_OP_INCREMENT_AND_CLAMP = VkStencilOp 3
pattern VK_STENCIL_OP_DECREMENT_AND_CLAMP = VkStencilOp 4
pattern VK_STENCIL_OP_INVERT = VkStencilOp 5
pattern VK_STENCIL_OP_INCREMENT_AND_WRAP = VkStencilOp 6
pattern VK_STENCIL_OP_DECREMENT_AND_WRAP = VkStencilOp 7
data VkSpecializationInfo =
VkSpecializationInfo{ vkMapEntryCount :: Word32
, vkPMapEntries :: Ptr VkSpecializationMapEntry
, vkDataSize :: CSize
, vkPData :: Ptr Void
}
deriving (Eq)
instance Storable VkSpecializationInfo where
sizeOf ~_ = 32
alignment ~_ = 8
peek ptr = VkSpecializationInfo <$> peek (ptr `plusPtr` 0)
<*> peek (ptr `plusPtr` 8)
<*> peek (ptr `plusPtr` 16)
<*> peek (ptr `plusPtr` 24)
poke ptr poked = poke (ptr `plusPtr` 0) (vkMapEntryCount (poked :: VkSpecializationInfo))
*> poke (ptr `plusPtr` 8) (vkPMapEntries (poked :: VkSpecializationInfo))
*> poke (ptr `plusPtr` 16) (vkDataSize (poked :: VkSpecializationInfo))
*> poke (ptr `plusPtr` 24) (vkPData (poked :: VkSpecializationInfo))
-- ** VkPipelineColorBlendStateCreateFlags
-- | Opaque flag
newtype VkPipelineColorBlendStateCreateFlags = VkPipelineColorBlendStateCreateFlags VkFlags
deriving (Eq, Storable)
newtype VkPipeline = VkPipeline Word64
deriving (Eq, Storable)
-- ** VkPipelineInputAssemblyStateCreateFlags
-- | Opaque flag
newtype VkPipelineInputAssemblyStateCreateFlags = VkPipelineInputAssemblyStateCreateFlags VkFlags
deriving (Eq, Storable)
-- ** vkCreateGraphicsPipelines
foreign import ccall "vkCreateGraphicsPipelines" vkCreateGraphicsPipelines ::
VkDevice ->
VkPipelineCache ->
Word32 ->
Ptr VkGraphicsPipelineCreateInfo ->
Ptr VkAllocationCallbacks -> Ptr VkPipeline -> IO VkResult
-- ** VkFrontFace
newtype VkFrontFace = VkFrontFace Int32
deriving (Eq, Storable)
pattern VK_FRONT_FACE_COUNTER_CLOCKWISE = VkFrontFace 0
pattern VK_FRONT_FACE_CLOCKWISE = VkFrontFace 1
-- ** VkPolygonMode
newtype VkPolygonMode = VkPolygonMode Int32
deriving (Eq, Storable)
pattern VK_POLYGON_MODE_FILL = VkPolygonMode 0
pattern VK_POLYGON_MODE_LINE = VkPolygonMode 1
pattern VK_POLYGON_MODE_POINT = VkPolygonMode 2
-- ** VkPipelineViewportStateCreateFlags
-- | Opaque flag
newtype VkPipelineViewportStateCreateFlags = VkPipelineViewportStateCreateFlags VkFlags
deriving (Eq, Storable)
-- ** VkLogicOp
newtype VkLogicOp = VkLogicOp Int32
deriving (Eq, Storable)
pattern VK_LOGIC_OP_CLEAR = VkLogicOp 0
pattern VK_LOGIC_OP_AND = VkLogicOp 1
pattern VK_LOGIC_OP_AND_REVERSE = VkLogicOp 2
pattern VK_LOGIC_OP_COPY = VkLogicOp 3
pattern VK_LOGIC_OP_AND_INVERTED = VkLogicOp 4
pattern VK_LOGIC_OP_NO_OP = VkLogicOp 5
pattern VK_LOGIC_OP_XOR = VkLogicOp 6
pattern VK_LOGIC_OP_OR = VkLogicOp 7
pattern VK_LOGIC_OP_NOR = VkLogicOp 8
pattern VK_LOGIC_OP_EQUIVALENT = VkLogicOp 9
pattern VK_LOGIC_OP_INVERT = VkLogicOp 10
pattern VK_LOGIC_OP_OR_REVERSE = VkLogicOp 11
pattern VK_LOGIC_OP_COPY_INVERTED = VkLogicOp 12
pattern VK_LOGIC_OP_OR_INVERTED = VkLogicOp 13
pattern VK_LOGIC_OP_NAND = VkLogicOp 14
pattern VK_LOGIC_OP_SET = VkLogicOp 15
-- ** VkPipelineCreateFlags
newtype VkPipelineCreateFlagBits = VkPipelineCreateFlagBits VkFlags
deriving (Eq, Storable, Bits, FiniteBits)
-- | Alias for VkPipelineCreateFlagBits
type VkPipelineCreateFlags = VkPipelineCreateFlagBits
pattern VK_PIPELINE_CREATE_DISABLE_OPTIMIZATION_BIT = VkPipelineCreateFlagBits 0x1
pattern VK_PIPELINE_CREATE_ALLOW_DERIVATIVES_BIT = VkPipelineCreateFlagBits 0x2
pattern VK_PIPELINE_CREATE_DERIVATIVE_BIT = VkPipelineCreateFlagBits 0x4
-- ** VkPipelineRasterizationStateCreateFlags
-- | Opaque flag
newtype VkPipelineRasterizationStateCreateFlags = VkPipelineRasterizationStateCreateFlags VkFlags
deriving (Eq, Storable)
-- ** VkDynamicState
newtype VkDynamicState = VkDynamicState Int32
deriving (Eq, Storable)
pattern VK_DYNAMIC_STATE_VIEWPORT = VkDynamicState 0
pattern VK_DYNAMIC_STATE_SCISSOR = VkDynamicState 1
pattern VK_DYNAMIC_STATE_LINE_WIDTH = VkDynamicState 2
pattern VK_DYNAMIC_STATE_DEPTH_BIAS = VkDynamicState 3
pattern VK_DYNAMIC_STATE_BLEND_CONSTANTS = VkDynamicState 4
pattern VK_DYNAMIC_STATE_DEPTH_BOUNDS = VkDynamicState 5
pattern VK_DYNAMIC_STATE_STENCIL_COMPARE_MASK = VkDynamicState 6
pattern VK_DYNAMIC_STATE_STENCIL_WRITE_MASK = VkDynamicState 7
pattern VK_DYNAMIC_STATE_STENCIL_REFERENCE = VkDynamicState 8
-- ** VkPipelineBindPoint
newtype VkPipelineBindPoint = VkPipelineBindPoint Int32
deriving (Eq, Storable)
pattern VK_PIPELINE_BIND_POINT_GRAPHICS = VkPipelineBindPoint 0
pattern VK_PIPELINE_BIND_POINT_COMPUTE = VkPipelineBindPoint 1
-- ** VkPipelineDynamicStateCreateFlags
-- | Opaque flag
newtype VkPipelineDynamicStateCreateFlags = VkPipelineDynamicStateCreateFlags VkFlags
deriving (Eq, Storable)
data VkPipelineRasterizationStateCreateInfo =
VkPipelineRasterizationStateCreateInfo{ vkSType :: VkStructureType
, vkPNext :: Ptr Void
, vkFlags :: VkPipelineRasterizationStateCreateFlags
, vkDepthClampEnable :: VkBool32
, vkRasterizerDiscardEnable :: VkBool32
, vkPolygonMode :: VkPolygonMode
, vkCullMode :: VkCullModeFlags
, vkFrontFace :: VkFrontFace
, vkDepthBiasEnable :: VkBool32
, vkDepthBiasConstantFactor :: CFloat
, vkDepthBiasClamp :: CFloat
, vkDepthBiasSlopeFactor :: CFloat
, vkLineWidth :: CFloat
}
deriving (Eq)
instance Storable VkPipelineRasterizationStateCreateInfo where
sizeOf ~_ = 64
alignment ~_ = 8
peek ptr = VkPipelineRasterizationStateCreateInfo <$> peek (ptr `plusPtr` 0)
<*> peek (ptr `plusPtr` 8)
<*> peek (ptr `plusPtr` 16)
<*> peek (ptr `plusPtr` 20)
<*> peek (ptr `plusPtr` 24)
<*> peek (ptr `plusPtr` 28)
<*> peek (ptr `plusPtr` 32)
<*> peek (ptr `plusPtr` 36)
<*> peek (ptr `plusPtr` 40)
<*> peek (ptr `plusPtr` 44)
<*> peek (ptr `plusPtr` 48)
<*> peek (ptr `plusPtr` 52)
<*> peek (ptr `plusPtr` 56)
poke ptr poked = poke (ptr `plusPtr` 0) (vkSType (poked :: VkPipelineRasterizationStateCreateInfo))
*> poke (ptr `plusPtr` 8) (vkPNext (poked :: VkPipelineRasterizationStateCreateInfo))
*> poke (ptr `plusPtr` 16) (vkFlags (poked :: VkPipelineRasterizationStateCreateInfo))
*> poke (ptr `plusPtr` 20) (vkDepthClampEnable (poked :: VkPipelineRasterizationStateCreateInfo))
*> poke (ptr `plusPtr` 24) (vkRasterizerDiscardEnable (poked :: VkPipelineRasterizationStateCreateInfo))
*> poke (ptr `plusPtr` 28) (vkPolygonMode (poked :: VkPipelineRasterizationStateCreateInfo))
*> poke (ptr `plusPtr` 32) (vkCullMode (poked :: VkPipelineRasterizationStateCreateInfo))
*> poke (ptr `plusPtr` 36) (vkFrontFace (poked :: VkPipelineRasterizationStateCreateInfo))
*> poke (ptr `plusPtr` 40) (vkDepthBiasEnable (poked :: VkPipelineRasterizationStateCreateInfo))
*> poke (ptr `plusPtr` 44) (vkDepthBiasConstantFactor (poked :: VkPipelineRasterizationStateCreateInfo))
*> poke (ptr `plusPtr` 48) (vkDepthBiasClamp (poked :: VkPipelineRasterizationStateCreateInfo))
*> poke (ptr `plusPtr` 52) (vkDepthBiasSlopeFactor (poked :: VkPipelineRasterizationStateCreateInfo))
*> poke (ptr `plusPtr` 56) (vkLineWidth (poked :: VkPipelineRasterizationStateCreateInfo))
-- ** VkBlendOp
newtype VkBlendOp = VkBlendOp Int32
deriving (Eq, Storable)
pattern VK_BLEND_OP_ADD = VkBlendOp 0
pattern VK_BLEND_OP_SUBTRACT = VkBlendOp 1
pattern VK_BLEND_OP_REVERSE_SUBTRACT = VkBlendOp 2
pattern VK_BLEND_OP_MIN = VkBlendOp 3
pattern VK_BLEND_OP_MAX = VkBlendOp 4
-- ** vkDestroyPipeline
foreign import ccall "vkDestroyPipeline" vkDestroyPipeline ::
VkDevice -> VkPipeline -> Ptr VkAllocationCallbacks -> IO ()
-- ** VkPipelineShaderStageCreateFlags
-- | Opaque flag
newtype VkPipelineShaderStageCreateFlags = VkPipelineShaderStageCreateFlags VkFlags
deriving (Eq, Storable)
data VkPipelineViewportStateCreateInfo =
VkPipelineViewportStateCreateInfo{ vkSType :: VkStructureType
, vkPNext :: Ptr Void
, vkFlags :: VkPipelineViewportStateCreateFlags
, vkViewportCount :: Word32
, vkPViewports :: Ptr VkViewport
, vkScissorCount :: Word32
, vkPScissors :: Ptr VkRect2D
}
deriving (Eq)
instance Storable VkPipelineViewportStateCreateInfo where
sizeOf ~_ = 48
alignment ~_ = 8
peek ptr = VkPipelineViewportStateCreateInfo <$> peek (ptr `plusPtr` 0)
<*> peek (ptr `plusPtr` 8)
<*> peek (ptr `plusPtr` 16)
<*> peek (ptr `plusPtr` 20)
<*> peek (ptr `plusPtr` 24)
<*> peek (ptr `plusPtr` 32)
<*> peek (ptr `plusPtr` 40)
poke ptr poked = poke (ptr `plusPtr` 0) (vkSType (poked :: VkPipelineViewportStateCreateInfo))
*> poke (ptr `plusPtr` 8) (vkPNext (poked :: VkPipelineViewportStateCreateInfo))
*> poke (ptr `plusPtr` 16) (vkFlags (poked :: VkPipelineViewportStateCreateInfo))
*> poke (ptr `plusPtr` 20) (vkViewportCount (poked :: VkPipelineViewportStateCreateInfo))
*> poke (ptr `plusPtr` 24) (vkPViewports (poked :: VkPipelineViewportStateCreateInfo))
*> poke (ptr `plusPtr` 32) (vkScissorCount (poked :: VkPipelineViewportStateCreateInfo))
*> poke (ptr `plusPtr` 40) (vkPScissors (poked :: VkPipelineViewportStateCreateInfo))
-- ** VkPipelineTessellationStateCreateFlags
-- | Opaque flag
newtype VkPipelineTessellationStateCreateFlags = VkPipelineTessellationStateCreateFlags VkFlags
deriving (Eq, Storable)
data VkPipelineVertexInputStateCreateInfo =
VkPipelineVertexInputStateCreateInfo{ vkSType :: VkStructureType
, vkPNext :: Ptr Void
, vkFlags :: VkPipelineVertexInputStateCreateFlags
, vkVertexBindingDescriptionCount :: Word32
, vkPVertexBindingDescriptions :: Ptr VkVertexInputBindingDescription
, vkVertexAttributeDescriptionCount :: Word32
, vkPVertexAttributeDescriptions :: Ptr VkVertexInputAttributeDescription
}
deriving (Eq)
instance Storable VkPipelineVertexInputStateCreateInfo where
sizeOf ~_ = 48
alignment ~_ = 8
peek ptr = VkPipelineVertexInputStateCreateInfo <$> peek (ptr `plusPtr` 0)
<*> peek (ptr `plusPtr` 8)
<*> peek (ptr `plusPtr` 16)
<*> peek (ptr `plusPtr` 20)
<*> peek (ptr `plusPtr` 24)
<*> peek (ptr `plusPtr` 32)
<*> peek (ptr `plusPtr` 40)
poke ptr poked = poke (ptr `plusPtr` 0) (vkSType (poked :: VkPipelineVertexInputStateCreateInfo))
*> poke (ptr `plusPtr` 8) (vkPNext (poked :: VkPipelineVertexInputStateCreateInfo))
*> poke (ptr `plusPtr` 16) (vkFlags (poked :: VkPipelineVertexInputStateCreateInfo))
*> poke (ptr `plusPtr` 20) (vkVertexBindingDescriptionCount (poked :: VkPipelineVertexInputStateCreateInfo))
*> poke (ptr `plusPtr` 24) (vkPVertexBindingDescriptions (poked :: VkPipelineVertexInputStateCreateInfo))
*> poke (ptr `plusPtr` 32) (vkVertexAttributeDescriptionCount (poked :: VkPipelineVertexInputStateCreateInfo))
*> poke (ptr `plusPtr` 40) (vkPVertexAttributeDescriptions (poked :: VkPipelineVertexInputStateCreateInfo))
-- ** VkPrimitiveTopology
newtype VkPrimitiveTopology = VkPrimitiveTopology Int32
deriving (Eq, Storable)
pattern VK_PRIMITIVE_TOPOLOGY_POINT_LIST = VkPrimitiveTopology 0
pattern VK_PRIMITIVE_TOPOLOGY_LINE_LIST = VkPrimitiveTopology 1
pattern VK_PRIMITIVE_TOPOLOGY_LINE_STRIP = VkPrimitiveTopology 2
pattern VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST = VkPrimitiveTopology 3
pattern VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP = VkPrimitiveTopology 4
pattern VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN = VkPrimitiveTopology 5
pattern VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY = VkPrimitiveTopology 6
pattern VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY = VkPrimitiveTopology 7
pattern VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY = VkPrimitiveTopology 8
pattern VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY = VkPrimitiveTopology 9
pattern VK_PRIMITIVE_TOPOLOGY_PATCH_LIST = VkPrimitiveTopology 10
data VkPipelineInputAssemblyStateCreateInfo =
VkPipelineInputAssemblyStateCreateInfo{ vkSType :: VkStructureType
, vkPNext :: Ptr Void
, vkFlags :: VkPipelineInputAssemblyStateCreateFlags
, vkTopology :: VkPrimitiveTopology
, vkPrimitiveRestartEnable :: VkBool32
}
deriving (Eq)
instance Storable VkPipelineInputAssemblyStateCreateInfo where
sizeOf ~_ = 32
alignment ~_ = 8
peek ptr = VkPipelineInputAssemblyStateCreateInfo <$> peek (ptr `plusPtr` 0)
<*> peek (ptr `plusPtr` 8)
<*> peek (ptr `plusPtr` 16)
<*> peek (ptr `plusPtr` 20)
<*> peek (ptr `plusPtr` 24)
poke ptr poked = poke (ptr `plusPtr` 0) (vkSType (poked :: VkPipelineInputAssemblyStateCreateInfo))
*> poke (ptr `plusPtr` 8) (vkPNext (poked :: VkPipelineInputAssemblyStateCreateInfo))
*> poke (ptr `plusPtr` 16) (vkFlags (poked :: VkPipelineInputAssemblyStateCreateInfo))
*> poke (ptr `plusPtr` 20) (vkTopology (poked :: VkPipelineInputAssemblyStateCreateInfo))
*> poke (ptr `plusPtr` 24) (vkPrimitiveRestartEnable (poked :: VkPipelineInputAssemblyStateCreateInfo))
data VkPipelineColorBlendStateCreateInfo =
VkPipelineColorBlendStateCreateInfo{ vkSType :: VkStructureType
, vkPNext :: Ptr Void
, vkFlags :: VkPipelineColorBlendStateCreateFlags
, vkLogicOpEnable :: VkBool32
, vkLogicOp :: VkLogicOp
, vkAttachmentCount :: Word32
, vkPAttachments :: Ptr VkPipelineColorBlendAttachmentState
, vkBlendConstants :: Vec (ToPeano 4) CFloat
}
deriving (Eq)
instance Storable VkPipelineColorBlendStateCreateInfo where
sizeOf ~_ = 56
alignment ~_ = 8
peek ptr = VkPipelineColorBlendStateCreateInfo <$> peek (ptr `plusPtr` 0)
<*> peek (ptr `plusPtr` 8)
<*> peek (ptr `plusPtr` 16)
<*> peek (ptr `plusPtr` 20)
<*> peek (ptr `plusPtr` 24)
<*> peek (ptr `plusPtr` 28)
<*> peek (ptr `plusPtr` 32)
<*> peek (ptr `plusPtr` 40)
poke ptr poked = poke (ptr `plusPtr` 0) (vkSType (poked :: VkPipelineColorBlendStateCreateInfo))
*> poke (ptr `plusPtr` 8) (vkPNext (poked :: VkPipelineColorBlendStateCreateInfo))
*> poke (ptr `plusPtr` 16) (vkFlags (poked :: VkPipelineColorBlendStateCreateInfo))
*> poke (ptr `plusPtr` 20) (vkLogicOpEnable (poked :: VkPipelineColorBlendStateCreateInfo))
*> poke (ptr `plusPtr` 24) (vkLogicOp (poked :: VkPipelineColorBlendStateCreateInfo))
*> poke (ptr `plusPtr` 28) (vkAttachmentCount (poked :: VkPipelineColorBlendStateCreateInfo))
*> poke (ptr `plusPtr` 32) (vkPAttachments (poked :: VkPipelineColorBlendStateCreateInfo))
*> poke (ptr `plusPtr` 40) (vkBlendConstants (poked :: VkPipelineColorBlendStateCreateInfo))
data VkPipelineDynamicStateCreateInfo =
VkPipelineDynamicStateCreateInfo{ vkSType :: VkStructureType
, vkPNext :: Ptr Void
, vkFlags :: VkPipelineDynamicStateCreateFlags
, vkDynamicStateCount :: Word32
, vkPDynamicStates :: Ptr VkDynamicState
}
deriving (Eq)
instance Storable VkPipelineDynamicStateCreateInfo where
sizeOf ~_ = 32
alignment ~_ = 8
peek ptr = VkPipelineDynamicStateCreateInfo <$> peek (ptr `plusPtr` 0)
<*> peek (ptr `plusPtr` 8)
<*> peek (ptr `plusPtr` 16)
<*> peek (ptr `plusPtr` 20)
<*> peek (ptr `plusPtr` 24)
poke ptr poked = poke (ptr `plusPtr` 0) (vkSType (poked :: VkPipelineDynamicStateCreateInfo))
*> poke (ptr `plusPtr` 8) (vkPNext (poked :: VkPipelineDynamicStateCreateInfo))
*> poke (ptr `plusPtr` 16) (vkFlags (poked :: VkPipelineDynamicStateCreateInfo))
*> poke (ptr `plusPtr` 20) (vkDynamicStateCount (poked :: VkPipelineDynamicStateCreateInfo))
*> poke (ptr `plusPtr` 24) (vkPDynamicStates (poked :: VkPipelineDynamicStateCreateInfo))
data VkSpecializationMapEntry =
VkSpecializationMapEntry{ vkConstantID :: Word32
, vkOffset :: Word32
, vkSize :: CSize
}
deriving (Eq)
instance Storable VkSpecializationMapEntry where
sizeOf ~_ = 16
alignment ~_ = 8
peek ptr = VkSpecializationMapEntry <$> peek (ptr `plusPtr` 0)
<*> peek (ptr `plusPtr` 4)
<*> peek (ptr `plusPtr` 8)
poke ptr poked = poke (ptr `plusPtr` 0) (vkConstantID (poked :: VkSpecializationMapEntry))
*> poke (ptr `plusPtr` 4) (vkOffset (poked :: VkSpecializationMapEntry))
*> poke (ptr `plusPtr` 8) (vkSize (poked :: VkSpecializationMapEntry))
-- ** VkPipelineVertexInputStateCreateFlags
-- | Opaque flag
newtype VkPipelineVertexInputStateCreateFlags = VkPipelineVertexInputStateCreateFlags VkFlags
deriving (Eq, Storable)
-- ** VkVertexInputRate
newtype VkVertexInputRate = VkVertexInputRate Int32
deriving (Eq, Storable)
pattern VK_VERTEX_INPUT_RATE_VERTEX = VkVertexInputRate 0
pattern VK_VERTEX_INPUT_RATE_INSTANCE = VkVertexInputRate 1
-- ** VkPipelineStageFlags
newtype VkPipelineStageFlagBits = VkPipelineStageFlagBits VkFlags
deriving (Eq, Storable, Bits, FiniteBits)
-- | Alias for VkPipelineStageFlagBits
type VkPipelineStageFlags = VkPipelineStageFlagBits
-- | Before subsequent commands are processed
pattern VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT = VkPipelineStageFlagBits 0x1
-- | Draw/DispatchIndirect command fetch
pattern VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT = VkPipelineStageFlagBits 0x2
-- | Vertex/index fetch
pattern VK_PIPELINE_STAGE_VERTEX_INPUT_BIT = VkPipelineStageFlagBits 0x4
-- | Vertex shading
pattern VK_PIPELINE_STAGE_VERTEX_SHADER_BIT = VkPipelineStageFlagBits 0x8
-- | Tessellation control shading
pattern VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT = VkPipelineStageFlagBits 0x10
-- | Tessellation evaluation shading
pattern VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT = VkPipelineStageFlagBits 0x20
-- | Geometry shading
pattern VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT = VkPipelineStageFlagBits 0x40
-- | Fragment shading
pattern VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT = VkPipelineStageFlagBits 0x80
-- | Early fragment (depth and stencil) tests
pattern VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT = VkPipelineStageFlagBits 0x100
-- | Late fragment (depth and stencil) tests
pattern VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT = VkPipelineStageFlagBits 0x200
-- | Color attachment writes
pattern VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT = VkPipelineStageFlagBits 0x400
-- | Compute shading
pattern VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT = VkPipelineStageFlagBits 0x800
-- | Transfer/copy operations
pattern VK_PIPELINE_STAGE_TRANSFER_BIT = VkPipelineStageFlagBits 0x1000
-- | After previous commands have completed
pattern VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT = VkPipelineStageFlagBits 0x2000
-- | Indicates host (CPU) is a source/sink of the dependency
pattern VK_PIPELINE_STAGE_HOST_BIT = VkPipelineStageFlagBits 0x4000
-- | All stages of the graphics pipeline
pattern VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT = VkPipelineStageFlagBits 0x8000
-- | All stages supported on the queue
pattern VK_PIPELINE_STAGE_ALL_COMMANDS_BIT = VkPipelineStageFlagBits 0x10000
data VkPipelineColorBlendAttachmentState =
VkPipelineColorBlendAttachmentState{ vkBlendEnable :: VkBool32
, vkSrcColorBlendFactor :: VkBlendFactor
, vkDstColorBlendFactor :: VkBlendFactor
, vkColorBlendOp :: VkBlendOp
, vkSrcAlphaBlendFactor :: VkBlendFactor
, vkDstAlphaBlendFactor :: VkBlendFactor
, vkAlphaBlendOp :: VkBlendOp
, vkColorWriteMask :: VkColorComponentFlags
}
deriving (Eq)
instance Storable VkPipelineColorBlendAttachmentState where
sizeOf ~_ = 32
alignment ~_ = 4
peek ptr = VkPipelineColorBlendAttachmentState <$> peek (ptr `plusPtr` 0)
<*> peek (ptr `plusPtr` 4)
<*> peek (ptr `plusPtr` 8)
<*> peek (ptr `plusPtr` 12)
<*> peek (ptr `plusPtr` 16)
<*> peek (ptr `plusPtr` 20)
<*> peek (ptr `plusPtr` 24)
<*> peek (ptr `plusPtr` 28)
poke ptr poked = poke (ptr `plusPtr` 0) (vkBlendEnable (poked :: VkPipelineColorBlendAttachmentState))
*> poke (ptr `plusPtr` 4) (vkSrcColorBlendFactor (poked :: VkPipelineColorBlendAttachmentState))
*> poke (ptr `plusPtr` 8) (vkDstColorBlendFactor (poked :: VkPipelineColorBlendAttachmentState))
*> poke (ptr `plusPtr` 12) (vkColorBlendOp (poked :: VkPipelineColorBlendAttachmentState))
*> poke (ptr `plusPtr` 16) (vkSrcAlphaBlendFactor (poked :: VkPipelineColorBlendAttachmentState))
*> poke (ptr `plusPtr` 20) (vkDstAlphaBlendFactor (poked :: VkPipelineColorBlendAttachmentState))
*> poke (ptr `plusPtr` 24) (vkAlphaBlendOp (poked :: VkPipelineColorBlendAttachmentState))
*> poke (ptr `plusPtr` 28) (vkColorWriteMask (poked :: VkPipelineColorBlendAttachmentState))
-- ** VkBlendFactor
newtype VkBlendFactor = VkBlendFactor Int32
deriving (Eq, Storable)
pattern VK_BLEND_FACTOR_ZERO = VkBlendFactor 0
pattern VK_BLEND_FACTOR_ONE = VkBlendFactor 1
pattern VK_BLEND_FACTOR_SRC_COLOR = VkBlendFactor 2
pattern VK_BLEND_FACTOR_ONE_MINUS_SRC_COLOR = VkBlendFactor 3
pattern VK_BLEND_FACTOR_DST_COLOR = VkBlendFactor 4
pattern VK_BLEND_FACTOR_ONE_MINUS_DST_COLOR = VkBlendFactor 5
pattern VK_BLEND_FACTOR_SRC_ALPHA = VkBlendFactor 6
pattern VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA = VkBlendFactor 7
pattern VK_BLEND_FACTOR_DST_ALPHA = VkBlendFactor 8
pattern VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA = VkBlendFactor 9
pattern VK_BLEND_FACTOR_CONSTANT_COLOR = VkBlendFactor 10
pattern VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_COLOR = VkBlendFactor 11
pattern VK_BLEND_FACTOR_CONSTANT_ALPHA = VkBlendFactor 12
pattern VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA = VkBlendFactor 13
pattern VK_BLEND_FACTOR_SRC_ALPHA_SATURATE = VkBlendFactor 14
pattern VK_BLEND_FACTOR_SRC1_COLOR = VkBlendFactor 15
pattern VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR = VkBlendFactor 16
pattern VK_BLEND_FACTOR_SRC1_ALPHA = VkBlendFactor 17
pattern VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA = VkBlendFactor 18
newtype VkSampleMask = VkSampleMask Word32
deriving (Eq, Storable)
-- ** VkPipelineMultisampleStateCreateFlags
-- | Opaque flag
newtype VkPipelineMultisampleStateCreateFlags = VkPipelineMultisampleStateCreateFlags VkFlags
deriving (Eq, Storable)
data VkPipelineMultisampleStateCreateInfo =
VkPipelineMultisampleStateCreateInfo{ vkSType :: VkStructureType
, vkPNext :: Ptr Void
, vkFlags :: VkPipelineMultisampleStateCreateFlags
, vkRasterizationSamples :: VkSampleCountFlagBits
, vkSampleShadingEnable :: VkBool32
, vkMinSampleShading :: CFloat
, vkPSampleMask :: Ptr VkSampleMask
, vkAlphaToCoverageEnable :: VkBool32
, vkAlphaToOneEnable :: VkBool32
}
deriving (Eq)
instance Storable VkPipelineMultisampleStateCreateInfo where
sizeOf ~_ = 48
alignment ~_ = 8
peek ptr = VkPipelineMultisampleStateCreateInfo <$> peek (ptr `plusPtr` 0)
<*> peek (ptr `plusPtr` 8)
<*> peek (ptr `plusPtr` 16)
<*> peek (ptr `plusPtr` 20)
<*> peek (ptr `plusPtr` 24)
<*> peek (ptr `plusPtr` 28)
<*> peek (ptr `plusPtr` 32)
<*> peek (ptr `plusPtr` 40)
<*> peek (ptr `plusPtr` 44)
poke ptr poked = poke (ptr `plusPtr` 0) (vkSType (poked :: VkPipelineMultisampleStateCreateInfo))
*> poke (ptr `plusPtr` 8) (vkPNext (poked :: VkPipelineMultisampleStateCreateInfo))
*> poke (ptr `plusPtr` 16) (vkFlags (poked :: VkPipelineMultisampleStateCreateInfo))
*> poke (ptr `plusPtr` 20) (vkRasterizationSamples (poked :: VkPipelineMultisampleStateCreateInfo))
*> poke (ptr `plusPtr` 24) (vkSampleShadingEnable (poked :: VkPipelineMultisampleStateCreateInfo))
*> poke (ptr `plusPtr` 28) (vkMinSampleShading (poked :: VkPipelineMultisampleStateCreateInfo))
*> poke (ptr `plusPtr` 32) (vkPSampleMask (poked :: VkPipelineMultisampleStateCreateInfo))
*> poke (ptr `plusPtr` 40) (vkAlphaToCoverageEnable (poked :: VkPipelineMultisampleStateCreateInfo))
*> poke (ptr `plusPtr` 44) (vkAlphaToOneEnable (poked :: VkPipelineMultisampleStateCreateInfo))
data VkVertexInputBindingDescription =
VkVertexInputBindingDescription{ vkBinding :: Word32
, vkStride :: Word32
, vkInputRate :: VkVertexInputRate
}
deriving (Eq)
instance Storable VkVertexInputBindingDescription where
sizeOf ~_ = 12
alignment ~_ = 4
peek ptr = VkVertexInputBindingDescription <$> peek (ptr `plusPtr` 0)
<*> peek (ptr `plusPtr` 4)
<*> peek (ptr `plusPtr` 8)
poke ptr poked = poke (ptr `plusPtr` 0) (vkBinding (poked :: VkVertexInputBindingDescription))
*> poke (ptr `plusPtr` 4) (vkStride (poked :: VkVertexInputBindingDescription))
*> poke (ptr `plusPtr` 8) (vkInputRate (poked :: VkVertexInputBindingDescription))
data VkPipelineDepthStencilStateCreateInfo =
VkPipelineDepthStencilStateCreateInfo{ vkSType :: VkStructureType
, vkPNext :: Ptr Void
, vkFlags :: VkPipelineDepthStencilStateCreateFlags
, vkDepthTestEnable :: VkBool32
, vkDepthWriteEnable :: VkBool32
, vkDepthCompareOp :: VkCompareOp
, vkDepthBoundsTestEnable :: VkBool32
, vkStencilTestEnable :: VkBool32
, vkFront :: VkStencilOpState
, vkBack :: VkStencilOpState
, vkMinDepthBounds :: CFloat
, vkMaxDepthBounds :: CFloat
}
deriving (Eq)
instance Storable VkPipelineDepthStencilStateCreateInfo where
sizeOf ~_ = 104
alignment ~_ = 8
peek ptr = VkPipelineDepthStencilStateCreateInfo <$> peek (ptr `plusPtr` 0)
<*> peek (ptr `plusPtr` 8)
<*> peek (ptr `plusPtr` 16)
<*> peek (ptr `plusPtr` 20)
<*> peek (ptr `plusPtr` 24)
<*> peek (ptr `plusPtr` 28)
<*> peek (ptr `plusPtr` 32)
<*> peek (ptr `plusPtr` 36)
<*> peek (ptr `plusPtr` 40)
<*> peek (ptr `plusPtr` 68)
<*> peek (ptr `plusPtr` 96)
<*> peek (ptr `plusPtr` 100)
poke ptr poked = poke (ptr `plusPtr` 0) (vkSType (poked :: VkPipelineDepthStencilStateCreateInfo))
*> poke (ptr `plusPtr` 8) (vkPNext (poked :: VkPipelineDepthStencilStateCreateInfo))
*> poke (ptr `plusPtr` 16) (vkFlags (poked :: VkPipelineDepthStencilStateCreateInfo))
*> poke (ptr `plusPtr` 20) (vkDepthTestEnable (poked :: VkPipelineDepthStencilStateCreateInfo))
*> poke (ptr `plusPtr` 24) (vkDepthWriteEnable (poked :: VkPipelineDepthStencilStateCreateInfo))
*> poke (ptr `plusPtr` 28) (vkDepthCompareOp (poked :: VkPipelineDepthStencilStateCreateInfo))
*> poke (ptr `plusPtr` 32) (vkDepthBoundsTestEnable (poked :: VkPipelineDepthStencilStateCreateInfo))
*> poke (ptr `plusPtr` 36) (vkStencilTestEnable (poked :: VkPipelineDepthStencilStateCreateInfo))
*> poke (ptr `plusPtr` 40) (vkFront (poked :: VkPipelineDepthStencilStateCreateInfo))
*> poke (ptr `plusPtr` 68) (vkBack (poked :: VkPipelineDepthStencilStateCreateInfo))
*> poke (ptr `plusPtr` 96) (vkMinDepthBounds (poked :: VkPipelineDepthStencilStateCreateInfo))
*> poke (ptr `plusPtr` 100) (vkMaxDepthBounds (poked :: VkPipelineDepthStencilStateCreateInfo))
-- ** vkCreateComputePipelines
foreign import ccall "vkCreateComputePipelines" vkCreateComputePipelines ::
VkDevice ->
VkPipelineCache ->
Word32 ->
Ptr VkComputePipelineCreateInfo ->
Ptr VkAllocationCallbacks -> Ptr VkPipeline -> IO VkResult
data VkStencilOpState =
VkStencilOpState{ vkFailOp :: VkStencilOp
, vkPassOp :: VkStencilOp
, vkDepthFailOp :: VkStencilOp
, vkCompareOp :: VkCompareOp
, vkCompareMask :: Word32
, vkWriteMask :: Word32
, vkReference :: Word32
}
deriving (Eq)
instance Storable VkStencilOpState where
sizeOf ~_ = 28
alignment ~_ = 4
peek ptr = VkStencilOpState <$> peek (ptr `plusPtr` 0)
<*> peek (ptr `plusPtr` 4)
<*> peek (ptr `plusPtr` 8)
<*> peek (ptr `plusPtr` 12)
<*> peek (ptr `plusPtr` 16)
<*> peek (ptr `plusPtr` 20)
<*> peek (ptr `plusPtr` 24)
poke ptr poked = poke (ptr `plusPtr` 0) (vkFailOp (poked :: VkStencilOpState))
*> poke (ptr `plusPtr` 4) (vkPassOp (poked :: VkStencilOpState))
*> poke (ptr `plusPtr` 8) (vkDepthFailOp (poked :: VkStencilOpState))
*> poke (ptr `plusPtr` 12) (vkCompareOp (poked :: VkStencilOpState))
*> poke (ptr `plusPtr` 16) (vkCompareMask (poked :: VkStencilOpState))
*> poke (ptr `plusPtr` 20) (vkWriteMask (poked :: VkStencilOpState))
*> poke (ptr `plusPtr` 24) (vkReference (poked :: VkStencilOpState))
| oldmanmike/vulkan | src/Graphics/Vulkan/Pipeline.hs | bsd-3-clause | 49,824 | 0 | 27 | 17,359 | 10,233 | 5,708 | 4,525 | 708 | 0 |
module Main
( main
) where
import qualified Control.Monad as CM
import qualified Data.Char as C
import qualified Data.List as L
import qualified Data.Map.Strict as M
import qualified Data.Maybe as DM
import qualified Data.Set as S
import ManPages
import MangledRegistry
import qualified System.Directory as D
import qualified System.Environment as E
import qualified System.FilePath as F
import qualified System.IO as SI
import qualified Text.PrettyPrint.HughesPJClass as P
main :: IO ()
main = do
[a, registryPath] <- E.getArgs
let api = API a
res <- parseRegistry toEnumType `fmap` readFile registryPath
case res of
Left msg -> SI.hPutStrLn SI.stderr msg
Right registry -> do
printTokens api registry
printGroups api registry
let sigMap = signatureMap registry
printForeign sigMap
printFunctions api registry sigMap
let extModules = extensionModules api registry
CM.forM_ extModules printExtensionModule
printReExports extModules
printExtensionSupport extModules
CM.forM_ (openGLVersions api) $ \v ->
CM.forM_ (supportedProfiles api v) $ \p -> printFeature api v p registry
printTopLevel api extModules
openGLVersions :: API -> [Version]
openGLVersions api =
map read $
case unAPI api of
"gl" ->
[ "1.0"
, "1.1"
, "1.2"
, "1.3"
, "1.4"
, "1.5"
, "2.0"
, "2.1"
, "3.0"
, "3.1"
, "3.2"
, "3.3"
, "4.0"
, "4.1"
, "4.2"
, "4.3"
, "4.4"
, "4.5"
, "4.6"
]
"gles1" -> ["1.0"]
"gles2" -> ["2.0", "3.0", "3.1", "3.2"]
a -> error $ "unknown API " ++ a
latestVersion :: API -> Version
latestVersion = last . openGLVersions
supportedProfiles :: API -> Version -> [Maybe ProfileName]
supportedProfiles api v =
case unAPI api of
"gl"
| major v < 3 -> [Nothing]
| otherwise -> map (Just . ProfileName) ["core", "compatibility"]
"gles1" -> map (Just . ProfileName) ["lite", "common"]
"gles2" -> [Nothing]
a -> error $ "unknown API " ++ a
latestProfiles :: API -> [Maybe ProfileName]
latestProfiles api = supportedProfiles api (latestVersion api)
profileToReExport :: API -> Maybe ProfileName
profileToReExport = last . latestProfiles
printFeature :: API -> Version -> Maybe ProfileName -> Registry -> IO ()
printFeature api version mbProfile registry =
printExtension [featureName version mbProfile] Nothing $
fixedReplay api version mbProfile registry
featureName :: Version -> Maybe ProfileName -> String
featureName version mbProfile =
maybe "Version" (capitalize . unProfileName) mbProfile ++
show (major version) ++ show (minor version)
printTokens :: API -> Registry -> IO ()
printTokens api registry = do
let cmnt =
[ Comment "All enumeration tokens from the"
, Comment "<http://www.opengl.org/registry/ OpenGL registry>."
]
startModule
["Tokens"]
(Just
"{-# LANGUAGE CPP, PatternSynonyms, ScopedTypeVariables #-}\n#if __GLASGOW_HASKELL__ >= 800\n{-# OPTIONS_GHC -Wno-missing-pattern-synonym-signatures #-}\n#endif")
cmnt $ \moduleName h -> do
hRender h $ Module moduleName P.empty
hRender h $ Import (moduleNameFor ["Types"]) P.empty
SI.hPutStrLn h ""
mapM_
(SI.hPutStrLn h . unlines . convertEnum)
[e | es <- M.elems (enums registry), e <- es, api `matches` enumAPI e]
printGroups :: API -> Registry -> IO ()
printGroups api registry = do
let cmnt =
[ Comment "All enumeration groups from the"
, Comment "<http://www.opengl.org/registry/ OpenGL registry>."
]
startModule ["Groups"] Nothing cmnt $ \moduleName h -> do
hRender h $ Module moduleName (P.text "(\n -- $EnumerantGroups\n)")
hRender h $ Comment "$EnumerantGroups"
hRender h $
Comment
"Note that the actual set of valid values depend on the OpenGL version, the"
hRender h $
Comment
"chosen profile and the supported extensions. Therefore, the groups mentioned"
hRender h $
Comment
"here should only be considered a rough guideline, for details see the OpenGL"
hRender h $ Comment "specification."
CM.forM_ (M.assocs (groups registry)) $ \(gn, g) -> do
let ugn = unGroupName gn
es = getGroupEnums api registry g
hRender h $ Comment ""
hRender h $ Comment ("=== #" ++ ugn ++ "# " ++ ugn)
hRender h $ Comment (groupHeader gn es)
hRender h $ Comment ""
-- TODO: Improve the alias computation below. It takes quadratic time and
-- is very naive about what is the canonical name and what is an alias.
CM.forM_ es $ \e -> do
let same = L.sort [f | f <- es, enumValue e == enumValue f]
CM.when (e == head same) $
hRender h $
Comment
("* " ++
linkToToken e ++
(case tail same of
[] -> ""
aliases ->
" (" ++
al ++
": " ++ L.intercalate ", " (map linkToToken aliases) ++ ")"
where al
| length aliases == 1 = "alias"
| otherwise = "aliases"))
linkToToken :: Enum' -> String
linkToToken e =
"'" ++
(case moduleNameFor ["Tokens"] of
ModuleName mn -> mn) ++
"." ++ (unEnumName . enumName) e ++ "'"
-- There are several enums which are mentioned in groups, but commented out in
-- enums (12 GL_*_ICC_SGIX enumerants). These are implicitly filtered out below.
getGroupEnums :: API -> Registry -> Group -> [Enum']
getGroupEnums api registry g =
[ e
| name <- groupEnums g
, Just es <- [M.lookup name (enums registry)]
, e <- es
, api `matches` enumAPI e
]
groupHeader :: GroupName -> [Enum'] -> String
groupHeader gn es =
case sortUnique (map enumTypeWithFix es)
-- There are 2 empty groups: DataType and FfdMaskSGIX.
of
[] -> "There are no values defined for this enumeration group."
[t]
| isMask t -> "A bitwise combination of several of the following values:"
| otherwise -> "One of the following values:"
tys ->
error $
"Contradicting enumerant types " ++
L.intercalate " and " (map unTypeName tys) ++
" in group " ++
unGroupName gn ++
":\n" ++
unlines
[ " " ++ unEnumName (enumName e) ++ " :: " ++ unTypeName (enumType e)
| e <- es
]
-- NV_path_rendering screws up typing: It uses GL_NONE as a bitfield, and this
-- leads to a collision in the PathFontStyle group. :-/
-- Furthermore, glClampColor uses GL_TRUE and GL_FALSE as a GLenum.
where
enumTypeWithFix e
| gn == GroupName "PathFontStyle" && enumName e == EnumName "GL_NONE" =
TypeName "GLbitfield"
| gn == GroupName "ClampColorModeARB" && enumName e == EnumName "GL_TRUE" =
TypeName "GLenum"
| gn == GroupName "ClampColorModeARB" && enumName e == EnumName "GL_FALSE" =
TypeName "GLenum"
| otherwise = enumType e
-- Calulate a map from compact signature to short names.
signatureMap :: Registry -> M.Map String String
signatureMap registry =
fst $ M.foldl' step (M.empty, 0 :: Integer) (commands registry)
where
step (m, n) command = memberAndInsert (n + 1) n (sig command) (dyn n) m
sig = flip (showSignatureFromCommand registry) False
dyn n = "dyn" ++ show n
memberAndInsert notFound found key value theMap =
(newMap, maybe notFound (const found) maybeValue)
where
(maybeValue, newMap) =
M.insertLookupWithKey (\_ _ s -> s) key value theMap
printForeign :: M.Map String String -> IO ()
printForeign sigMap = do
let cmnt = [Comment "All foreign imports."]
startModule
["Foreign"]
(Just "{-# LANGUAGE CPP #-}\n{-# OPTIONS_HADDOCK hide #-}")
cmnt $ \moduleName h -> do
hRender h $ Module moduleName P.empty
hRender h $ Import (ModuleName "Foreign.C.Types") P.empty
hRender h $
Import (ModuleName "Foreign.Marshal.Error") (P.text "( throwIf )")
hRender h $ Import (ModuleName "Foreign.Ptr") P.empty
hRender h $
Import (moduleNameFor ["GetProcAddress"]) (P.text "( getProcAddress )")
hRender h $ Import (moduleNameFor ["Types"]) P.empty
hRender h $ Import (ModuleName "Numeric.Fixed") P.empty
hRender h $ Import (ModuleName "Numeric.Half") P.empty
SI.hPutStrLn h ""
SI.hPutStrLn h "getCommand :: String -> IO (FunPtr a)"
SI.hPutStrLn h "getCommand cmd ="
SI.hPutStrLn
h
" throwIfNullFunPtr (\"unknown OpenGL command \" ++ cmd) $ getProcAddress cmd"
SI.hPutStrLn
h
" where throwIfNullFunPtr :: String -> IO (FunPtr a) -> IO (FunPtr a)"
SI.hPutStrLn h " throwIfNullFunPtr = throwIf (== nullFunPtr) . const"
SI.hPutStrLn h ""
mapM_ (SI.hPutStrLn h . uncurry makeImportDynamic) (M.assocs sigMap)
chunksOf :: Int -> [a] -> [[a]]
chunksOf n = takeWhile (not . null) . L.unfoldr (Just . splitAt n)
justifyRight :: Int -> a -> [a] -> [a]
justifyRight n c xs =
reverse . take (max n (length xs)) . (++ repeat c) . reverse $ xs
printFunctions :: API -> Registry -> M.Map String String -> IO ()
printFunctions api registry sigMap = do
let cmnt =
[ Comment "All raw functions from the"
, Comment "<http://www.opengl.org/registry/ OpenGL registry>."
]
cmds = chunksOf 100 . M.toAscList . commands $ registry
mnames =
[ ["Functions", "F" ++ justifyRight 2 '0' (show i)]
| i <- [1 .. length cmds]
]
startModule ["Functions"] Nothing cmnt $ \moduleName h -> do
hRender h $
Module
moduleName
(P.text
("(\n" ++
separate
(\x ->
"module " ++
(case moduleNameFor x of
ModuleName mn -> mn))
mnames ++
"\n)"))
CM.forM_ mnames $ \mname -> hRender h $ Import (moduleNameFor mname) P.empty
CM.zipWithM_ (printSubFunctions api registry sigMap) mnames cmds
printSubFunctions ::
API
-> Registry
-> M.Map String String
-> [String]
-> [(CommandName, Command)]
-> IO ()
printSubFunctions api registry sigMap mname cmds = do
let cmnt =
[ Comment "Raw functions from the"
, Comment "<http://www.opengl.org/registry/ OpenGL registry>."
]
startModule mname (Just "{-# OPTIONS_HADDOCK hide #-}") cmnt $ \moduleName h -> do
hRender h $
Module
moduleName
(P.text ("(\n" ++ separate unCommandName (map fst cmds) ++ "\n)"))
hRender h $
Import (ModuleName "Control.Monad.IO.Class") (P.text "( MonadIO(..) )")
hRender h $ Import (ModuleName "Foreign.Ptr") P.empty
hRender h $ Import (moduleNameFor ["Foreign"]) P.empty
hRender h $ Import (moduleNameFor ["Types"]) P.empty
hRender h $
Import (ModuleName "System.IO.Unsafe") (P.text "( unsafePerformIO )")
SI.hPutStrLn h ""
mapM_ (SI.hPutStrLn h . showCommand api registry sigMap . snd) cmds
type ExtensionParts = ([TypeName], [Enum'], [Command])
type ExtensionModule = (ExtensionName, ExtensionName, ExtensionParts)
printExtensionModule :: ExtensionModule -> IO ()
printExtensionModule (extName, mangledExtName, extensionParts) =
printExtension
[extensionNameCategory mangledExtName, extensionNameName mangledExtName]
(Just extName)
extensionParts
extendWithProfile :: ExtensionName -> Maybe ProfileName -> ExtensionName
extendWithProfile extName =
maybe
extName
(\p ->
extName
{ extensionNameName =
joinWords [extensionNameName extName, capitalize (unProfileName p)]
})
mangleExtensionName :: ExtensionName -> ExtensionName
mangleExtensionName extName =
extName
{ extensionNameCategory = fixCategory $ extensionNameCategory extName
, extensionNameName =
zip (splitWords (extensionNameName extName)) [0 :: Integer ..] >>=
fixExtensionWord
}
where
fixCategory c =
case c of
"3DFX" -> "ThreeDFX"
_ -> c
fixExtensionWord (w, pos) =
case w of
"422"
| pos == 0 -> "FourTwoTwo"
"64bit" -> "64Bit"
"ES2" -> "ES2"
"ES3" -> "ES3"
"FXT1" -> "FXT1"
"a2ui" -> "A2UI"
"abgr" -> "ABGR"
"astc" -> "ASTC"
"bgra" -> "BGRA"
"bptc" -> "BPTC"
"cl" -> "CL"
"cmyka" -> "CMYKA"
"dxt1" -> "DXT1"
"es" -> "ES"
"ffd" -> "FFD"
"fp64" -> "FP64"
"gpu" -> "GPU"
"hdr" -> "HDR"
"latc" -> "LATC"
"ldr" -> "LDR"
"lod" -> "LOD"
"pn" -> "PN"
"rg" -> "RG"
"rgb" -> "RGB"
"rgb10" -> "RGB10"
"rgb32" -> "RGB32"
"rgtc" -> "RGTC"
"s3tc" -> "S3TC"
"sRGB" -> "SRGB"
"snorm" -> "SNorm"
"texture3D" -> "Texture3D"
"texture4D" -> "Texture4D"
"vdpau" -> "VDPAU"
"ycbcr" -> "YCbCr"
"ycrcb" -> "YCrCb"
"ycrcba" -> "YCrCbA"
_ -> capitalize w
extensionModules :: API -> Registry -> [ExtensionModule]
extensionModules api registry =
[ (extName, mangledExtName, executeModifications api mbProfile registry mods)
| (extName, mods) <- supportedExtensions api registry
, mbProfile <-
if isProfileDependent mods
then suppProfs
else [Nothing]
, let mangledExtName =
mangleExtensionName (extendWithProfile extName mbProfile)
]
where
suppProfs = latestProfiles api
isProfileDependent mods =
any (`S.member` allProfileNames) (mentionedProfileNames mods)
mentionedProfileNames = DM.mapMaybe modificationProfile
allProfileNames = S.fromList . DM.catMaybes $ suppProfs
-- We only consider non-empty supported extensions/modifications for the given API.
supportedExtensions :: API -> Registry -> [(ExtensionName, [Modification])]
supportedExtensions api registry =
[ nameAndMods
| ext <- extensions registry
, api `supports` extensionSupported ext
, nameAndMods@(_, _:_) <- [nameAndModifications ext]
]
where
nameAndModifications :: Extension -> (ExtensionName, [Modification])
nameAndModifications e =
( extensionName e
, [ conditionalModificationModification cm
| cm <- extensionsRequireRemove e
, api `matches` conditionalModificationAPI cm
-- ARB_compatibility has an empty "require" element only
, not .
null .
modificationInterfaceElements . conditionalModificationModification $
cm
])
extensionHyperlink :: ExtensionName -> String
extensionHyperlink n =
"<https://www.opengl.org/registry/specs/" ++
fixRegistryPath (extensionNameCategory n ++ "/" ++ extensionNameName n) ++
".txt " ++ joinWords [extensionNameCategory n, extensionNameName n] ++ ">"
where
fixRegistryPath :: String -> String
fixRegistryPath path =
case path of
"3DFX/multisample" -> "3DFX/3dfx_multisample"
"EXT/debug_label" -> "EXT/EXT_debug_label"
"EXT/debug_marker" -> "EXT/EXT_debug_marker"
"EXT/multisample" -> "EXT/wgl_multisample"
"EXT/texture_cube_map" -> "ARB/texture_cube_map"
"INGR/blend_func_separate" -> "EXT/blend_func_separate"
"KHR/blend_equation_advanced_coherent" -> "KHR/blend_equation_advanced"
"KHR/texture_compression_astc_ldr" -> "KHR/texture_compression_astc_hdr"
"NV/blend_equation_advanced_coherent" -> "NV/blend_equation_advanced"
"NVX/conditional_render" -> "NVX/nvx_conditional_render"
"OES/byte_coordinates" -> "OES/OES_byte_coordinates"
"OES/compressed_paletted_texture" ->
"OES/OES_compressed_paletted_texture"
"OES/fixed_point" -> "OES/OES_fixed_point"
"OES/query_matrix" -> "OES/OES_query_matrix"
"OES/read_format" -> "OES/OES_read_format"
"OES/single_precision" -> "OES/OES_single_precision"
"SGIS/fog_function" -> "SGIS/fog_func"
"SGIS/point_parameters" -> "EXT/point_parameters"
"SGIX/fragment_lighting" -> "EXT/fragment_lighting"
"SGIX/pixel_texture" -> "SGIX/sgix_pixel_texture"
"SGIX/texture_add_env" -> "SGIX/texture_env_add"
_ -> path
printReExports :: [ExtensionModule] -> IO ()
printReExports extModules = do
let extMap =
M.fromListWith
(++)
[ ( ( extensionNameCategory extName
, extensionNameCategory mangledExtName)
, [mangledExtName])
| (extName, mangledExtName, _) <- extModules
]
reExports =
[ (cat, L.sort mangledExtNames)
| (cat, mangledExtNames) <- M.toList extMap
]
CM.forM_ reExports $ \((category, mangledCategory), mangledExtNames) -> do
let cmnt =
[ Comment
("A convenience module, combining all raw modules containing " ++
category ++ " extensions.")
]
startModule [mangledCategory] Nothing cmnt $ \moduleName h -> do
hRender h $
Module
moduleName
(P.text
("(\n" ++
separate
(\mangledExtName ->
"module " ++
(case extensionNameFor mangledExtName of
ModuleName mn -> mn))
mangledExtNames ++
"\n)"))
CM.forM_ mangledExtNames $ \mangledExtName ->
hRender h $ Import (extensionNameFor mangledExtName) P.empty
printExtensionSupport :: [ExtensionModule] -> IO ()
printExtensionSupport extModules = do
let cmnt = [Comment "Extension support predicates."]
startModule ["ExtensionPredicates"] (Just "{-# OPTIONS_HADDOCK hide #-}") cmnt $ \moduleName h -> do
hRender h $ Module moduleName P.empty
hRender h $
Import (ModuleName "Control.Monad.IO.Class") (P.text "( MonadIO(..) )")
hRender h $ Import (ModuleName "Data.Set") (P.text "( member )")
hRender h $
Import
(moduleNameFor ["GetProcAddress"])
(P.text "( getExtensions, extensions )")
let names = sortUnique [extName | (extName, _, _) <- extModules]
CM.forM_ names $ \extName -> do
let predNameMonad = extensionPredicateNameMonad extName
predName = extensionPredicateName extName
extString =
joinWords
[ extensionNameAPI extName
, extensionNameCategory extName
, extensionNameName extName
]
SI.hPutStrLn h ""
hRender h $
Comment
("| Is the " ++ extensionHyperlink extName ++ " extension supported?")
SI.hPutStrLn h $ predNameMonad ++ " :: MonadIO m => m Bool"
SI.hPutStrLn h $
predNameMonad ++
" = getExtensions >>= (return . member " ++ show extString ++ ")"
SI.hPutStrLn h ""
hRender h $
Comment
("| Is the " ++ extensionHyperlink extName ++ " extension supported?")
hRender h $
Comment
"Note that in the presence of multiple contexts with different capabilities,"
hRender h $
Comment
("this might be wrong. Use '" ++
predNameMonad ++ "' in those cases instead.")
SI.hPutStrLn h $ predName ++ " :: Bool"
SI.hPutStrLn h $
predName ++ " = member " ++ show extString ++ " extensions"
SI.hPutStrLn h $ "{-# NOINLINE " ++ predName ++ " #-}"
extensionNameFor :: ExtensionName -> ModuleName
extensionNameFor mangledExtName =
moduleNameFor
[extensionNameCategory mangledExtName, extensionNameName mangledExtName]
supports :: API -> Maybe [API] -> Bool
_ `supports` Nothing = True
a `supports` Just apis = a `elem` apis
capitalize :: String -> String
capitalize str = C.toUpper (head str) : map C.toLower (tail str)
separate :: (a -> String) -> [a] -> String
separate f = L.intercalate ",\n" . map ((" " ++) . f)
-- Note that we handle features just like extensions.
printExtension :: [String] -> Maybe ExtensionName -> ExtensionParts -> IO ()
printExtension moduleNameSuffix mbExtName (ts, es, cs) = do
let pragma =
if null es
then Nothing
else Just "{-# LANGUAGE PatternSynonyms #-}"
startModule moduleNameSuffix pragma [] $ \moduleName h -> do
let extStr =
flip (maybe "") mbExtName $ \extName ->
" -- * Extension Support\n" ++
separate
id
[ extensionPredicateNameMonad extName
, extensionPredicateName extName
] ++
",\n"
typeStr
| null ts = ""
| otherwise =
" -- * Types\n" ++
separate unTypeName ts ++
if null es && null cs
then "\n"
else ",\n"
enumStr
| null es = ""
| otherwise =
" -- * Enums\n" ++
separate (("pattern " ++) . unEnumName . enumName) es ++
if null cs
then "\n"
else ",\n"
funcStr
| null cs = ""
| otherwise =
" -- * Functions\n" ++
separate (unCommandName . commandName) cs ++ "\n"
hRender h $
Module
moduleName
(P.text ("(\n" ++ extStr ++ typeStr ++ enumStr ++ funcStr ++ ")"))
CM.when (DM.isJust mbExtName) $
hRender h $ Import (moduleNameFor ["ExtensionPredicates"]) P.empty
CM.unless (null ts) $ hRender h $ Import (moduleNameFor ["Types"]) P.empty
CM.unless (null es) $ hRender h $ Import (moduleNameFor ["Tokens"]) P.empty
CM.unless (null cs) $
hRender h $ Import (moduleNameFor ["Functions"]) P.empty
extensionPredicateName :: ExtensionName -> String
extensionPredicateName extName =
joinWords
[ map C.toLower (extensionNameAPI extName)
, extensionNameCategory extName
, extensionNameName extName
]
extensionPredicateNameMonad :: ExtensionName -> String
extensionPredicateNameMonad extName =
map C.toLower (extensionNameAPI mangledExtName) ++
"Get" ++
extensionNameCategory mangledExtName ++ extensionNameName mangledExtName
where
mangledExtName = mangleExtensionName extName
printTopLevel :: API -> [ExtensionModule] -> IO ()
printTopLevel api extModules = do
let mangledCategories =
sortUnique
[ extensionNameCategory mangledExtName
| (_, mangledExtName, _) <- extModules
]
profToReExport = profileToReExport api
lastComp = featureName (latestVersion api) profToReExport
moduleNames =
[ moduleNameFor [c]
| c <- [lastComp, "GetProcAddress"] ++ mangledCategories
]
cmnt =
[ Comment
(unwords
[ "A convenience module, combining the latest"
, apiName api
, maybe
"version"
(\p -> unProfileName p ++ " profile")
profToReExport
, "plus"
])
, Comment "all extensions."
]
startModule [] Nothing cmnt $ \moduleName h -> do
hRender h $
Module
moduleName
(P.text
("(\n" ++
separate (\(ModuleName m) -> "module " ++ m) moduleNames ++ "\n)"))
CM.forM_ moduleNames $ \theModuleName ->
hRender h $ Import theModuleName P.empty
apiName :: API -> String
apiName api =
case unAPI api of
"gl" -> "OpenGL"
"gles1" -> "OpenGL ES 1.x"
"gles2" -> "OpenGL ES"
a -> error $ "unknown API " ++ a
sortUnique :: Ord a => [a] -> [a]
sortUnique = S.toList . S.fromList
startModule ::
[String]
-> Maybe String
-> [Comment]
-> (ModuleName -> SI.Handle -> IO ())
-> IO ()
startModule moduleNameSuffix mbPragma comments action = do
let path = modulePathFor moduleNameSuffix
moduleName = moduleNameFor moduleNameSuffix
D.createDirectoryIfMissing True $ F.takeDirectory path
SI.withFile path SI.WriteMode $ \h -> do
printModuleHeader h mbPragma moduleName comments
action moduleName h
moduleNameFor :: [String] -> ModuleName
moduleNameFor = ModuleName . L.intercalate "." . moduleNameParts
modulePathFor :: [String] -> FilePath
modulePathFor moduleNameSuffix =
F.joinPath (moduleNameParts moduleNameSuffix) `F.addExtension` "hs"
moduleNameParts :: [String] -> [String]
moduleNameParts = (["Graphics", "GL"] ++)
printModuleHeader ::
SI.Handle -> Maybe String -> ModuleName -> [Comment] -> IO ()
printModuleHeader h mbPragma (ModuleName moduleName) comments = do
maybe (return ()) (SI.hPutStrLn h) mbPragma
hRender h $
Comment
"------------------------------------------------------------------------------"
hRender h $ Comment "|"
hRender h $ Comment ("Module : " ++ moduleName)
hRender h $ Comment "Copyright : (c) Sven Panne 2019"
hRender h $ Comment "License : BSD3"
hRender h $ Comment ""
hRender h $ Comment "Maintainer : Sven Panne <svenpanne@gmail.com>"
hRender h $ Comment "Stability : stable"
hRender h $ Comment "Portability : portable"
hRender h $ Comment ""
CM.unless (null comments) $ do
mapM_ (hRender h) comments
hRender h $ Comment ""
hRender h $
Comment
"------------------------------------------------------------------------------"
SI.hPutStrLn h ""
-- Annoyingly enough, the OpenGL registry doesn't contain any enums for
-- OpenGL 1.0, so let's just use the OpenGL 1.1 ones. Furthermore, features
-- don't explicitly list the types referenced by commands, so we add them.
fixedReplay :: API -> Version -> Maybe ProfileName -> Registry -> ExtensionParts
fixedReplay api version mbProfile registry
| api == API "gl" && version == read "1.0" = (ts', es11, cs)
| otherwise = (ts', es, cs)
where
(ts, es, cs) = replay api version mbProfile registry
(_, es11, _) = replay api (read "1.1") mbProfile registry
ts' =
S.toList . addFuncsAndMakes . S.unions $
S.fromList ts : map referencedTypes cs
-- For debug callbacks, we want to export the Haskell types and their creators, too.
addFuncsAndMakes :: S.Set TypeName -> S.Set TypeName
addFuncsAndMakes =
flip
(foldr addFuncAndMake)
["GLDEBUGPROC", "GLDEBUGPROCAMD", "GLDEBUGPROCARB", "GLDEBUGPROCKHR"]
where
addFuncAndMake t ts
| TypeName t `S.member` ts =
ts `S.union` S.fromList (map TypeName [t ++ "Func", "make" ++ t])
| otherwise = ts
-- Here is the heart of the feature construction logic: Chronologically replay
-- the whole version history for the given API/version/profile triple.
replay :: API -> Version -> Maybe ProfileName -> Registry -> ExtensionParts
replay api version mbProfile registry =
executeModifications api mbProfile registry modifications
where
modifications = history >>= flip lookup' (features registry)
history =
L.sort
[key | key@(a, v) <- M.keys (features registry), a == api, v <= version]
executeModifications ::
API -> Maybe ProfileName -> Registry -> [Modification] -> ExtensionParts
executeModifications api mbProfile registry modifications = (ts, es, cs)
where
ts = [n | TypeElement n <- lst]
es =
[ e
| EnumElement n <- lst
, e <- lookup' n (enums registry)
, api `matches` enumAPI e
]
cs = [lookup' n (commands registry) | CommandElement n <- lst]
lst = S.toList $ interfaceElementsFor mbProfile modifications
interfaceElementsFor ::
Maybe ProfileName -> [Modification] -> S.Set InterfaceElement
interfaceElementsFor mbProfile modifications =
foldl (flip ($)) S.empty modificationsFor
where
modificationsFor =
[ op (modificationKind m) ie
| m <- modifications
, maybe True (`matches` modificationProfile m) mbProfile
, ie <- modificationInterfaceElements m
]
op Require = S.insert
op Remove = S.delete
lookup' :: (Ord k, Show k) => k -> M.Map k a -> a
lookup' k = M.findWithDefault (error ("unknown name " ++ show k)) k
matches :: Eq a => a -> Maybe a -> Bool
_ `matches` Nothing = True
s `matches` Just t = s == t
convertEnum :: Enum' -> [String]
convertEnum e =
[ "pattern " ++
n ++ " = " ++ unEnumValue (enumValue e) ++ " :: " ++ unTypeName (enumType e)
]
where
n = unEnumName . enumName $ e
showCommand :: API -> Registry -> M.Map String String -> Command -> String
showCommand api registry sigMap c =
showString
(P.render
(P.pPrint (Comment (take 77 (name ++ " " ++ repeat '-'))) P.$+$ P.text "" P.$+$
P.text "")) .
showString (P.render cmnt) .
showString (name ++ "\n") .
showString " :: MonadIO m\n" .
showString (" => " ++ signature True) .
showString
(name ++
args ++ " = liftIO $ " ++ dyn_name ++ " " ++ ptr_name ++ args ++ "\n\n") .
showString ("{-# NOINLINE " ++ ptr_name ++ " #-}\n") .
showString (ptr_name ++ " :: FunPtr (" ++ compactSignature ++ ")\n") .
showString
(ptr_name ++ " = unsafePerformIO $ getCommand " ++ str_name ++ "\n") $
""
where
name = signatureElementName (resultType c)
dyn_name = lookup' compactSignature sigMap
ptr_name = "ptr_" ++ name
str_name = show name
compactSignature = signature False
signature = showSignatureFromCommand registry c
urls = M.findWithDefault [] (api, CommandName name) manPageURLs
links = L.intercalate " or " (map renderURL urls)
cmnt =
case concat (man ++ ve ++ al) of
"" -> P.empty
cs -> P.pPrint (Comment ("|" ++ cs)) P.$+$ P.text ""
man =
case urls of
[] -> []
[_] -> [" Manual page for " ++ links ++ "."]
_ -> [" Manual pages for " ++ links ++ "."]
ve =
[ " The vector equivalent of this command is '" ++ unCommandName v ++ "'."
| Just v <- [vecEquiv c]
]
al =
[ " This command is an alias for '" ++ unCommandName a ++ "'."
| Just a <- [alias c]
]
renderURL (u, l) = "<" ++ u ++ " " ++ l ++ ">"
args = [1 .. length (paramTypes c)] >>= \i -> " v" ++ show i
makeImportDynamic :: String -> String -> String
makeImportDynamic compactSignature dyn_name =
"foreign import CALLCONV \"dynamic\" " ++
dyn_name ++
"\n" ++
" :: FunPtr (" ++
compactSignature ++ ")\n" ++ " -> " ++ compactSignature ++ "\n"
showSignatureFromCommand :: Registry -> Command -> Bool -> String
showSignatureFromCommand registry c withComment =
L.intercalate
((if withComment
then " "
else "") ++
" -> ")
([showSignatureElement registry withComment False t | t <- paramTypes c] ++
[showSignatureElement registry withComment True (resultType c)])
showSignatureElement :: Registry -> Bool -> Bool -> SignatureElement -> String
showSignatureElement registry withComment isResult sigElem = el ++ cmnt
where
el
| isResult = monad ++ " " ++ showsPrec 11 sigElem ""
| otherwise = show sigElem
monad
| withComment = "m"
| otherwise = "IO"
cmnt
| withComment =
P.render (showComment registry name sigElem P.$+$ P.text "")
| otherwise = ""
name
| isResult = ""
| otherwise = signatureElementName sigElem
showComment :: Registry -> String -> SignatureElement -> P.Doc
showComment registry name sigElem
| null name' && null info = P.text ""
| otherwise = P.text " " P.<> P.pPrint (Comment ("^" ++ name' ++ info ++ "."))
where
name'
| null name = ""
| otherwise = " " ++ inlineCode name
info
| isInteresting = elms ++ " of type " ++ hurz
| otherwise = ""
-- Alas, there are tons of group names which are referenced, but never
-- defined, so we have to leave them without a link.
-- TODO: Do not use Show instance for SignatureElement.
hurz =
case belongsToGroup sigElem of
Just gn
| numPointer sigElem <= 1 && fgn `M.member` groups registry ->
linkToGroup fgn
where fgn = fixGroupName gn
_ -> inlineCode (show (base sigElem))
isInteresting =
DM.isJust (arrayLength sigElem) || DM.isJust (belongsToGroup sigElem)
elms
| numPointer sigElem > 0 = " pointing to" ++ len ++ " " ++ elements
| otherwise = ""
elements
| arrayLength sigElem == Just "1" = "element"
| otherwise = "elements"
len = maybe "" (\l -> " " ++ inlineCode l) (arrayLength sigElem)
base = maybeDeref . maybeSetBaseType
maybeDeref e
| numPointer e > 0 = e {numPointer = numPointer e - 1}
| otherwise = e
maybeSetBaseType e =
maybe e (\g -> e {baseType = TypeName (unGroupName g)}) (belongsToGroup e)
fixGroupName :: GroupName -> GroupName
fixGroupName g
| g == GroupName "PixelInternalFormat" = GroupName "InternalFormat"
| g == GroupName "SGIXFfdMask" = GroupName "FfdMaskSGIX"
| otherwise = g
-- TODO: This is very fragile, but currently there is no clean way to specify
-- link texts when referencing anchors in Haddock.
linkToGroup :: GroupName -> String
linkToGroup g =
"[" ++ n ++ "](" ++ htmlFilenameFor ["Groups"] ++ "#" ++ n ++ ")"
where
n = unGroupName g
htmlFilenameFor :: [String] -> String
htmlFilenameFor = (++ ".html") . L.intercalate "-" . moduleNameParts
inlineCode :: String -> String
inlineCode s = "@" ++ s ++ "@"
-- TODO: Use Either instead of error below?
toEnumType :: ToEnumType
toEnumType eNamespace eGroup eType suffix eName =
TypeName $
case (eNamespace, eGroup, eType, unTypeSuffix `fmap` suffix, eName)
-- glx.xml
of
(Just "GLXStrings", _, _, _, _) -> "String"
(Just ('G':'L':'X':_), _, _, _, _) -> "CInt"
-- egl.xml
-- TODO: EGLenum for EGL_OPENGL_API, EGL_OPENGL_ES_API, EGL_OPENVG_API, EGL_OPENVG_IMAGE?
(Just ('E':'G':'L':_), _, Nothing, Just "ull", _) -> "EGLTime"
(Just ('E':'G':'L':_), _, _, _, _) -> "EGLint"
-- wgl.xml
(Just "WGLLayerPlaneMask", _, _, _, _) -> "UINT"
(Just "WGLColorBufferMask", _, _, _, _) -> "UINT"
(Just "WGLContextFlagsMask", _, _, _, _) -> "INT"
(Just "WGLContextProfileMask", _, _, _, _) -> "INT"
(Just "WGLImageBufferMaskI3D", _, _, _, _) -> "UINT"
(Just "WGLDXInteropMaskNV", _, _, _, _) -> "GLenum"
(Just ('W':'G':'L':_), _, _, _, _) -> "CInt"
-- gl.xml
(Just "OcclusionQueryEventMaskAMD", _, _, _, _) -> "GLuint"
(Just "GL", Just "SpecialNumbers", _, _, "GL_FALSE") -> "GLboolean"
(Just "GL", Just "SpecialNumbers", _, _, "GL_TRUE") -> "GLboolean"
(Just "GL", Just "PathRenderingTokenNV", _, _, _) -> "GLubyte"
(Just "GL", _, Just "bitmask", _, _) -> "GLbitfield"
(Just "GL", _, Nothing, Just "u", _) -> "GLuint"
(Just "GL", _, Nothing, Just "ull", _) -> "GLuint64"
(Just "GL", _, Nothing, Nothing, _) -> "GLenum"
(_, _, _, _, _) -> error "can't determine enum type"
isMask :: TypeName -> Bool
isMask = (== TypeName "GLbitfield")
--------------------------------------------------------------------------------
data Module =
Module ModuleName
Exports
instance P.Pretty Module where
pPrint (Module mn ex) =
P.text "module" P.<+> P.pPrint mn P.<+> ex P.<+> P.text "where\n"
type Exports = P.Doc
data Import =
Import ModuleName
ImportSpecs
instance P.Pretty Import where
pPrint (Import mn im) = P.text "import" P.<+> P.pPrint mn P.<+> im
type ImportSpecs = P.Doc
newtype ModuleName =
ModuleName String
instance P.Pretty ModuleName where
pPrint (ModuleName m) = P.text m
newtype Comment =
Comment String
instance P.Pretty Comment where
pPrint (Comment c)
| null c = P.text "--"
| all (== '-') c = P.pPrint (Comment "") P.<> P.text c
| otherwise = P.pPrint (Comment "") P.<+> P.text c
hRender :: P.Pretty a => SI.Handle -> a -> IO ()
hRender h = SI.hPutStrLn h . P.render . P.pPrint
| haskell-opengl/OpenGLRaw | RegistryProcessor/src/Main.hs | bsd-3-clause | 35,625 | 0 | 33 | 9,469 | 10,423 | 5,209 | 5,214 | 859 | 38 |
{-# LANGUAGE DataKinds #-}
import Debug.Trace
import Test.QuickCheck
import Spec.SimplTest
import LSI.RationalFunction
prop_simpl :: RationalFunction 2 Rational -> (Rational, Rational) -> Bool
prop_simpl r zs = let r' = simplify r in
eval zs r' == eval zs r
main :: IO ()
main = do
let args = stdArgs { maxSize = 40 }
quickCheckWith args prop_simpl
| gdeest/lsi-systems | test/Spec.hs | bsd-3-clause | 360 | 0 | 11 | 69 | 124 | 63 | 61 | 12 | 1 |
{-# LANGUAGE DeriveDataTypeable, DeriveFoldable, DeriveTraversable, DeriveFunctor, FlexibleContexts #-}
module Language.Haskell.AST.Sugar
where
import Data.Data
import Data.Foldable (Foldable)
import Data.Traversable (Traversable)
import Language.Haskell.AST.Core hiding (Exp, Alt, Pat, Type)
-- | Extension of @GType@ with standard syntactic sugar
data Type ty id l
= TyTuple l Boxed [ty id l] -- ^ tuple type, possibly boxed
| TyList l (ty id l) -- ^ list syntax, e.g. [a], as opposed to [] a
| TyParen l (ty id l) -- ^ type surrounded by parentheses
| TyInfix l (ty id l) (QName id l) (ty id l) -- ^ infix type constructor
| TyKind l (ty id l) (Kind id l) -- ^ type with explicit kind signature
deriving (Eq,Ord,Show,Typeable,Data,Foldable,Traversable,Functor)
-- | Extension of @GPat@ with standard syntactic sugar
data Pat lit pat id l
= PLit l (lit l) -- ^ literal constant
| PNeg l (pat id l) -- ^ negated pattern
| PInfixApp l (pat id l) (QName id l) (pat id l) -- ^ pattern with an infix data constructor
| PTuple l Boxed [pat id l] -- ^ tuple pattern
| PList l [pat id l] -- ^ list pattern
| PParen l (pat id l) -- ^ parenthesized pattern
| PRec l (QName id l) [PatField pat id l] -- ^ labelled pattern, record style
| PAsPat l (Name id l) (pat id l) -- ^ @\@@-pattern
| PIrrPat l (pat id l) -- ^ irrefutable pattern: @~/pat/@
deriving (Eq,Ord,Show,Typeable,Data,Foldable,Traversable,Functor)
-- | An /fpat/ in a labeled record pattern.
data PatField pat id l
= PFieldPat l (QName id l) (pat id l) -- ^ ordinary label-pattern pair
| PFieldPun l (Name id l) -- ^ record field pun
| PFieldWildcard l -- ^ record field wildcard
deriving (Eq,Ord,Show,Typeable,Data,Foldable,Traversable,Functor)
-- | Extension of @GExp@ with standard syntactic sugar
data Exp binds ty guard pat stmtext exp id l
= CaseAlt l (exp id l)
[Alt binds guard exp pat id l] -- ^ @case@ /exp/ @of@ /alts/
| InfixApp l (exp id l) (QOp id l) (exp id l) -- ^ infix application
| NegApp l (exp id l) -- ^ negation expression @-/exp/@ (unary minus)
| If l (exp id l) (exp id l) (exp id l) -- ^ @if@ /exp/ @then@ /exp/ @else@ /exp/
| Do l [Stmt binds exp pat stmtext id l] -- ^ @do@-expression:
-- the last statement in the list
-- should be an expression.
| Tuple l Boxed [exp id l] -- ^ tuple expression
| TupleSection l Boxed [Maybe (exp id l)] -- ^ tuple section expression, e.g. @(,,3)@
| List l [exp id l] -- ^ list expression
| Paren l (exp id l) -- ^ parenthesised expression
| LeftSection l (exp id l) (QOp id l) -- ^ left section @(@/exp/ /qop/@)@
| RightSection l (QOp id l) (exp id l) -- ^ right section @(@/qop/ /exp/@)@
| RecConstr l (QName id l) [FieldUpdate exp id l] -- ^ record construction expression
| RecUpdate l (exp id l) [FieldUpdate exp id l] -- ^ record update expression
| EnumFrom l (exp id l) -- ^ unbounded arithmetic sequence,
-- incrementing by 1: @[from ..]@
| EnumFromTo l (exp id l) (exp id l) -- ^ bounded arithmetic sequence,
-- incrementing by 1 @[from .. to]@
| EnumFromThen l (exp id l) (exp id l) -- ^ unbounded arithmetic sequence,
-- with first two elements given @[from, then ..]@
| EnumFromThenTo l (exp id l) (exp id l) (exp id l)
-- ^ bounded arithmetic sequence,
-- with first two elements given @[from, then .. to]@
| ListComp l (exp id l)
[Stmt binds exp pat stmtext id l] -- ^ ordinary list comprehension
| ExpTypeSig l (exp id l) (ty id l) -- ^ expression with explicit type signature
deriving (Eq,Ord,Show,Typeable,Data,Foldable,Traversable,Functor)
-- | Possibly qualified infix operators (/qop/), appearing in expressions.
data QOp id l
= QVarOp l (QName id l) -- ^ variable operator (/qvarop/)
| QConOp l (QName id l) -- ^ constructor operator (/qconop/)
deriving (Eq,Ord,Show,Typeable,Data,Foldable,Traversable,Functor)
-- | An /fbind/ in a labeled construction or update expression.
data FieldUpdate exp id l
= FieldUpdate l (QName id l) (exp id l) -- ^ ordinary label-expresion pair
| FieldPun l (Name id l) -- ^ record field pun
| FieldWildcard l -- ^ record field wildcard
deriving (Eq,Ord,Show,Typeable,Data,Foldable,Traversable,Functor)
-- | An /alt/ alternative in a @case@ expression.
data Alt binds guard exp pat id l
= Alt l (pat id l) (GuardedAlts guard exp id l) (Maybe (binds id l))
deriving (Eq,Ord,Show,Typeable,Data,Foldable,Traversable,Functor)
-- | The right-hand sides of a @case@ alternative,
-- which may be a single right-hand side or a
-- set of guarded ones.
data GuardedAlts guard exp id l
= UnGuardedAlt l (exp id l) -- ^ @->@ /exp/
| GuardedAlts l [GuardedAlt guard exp id l] -- ^ /gdpat/
deriving (Eq,Ord,Show,Typeable,Data,Foldable,Traversable,Functor)
-- | A guarded case alternative @|@ /exp/ @->@ /exp/.
-- | NB. This follows the haskell'98 specification (no pattern guards)
data GuardedAlt guard exp id l
= GuardedAlt l (guard id l) (exp id l)
deriving (Eq,Ord,Show,Typeable,Data,Foldable,Traversable,Functor)
-- | A statement, representing both a /stmt/ in a @do@-expression,
-- an ordinary /qual/ in a list comprehension, as well as a /stmt/
-- in a pattern guard.
data Stmt binds exp pat stmtext id l
= Generator l (pat id l) (exp id l) -- ^ a generator: /pat/ @<-@ /exp/
| Qualifier l (exp id l) -- an action whose result is discarded;
-- in a list comprehension and pattern guard,
-- a guard expression
| LetStmt l (binds id l) -- ^ local bindings
| StmtExt (stmtext id l) -- ^ an extended statement
deriving (Eq,Ord,Show,Typeable,Data,Foldable,Traversable,Functor)
instance Annotated (Type ty id) where
ann t = case t of
TyTuple l _ _ -> l
TyList l _ -> l
TyParen l _ -> l
TyInfix l _ _ _ -> l
TyKind l _ _ -> l
instance Annotated (Pat lit pat id) where
ann p = case p of
PLit l _ -> l
PNeg l _ -> l
PInfixApp l _ _ _ -> l
PTuple l _ _ -> l
PList l _ -> l
PParen l _ -> l
PRec l _ _ -> l
PAsPat l _ _ -> l
PIrrPat l _ -> l
instance Annotated (PatField pat id) where
ann (PFieldPat l _ _) = l
ann (PFieldPun l _) = l
ann (PFieldWildcard l) = l
instance Annotated (Exp binds ty guard pat stmtext exp id) where
ann e = case e of
CaseAlt l _ _ -> l
InfixApp l _ _ _ -> l
NegApp l _ -> l
If l _ _ _ -> l
Do l _ -> l
Tuple l _ _ -> l
TupleSection l _ _ -> l
List l _ -> l
Paren l _ -> l
LeftSection l _ _ -> l
RightSection l _ _ -> l
RecConstr l _ _ -> l
RecUpdate l _ _ -> l
EnumFrom l _ -> l
EnumFromTo l _ _ -> l
EnumFromThen l _ _ -> l
EnumFromThenTo l _ _ _ -> l
ListComp l _ _ -> l
ExpTypeSig l _ _ -> l
instance Annotated (QOp id) where
ann (QVarOp l _) = l
ann (QConOp l _) = l
instance Annotated (FieldUpdate exp id) where
ann (FieldUpdate l _ _) = l
ann (FieldPun l _) = l
ann (FieldWildcard l) = l
instance Annotated (Alt binds guard pat exp id) where
ann (Alt l _ _ _) = l
instance Annotated (GuardedAlts guard exp id) where
ann (UnGuardedAlt l _) = l
ann (GuardedAlts l _) = l
instance Annotated (GuardedAlt guard exp id) where
ann (GuardedAlt l _ _) = l
instance Annotated (stmtext id) => Annotated (Stmt binds exp pat stmtext id) where
ann (Generator l _ _) = l
ann (Qualifier l _) = l
ann (LetStmt l _) = l
ann (StmtExt e) = ann e
| jcpetruzza/haskell-ast | src/Language/Haskell/AST/Sugar.hs | bsd-3-clause | 8,972 | 0 | 10 | 3,295 | 2,523 | 1,339 | 1,184 | 139 | 0 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE DeriveDataTypeable #-}
-- | This takes care of querying, identifing, and deleting the problem layers.
-- Right now, *problem layers* is defined as being those that are missing
-- Postgres tables, even though PostGIS believes the should exist and GeoServer
-- does as well.
--
-- Currently, this:
--
-- 1. Queries Postgres to identify the problem layers;
--
-- 2. Gets the data available from GeoServer for those layers and saves it to
-- a file;
--
-- 3. /TODO/: deletes the layer from GeoServer; and
--
-- 4. /TODO/: deletes the PostGIS row for that resource from geometry_columns.
module Main where
import Control.Applicative
import qualified Control.Exception as E
import qualified Control.Exception.Lifted as EL
import qualified Control.Monad as M
import Control.Monad.Error
import qualified Data.Aeson as A
import qualified Data.Aeson.Types as AT
import qualified Data.ByteString.Lazy as BSL
import qualified Data.Conduit as C
import qualified Data.Conduit.List as CL
import Data.Int (Int64)
import Data.Monoid
import Data.String (IsString(..))
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import Data.Typeable
import Database.Persist.GenericSql
import Database.Persist.GenericSql.Raw
import Database.Persist.Postgresql
import Database.Persist.Store (PersistValue(..))
import qualified Filesystem.Path.CurrentOS as FS
import Network.HTTP.Conduit
import Network.HTTP.Conduit.Browser
import Network.HTTP.Types (Method)
-- import Debug.Trace
-- | This represents a problem layer. It contains the database name and table
-- name.
data ProblemLayer = ProblemLayer
{ problemDbName :: T.Text
, problemTableName :: T.Text
}
-- | By default, ProblemLayers display as dot-separated.
instance Show ProblemLayer where
show (ProblemLayer {..}) =
T.unpack $ problemDbName <> "." <> problemTableName
type AuthFn = Request (C.ResourceT IO) -> Request (C.ResourceT IO)
-- | This is the base URL for the GeoServer instance.
geoServerBaseUrl :: String
geoServerBaseUrl = "http://libsvr35.lib.virginia.edu:8080/geoserver/rest"
-- geoServerBaseUrl = "http://geoserver.dev:8080/geoserver/rest"
-- | This is the GeoServer authentication information.
geoServerAuth :: AuthFn
geoServerAuth = applyBasicAuth "slabadmin" "GIS4slab!"
-- | This is the base connection string for Postgres.
cxnString :: ConnectionString
cxnString = "host=lon.lib.virginia.edu user=err8n"
-- | Handle HttpException with ErrorT
data HttpError = HttpError
| HttpMsgError String
| HttpExc String HttpException
deriving (Show, Typeable)
instance E.Exception HttpError
instance IsString HttpError where
fromString = HttpMsgError
instance Error HttpError where
noMsg = HttpError
strMsg = HttpMsgError
type HttpMonad = ErrorT HttpError IO
maybeErr :: (Monad m, Error b) => b -> Maybe a -> ErrorT b m a
maybeErr _ (Just a) = return a
maybeErr b Nothing = throwError b
-- | This performs a REST request and returns the raw ByteString.
restBS :: String -> Method -> AuthFn -> HttpMonad BSL.ByteString
restBS url method authFn = do
man <- liftIO $ newManager def
req <- liftIO (authFn <$> parseUrl url)
resp <- liftIO . getResource man $ req {method=method}
case resp of
Right resp' -> return resp'
Left err -> throwError $ HttpExc url err
-- | This gets a resource, trapping the error, and returning either the result
-- or the error string.
getResource :: Manager -> Request (C.ResourceT IO)
-> IO (Either HttpException BSL.ByteString)
getResource manager req = C.runResourceT $
EL.catch ((Right . responseBody) <$> browse manager (makeRequestLbs req))
(return . Left)
-- | This performs a REST request and parses the resulting JSON.
restJson :: AT.FromJSON a => String -> Method -> AuthFn -> HttpMonad a
restJson url method authFn =
restBS url method authFn >>=
maybeErr "Invalid JSON object." . A.decode
-- | This takes a directory name, a problem layer, and a GeoServer URL, and it
-- attempts to download the layer's data as XML from the source. Whatever it
-- can download, it saves in the output directory.
getProblemData :: String
-> AuthFn
-> FS.FilePath
-> ProblemLayer
-> HttpMonad FS.FilePath
getProblemData gsUrl authFn dirName (ProblemLayer {..}) =
restBS url "GET" authFn >>=
liftIO . BSL.writeFile (FS.encodeString xml) >>
return xml
where url = gsUrl ++ "/workspaces/" ++ T.unpack problemDbName
++ "/datastores/" ++ T.unpack problemDbName ++ ".json"
base = T.concat [ problemDbName
, "-"
, problemTableName
]
xml = dirName FS.</> FS.fromText base FS.<.> "xml"
-- | This takes a single-item tuple containing text and returns the text.
getTextValue :: [PersistValue] -> Maybe T.Text
getTextValue [PersistText t] = Just t
getTextValue _ = Nothing
-- | This takes a single-item tuple containing an integer and returns the
-- number.
getIntValue :: [PersistValue] -> Maybe Int64
getIntValue [PersistInt64 i] = Just i
getIntValue _ = Nothing
-- | This gets the list of databases on the server.
getDbs :: ConnectionString -> IO [T.Text]
getDbs cxn = withPostgresqlConn cxn $ runSqlConn $ do
let sql = "SELECT datname FROM pg_database WHERE datistemplate=false;"
C.runResourceT $ withStmt sql []
C.$= CL.mapMaybe getTextValue C.$$ CL.consume
-- | This gets the problem layers in the database.
getProblemLayers :: T.Text -> IO [ProblemLayer]
getProblemLayers dbName = withPostgresqlPool cxnString' 3 $ runSqlPool $ do
isGis <- isGisDb
if isGis
then getMissingGisTables >>= M.mapM (return . ProblemLayer dbName)
else return []
where
cxnString' = cxnString <> " dbname=" <> TE.encodeUtf8 dbName
isGisDb = do
let sql = "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema='public' AND table_name='geometry_columns';"
output <- C.runResourceT $ withStmt sql []
C.$= CL.mapMaybe getIntValue C.$= CL.map (== 1) C.$$ CL.take 1
return (output == [True])
getMissingGisTables = do
let sql = "SELECT f_table_name FROM geometry_columns WHERE f_table_name NOT IN (SELECT DISTINCT table_name FROM information_schema.tables WHERE table_schema='public') ORDER BY f_table_name"
C.runResourceT $ withStmt sql []
C.$= CL.mapMaybe getTextValue C.$$ CL.consume
main :: IO ()
main =
getDbs cxnString >>=
M.liftM concat . M.mapM getProblemLayers >>=
M.mapM ( runErrorT
. getProblemData geoServerBaseUrl geoServerAuth "layers") >>=
M.mapM_ (either (putStrLn . mappend "ERROR : " . show)
(putStrLn . ("OK : " ++) . FS.encodeString))
| erochest/problayers | ProbLayers.hs | bsd-3-clause | 7,313 | 0 | 15 | 1,817 | 1,476 | 795 | 681 | 123 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module Article.DataSource.Timeline
(
addTimeline
, removeTimeline
, removeTimelineList
, removeTimelineListById
, getIdListByTimeline
, countTimeline
, getTimelineListById
, saveTimelineMeta
, removeTimelineMeta
, getTimelineMeta
) where
import Article.Types
import Control.Monad (void)
import Data.Int (Int64)
import Data.Maybe (listToMaybe)
import Data.String (fromString)
import Data.UnixTime
import Database.MySQL.Simple (Only (..), execute, insertID, query)
import Yuntan.Types.HasMySQL (MySQL)
import Yuntan.Types.ListResult (From, Size)
import Yuntan.Types.OrderBy (OrderBy)
addTimeline :: String -> ID -> MySQL ID
addTimeline name aid prefix conn = do
t <- getUnixTime
void $ execute conn sql (name, aid, show $ toEpochTime t)
fromIntegral <$> insertID conn
where sql = fromString $ concat [ "REPLACE INTO `", prefix, "_timeline` (`name`, `art_id`, `created_at`) values ( ?, ?, ? )" ]
removeTimeline :: String -> ID -> MySQL Int64
removeTimeline name aid prefix conn = execute conn sql (name, aid)
where sql = fromString $ concat [ "DELETE FROM `", prefix, "_timeline` WHERE `name` = ? AND `art_id` = ?" ]
removeTimelineList :: String -> MySQL Int64
removeTimelineList name prefix conn = execute conn sql (Only name)
where sql = fromString $ concat [ "DELETE FROM `", prefix, "_timeline` WHERE `name` = ?" ]
removeTimelineListById :: ID -> MySQL Int64
removeTimelineListById aid prefix conn = execute conn sql (Only aid)
where sql = fromString $ concat [ "DELETE FROM `", prefix, "_timeline` WHERE `art_id` = ?" ]
getIdListByTimeline :: String -> From -> Size -> OrderBy -> MySQL [ID]
getIdListByTimeline name f s o prefix conn = map fromOnly <$> query conn sql (name, f, s)
where sql = fromString $ concat [ "SELECT `art_id` FROM `", prefix, "_timeline`"
, " WHERE `name`=? "
, show o
, " LIMIT ?,?"
]
countTimeline :: String -> MySQL Int64
countTimeline name prefix conn = maybe 0 fromOnly . listToMaybe <$> query conn sql (Only name)
where sql = fromString $ concat [ "SELECT count(*) FROM `", prefix, "_timeline` WHERE `name`=?" ]
getTimelineListById :: ID -> MySQL [String]
getTimelineListById aid prefix conn = map fromOnly <$> query conn sql (Only aid)
where sql = fromString $ concat [ "SELECT `name` FROM `", prefix, "_timeline` WHERE `art_id` = ?" ]
saveTimelineMeta :: String -> Title -> Summary -> MySQL Int64
saveTimelineMeta name title summary prefix conn = execute conn sql (name, title, summary)
where sql = fromString $ concat [ "REPLACE INTO `", prefix, "_timeline_meta` (`name`, `title`, `summary`) values (?, ?, ?)" ]
getTimelineMeta :: String -> MySQL (Maybe (Title, Summary))
getTimelineMeta name prefix conn = listToMaybe <$> query conn sql (Only name)
where sql = fromString $ concat [ "SELECT `title`, `summary` FROM `", prefix, "_timeline_meta` WHERE `name`=?" ]
removeTimelineMeta :: String -> MySQL Int64
removeTimelineMeta name prefix conn = execute conn sql (Only name)
where sql = fromString $ concat [ "DELETE FROM `", prefix, "_timeline_meta` WHERE `name`=?" ]
| Lupino/dispatch-article | src/Article/DataSource/Timeline.hs | bsd-3-clause | 3,394 | 0 | 11 | 820 | 893 | 482 | 411 | 59 | 1 |
{-# LANGUAGE UndecidableInstances #-}
-- | A bicomplex aka double complex, of free Z-modules. We use the
-- convention that the squares in the complex *anticommute*.
module Math.Algebra.Bicomplex where
import Math.Algebra.Combination
import Math.Algebra.ChainComplex hiding (FiniteType)
import qualified Math.Algebra.ChainComplex as CC (FiniteType)
import Prelude hiding (id, return, (.))
newtype Bidegree = Bidegree (Int, Int)
deriving Show via (Int, Int)
-- This should just be a monoid instance.
instance Num Bidegree where
fromInteger 0 = Bidegree (0, 0)
fromInteger _ = error "Bidegree: fromInteger"
(Bidegree (h,v)) + (Bidegree (h',v')) = Bidegree (h+h', v+v')
negate _ = error "Bidegree: negate"
(*) = error "Bidegree: (*)"
abs = error "Bidegree: abs"
signum = error "Bidegree: signum"
class Eq (Bibasis a) => Bicomplex a where
type Bibasis a = s | s -> a
isBibasis :: a -> Bibasis a -> Bool
isBibasis _ _ = True
bidegree :: a -> Bibasis a -> (Int, Int)
hdiff :: a -> Bimorphism a a -- degree (-1, 0)
vdiff :: a -> Bimorphism a a -- degree (0, -1)
class Bicomplex a => FiniteType a where
bidim :: a -> (Int, Int) -> Int
bidim a i = length (bibasis a i)
-- * `all isSimplex (basis n)`
bibasis :: a -> (Int, Int) -> [Bibasis a]
type Bimorphism a b = UMorphism Bidegree (Bibasis a) (Bibasis b)
validBicomb :: Bicomplex a => a -> Combination (Bibasis a) -> Bool
validBicomb a (Combination bs) = and $ fmap (\(_, b) -> isBibasis a b) bs
newtype Tot a = Tot a
newtype TotBasis a = TotBasis a
deriving Eq
deriving Show via a
instance (Bicomplex a) => ChainComplex (Tot a) where
type Basis (Tot a) = TotBasis (Bibasis a)
isBasis (Tot a) (TotBasis b) = isBibasis a b
degree (Tot a) (TotBasis b) =
let (p, q) = bidegree a b in p + q
diff (Tot a) = Morphism (-1) $ \(TotBasis b) ->
fmap TotBasis $ hdiff a `onBasis` b + vdiff a `onBasis` b
instance (Bicomplex a, FiniteType a) => CC.FiniteType (Tot a) where
basis (Tot a) d = do
vd <- [0 .. d]
let hd = d - vd
TotBasis <$> bibasis a (hd, vd)
| mvr/at | src/Math/Algebra/Bicomplex.hs | bsd-3-clause | 2,076 | 11 | 13 | 452 | 778 | 422 | 356 | -1 | -1 |
{-# LANGUAGE ScopedTypeVariables #-}
module Com.DiagClientEvent where
import Com.DiagMessage
import Com.HSFZMessage
import Diag.DiagnosisCodes
import Network(PortID(PortNumber),connectTo)
import System.IO
import System.CPUTime
import System.TimeIt
import Control.Concurrent(putMVar,MVar,forkIO,newEmptyMVar,takeMVar)
import Foreign(Ptr,Word8,free,mallocBytes)
import Foreign.C.String(peekCStringLen)
import Foreign.C.Types(CChar)
import Control.Monad.Reader
import Control.Exception
import Text.Printf(printf)
import System.Posix(sleep)
import Util.Encoding(string2hex)
import Control.Applicative((<$>))
import Debug.Trace
import Data.List(replicate)
import Prelude hiding (catch,log)
timeInSec :: IO Double
timeInSec = do
t1 <- getCPUTime
return $ fromIntegral t1 * 1e-6
test = timeItT (print "hi")
pollingMs = 100
receiveBufSize = 4096
data DiagConnection = DiagConnection { diagHandle :: Handle, chatty :: Bool }
data DiagConfig = MkDiagConfig {
host :: String,
port :: Int,
source :: Word8,
target :: Word8,
verbose :: Bool
} deriving (Show)
type Callback = Maybe DiagnosisMessage -> IO ()
type Net = ReaderT DiagConnection IO
sendWithCallback :: Int -> DiagConfig -> [Word8] -> Callback -> IO()
sendWithCallback listenTime c xs = sendMessageWithCallback listenTime c hsfzMsg
where diagMsg = DiagnosisMessage (source c) (target c) xs
hsfzMsg = diag2hsfz diagMsg DataBit
sendMessageWithCallback :: Int -> DiagConfig -> HSFZMessage -> Callback -> IO ()
sendMessageWithCallback listenTime c msg cb = bracket (diagConnect c) (disconnectWithTimeout 10) loop
where
disconnectWithTimeout t con = do
sleep t
print "disconnecting....with timeout" >>(hClose . diagHandle) con
loop st = catch (runReaderT (run listenTime c cb msg) st) (\(err :: IOException) -> print err)
main :: IO ()
main = do
-- sendWithCallback 10 c [0x22,0x20,0x00] cb
sendWithCallback 5 c [ 0xbf,0x10,0x1,0x1 ] cb
sendWithCallback 5 c [0xBF,0xFF,0x77,0x03,0x00,0xC8] cb
sendWithCallback 10 c [0x31,0x01,0xF7,0x65,0x10,0xFF,0xFF,0x07,0x99,0x00,0x00,0x10,0x00] cb
sendWithCallback 5 c [0xBF,0xFF,0x77,0xFF] cb
sendWithCallback 5 c [0x31,0x02,0xF7,0x65] cb
where c = MkDiagConfig "10.40.39.19" 6801 0xf4 0x40 True
cb m = print $ "received s.th.:" ++ show m
diagConnect :: DiagConfig -> IO DiagConnection
diagConnect c = notify $ do
h <- connectTo (host c) (PortNumber $ fromIntegral (port c))
hSetBuffering h NoBuffering
return (DiagConnection h (verbose c))
where
notify
| verbose c = bracket_ (printf "Connecting to %s ... " (host c) >> hFlush stdout) (putStrLn "done.")
| otherwise = bracket_ (return ()) (return ())
run :: Int -> DiagConfig -> Callback -> HSFZMessage -> Net ()
run listenTime c cb msg = do
ReaderT $ \r -> forkIO $ runReaderT (asks diagHandle >>= listen listenTime c cb) r
pushOutMessage msg
pushOutMessage :: HSFZMessage -> Net ()
pushOutMessage msg = do
h <- asks diagHandle
log ("--> " ++ show msg)
io $ hPutStr h (msg2ByteString msg)
io $ hFlush h -- Make sure that we send data immediately
listen :: Int -> DiagConfig -> Callback -> Handle -> Net ()
listen listenTime c cb h = do -- forever $ do
startTime <- io getCPUTime
let repeatTimes = round $ (fromIntegral listenTime*1000)/fromIntegral diagTimeout
io $ print ("repeating n times: " ++ show repeatTimes)
replicateM_ repeatTimes (receiveResponse cb)
receiveResponse :: Callback -> Net ()
receiveResponse cb = do
io $ print "calling receiveResponse .............................."
buf <- io $ mallocBytes receiveBufSize
dataResp <- receiveDataMsg buf
io $ free buf
if responsePending dataResp
then log "...received response pending" >> receiveResponse cb
else io $ cb $ hsfz2diag <$> dataResp
receiveDataMsg :: Ptr CChar -> Net (Maybe HSFZMessage)
receiveDataMsg buf = do
msg <- receiveMsg buf
log $ "was " ++ show msg
maybe (return ()) (\m -> log $ "<-- " ++ show m) msg
maybe (return Nothing)
(\m->if isData m then log "was data!" >> return msg else log "was no data packet" >> receiveDataMsg buf) msg
receiveMsg :: Ptr CChar -> Net (Maybe HSFZMessage)
receiveMsg buf = do
h <- asks diagHandle
dataAvailable <- io $ waitForData diagTimeout h
if not dataAvailable then io (print "no message available...") >> return Nothing
else do
answereBytesRead <- io $ hGetBufNonBlocking h buf receiveBufSize
res2 <- io $ peekCStringLen (buf,answereBytesRead)
log $ "received over the wire: " ++ showBinString res2
return $ bytes2msg res2
waitForData :: Int -> Handle -> IO Bool
waitForData waitTime_ms h = do
putStr "."
inputAvailable <- hWaitForInput h pollingMs
if inputAvailable then return True
else if waitTime_ms > 0
then waitForData (waitTime_ms - pollingMs) h
else return False
io :: IO a -> Net a
io = liftIO
log :: (Show a) => a -> Net ()
log s = do
v <- asks chatty
when v $ io $ print s
responsePending :: Maybe HSFZMessage -> Bool
responsePending =
maybe False (\m->
let p = diagPayload (hsfz2diag m) in
length p == 3 && head p == 0x7f && p!!2 == 0x78)
| marcmo/hsDiagnosis | other/DiagClientEvent.hs | bsd-3-clause | 5,234 | 0 | 16 | 1,067 | 1,862 | 939 | 923 | 127 | 3 |
{-# LANGUAGE TypeFamilies, QuasiQuotes, MultiParamTypeClasses,
TemplateHaskell, OverloadedStrings, StandaloneDeriving #-}
import System.Environment (getEnv)
import System.Exit (exitFailure)
import System.IO.Error (isDoesNotExistError)
import Yesod
import Yesod.Auth
import Yesod.Auth.Facebook.ClientSide
import Yesod.Form.I18n.English
import qualified Control.Exception.Lifted as E
import qualified Data.ByteString.Char8 as B
import qualified Data.Text as T
import qualified Facebook as FB
import qualified Network.HTTP.Conduit as H
data Test = Test { httpManager :: H.Manager
, fbCreds :: FB.Credentials }
mkYesod "Test" [parseRoutes|
/ HomeR GET
/auth AuthR Auth getAuth
/fbchannelfile FbChannelFileR GET
|]
instance Yesod Test where
approot = FIXME -- FIXME: Put your approot here
instance RenderMessage Test FormMessage where
renderMessage _ _ = englishFormMessage
instance YesodAuth Test where
type AuthId Test = T.Text
loginDest _ = HomeR
logoutDest _ = HomeR
getAuthId creds@(Creds _ id_ _) = do
setSession "creds" (T.pack $ show creds)
return (Just id_)
authPlugins _ = [authFacebookClientSide]
redirectToReferer _ = True
authHttpManager = httpManager
deriving instance Show (Creds m)
instance YesodAuthFbClientSide Test where
fbCredentials = fbCreds
getFbChannelFile = return FbChannelFileR
getHomeR :: Handler RepHtml
getHomeR = do
muid <- maybeAuthId
mcreds <- lookupSession "creds"
mtoken <- getUserAccessToken
let perms = []
pc <- widgetToPageContent $ [whamlet|
^{facebookJSSDK AuthR}
<p>
Current uid: #{show muid}
<br>
Current credentials: #{show mcreds}
<br>
Current access token: #{show mtoken}
<p>
<button onclick="#{facebookLogin perms}">
Login
<p>
<a href="@{AuthR $ facebookForceLoginR perms}">
Force login route (avoid this in your code when possible).
<p>
<button onclick="#{facebookLogout}">
Logout
|]
hamletToRepHtml [hamlet|
$doctype 5
<html>
<head>
<title>Yesod.Auth.Facebook.ClientSide test
^{pageHead pc}
<body>
^{pageBody pc}
|]
getFbChannelFileR :: GHandler sub master ChooseRep
getFbChannelFileR = serveChannelFile
main :: IO ()
main = do
manager <- H.newManager H.def
creds <- getCredentials
warpDebug 3000 (Test manager creds)
-- Copy & pasted from the "fb" package:
-- | Grab the Facebook credentials from the environment.
getCredentials :: IO FB.Credentials
getCredentials = tryToGet `E.catch` showHelp
where
tryToGet = do
[appName, appId, appSecret] <- mapM getEnv ["APP_NAME", "APP_ID", "APP_SECRET"]
return $ FB.Credentials (B.pack appName) (B.pack appId) (B.pack appSecret)
showHelp exc | not (isDoesNotExistError exc) = E.throw exc
showHelp _ = do
putStrLn $ unlines
[ "In order to run the tests from the 'fb' package, you need"
, "developer access to a Facebook app. The tests are designed"
, "so that your app isn't going to be hurt, but we may not"
, "create a Facebook app for this purpose and then distribute"
, "its secret keys in the open."
, ""
, "Please give your app's name, id and secret on the enviroment"
, "variables APP_NAME, APP_ID and APP_SECRET, respectively. "
, "For example, before running the test you could run in the shell:"
, ""
, " $ export APP_NAME=\"example\""
, " $ export APP_ID=\"458798571203498\""
, " $ export APP_SECRET=\"28a9d0fa4272a14a9287f423f90a48f2304\""
, ""
, "Of course, these values above aren't valid and you need to"
, "replace them with your own."
, ""
, "(Exiting now with a failure code.)"]
exitFailure
| prowdsponsor/yesod-auth-fb | demo/clientside.hs | bsd-3-clause | 3,984 | 0 | 13 | 1,066 | 661 | 363 | 298 | 77 | 2 |
module Ditto.Funify where
import Ditto.Syntax
import Ditto.Whnf
import Ditto.Monad
import Ditto.Conv
import Ditto.Sub
import Ditto.Throw
----------------------------------------------------------------------
funifies :: [Name] -> Args -> Args -> TCM (Maybe Sub)
funifies xs [] [] = return . Just $ []
funifies xs (a1:as1) (a2:as2) = funify xs a1 a2 >>= \case
Nothing -> return Nothing
Just s -> do
as1' <- subs as1 s
as2' <- subs as2 s
funifies xs as1' as2' >>= \case
Nothing -> return Nothing
-- TODO this may need to be substitution composition
Just s' -> return . Just $ s ++ s'
funifies _ _ _ = throwGenErr "Unifiying equations of differing lengths"
funify :: [Name] -> Arg -> Arg -> TCM (Maybe Sub)
funify xs (i1, a1) (i2, a2) | i1 == i2 = do
a1' <- whnf a1
a2' <- whnf a2
funify' xs a1' a2'
funify xs (i1, a1) (i2, a2) = return Nothing
funify' :: [Name] -> Exp -> Exp -> TCM (Maybe Sub)
funify' xs (EVar x) a | x `elem` fv a = return Nothing
funify' xs a (EVar x) | x `elem` fv a = return Nothing
funify' xs (EVar x) a | x `elem` xs = return . Just $ [(x, a)]
funify' xs a (EVar x) | x `elem` xs = return . Just $ [(x, a)]
funify' xs (ECon _ x1 as1) (ECon _ x2 as2) | x1 /= x2 = return Nothing
funify' xs (ECon _ x1 as1) (ECon _ x2 as2) = funifies xs as1 as2
funify' xs a1 a2 = convStatic (Just []) a1 a2
---------------------------------------------------------------------- | ditto-lang/ditto | src/Ditto/Funify.hs | gpl-3.0 | 1,426 | 0 | 17 | 306 | 662 | 331 | 331 | -1 | -1 |
{-# LANGUAGE DeriveDataTypeable, RankNTypes, ScopedTypeVariables, BangPatterns, MagicHash #-}
module Utils.Misc (
-- * Environment
envIsSet
, getEnvMaybe
-- * List operations
, subsetOf
, noDuplicates
, equivClasses
, partitions
, nonTrivialPartitions
, twoPartitions
-- * Control
, whileTrue
-- * Hashing
, stringSHA256
-- * Set operations
, setAny
-- * Map operations
, invertMap
-- * unsafeEq
, unsafeEq
) where
import Data.List
import System.Environment
import System.IO.Unsafe
import Data.Maybe
import Data.Set (Set)
import qualified Data.Set as S
import Data.Map ( Map )
import qualified Data.Map as M
import qualified Data.Map.Strict as M'
import Data.Digest.Pure.SHA (bytestringDigest, sha256)
import Blaze.ByteString.Builder (toLazyByteString)
import qualified Data.ByteString.Char8 as C8
import qualified Data.ByteString.Lazy as L
import qualified Data.ByteString.Base64 as B64 (encode)
import qualified Blaze.ByteString.Builder.Char.Utf8 as Utf8 (fromString)
import GHC.Exts (reallyUnsafePtrEquality#, Int (I#))
-- | @noDuplicates xs@ returns @True@ if the list @xs@ contains no duplicates
noDuplicates :: (Ord a) => [a] -> Bool
noDuplicates xs = all ((==1).length) . group . sort $ xs
-- | @getEnvMaybe k@ returns @Just v@ if @k=v@ is in the environment and @Nothing@ otherwise
getEnvMaybe :: String -> Maybe String
getEnvMaybe k = unsafePerformIO $ do
l <- getEnvironment
return $ lookup k l
-- | @envIsSet k@ returns @True@ if there is a v such @k=v@ is in the environment and @False@ otherwise.
envIsSet :: String -> Bool
envIsSet k = isJust $ getEnvMaybe k
-- | @subsetOf xs ys@ return @True@ if @set xs@ is a subset of @set ys@
subsetOf :: Ord a => [a] -> [a] -> Bool
subsetOf xs ys = (S.fromList xs) `S.isSubsetOf` (S.fromList ys)
-- | Inverts a bijective Map.
invertMap :: Ord v => Map k v -> Map v k
invertMap = M.fromList . map (uncurry (flip (,))) . M.toList
-- | @whileTrue m@ iterates m until it returns @False@.
-- Returns the number of iterations @m@ was run. @0@
-- means @m@ never returned @True@.
whileTrue :: Monad m => m Bool -> m Int
whileTrue m = go 0
where go (!n) = m >>= \b -> if b then go (n+1) else return n
-- | Compute the equality classes given wrto a partial function.
equivClasses :: (Ord a, Ord b) => [(a, b)] -> M.Map b (S.Set a)
equivClasses =
foldl' insertEdge M.empty
where
insertEdge m (from,to) = M'.insertWith S.union to (S.singleton from) m
-- | The SHA-256 hash of a string in base64 notation.
stringSHA256 :: String -> String
stringSHA256 =
C8.unpack . urlEncodeBase64 . C8.concat . L.toChunks
. bytestringDigest . sha256 . toLazyByteString . Utf8.fromString
where
urlEncodeBase64 = C8.init . C8.map replace . B64.encode
replace '/' = '_'
replace '+' = '-'
replace c = c
setAny :: (a -> Bool) -> Set a -> Bool
setAny f = S.foldr (\x b -> f x || b) False
unsafeEq :: a -> a -> Bool
unsafeEq a b =
(I# (reallyUnsafePtrEquality# a b)) == 1
-- | Generate all possible partitions of a list
partitions :: [a] -> [[[a]]]
partitions [] = [[]]
partitions (x:xs) = [ys | yss <- partitions xs, ys <- bloat x yss]
bloat :: a -> [[a]] -> [[[a]]]
bloat x [] = [[[x]]]
bloat x (xs:xss) = ((x:xs):xss) : map (xs:) (bloat x xss)
-- | Generate all possible partitions of a list, excluding the trivial partition
nonTrivialPartitions :: Eq a => [a] -> [[[a]]]
nonTrivialPartitions l = delete [l] $ partitions l
-- | Generate all possible ways of partitioning a list into two partitions
twoPartitions :: [a] -> [([a], [a])]
twoPartitions [] = []
twoPartitions (x:[]) = [ ([x],[]) ]
twoPartitions (x:xs) = (map addToFirst ps) ++ (map addToSecond ps)
where
addToFirst (a, b) = (x:a, b)
addToSecond (a, b) = (a, x:b)
ps = twoPartitions xs
| rsasse/tamarin-prover | lib/utils/src/Utils/Misc.hs | gpl-3.0 | 3,896 | 0 | 12 | 848 | 1,227 | 689 | 538 | 78 | 3 |
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{- |
Module : Neovim.Plugin.ConfigHelper
Description : Helper plugin to ease recompiling the nvim-hs config
Copyright : (c) Sebastian Witte
License : Apache-2.0
Maintainer : woozletoff@gmail.com
Stability : experimental
Portability : GHC
-}
module Neovim.Plugin.ConfigHelper
where
import Neovim.API.TH
import Neovim.Config
import Neovim.Context
import Neovim.Plugin.Classes
import Neovim.Plugin.ConfigHelper.Internal
import Neovim.Plugin.Internal
import Neovim.Plugin.Startup
import Config.Dyre.Paths (getPaths)
import Data.Default
plugin :: Neovim (StartupConfig NeovimConfig) () NeovimPlugin
plugin = asks dyreParams >>= \case
Nothing ->
wrapPlugin Plugin { exports = [], statefulExports = [] }
Just params -> do
ghcEnv <- asks ghcEnvironmentVariables
(_, _, cfgFile, _, libsDir) <- liftIO $ getPaths params
wrapPlugin Plugin
{ exports =
[ $(function' 'pingNvimhs) Sync
]
, statefulExports =
[ ((params, ghcEnv), [],
[ $(autocmd 'recompileNvimhs) "BufWritePost" def
{ acmdPattern = cfgFile
}
, $(autocmd 'recompileNvimhs) "BufWritePost" def
{ acmdPattern = libsDir++"/*"
}
, $(command' 'restartNvimhs) [CmdSync Async, CmdBang, CmdRegister]
])
]
}
| lslah/nvim-hs | library/Neovim/Plugin/ConfigHelper.hs | apache-2.0 | 1,726 | 0 | 20 | 638 | 309 | 175 | 134 | 30 | 2 |
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE FlexibleContexts #-}
module Pontarius.E2E.Helpers where
import Control.Applicative (Applicative, (<$>), (<*>), pure)
import Control.Monad.Reader
import Control.Monad.State
import Control.Monad.Except
import Control.Monad.Identity
import Crypto.Number.ModArithmetic as Mod
import qualified Crypto.Random as CRandom
import Data.Bits (shiftR)
import qualified Data.ByteString as BS
import Data.Byteable (constEqBytes)
import Pontarius.E2E.Monad
import Pontarius.E2E.Serialize
import Pontarius.E2E.Types
(=~=) :: BS.ByteString -> BS.ByteString -> Bool
(=~=) = constEqBytes
prime :: MonadReader E2EGlobals m => m Integer
prime = parameter paramDHPrime
gen :: MonadReader E2EGlobals m => m Integer
gen = parameter paramDHGenerator
-- | Encrypt a ByteString. The IV is padded with 0s to the required length
encCtr :: MonadReader E2EGlobals m =>
BS.ByteString -> BS.ByteString -> BS.ByteString -> m BS.ByteString
encCtr key ivHi pl = do
ebs <- parameter paramEncryptionBlockSize
eks <- parameter paramEncryptionKeySize
let iv = ivHi `BS.append` BS.replicate ((ebs `div` 8) - BS.length ivHi) 0
let k = (BS.take (eks `div` 8) key)
ectr <- parameter paramEncrypt
return $ ectr iv k pl
decCtr :: MonadReader E2EGlobals m =>
BS.ByteString -> BS.ByteString -> BS.ByteString -> m BS.ByteString
decCtr = encCtr
encCtrZero :: MonadReader E2EGlobals m =>
BS.ByteString -> BS.ByteString -> m BS.ByteString
encCtrZero key pl = encCtr key BS.empty pl
decCtrZero :: MonadReader E2EGlobals m =>
BS.ByteString -> BS.ByteString -> m BS.ByteString
decCtrZero = encCtrZero
hash :: MonadReader E2EGlobals m => BS.ByteString -> m BS.ByteString
hash pl = do
h <- parameter paramHash
return $ h pl
mac :: MonadReader E2EGlobals m =>
BS.ByteString -> BS.ByteString -> m BS.ByteString
mac key pl = do
m <- parameter paramMac
return $ m key pl
mkKey :: (MonadReader E2EGlobals m, CRandom.CPRG g, MonadRandom g m) =>
m BS.ByteString
mkKey = do
bs <- getBytes =<< parameter paramEncryptionKeySize
return $! bs
putAuthState :: MonadState E2EState m => AuthState -> m ()
putAuthState as = do modify $ \s -> s{authState = as }
putMsgState :: MsgState -> E2E g ()
putMsgState newSt = do
oldSt <- gets msgState
stateChange oldSt newSt
modify $ \s -> s{msgState = newSt }
makeDHSharedSecret :: Integer -> Integer -> E2E g Integer
makeDHSharedSecret private public = do
p <- prime
return $ Mod.exponantiation_rtl_binary public private p
parameter :: MonadReader E2EGlobals m => (E2EParameters -> a) -> m a
parameter = asks . (. parameters)
doHash :: MonadReader E2EGlobals m => BS.ByteString -> m BS.ByteString
doHash pl = do
h <- parameter paramHash
return $ h pl
makeDHKeyPair :: (Applicative m, MonadReader E2EGlobals m, CRandom.CPRG g,
MonadRandom g m) =>
m DHKeyPair
makeDHKeyPair = do
ks <- parameter paramDHKeySizeBits
x <- randomIntegerBits (fromIntegral ks)
gx <- gen ^. (pure x)
return $ DHKeyPair gx x
where
b ^. e = do Mod.exponantiation_rtl_binary <$> b <*> e <*> prime
-- randomIntegerBytes :: Int ->Otr Integer
randomIntegerBits :: (CRandom.CPRG g, MonadRandom g m)
=> Int -> m Integer
randomIntegerBits b = ((`shiftR` ((8 - b) `mod` 8)) . rollInteger . BS.unpack)
`liftM` getBytes ((b+7) `div` 8)
protocolGuard :: MonadError E2EError m => ProtocolError -> String -> Bool -> m ()
protocolGuard e s p = unless p . throwError $ ProtocolError e s
protocolGuard' :: MonadError E2EError m => ProtocolError -> Bool -> m ()
protocolGuard' e p = protocolGuard e "" p
newState :: CRandom.CPRG g => ReaderT E2EGlobals (RandT g Identity) E2EState
newState = do
opk <- makeDHKeyPair
ock <- makeDHKeyPair
ndh <- makeDHKeyPair
return E2EState{ ourPreviousKey = opk
, ourCurrentKey = ock
, theirPubKey = Nothing
, ourKeyID = 1
, theirCurrentKey = Nothing
, mostRecentKey = 2
, nextDH = ndh
, theirPreviousKey = Nothing
, theirKeyID = 0
, authState = AuthStateNone
, msgState = MsgStatePlaintext
, counter = 1
, ssid = Nothing
, smpState = SmpDone
}
-- withNewState :: CRandom.CPRG g => E2EGlobals
-- -> g
-- -> E2E g a
-- -> Messaging ((Either E2EError a, E2EState), g)
-- withNewState gs g side = do
-- let (st, g') = runIdentity $ runRandT g $ runReaderT newState gs
-- runE2E gs st g' side
| Philonous/pontarius-xmpp-e2e | source/Pontarius/E2E/Helpers.hs | apache-2.0 | 5,032 | 0 | 15 | 1,485 | 1,414 | 737 | 677 | 107 | 1 |
{-| Crypto-related helper functions.
-}
{-
Copyright (C) 2011, 2012 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Ganeti.Hash
( computeMac
, verifyMac
, HashKey
) where
import qualified Data.ByteString as B
import qualified Data.ByteString.UTF8 as BU
import Crypto.Hash.Algorithms
import Crypto.MAC.HMAC
import Data.Char
import Data.Word
-- | Type alias for the hash key. This depends on the library being
-- used.
type HashKey = [Word8]
-- | Computes the HMAC for a given key/test and salt.
computeMac :: HashKey -> Maybe String -> String -> String
computeMac key salt text =
let hashable = maybe text (++ text) salt
in show . hmacGetDigest $
(hmac (B.pack key) (BU.fromString hashable) :: HMAC SHA1)
-- | Verifies the HMAC for a given message.
verifyMac :: HashKey -> Maybe String -> String -> String -> Bool
verifyMac key salt text digest =
map toLower digest == computeMac key salt text
| mbakke/ganeti | src/Ganeti/Hash.hs | bsd-2-clause | 2,152 | 0 | 12 | 362 | 217 | 122 | 95 | 19 | 1 |
--------------------------------------------------------------------
-- |
-- Copyright : (c) Edward Kmett and Dan Doel 2013-2014
-- License : BSD2
-- Maintainer: Dan Doel <dan.doel@gmail.com>
-- Stability : experimental
-- Portability: non-portable
--------------------------------------------------------------------
module Ermine.Syntax.Hint
( Hint
) where
import Data.Text (Text)
type Hint = Maybe Text
| PipocaQuemada/ermine | src/Ermine/Syntax/Hint.hs | bsd-2-clause | 418 | 0 | 5 | 56 | 39 | 27 | 12 | 4 | 0 |
{--------------------------------------------------------------------------------
Copyright (c) Daan Leijen 2003
wxWindows License.
A file browser in wxHaskell.
Demonstrates:
- tree control and list control
- image lists
- basic directory handling in Haskell
--------------------------------------------------------------------------------}
module Main where
import System.Directory
import Data.List( zip3 )
import System.FilePath
import Graphics.UI.WX
import Graphics.UI.WXCore
import Control.Exception
main :: IO ()
main
= start gui
{--------------------------------------------------------------------------------
Images
--------------------------------------------------------------------------------}
imgComputer = "computer"
imgDisk = "disk"
imgFile = "file"
imgHFile = "hsicon"
imgFolder = "f_closed"
imgFolderOpen = "f_open"
-- plain names of images
imageNames
= [imgComputer,imgDisk,imgFile,imgHFile,imgFolder,imgFolderOpen]
-- file names of the images
imageFiles
= map (\name -> "../bitmaps/" ++ name ++ ".ico") imageNames
-- get the index of an image
imageIndex :: String -> Int
imageIndex name
= case lookup name (zip imageNames [0..]) of
Just idx -> idx
Nothing -> imageNone
-- (-1) means no image present
imageNone :: Int
imageNone = (-1)
{--------------------------------------------------------------------------------
The client data of the directory tree is the full path of the
tree node. Here we wrap the "unsafe" basic calls into safe wrappers.
--------------------------------------------------------------------------------}
treeCtrlSetItemPath :: TreeCtrl a -> TreeItem -> FilePath -> IO ()
treeCtrlSetItemPath t item path
= treeCtrlSetItemClientData t item (return ()) path
treeCtrlGetItemPath :: TreeCtrl a -> TreeItem -> IO FilePath
treeCtrlGetItemPath t item
= do mbpath <- unsafeTreeCtrlGetItemClientData t item
case mbpath of
Just path -> return path
Nothing -> return ""
{--------------------------------------------------------------------------------
GUI
--------------------------------------------------------------------------------}
gui :: IO ()
gui
= do -- main gui elements: frame, panel
f <- frame [text := "File browser" ] -- , image := "../bitmaps/wxwin.ico"]
-- panel: just for the nice grey color
p <- panel f []
-- image list
imagePaths <- mapM getAbsoluteFilePath imageFiles -- make relative to application
images <- imageListFromFiles (sz 16 16) imagePaths
-- splitter window between directory tree and file view.
s <- splitterWindow p []
-- initialize tree control
t <- treeCtrl s []
treeCtrlAssignImageList t images {- 'assign' deletes the imagelist on delete -}
-- set top node
top <- treeCtrlAddRoot t "System" (imageIndex imgComputer) imageNone objectNull
treeCtrlSetItemPath t top ""
-- add root directory
(rootPath,rootName) <- getRootDir
root <- treeCtrlAppendItem t top rootName (imageIndex imgDisk) imageNone objectNull
treeCtrlSetItemPath t root rootPath
treeCtrlAddSubDirs t root
-- expand top node
treeCtrlExpand t top
-- list control
l <- listCtrl s [clipChildren := True, columns := [("Name",AlignLeft,140),("Permissions",AlignLeft,80),("Date",AlignLeft,100)]]
listCtrlSetImageList l images wxIMAGE_LIST_SMALL
-- status bar
status <- statusField [text := "wxHaskell file browser example"]
-- install event handlers
set t [on treeEvent := onTreeEvent t l status]
set l [on listEvent := onListEvent l status]
-- specify layout
set f [layout := container p $ margin 5 $
fill $ vsplit s 5 {- sash width -} 160 {- left pane width -} (widget t) (widget l)
,statusBar := [status]
,clientSize := sz 500 300
]
return ()
{--------------------------------------------------------------------------------
On tree event
--------------------------------------------------------------------------------}
onTreeEvent :: TreeCtrl a -> ListCtrl b -> StatusField -> EventTree -> IO ()
onTreeEvent t l status event
= case event of
TreeItemExpanding item veto | treeItemIsOk item
-> do wxcBeginBusyCursor
treeCtrlChildrenAddSubDirs t item
wxcEndBusyCursor
propagateEvent
TreeSelChanged item olditem | treeItemIsOk item
-> do wxcBeginBusyCursor
path <- treeCtrlGetItemPath t item
set status [text := path]
listCtrlShowDir l path
wxcEndBusyCursor
propagateEvent
other
-> propagateEvent
onListEvent :: ListCtrl a -> StatusField -> EventList -> IO ()
onListEvent l status event
= case event of
ListItemSelected item
-> do count <- listCtrlGetSelectedItemCount l
set status [text := (show count ++ " item" ++ (if count /= 1 then "s" else "") ++ " selected") ]
propagateEvent
other
-> propagateEvent
ioExceptionHandler :: a -> IOException -> IO a
ioExceptionHandler res _ = return res
swallowIOExceptions :: a -> IO a -> IO a
swallowIOExceptions def act =
act `catch` ioExceptionHandler def
{--------------------------------------------------------------------------------
View directory files
--------------------------------------------------------------------------------}
listCtrlShowDir :: ListCtrl a -> FilePath -> IO ()
listCtrlShowDir listCtrl path
= swallowIOExceptions () $
do itemsDelete listCtrl
contents <- getDirectoryContents path
let paths = map (\cont -> path ++ cont) contents
mapM_ (listCtrlAddFile listCtrl) (zip3 [0..] contents paths)
listCtrlAddFile l (idx,fname,fpath)
= do isdir <- swallowIOExceptions False $ doesDirectoryExist fpath
perm <- getPermissions fpath
time <- getModificationTime fpath
let image = imageIndex (if isdir
then imgFolder
else if (extension fname == "hs")
then imgHFile
else imgFile)
listCtrlInsertItemWithLabel l idx fpath image -- use this instead of 'items' so we can set the image.
set l [item idx := [fname,showPerm perm,show time]]
extension fname
| elem '.' fname = reverse (takeWhile (/='.') (reverse fname))
| otherwise = ""
showPerm perm
= [if readable perm then 'r' else '-'
,if writable perm then 'w' else '-'
,if executable perm then 'x' else '-'
,if searchable perm then 's' else '-'
]
{--------------------------------------------------------------------------------
Directory tree helpers
--------------------------------------------------------------------------------}
treeCtrlChildrenAddSubDirs :: TreeCtrl a -> TreeItem -> IO ()
treeCtrlChildrenAddSubDirs t parent
= do children <- treeCtrlGetChildren t parent
mapM_ (treeCtrlAddSubDirs t) children
treeCtrlAddSubDirs :: TreeCtrl a -> TreeItem -> IO ()
treeCtrlAddSubDirs t parent
= do fpath <- treeCtrlGetItemPath t parent
dirs <- getSubdirs fpath
treeCtrlDeleteChildren t parent
mapM_ addChild dirs
treeCtrlSetItemHasChildren t parent (not (null dirs))
where
addChild (path,name)
= do item <- treeCtrlAppendItem t parent name (imageIndex imgFolder) (imageIndex imgFolderOpen) objectNull
treeCtrlSetItemPath t item path
{--------------------------------------------------------------------------------
General directory operations
--------------------------------------------------------------------------------}
-- Return the sub directories of a certain directory as a tuple: the full path and the directory name.
getSubdirs :: FilePath -> IO [(FilePath,FilePath)]
getSubdirs fpath
= do contents <- swallowIOExceptions [] $ getDirectoryContents fpath
let names = filter (\dir -> head dir /= '.') $ contents
paths = map (\dir -> fpath ++ dir ++ "/") names
isdirs <- mapM (\dir -> swallowIOExceptions False $ doesDirectoryExist dir) paths
let dirs = [(path,name) | (isdir,(path,name)) <- zip isdirs (zip paths names), isdir]
return dirs
-- Return the root directory as a tuple: the full path and name.
getRootDir :: IO (FilePath,FilePath)
getRootDir
= do current <- getCurrentDirectory
let rootName = takeWhile (not . isPathSeparator) current
rootPath = rootName ++ "/"
exist <- swallowIOExceptions False $ doesDirectoryExist rootPath
if exist
then return (rootPath,rootName)
else return (current ++ "/", reverse (takeWhile (not . isPathSeparator) (reverse current)))
| ekmett/wxHaskell | samples/wx/FileBrowse.hs | lgpl-2.1 | 8,953 | 0 | 18 | 2,132 | 2,033 | 1,007 | 1,026 | 151 | 5 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE CPP
, NoImplicitPrelude
, BangPatterns
, MagicHash
#-}
-- ----------------------------------------------------------------------------
--
-- (c) The University of Glasgow 2006
--
-- Fingerprints for recompilation checking and ABI versioning, and
-- implementing fast comparison of Typeable.
--
-- ----------------------------------------------------------------------------
module GHC.Fingerprint (
Fingerprint(..), fingerprint0,
fingerprintData,
fingerprintString,
fingerprintFingerprints,
getFileHash
) where
import GHC.IO
import GHC.Base
import GHC.Num
import GHC.List
import GHC.Real
import GHC.Show
import Foreign
import Foreign.C
import System.IO
import GHC.Fingerprint.Type
-- XXX instance Storable Fingerprint
-- defined in Foreign.Storable to avoid orphan instance
-- TODO: Replace with Java FFI
fingerprint0 :: Fingerprint
fingerprint0 = Fingerprint 0 0
fingerprintFingerprints :: [Fingerprint] -> Fingerprint
fingerprintFingerprints fs = unsafeDupablePerformIO $
withArrayLen fs $ \len p -> do
fingerprintData (castPtr p) (len * sizeOf (head fs))
fingerprintData :: Ptr Word8 -> Int -> IO Fingerprint
fingerprintData buf len = do
pctxt <- c_MD5Init
c_MD5Update pctxt buf (fromIntegral len)
allocaBytes 16 $ \pdigest -> do
c_MD5Final pdigest pctxt
peek (castPtr pdigest :: Ptr Fingerprint)
-- This is duplicated in compiler/utils/Fingerprint.hsc
fingerprintString :: String -> Fingerprint
fingerprintString str = unsafeDupablePerformIO $
withArrayLen word8s $ \len p ->
fingerprintData p len
where word8s = concatMap f str
f c = let w32 :: Word32
w32 = fromIntegral (ord c)
in [fromIntegral (w32 `shiftR` 24),
fromIntegral (w32 `shiftR` 16),
fromIntegral (w32 `shiftR` 8),
fromIntegral w32]
-- | Computes the hash of a given file.
-- This function loops over the handle, running in constant memory.
--
-- @since 4.7.0.0
getFileHash :: FilePath -> IO Fingerprint
getFileHash path = withBinaryFile path ReadMode $ \h -> do
pctxt <- c_MD5Init
processChunks h (\buf size -> c_MD5Update pctxt buf (fromIntegral size))
allocaBytes 16 $ \pdigest -> do
c_MD5Final pdigest pctxt
peek (castPtr pdigest :: Ptr Fingerprint)
where
_BUFSIZE = 4096
-- | Loop over _BUFSIZE sized chunks read from the handle,
-- passing the callback a block of bytes and its size.
processChunks :: Handle -> (Ptr Word8 -> Int -> IO ()) -> IO ()
processChunks h f = allocaBytes _BUFSIZE $ \arrPtr ->
let loop = do
count <- hGetBuf h arrPtr _BUFSIZE
eof <- hIsEOF h
when (count /= _BUFSIZE && not eof) $ error $
"GHC.Fingerprint.getFileHash: only read " ++ show count ++ " bytes"
f arrPtr count
when (not eof) loop
in loop
data {-# CLASS "java.security.MessageDigest" #-} MD5Context
= MD5Context (Object# MD5Context)
foreign import java unsafe "@static eta.base.Utils.c_MD5Init"
c_MD5Init :: IO MD5Context
foreign import java unsafe "@static eta.base.Utils.c_MD5Update"
c_MD5Update :: MD5Context -> Ptr Word8 -> CInt -> IO ()
foreign import java unsafe "@static eta.base.Utils.c_MD5Final"
c_MD5Final :: Ptr Word8 -> MD5Context -> IO ()
| pparkkin/eta | libraries/base/GHC/Fingerprint.hs | bsd-3-clause | 3,422 | 9 | 23 | 802 | 784 | 404 | 380 | -1 | -1 |
{-# LANGUAGE Unsafe #-}
{-# LANGUAGE ConstraintKinds #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Typeable.Internal
-- Copyright : (c) The University of Glasgow, CWI 2001--2011
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- The representations of the types TyCon and TypeRep, and the
-- function mkTyCon which is used by derived instances of Typeable to
-- construct a TyCon.
--
-----------------------------------------------------------------------------
{-# LANGUAGE CPP
, NoImplicitPrelude
, OverlappingInstances
, ScopedTypeVariables
, FlexibleInstances
, MagicHash
, KindSignatures
, PolyKinds
, DeriveDataTypeable
, StandaloneDeriving #-}
module Data.Typeable.Internal (
Proxy (..),
TypeRep(..),
Fingerprint(..),
typeOf, typeOf1, typeOf2, typeOf3, typeOf4, typeOf5, typeOf6, typeOf7,
Typeable1, Typeable2, Typeable3, Typeable4, Typeable5, Typeable6, Typeable7,
TyCon(..),
typeRep,
mkTyCon,
mkTyCon3,
mkTyConApp,
mkAppTy,
typeRepTyCon,
Typeable(..),
mkFunTy,
splitTyConApp,
funResultTy,
typeRepArgs,
showsTypeRep,
tyConString,
listTc, funTc
) where
import GHC.Base
import GHC.Word
import GHC.Show
import Data.Maybe
import Data.Proxy
import GHC.Num
import GHC.Real
-- import GHC.IORef
-- import GHC.IOArray
-- import GHC.MVar
import GHC.ST ( ST )
import GHC.STRef ( STRef )
import GHC.Ptr ( Ptr, FunPtr )
-- import GHC.Stable
import GHC.Arr ( Array, STArray )
import Data.Type.Coercion
import Data.Type.Equality
-- import Data.Int
import GHC.IntWord64 (wordToWord64#)
import GHC.Fingerprint.Type
import {-# SOURCE #-} GHC.Fingerprint
-- loop: GHC.Fingerprint -> Foreign.Ptr -> Data.Typeable
-- Better to break the loop here, because we want non-SOURCE imports
-- of Data.Typeable as much as possible so we can optimise the derived
-- instances.
-- | A concrete representation of a (monomorphic) type. 'TypeRep'
-- supports reasonably efficient equality.
data TypeRep = TypeRep {-# UNPACK #-} !Fingerprint TyCon [TypeRep]
-- Compare keys for equality
instance Eq TypeRep where
(TypeRep k1 _ _) == (TypeRep k2 _ _) = k1 == k2
instance Ord TypeRep where
(TypeRep k1 _ _) <= (TypeRep k2 _ _) = k1 <= k2
-- | An abstract representation of a type constructor. 'TyCon' objects can
-- be built using 'mkTyCon'.
data TyCon = TyCon {
tyConHash :: {-# UNPACK #-} !Fingerprint,
tyConPackage :: String, -- ^ /Since: 4.5.0.0/
tyConModule :: String, -- ^ /Since: 4.5.0.0/
tyConName :: String -- ^ /Since: 4.5.0.0/
}
instance Eq TyCon where
(TyCon t1 _ _ _) == (TyCon t2 _ _ _) = t1 == t2
instance Ord TyCon where
(TyCon k1 _ _ _) <= (TyCon k2 _ _ _) = k1 <= k2
----------------- Construction --------------------
#include "MachDeps.h"
-- mkTyCon is an internal function to make it easier for GHC to
-- generate derived instances. GHC precomputes the MD5 hash for the
-- TyCon and passes it as two separate 64-bit values to mkTyCon. The
-- TyCon for a derived Typeable instance will end up being statically
-- allocated.
#if HASTE_HOST_WORD_SIZE_IN_BITS < 64
mkTyCon :: Word64# -> Word64# -> String -> String -> String -> TyCon
mkTyCon high# low# pkg modl name
= TyCon (Fingerprint (W64# high#) (W64# low#)) pkg modl name
#else
mkTyCon :: Word# -> Word# -> String -> String -> String -> TyCon
mkTyCon high# low# pkg modl name
= TyCon (Fingerprint (mkw64# high#) (mkw64# low#)) pkg modl name
mkw64# :: Word# -> Word64
mkw64# w = W64# (wordToWord64# w)
#endif
-- | Applies a type constructor to a sequence of types
mkTyConApp :: TyCon -> [TypeRep] -> TypeRep
mkTyConApp tc@(TyCon tc_k _ _ _) []
= TypeRep tc_k tc [] -- optimisation: all derived Typeable instances
-- end up here, and it helps generate smaller
-- code for derived Typeable.
mkTyConApp tc@(TyCon tc_k _ _ _) args
= TypeRep (fingerprintFingerprints (tc_k : arg_ks)) tc args
where
arg_ks = [k | TypeRep k _ _ <- args]
-- | A special case of 'mkTyConApp', which applies the function
-- type constructor to a pair of types.
mkFunTy :: TypeRep -> TypeRep -> TypeRep
mkFunTy f a = mkTyConApp funTc [f,a]
-- | Splits a type constructor application
splitTyConApp :: TypeRep -> (TyCon,[TypeRep])
splitTyConApp (TypeRep _ tc trs) = (tc,trs)
-- | Applies a type to a function type. Returns: @'Just' u@ if the
-- first argument represents a function of type @t -> u@ and the
-- second argument represents a function of type @t@. Otherwise,
-- returns 'Nothing'.
funResultTy :: TypeRep -> TypeRep -> Maybe TypeRep
funResultTy trFun trArg
= case splitTyConApp trFun of
(tc, [t1,t2]) | tc == funTc && t1 == trArg -> Just t2
_ -> Nothing
-- | Adds a TypeRep argument to a TypeRep.
mkAppTy :: TypeRep -> TypeRep -> TypeRep
mkAppTy (TypeRep _ tc trs) arg_tr = mkTyConApp tc (trs ++ [arg_tr])
-- Notice that we call mkTyConApp to construct the fingerprint from tc and
-- the arg fingerprints. Simply combining the current fingerprint with
-- the new one won't give the same answer, but of course we want to
-- ensure that a TypeRep of the same shape has the same fingerprint!
-- See Trac #5962
-- | Builds a 'TyCon' object representing a type constructor. An
-- implementation of "Data.Typeable" should ensure that the following holds:
--
-- > A==A' ^ B==B' ^ C==C' ==> mkTyCon A B C == mkTyCon A' B' C'
--
--
mkTyCon3 :: String -- ^ package name
-> String -- ^ module name
-> String -- ^ the name of the type constructor
-> TyCon -- ^ A unique 'TyCon' object
mkTyCon3 pkg modl name =
TyCon (fingerprintString (pkg ++ (' ':modl) ++ (' ':name))) pkg modl name
----------------- Observation ---------------------
-- | Observe the type constructor of a type representation
typeRepTyCon :: TypeRep -> TyCon
typeRepTyCon (TypeRep _ tc _) = tc
-- | Observe the argument types of a type representation
typeRepArgs :: TypeRep -> [TypeRep]
typeRepArgs (TypeRep _ _ args) = args
-- | Observe string encoding of a type representation
{-# DEPRECATED tyConString "renamed to 'tyConName'; 'tyConModule' and 'tyConPackage' are also available." #-} -- deprecated in 7.4
tyConString :: TyCon -> String
tyConString = tyConName
-------------------------------------------------------------
--
-- The Typeable class and friends
--
-------------------------------------------------------------
-- | The class 'Typeable' allows a concrete representation of a type to
-- be calculated.
class Typeable a where
typeRep# :: Proxy# a -> TypeRep
-- | Takes a value of type @a@ and returns a concrete representation
-- of that type.
--
-- /Since: 4.7.0.0/
typeRep :: forall proxy a. Typeable a => proxy a -> TypeRep
typeRep _ = typeRep# (proxy# :: Proxy# a)
{-# INLINE typeRep #-}
-- Keeping backwards-compatibility
typeOf :: forall a. Typeable a => a -> TypeRep
typeOf _ = typeRep (Proxy :: Proxy a)
typeOf1 :: forall t (a :: *). Typeable t => t a -> TypeRep
typeOf1 _ = typeRep (Proxy :: Proxy t)
typeOf2 :: forall t (a :: *) (b :: *). Typeable t => t a b -> TypeRep
typeOf2 _ = typeRep (Proxy :: Proxy t)
typeOf3 :: forall t (a :: *) (b :: *) (c :: *). Typeable t
=> t a b c -> TypeRep
typeOf3 _ = typeRep (Proxy :: Proxy t)
typeOf4 :: forall t (a :: *) (b :: *) (c :: *) (d :: *). Typeable t
=> t a b c d -> TypeRep
typeOf4 _ = typeRep (Proxy :: Proxy t)
typeOf5 :: forall t (a :: *) (b :: *) (c :: *) (d :: *) (e :: *). Typeable t
=> t a b c d e -> TypeRep
typeOf5 _ = typeRep (Proxy :: Proxy t)
typeOf6 :: forall t (a :: *) (b :: *) (c :: *) (d :: *) (e :: *) (f :: *).
Typeable t => t a b c d e f -> TypeRep
typeOf6 _ = typeRep (Proxy :: Proxy t)
typeOf7 :: forall t (a :: *) (b :: *) (c :: *) (d :: *) (e :: *) (f :: *)
(g :: *). Typeable t => t a b c d e f g -> TypeRep
typeOf7 _ = typeRep (Proxy :: Proxy t)
type Typeable1 (a :: * -> *) = Typeable a
type Typeable2 (a :: * -> * -> *) = Typeable a
type Typeable3 (a :: * -> * -> * -> *) = Typeable a
type Typeable4 (a :: * -> * -> * -> * -> *) = Typeable a
type Typeable5 (a :: * -> * -> * -> * -> * -> *) = Typeable a
type Typeable6 (a :: * -> * -> * -> * -> * -> * -> *) = Typeable a
type Typeable7 (a :: * -> * -> * -> * -> * -> * -> * -> *) = Typeable a
{-# DEPRECATED Typeable1 "renamed to 'Typeable'" #-} -- deprecated in 7.8
{-# DEPRECATED Typeable2 "renamed to 'Typeable'" #-} -- deprecated in 7.8
{-# DEPRECATED Typeable3 "renamed to 'Typeable'" #-} -- deprecated in 7.8
{-# DEPRECATED Typeable4 "renamed to 'Typeable'" #-} -- deprecated in 7.8
{-# DEPRECATED Typeable5 "renamed to 'Typeable'" #-} -- deprecated in 7.8
{-# DEPRECATED Typeable6 "renamed to 'Typeable'" #-} -- deprecated in 7.8
{-# DEPRECATED Typeable7 "renamed to 'Typeable'" #-} -- deprecated in 7.8
-- | Kind-polymorphic Typeable instance for type application
instance (Typeable s, Typeable a) => Typeable (s a) where
typeRep# = \_ -> rep
where rep = typeRep# (proxy# :: Proxy# s)
`mkAppTy` typeRep# (proxy# :: Proxy# a)
----------------- Showing TypeReps --------------------
instance Show TypeRep where
showsPrec p (TypeRep _ tycon tys) =
case tys of
[] -> showsPrec p tycon
[x] | tycon == listTc -> showChar '[' . shows x . showChar ']'
[a,r] | tycon == funTc -> showParen (p > 8) $
showsPrec 9 a .
showString " -> " .
showsPrec 8 r
xs | isTupleTyCon tycon -> showTuple xs
| otherwise ->
showParen (p > 9) $
showsPrec p tycon .
showChar ' ' .
showArgs (showChar ' ') tys
showsTypeRep :: TypeRep -> ShowS
showsTypeRep = shows
instance Show TyCon where
showsPrec _ t = showString (tyConName t)
isTupleTyCon :: TyCon -> Bool
isTupleTyCon (TyCon _ _ _ ('(':',':_)) = True
isTupleTyCon _ = False
-- Some (Show.TypeRep) helpers:
showArgs :: Show a => ShowS -> [a] -> ShowS
showArgs _ [] = id
showArgs _ [a] = showsPrec 10 a
showArgs sep (a:as) = showsPrec 10 a . sep . showArgs sep as
showTuple :: [TypeRep] -> ShowS
showTuple args = showChar '('
. showArgs (showChar ',') args
. showChar ')'
listTc :: TyCon
listTc = typeRepTyCon (typeOf [()])
funTc :: TyCon
funTc = typeRepTyCon (typeRep (Proxy :: Proxy (->)))
-------------------------------------------------------------
--
-- Instances of the Typeable classes for Prelude types
--
-------------------------------------------------------------
deriving instance Typeable ()
deriving instance Typeable []
deriving instance Typeable Maybe
deriving instance Typeable Ratio
deriving instance Typeable (->)
deriving instance Typeable IO
deriving instance Typeable Array
deriving instance Typeable ST
deriving instance Typeable STRef
deriving instance Typeable STArray
deriving instance Typeable (,)
deriving instance Typeable (,,)
deriving instance Typeable (,,,)
deriving instance Typeable (,,,,)
deriving instance Typeable (,,,,,)
deriving instance Typeable (,,,,,,)
deriving instance Typeable Ptr
deriving instance Typeable FunPtr
-------------------------------------------------------
--
-- Generate Typeable instances for standard datatypes
--
-------------------------------------------------------
deriving instance Typeable Bool
deriving instance Typeable Char
deriving instance Typeable Float
deriving instance Typeable Double
deriving instance Typeable Int
deriving instance Typeable Word
deriving instance Typeable Integer
deriving instance Typeable Ordering
deriving instance Typeable Word8
deriving instance Typeable Word16
deriving instance Typeable Word32
deriving instance Typeable Word64
deriving instance Typeable TyCon
deriving instance Typeable TypeRep
deriving instance Typeable RealWorld
deriving instance Typeable Proxy
deriving instance Typeable (:~:)
deriving instance Typeable Coercion
| beni55/haste-compiler | libraries/ghc-7.8/base/Data/Typeable/Internal.hs | bsd-3-clause | 12,359 | 0 | 15 | 2,875 | 2,893 | 1,622 | 1,271 | 210 | 2 |
module LiquidClass where
-- | Typing classes
-- | Step 1: Refine type dictionaries:
class Compare a where
cmax :: a -> a -> a
cmin :: a -> a -> a
instance Compare Int where
{-@ instance Compare Int where
cmax :: Odd -> Odd -> Odd ;
cmin :: Int -> Int -> Int
@-}
cmax y x = if x >= y then x else y
cmin y x = if x >= y then x else y
-- | creates dictionary environment:
-- | * add the following environment
-- | dictionary $fCompareInt :: Compare Int
-- | { $ccmax :: Odd -> Odd -> Odd
-- | , $ccmin :: Int -> Int -> Int
-- | }
-- |
-- | Important: do not type dictionaries, as preconditions
-- | of fields cannot be satisfied!!!!!
-- | Dictionary application
-- | ((cmax Int) @fcompareInt) :: Odd -> Odd -> Odd
-- | ((cmin Int) @fcompareInt) :: Int -> Int -> Int
-- | (anything_else @fcompareInt) :: default
{-@ foo :: Odd -> Odd -> Odd @-}
foo :: Int -> Int -> Int
foo x y = cmax x y
| abakst/liquidhaskell | tests/pos/LiquidClass.hs | bsd-3-clause | 957 | 3 | 9 | 268 | 139 | 81 | 58 | 9 | 1 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE NoImplicitPrelude #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.Magic
-- Copyright : (c) The University of Glasgow 2009
-- License : see libraries/ghc-prim/LICENSE
--
-- Maintainer : cvs-ghc@haskell.org
-- Stability : internal
-- Portability : non-portable (GHC Extensions)
--
-- GHC magic.
--
-- Use GHC.Exts from the base package instead of importing this
-- module directly.
--
-----------------------------------------------------------------------------
module GHC.Magic ( inline, lazy ) where
-- | The call '(inline f)' arranges that 'f' is inlined, regardless of
-- its size. More precisely, the call '(inline f)' rewrites to the
-- right-hand side of 'f'\'s definition. This allows the programmer to
-- control inlining from a particular call site rather than the
-- definition site of the function (c.f. 'INLINE' pragmas).
--
-- This inlining occurs regardless of the argument to the call or the
-- size of 'f'\'s definition; it is unconditional. The main caveat is
-- that 'f'\'s definition must be visible to the compiler; it is
-- therefore recommended to mark the function with an 'INLINABLE'
-- pragma at its definition so that GHC guarantees to record its
-- unfolding regardless of size.
--
-- If no inlining takes place, the 'inline' function expands to the
-- identity function in Phase zero, so its use imposes no overhead.
{-# NOINLINE[0] inline #-}
inline :: a -> a
inline x = x
-- | The 'lazy' function restrains strictness analysis a little. The
-- call '(lazy e)' means the same as 'e', but 'lazy' has a magical
-- property so far as strictness analysis is concerned: it is lazy in
-- its first argument, even though its semantics is strict. After
-- strictness analysis has run, calls to 'lazy' are inlined to be the
-- identity function.
--
-- This behaviour is occasionally useful when controlling evaluation
-- order. Notably, 'lazy' is used in the library definition of
-- 'Control.Parallel.par':
--
-- > par :: a -> b -> b
-- > par x y = case (par# x) of _ -> lazy y
--
-- If 'lazy' were not lazy, 'par' would look strict in 'y' which
-- would defeat the whole purpose of 'par'.
--
-- Like 'seq', the argument of 'lazy' can have an unboxed type.
lazy :: a -> a
lazy x = x
-- Implementation note: its strictness and unfolding are over-ridden
-- by the definition in MkId.lhs; in both cases to nothing at all.
-- That way, 'lazy' does not get inlined, and the strictness analyser
-- sees it as lazy. Then the worker/wrapper phase inlines it.
-- Result: happiness
| frantisekfarka/ghc-dsi | libraries/ghc-prim/GHC/Magic.hs | bsd-3-clause | 2,615 | 0 | 5 | 460 | 105 | 84 | 21 | 8 | 1 |
{-# LANGUAGE BangPatterns #-}
module Main where
import ByteCodeLink
import CoreMonad
import Data.Array
import DataCon
import DebuggerUtils
import GHC
import HscTypes
import Linker
import RtClosureInspect
import TcEnv
import Type
import TcRnMonad
import TcType
import Control.Applicative
import Name (getOccString)
import Unsafe.Coerce
import Control.Monad
import Data.Maybe
import Bag
import Outputable
import GhcMonad
import X
import System.Environment
main :: IO ()
main = do [libdir] <- getArgs
runGhc (Just libdir) doit
doit :: Ghc ()
doit = do
dflags' <- getSessionDynFlags
primPackages <- setSessionDynFlags dflags'
dflags <- getSessionDynFlags
defaultCleanupHandler dflags $ do
target <- guessTarget "X.hs" Nothing
setTargets [target]
load LoadAllTargets
() <- chaseConstructor (unsafeCoerce False)
() <- chaseConstructor (unsafeCoerce [1,2,3])
() <- chaseConstructor (unsafeCoerce (3 :-> 2))
() <- chaseConstructor (unsafeCoerce (4 :->. 4))
() <- chaseConstructor (unsafeCoerce (4 :->.+ 4))
return ()
chaseConstructor :: (GhcMonad m) => HValue -> m ()
chaseConstructor !hv = do
dflags <- getDynFlags
liftIO $ putStrLn "====="
closure <- liftIO $ getClosureData dflags hv
case tipe closure of
Indirection _ -> chaseConstructor (ptrs closure ! 0)
Constr -> do
withSession $ \hscEnv -> liftIO $ initTcForLookup hscEnv $ do
eDcname <- dataConInfoPtrToName (infoPtr closure)
case eDcname of
Left _ -> return ()
Right dcName -> do
liftIO $ putStrLn $ "Name: " ++ showPpr dflags dcName
liftIO $ putStrLn $ "OccString: " ++ "'" ++ getOccString dcName ++ "'"
dc <- tcLookupDataCon dcName
liftIO $ putStrLn $ "DataCon: " ++ showPpr dflags dc
_ -> return ()
| siddhanathan/ghc | testsuite/tests/ghc-api/T4891/T4891.hs | bsd-3-clause | 1,839 | 0 | 26 | 425 | 593 | 289 | 304 | 61 | 4 |
-- !!! Test monomorphism + RULES
module ShouldCompile where
-- This example crashed GHC 4.08.1.
-- The reason was that foobar is monomorphic, so the RULE
-- should not generalise over it.
{-# NOINLINE [1] foo #-}
foo 1 = 2
{-# NOINLINE [1] bar #-}
bar 0 = 1
foobar = 2
{-# RULES
"foo/bar" foo bar = foobar
#-}
| siddhanathan/ghc | testsuite/tests/typecheck/should_compile/tc111.hs | bsd-3-clause | 322 | 0 | 5 | 72 | 32 | 21 | 11 | 8 | 1 |
-----------------------------------------------------------------------------
--
-- Module : Language.PureScript.CodeGen.JS.Optimizer.Blocks
-- Copyright : (c) Phil Freeman 2013-14
-- License : MIT
--
-- Maintainer : Phil Freeman <paf31@cantab.net>
-- Stability : experimental
-- Portability :
--
-- |
-- Optimizer steps for simplifying Javascript blocks
--
-----------------------------------------------------------------------------
module Language.PureScript.CodeGen.JS.Optimizer.Blocks
( collapseNestedBlocks
, collapseNestedIfs
) where
import Language.PureScript.CodeGen.JS.AST
-- |
-- Collapse blocks which appear nested directly below another block
--
collapseNestedBlocks :: JS -> JS
collapseNestedBlocks = everywhereOnJS collapse
where
collapse :: JS -> JS
collapse (JSBlock sts) = JSBlock (concatMap go sts)
collapse js = js
go :: JS -> [JS]
go (JSBlock sts) = sts
go s = [s]
collapseNestedIfs :: JS -> JS
collapseNestedIfs = everywhereOnJS collapse
where
collapse :: JS -> JS
collapse (JSIfElse cond1 (JSBlock [JSIfElse cond2 body Nothing]) Nothing) =
JSIfElse (JSBinary And cond1 cond2) body Nothing
collapse js = js
| michaelficarra/purescript | src/Language/PureScript/CodeGen/JS/Optimizer/Blocks.hs | mit | 1,187 | 0 | 13 | 200 | 228 | 131 | 97 | 18 | 3 |
module Language.HAsm.Parse where
import Data.Char
import Data.Either (lefts, rights)
import Data.List (intercalate, nub, sort)
import qualified Data.Map as M
import qualified Control.Arrow as Arr
import Control.Applicative ((<$>), (<*), liftA2)
import Control.Monad (when)
import Numeric
import Text.Parsec
import Text.Parsec.String (Parser)
import Language.HAsm.Types
import Language.HAsm.X86.CPU
hasmParseFile :: FilePath -> IO (Either ParseError ParseResult)
hasmParseFile fname = hasmParseWithSource fname <$> readFile fname
hasmParseWithSource :: FilePath -> String -> Either ParseError ParseResult
hasmParseWithSource fname ss = parse (asmfile <* eof) fname ss
asmfile :: Parser ParseResult
asmfile = do
blanklines
--mbasmspaces
many $ do
pos <- getPosition
stmt <- asmstmt
blanklines
--mbasmspaces
return (stmt, toHasmPos pos)
asmstmt :: Parser HasmStatement
asmstmt = try asmlabel <|> try asmdir <|> asmop <?> "assembly statement"
blanklines = many ((linecomment <|> newline) >> mbasmspaces) >> return ()
linecomment = do
char '#'; many (noneOf "\n"); newline
dirchar = letter <|> char '_'
idschar = letter <|> oneOf "._$"
idchar = idschar <|> digit
symbol = cons idschar (many idchar)
endstmt = mbasmspaces >> optional ((oneOf ";" >> return ()) <|> eof)
endlbl = (mbasmspaces >> blanklines) <|> eof
mbasmspaces = many (oneOf " \t")
cons a b = liftA2 (:) a b
opchar = letter <|> digit
opcode = cons letter (many1 opchar)
regname = cons letter (many1 opchar)
asmdir = do
char '.'
dir <- many1 dirchar
mbasmspaces
dirargs <- sepBy (many1 $ noneOf "\n,") (char ',' >> mbasmspaces)
endstmt
case readDirective dir dirargs of
Right d -> return $ HasmStDirective d
Left e -> parserFail e
asmlabel = HasmStLabel <$> (symbol <* char ':' <* endlbl) <?> "label"
asmop = do
op <- opcode
mbasmspaces
opnds <- sepBy asmopnd (char ',' >> mbasmspaces)
endstmt
case readOperation op opnds of
Left e -> parserFail e
Right o -> return $ HasmStInstr [] o
asmopnd :: Parser OpOperand
asmopnd = try (OpndImm <$> asmimm) <|>
try (OpndReg <$> asmregister) <|>
try asmmem <?> "opcode operand"
immToDispl iv@(ImmL imm)
| isWord8 iv = Displ8 $ fromIntegral imm
| otherwise = Displ32 imm
asmdispl = try (immToDispl <$> readIntegerLit)
<|> (DisplLabel <$> symbol)
<?> "displacement before ("
asmmem = do
mbDspl <- optionMaybe asmdispl
mbSIB <- optionMaybe asmsib
when (mbDspl == Nothing && mbSIB == Nothing) $ fail "no displacement and no SIB"
let dspl = maybe NoDispl id mbDspl
let sib = maybe noSIB id mbSIB
return $ OpndRM sib dspl
{-- SIBs and memory refs --}
data SIBPart = SIBReg GPRegister | SIBScale Word8 | SIBNothing
immToSIBScale (ImmL imm) = SIBScale $ fromIntegral imm
sibpart = try (SIBReg <$> asmgpregister) <|>
try (immToSIBScale <$> readIntegerLit) <|>
return SIBNothing
sibparts = between (char '(') (char ')') $ sepBy sibpart (char ',' >> mbasmspaces)
asmsib = do
sps <- sibparts
case sps of
-- (%reg)
[SIBReg base] -> return $ SIB 1 Nothing (Just base)
-- (%reg, %reg)
[SIBReg base, SIBReg ind] -> return $ SIB 1 (Just ind) (Just base)
-- (%reg, %reg, )
[SIBReg base, SIBReg ind, SIBNothing] -> return $ SIB 1 (Just ind) (Just base)
-- (, %reg)
[SIBNothing, SIBReg ind] -> return $ SIB 1 (Just ind) Nothing
-- (%reg, scale)
[SIBReg ind, SIBScale scale ] -> makeSIB scale (Just ind) Nothing
-- (, %reg, scale)
[SIBNothing, SIBReg ind, SIBScale scale ] -> makeSIB scale (Just ind) Nothing
-- (%reg, %reg, scale)
[SIBReg base, SIBReg ind, SIBScale scale ] -> makeSIB scale (Just ind) (Just base)
-- everything else:
_ -> fail "SIB format is invalid"
where
makeSIB scale mbInd mbBase =
if scale `elem` [1,2,4,8]
then return $ SIB (fromIntegral scale) mbInd mbBase
else fail "Scale is not 1,2,4,8"
asmregister = do
char '%'
reg <- regname
case mbRegByName reg of
Just r -> return r
_ -> parserFail $ "Not a register name: " ++ reg
asmgpregister = do
RegL reg <- asmregister
return reg
{-- Number literals --}
asmimm = do
char '$'
try readIntegerLit <|> (ImmS <$> symbol) <?> "integer or symbol in immediate value"
readIntegerLit = (ImmL . fromIntegral) <$> (intneg <|> intparse <?> "number")
intneg = do
char '-'
num <- intparse
return $ negate num
hexint = do
ds <- many1 (oneOf "0123456789abcdefABCDEF")
case readHex ds of
[(num, "")] -> return num
_ -> parserFail "failed to parse hexadecimal number"
octint = do
ds <- many1 (oneOf "01234567")
case readOct ds of
[(num, "")] -> return num
_ -> parserFail "failed to parse octal number"
intparse = do
d <- digit
if d == '0'
then do
try (char 'x' >> hexint) <|> try octint <|> return 0
else do
ds <- many digit
case readDec (d:ds) of
[(num, "")] -> return num
_ -> parserFail "failed to parse a number"
{-- Directives --}
readDirective :: String -> [String] -> Either String Directive
readDirective dir args =
case dir of
"section" ->
case args of
[] -> Left $ ".section takes at least section name"
[name] -> Right $ DirSection name 0 ""
[name, subsect] -> case (reads :: ReadS Int) subsect of
[(nsubsect, "")] -> Right $ DirSection name nsubsect ""
_ -> Left $ "Failed to parse subsection: " ++ show subsect
_ -> Left $ "invalid .section format"
sect | sect `elem` ["text", "data"] ->
case args of
[] -> Right $ DirSection sect 0 ""
[subsect] -> case (reads :: ReadS Int) subsect of
[(nsubsect, "")] -> Right $ DirSection sect nsubsect ""
_ -> Left $ "Failed to parse subsection: " ++ show subsect
glbl | glbl `elem` ["global", "globl"] ->
let eiSyms = map (parse (symbol <* eof) "") args
in case lefts eiSyms of
[] -> Right $ DirGlobal (rights eiSyms)
(err:_) -> Left $ "failed to parse symbol " ++ show err
"extern" ->
let eiSyms = map (parse (symbol <* eof) "") args
in case lefts eiSyms of
[] -> Right $ DirExtern (rights eiSyms)
(err:_) -> Left $ "failed to parse symbol " ++ show err
"file" ->
case args of
[fname] -> Right $ DirFile fname
_ -> Left ".file takes only one string parameter"
"type" ->
case args of
[sym, ty] -> Right $ DirType sym ty
_ -> Left ".type takes two arguments: .type <sym>, <type>"
--"asciz" ->
_ -> Left $ "Unknown directive: " ++ dir ++ " " ++ intercalate "," args
type OpSuffix = Char
type OpInfo = (Instr, [Int], [OpSuffix])
opsyntax :: [(String, OpInfo)]
opsyntax = [
("mov", (OpMov, [2], "lwb")),
("add", (OpAdd, [2], "lwb")),
("ret", (OpRet, [0,1], "w" )),
("push", (OpPush, [1], "lwb")),
("pop", (OpPop, [1], "lwb")),
("cmp", (OpCmp, [2], "lwb")),
("int", (OpInt, [1], "b" )),
("jmp", (OpJmp, [1], "lwb")),
("call", (OpCall, [1], "l" )),
("imul", (OpIMul, [1,2,3],"lwb")),
("je", (OpJe, [1], "" )), -- ZF=1
("jz", (OpJe, [1], "" )),
("jne", (OpJne, [1], "" )), -- ZF=0
("jnz", (OpJne, [1], "" )),
("jge", (OpJge, [1], "" )), -- SF=OF
("jnl", (OpJge, [1], "" )),
("jl", (OpJl, [1], "" )), -- SF<>OF
("jnge", (OpJl, [1], "" )),
("jle", (OpJle, [1], "" )), -- ZF=1, SF<>OF
("jng", (OpJle, [1], "" )),
("jg", (OpJg, [1], "" )), -- ZF=0, SF=OF
("jnle", (OpJg, [1], "" )),
("jnp", (OpJnp, [1], "" )), -- PF=0
("jpo", (OpJnp, [1], "" )),
("jp", (OpJp, [1], "" )), -- PF=1
("jpe", (OpJp, [1], "" )),
("jno", (OpJno, [1], "" )), -- OF=0
("jo", (OpJo, [1], "" )), -- OF=1
("jns", (OpJns, [1], "" )), -- SF=0
("js", (OpJs, [1], "" )), -- SF=1
("jae", (OpJnc, [1], "" )), -- CF=0
("jnb", (OpJnc, [1], "" )),
("jnc", (OpJnc, [1], "" )),
("jc", (OpJc, [1], "" )), -- CF=1
("jb", (OpJc, [1], "" )),
("jnae", (OpJc, [1], "" )),
("ja", (OpJa, [1], "" )), -- CF=0, ZF=0
("jnbe", (OpJa, [1], "" )),
("jbe", (OpJbe, [1], "" )), -- CF=1, ZF=1
("jna", (OpJbe, [1], "" )),
("jecxz", (OpJecxz,[1], "" )) ]
opmap = M.fromList opsyntax
oplookup :: String -> Either String (OpInfo, OpSuffix)
oplookup opname =
case M.lookup opname opmap of
Just opinfo ->
Right (opinfo, '?')
Nothing ->
-- search without possible suffixes:
let suf = last opname
opname' = init opname
in case M.lookup opname' opmap of
Just opinfo@(_, _, suffs) ->
if suf `elem` suffs
then Right (opinfo, suf)
else Left $ "Invalid suffix for command " ++ opname'
Nothing -> Left $ "Unknown instruction: " ++ opname
readOperation :: String -> [OpOperand] -> Either String Operation
readOperation opname opnds =
case oplookup opname of
Left e -> Left e
Right (opinfo@(op, arglens, suffs), suf) ->
if length opnds `elem` arglens
then case unifyOperandTypes opinfo suf opnds of
Right opnds' -> Right $ Operation op opnds'
Left e -> Left $ "Operand type mismatch: " ++ e
else Left $ "Opcode '" ++ opname ++ "' does not take " ++ show (length opnds) ++ " parameter(s)"
getOpndType :: OpOperand -> OpSuffix
getOpndType opnd =
case opnd of
OpndImm _ -> '?' -- any, needs adjusting to OpndReg size
OpndRM _ _ -> '?' -- memory can be read by 1,2,4 bytes
OpndReg (SReg _) -> 's' -- compatible with w and l at the same time
OpndReg (RegL _) -> 'l' -- these registers are rigid
OpndReg (RegW _) -> 'w'
OpndReg (RegB _) -> 'b'
getOperandsTypes :: OpSuffix -> [OpOperand] -> [OpSuffix]
getOperandsTypes opsuf opnds =
nub $ sort $ (opsuf : map getOpndType opnds) -- what types are present?
unifyOperandTypes :: OpInfo -> OpSuffix -> [OpOperand] -> Either String [OpOperand]
unifyOperandTypes (opname, lens, sufs) opsuf opnds =
let ts = filter (not . flip elem "s?") $ getOperandsTypes opsuf opnds
in case ts of
"" -> Right opnds
"l" -> Right opnds -- parser defaults to ImmL
"w" -> adjustImmediatesWith immToW opnds
"b" -> adjustImmediatesWith immToB opnds
_ -> Left $ "Operand type mismatch" -- TODO: e.g. movsx with different types
adjustImmediatesWith :: (ImmValue -> Either String ImmValue) ->
[OpOperand] -> Either String [OpOperand]
adjustImmediatesWith adjimm = mapM adj
where
adj (OpndImm imm) = OpndImm <$> adjimm imm
adj op = Right op
toHasmPos :: SourcePos -> SrcPos
toHasmPos src = SrcPos (sourceName src) (sourceLine src) (sourceColumn src)
| EarlGray/hasm | src/Language/HAsm/Parse.hs | mit | 11,011 | 0 | 17 | 3,010 | 4,070 | 2,197 | 1,873 | 268 | 17 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
module LDAP.Classy.SSha where
import Prelude (Eq, Int, Show,show,(==))
import Control.Applicative ((<$>))
import Control.Category ((.))
import Control.Lens
import Control.Monad (replicateM)
import Data.Bool (Bool (..))
import Data.ByteString.Base64.Lazy (encode)
import Data.ByteString.Lazy (ByteString, pack)
import Data.Digest.Pure.SHA (bytestringDigest, sha1)
import Data.Function (flip, ($))
import Data.Functor (fmap)
import Data.Monoid ((<>))
import Data.Text.Lazy (Text, unpack)
import Data.Text.Lazy.Encoding (decodeUtf8, encodeUtf8)
import System.IO (IO)
import System.Random (getStdRandom, random)
newtype Salt = Salt ByteString deriving Eq
makeWrapped ''Salt
data SSha = SSha
{ _sShaDigest :: ByteString
, _sShaSalt :: Salt
} deriving (Eq)
makeLenses ''SSha
instance Show SSha where
show = unpack . decodeUtf8 . sShaToByteString
toSSha :: Text -> IO SSha
toSSha t = hash t <$> getSalt 4
hash :: Text -> Salt -> SSha
hash pw s = SSha
(bytestringDigest . sha1 $ encodeUtf8 pw <> s^._Wrapped)
s
sShaToByteString :: SSha -> ByteString
sShaToByteString (SSha d (Salt s)) = "{SSHA}" <> encode (d <> s)
verifySSha :: SSha -> Text -> Bool
verifySSha sSha pw = sSha == hash pw (sSha^.sShaSalt)
getSalt :: Int -> IO Salt
getSalt = fmap (Salt . pack) . flip replicateM (getStdRandom random)
| benkolera/haskell-ldap-classy | LDAP/Classy/SSha.hs | mit | 1,895 | 0 | 10 | 602 | 500 | 288 | 212 | 44 | 1 |
{-# LANGUAGE OverloadedStrings, RecordWildCards #-}
module Text.Feed.Crawl where
import Text.Feed.Crawl.Common
import Text.Feed.Crawl.DetectLink
import Network.Connection (TLSSettings(..))
import Network.HTTP.Conduit
import qualified Data.Conduit as C
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy.Char8 as BL
import System.Environment
import System.IO
import Control.Monad.Trans.State.Lazy
import Control.Monad.Trans.Class (lift)
import Network.HTTP.Types.Status (statusCode)
import Network.HTTP.Types.Header
import Control.Monad.IO.Class
import Data.Maybe (listToMaybe, catMaybes)
import qualified Control.Exception as E
import Network.URI
import Control.Applicative
import Data.Monoid
import Control.Monad (join)
test :: String -> IO ()
test url = do
r <- crawlURL url
print r
-- | Spoof a Safari Browser because some sites don't even serve feeds to
-- an http-conduit client
userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.75.14 (KHTML, like Gecko) Version/7.0.3 Safari/7046A194A"
-- |The main function
crawlURL :: String
-> IO CrawlResult
crawlURL url = do
request <- parseUrl url
let request' = request {
requestHeaders = ("User-Agent", userAgent):(requestHeaders request)
}
let settings = mkManagerSettings (TLSSettingsSimple True False False) Nothing
(mkCrawlResult url =<< withRedirectTracking settings request')
`E.catch` (\e -> return . Left . CrawlHttpError $ e)
mkCrawlResult :: String -> (Response BL.ByteString, [Status]) -> IO CrawlResult
mkCrawlResult firstUrl (resp, statuses) = do
let ct = lookup hContentType . responseHeaders $ resp
let loc = lookup hLocation . responseHeaders $ resp
let urls = catMaybes [ sLocation | Status{..} <- statuses ]
let lastUrl = head (urls ++ [B.pack firstUrl])
if isFeedContentType ct
then return . Right $ CrawlSuccess {
crawlLastContentType = ct
, crawlLastUrl = lastUrl
, crawlFeedContent = responseBody resp
}
else do
links <- findFeedLinks (BL.unpack . responseBody $ resp)
-- TODO this ignore any the <base> tag in the html page
return . Left . CrawlFoundFeedLinks (responseBody resp)
. map (ensureLinkIsAbsolute lastUrl) $ links
where ensureLinkIsAbsolute :: B.ByteString -> Link -> Link
ensureLinkIsAbsolute linkBaseUrl x@Link{..} =
let linkHref' =
maybe linkHref id
$ ensureAbsURL'
(parseURI . B.unpack $ linkBaseUrl)
linkHref
in x { linkHref = linkHref' }
-- |Returns a tuple of response and list of redirect locations.
-- The first location is the last redirect.
withRedirectTracking :: ManagerSettings
-> Request
-> IO (Response BL.ByteString, [Status])
withRedirectTracking settings request = do
m <- newManager settings
r <- runStateT (traceRedirects request m) []
return r
traceRedirects :: Request
-> Manager
-> StateT [Status] IO (Response BL.ByteString)
traceRedirects req' man = do
let req = req' { checkStatus = \_ _ _ -> Nothing }
res <- httpLbs req{redirectCount=0} man
let req2 = getRedirectedRequest req (responseHeaders res) (responseCookieJar res) (statusCode (responseStatus res))
let location = lookup hLocation . responseHeaders $ res
case (req2, location) of
(Just req2', Just location') -> do
let location' = ensureAbsURL req location
let st = Status {
sStatusCode = statusCode (responseStatus res)
, sLocation = location'
, sContentType = lookup hContentType . responseHeaders $ res
}
modify (st:)
traceRedirects req2' man
_ -> return res
isFeed :: Status -> Bool
isFeed Status{..} = isFeedContentType sContentType
ensureAbsURL :: Request -> Maybe B.ByteString -> Maybe B.ByteString
ensureAbsURL req url =
let sUrl = B.unpack `fmap` url
in case sUrl of
Nothing -> Nothing
Just sUrl' -> B.pack <$> ensureAbsURL' (baseURL req) sUrl'
ensureAbsURL' :: Maybe URI -> String -> Maybe String
ensureAbsURL' baseURI s =
case parseURI s of
Just _ -> Just s -- is a valid full URI
Nothing -> -- url may be relative path, join to request info
(\x -> uriToString id x "")
<$> (nonStrictRelativeTo
<$> (parseRelativeReference s)
<*> baseURI)
baseURL :: Request -> Maybe URI
baseURL req =
let protocol = if secure req then "https://" else "http://"
in parseURI $ mconcat [
protocol
, B.unpack . host $ req
, case port req of
80 -> ""
n -> ":" ++ show n
]
| danchoi/feed-crawl | Text/Feed/Crawl.hs | mit | 4,984 | 0 | 19 | 1,405 | 1,330 | 695 | 635 | 110 | 3 |
module Y2017.M01.D12.Exercise where
import Data.Set (Set)
import qualified Data.Set as Set
{--
Continuing the conversation of partial functions, studying Haskell pitfalls from
@bitemyapp.
Yesterday we looked at partial functions on List and solved that problem. Today,
we'll look at the more general problem of partial functions on Foldable t:
maximum and minimum.
The problem here is that these functions have nothing to go off of if your
list is empty:
*hask> maximum [1,2,3] ~> 3 works find but:
*hask> minimum [] ~> gives you
*** Exception: Prelude.minimum: empty list
Not good. But we can't write total functions just for lists because the
type-signature of these functions are:
*hask> :t maximum
maximum :: (Ord a, Foldable t) => t a -> a
So, to write total functions for maximum and minimum, we must consider any
Foldable t type, because:
*hask> minimum (Set.fromList [1,2,3,2]) ~> 1 works, but:
*hask> maximum Set.empty ~> has to work correctly, too:
*** Exception: Set.findMax: empty set has no maximal element
So, how to make this work is today's Haskell Exerise.
For maximum and minimum define total functions maximumOr and minimumOr
that take a minimum or maximum alternative value if the foldable value is
empty:
--}
minimumOr, maximumOr :: (Ord a, Foldable t) => a -> t a -> a
minimumOr minval values = undefined
maximumOr maxval values = undefined
{--
I'll grant you:
The minimumOr and maximumOr both demand of you, the functional programmer, to
know, a priori, what your data looks like and what you expect from those data.
But, hey, if you don't know that, then, why are you coding using minimum and
maximum in the first place. "Hey, I want to take the minimum of a set of values
that I know have no values." That's dumb. Almost as dumb as: 'Hey, this possibly
empty set of values? I have no clue what the maximum and minimum values may be,
so I'll just assume 0 is the minimum, because I have no clue if there are
negative values here."
Okay, fer realz? fo' shur? because ... REALLY?
But I digress.
So, what are the values of maximumOr 0 and minimumOr 314159 for the following
values:
--}
nada, soma :: [Int]
nada = []
soma = [1..99]
zumbo, jumbo :: Set Int
zumbo = Set.empty
jumbo = Set.fromList [236..1040]
| geophf/1HaskellADay | exercises/HAD/Y2017/M01/D12/Exercise.hs | mit | 2,254 | 0 | 8 | 412 | 140 | 83 | 57 | 12 | 1 |
{-# LANGUAGE CPP #-}
module GHCJS.DOM.HTMLMarqueeElement (
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
module GHCJS.DOM.JSFFI.Generated.HTMLMarqueeElement
#else
module Graphics.UI.Gtk.WebKit.DOM.HTMLMarqueeElement
#endif
) where
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
import GHCJS.DOM.JSFFI.Generated.HTMLMarqueeElement
#else
import Graphics.UI.Gtk.WebKit.DOM.HTMLMarqueeElement
#endif
| plow-technologies/ghcjs-dom | src/GHCJS/DOM/HTMLMarqueeElement.hs | mit | 475 | 0 | 5 | 39 | 33 | 26 | 7 | 4 | 0 |
module StateMonad where
newtype State s a = State { runState :: s -> (a,s) }
instance Functor (State s) where
fmap f (State x) = State $ \s -> let (v, s') = x s in (f v, s')
instance Applicative (State s) where
pure a = State $ \s -> (a, s)
(State f) <*> (State a) = State $ \s -> let (f', s1) = f s
(a', s') = a s1
in (f' a', s')
instance Monad (State s) where
return a = State $ \s -> (a,s)
(State x) >>= f = State $ \s -> let (v, s') = x s in runState (f v) s'
get :: State s s
get = State $ \s -> (s,s)
put :: s -> State s ()
put x = State $ const ((), x)
| limdauto/learning-haskell | monads/StateMonad.hs | mit | 686 | 0 | 12 | 265 | 376 | 199 | 177 | 16 | 1 |
module Gist where
import Imports
-- Clipboard gists via https://github.com/defunkt/gist
gistFromClipboard :: String -> XX ()
gistFromClipboard filename = forkXio $ do
url <- syncSpawnAndRead "gist" ["-P", "-p", "-f", filename]
logInfo $ "Gist url from clipboard: " <> fromString url
syncSpawn "xdg-open" [url]
| mgsloan/compconfig | env/src/Gist.hs | mit | 318 | 0 | 10 | 51 | 83 | 43 | 40 | 7 | 1 |
import Test.DocTest
import System.FilePath
import System.Directory
-- |
-- >>> collectTestFiles ["a.cpp","a.hs","c",".d"]
-- ["a.hs"]
--
collectTestFiles :: [FilePath] -> [FilePath]
collectTestFiles files = filter isHs files where
isHs = (== ".hs") . snd . splitExtension
main :: IO ()
main = do
setCurrentDirectory "src"
files <- fmap collectTestFiles $ getDirectoryContents "."
-- mapM_ print files
doctest $ "-isrc" : files
| tshm/fmon | test/Spec.hs | mit | 440 | 0 | 9 | 73 | 117 | 62 | 55 | 11 | 1 |
import Control.Applicative
import Data.List
euler012 :: [[Int]] -> Int
euler012 m =
let directions = [id, transpose, diag, diag . reverse]
in maximum . map max_product $ directions <*> pure m
where
max_product = maximum . map (product . take 4) . tails . concat
diag = concatMap (transpose . diag') . tails
where
diag' (x:xs) = x : (diag' . map (drop 1) $ xs)
diag' [] = []
main :: IO ()
main = do
numbers <- map (map read . words) . lines <$> readFile "numbers.txt"
print $ euler012 numbers
| marknsikora/euler | euler011/euler011.hs | mit | 535 | 0 | 15 | 136 | 239 | 121 | 118 | 14 | 2 |
module Handler.EinsendungAnlegen where
import Import
import Handler.AufgabeKonfiguration (checkKonfiguration)
import Yesod.Form.Fields.PreField (preField)
import qualified Control.Exception as Exception
import Data.ByteString (ByteString)
import Data.Conduit (($$))
import Data.Conduit.Binary (sinkLbs)
import Data.Digest.CRC32 (crc32)
import Data.String (fromString)
import Data.Text.Lazy (toStrict)
import Data.Text.Lazy.Encoding (decodeUtf8)
import Text.Blaze.Html5.Attributes (class_)
import Text.Blaze.Html ((!))
import Data.Time.Clock (getCurrentTime)
import Util.Xml.Output (xmlStringToOutput)
import Autolib.Output (render)
import Autolib.Multilingual (specialize)
import qualified Control.Types as T
import Operate.Bank (bank)
import Operate.Click (Click (Example))
import qualified Operate.Param as P
import qualified Operate.Store as Store (Type (Input), latest)
import Service.Interface (get_task_instance_localized, grade_task_solution_localized)
import Types.Basic (Task)
import Types.Config (Config)
import Types.Description (Description (DString))
import Types.Documented (Documented (contents), documentation)
import Types.Instance (Instance)
import Types.Signed (Signed)
import Types.Solution (Solution (SString))
data Aktion = BeispielLaden | VorherigeEinsendungLaden deriving (Show, Read)
aktion :: Text
aktion = "aktion"
eingeben :: Text
eingeben = "eingeben"
hochladen :: Text
hochladen = "hochladen"
getEinsendungAnlegenR :: AufgabeId -> Handler Html
getEinsendungAnlegenR = postEinsendungAnlegenR
postEinsendungAnlegenR :: AufgabeId -> Handler Html
postEinsendungAnlegenR aufgabeId = do
aktuelleZeit <- lift getCurrentTime
maufgabe <- runDB $ get aufgabeId
aufgabe <- case maufgabe of
Nothing -> notFound
Just a -> return a
let server = aufgabeServer aufgabe
typ = aufgabeTyp aufgabe
konfiguration = aufgabeKonfiguration aufgabe
mhinweis = aufgabeHinweis aufgabe
studentId <- requireAuthId
mstudent <- fmap listToMaybe $ runDB $ selectList [StudentId ==. studentId] []
student <- case mstudent of
Nothing ->
-- Benutzer nicht in DB gefunden (passiert nie)
redirect $ AufgabeTestenR server typ konfiguration ""
Just s -> return s
case zeitStatus (aufgabeVon aufgabe) (aufgabeBis aufgabe) aktuelleZeit of
T.Late -> do
setMessageI MsgAufgabeVorbei
redirect $ AufgabeTestenR server typ konfiguration $ studentMatrikelNummer $ entityVal student
T.Early -> return ()
T.Current -> return ()
esigned <- checkKonfiguration server typ konfiguration
signed <- case esigned of
Left fehler -> do
setMessage fehler
redirect $ AufgabenR $ aufgabeVorlesungId aufgabe
Right signed' -> return signed'
((resultUpload, formWidgetUpload), formEnctypeUpload) <- runFormPost $ identifyForm "hochladen" $ renderBootstrap3 BootstrapBasicForm einsendungHochladenForm
let mfile = case resultUpload of
FormSuccess f -> Just f
_ -> Nothing
mvorherigeEinsendung <- runMaybeT $ do
maktion <- lookupPostParam $ pack $ show aktion
let vorher = do
mvorherigeEinsendung' <- lift $ getVorherigeEinsendung mstudent aufgabe aufgabeId
maktuelleEinsendung <- lift $ getMaybeEinsendung mfile
MaybeT . return $ mplus maktuelleEinsendung mvorherigeEinsendung'
case maktion of
Nothing -> vorher
Just aktion' ->
case read $ unpack aktion' of
VorherigeEinsendungLaden -> vorher
BeispielLaden -> MaybeT . return $ Nothing
(signed', beispiel, atyp, aufgabenstellung) <-
getAufgabeInstanz server signed $ getCrc (T.VNr $ keyToInt $ aufgabeVorlesungId aufgabe) (Just $ T.ANr $ keyToInt aufgabeId) (T.MNr $ unpack $ studentMatrikelNummer $ entityVal student)
(formWidget, formEnctype) <- generateFormPost $ identifyForm "senden" $ renderBootstrap3 BootstrapBasicForm $ aufgabeEinsendenForm (checkEinsendung server signed') atyp $ Just $ fromMaybe beispiel mvorherigeEinsendung
let hochladenForm = formToWidget (EinsendungAnlegenR aufgabeId) $ Just hochladen
eingebenForm = formToWidget (EinsendungAnlegenR aufgabeId) $ Just eingeben
mbewertung' <- getBewertung server signed' mfile
let mbewertung = fmap snd mbewertung'
mvorlageForm <- fmap Just $ generateFormPost $ identifyForm (pack $ show aktion) $ renderBootstrap3 BootstrapBasicForm vorlageForm
mlog <- logSchreiben mstudent aufgabe aufgabeId aufgabenstellung mbewertung' mfile
defaultLayout $
$(widgetFile "einsendungAnlegen")
einsendungHochladenForm :: AForm Handler FileInfo
einsendungHochladenForm =
areq fileField "Datei Hochladen" Nothing
<* bootstrapSubmit (BootstrapSubmit MsgLösungAbsenden "btn-success" [])
vorlageForm :: AForm Handler ()
vorlageForm =
let actionType v = [("name", pack $ show aktion), ("value", pack $ show v)]
in bootstrapSubmit (BootstrapSubmit MsgBeispielLaden "btn-primary" $ actionType BeispielLaden)
*> bootstrapSubmit (BootstrapSubmit MsgVorherigeEinsendungLaden "btn-primary" $ actionType VorherigeEinsendungLaden)
einsendenId :: Text
einsendenId = "einsenden"
checkEinsendung :: ServerUrl -> Signed (Task, Instance) -> Text -> Handler (Either Description (Documented Double))
checkEinsendung server signedAufgabe einsendung = do
sprache <- getBevorzugteSprache
lift $ grade_task_solution_localized (unpack server) signedAufgabe (SString $ unpack einsendung) sprache
aufgabeEinsendenForm :: ToMarkup t => (Text -> Handler (Either a b)) -> t -> Maybe Text -> AForm Handler Text
aufgabeEinsendenForm checkMethode typ meinsendung =
aopt (preField typ) (bfs MsgAufgabeLösungTyp) {fsAttrs = []} Nothing
*> areq einsendenField (addAttrs $ bfs MsgLösung) meinsendung
<* bootstrapSubmit (BootstrapSubmit MsgLösungAbsenden "btn-success" [])
where
addAttrs field = field {
fsAttrs = ("rows", pack . show $ 2 + maybe 0 (length . lines) meinsendung) : fsAttrs field,
fsName = Just einsendenId
}
einsendenField = checkMMap (\ (Textarea einsendung) -> do
check' <- checkMethode einsendung
case check' of
Left _ -> return $ Left MsgEinsendungFalsch
Right _ -> return $ Right einsendung
) Textarea textareaField
getCrc :: T.VNr -> Maybe T.ANr -> T.MNr -> Integer
getCrc vnr manr matrikel = fromIntegral $ crc32 (fromString (show vnr ++ show manr ++ T.toString matrikel) :: ByteString)
getAufgabeInstanz :: ServerUrl -> Signed (Task, Config) -> Integer -> Handler (Signed (Task, Instance), Text, Html, Html)
getAufgabeInstanz server signed crc = do
sprache <- getBevorzugteSprache
(signed', DString aufgabenstellung, einsendung) <- lift $ get_task_instance_localized (unpack server) signed (show crc) sprache
let SString einsendung' = contents einsendung
DString atyp = documentation einsendung
atyp' = specialize sprache $ render $ xmlStringToOutput atyp
aufgabenstellung' = specialize sprache $ render $ xmlStringToOutput aufgabenstellung
return (signed', pack einsendung', atyp', aufgabenstellung')
getMaybeEinsendung :: Maybe FileInfo -> Handler (Maybe Text)
getMaybeEinsendung mfile = runMaybeT $ do
meinsendung <- case mfile of
Just r -> lift $ fmap (Just . toStrict . decodeUtf8) $ fileSource r $$ sinkLbs
Nothing -> lookupPostParam einsendenId
MaybeT . return $ meinsendung
getBewertung :: ServerUrl -> Signed (Task, Instance) -> Maybe FileInfo -> Handler (Maybe (Maybe Integer, Html))
getBewertung server signed mfile = runMaybeT $ do
sprache <- getBevorzugteSprache
meinsendung <- lift $ getMaybeEinsendung mfile
einsendung <- MaybeT . return $ meinsendung
bewertung <- lift $ checkEinsendung server signed einsendung
let DString beschreibung = either id documentation bewertung
hinweis' = specialize sprache $ render $ xmlStringToOutput beschreibung
hinweis'' = hinweis' ! class_ ( either (const "alert-danger") (const "alert-success") bewertung)
mwert = either (const Nothing) (Just . round . contents) bewertung
return (mwert, hinweis'')
getVorherigeEinsendung :: Maybe (Entity Student) -> Aufgabe -> AufgabeId -> Handler (Maybe Text)
getVorherigeEinsendung mstudent aufgabe aufgabeId = runMaybeT $ do
let stringToMaybeText t = if null t then Nothing else Just $ pack t
student <- MaybeT . return $ mstudent
mvorherigeEinsendung <- lift $ lift $ Store.latest Store.Input (getDefaultParam (entityVal student) (entityKey student) aufgabe aufgabeId)
`Exception.catch` \ (Exception.SomeException _) -> return []
MaybeT . return $ stringToMaybeText mvorherigeEinsendung
logSchreiben :: Maybe (Entity Student) -> Aufgabe -> AufgabeId -> Html -> Maybe (Maybe Integer, Html) -> Maybe FileInfo -> Handler (Maybe Text)
logSchreiben mstudent aufgabe aufgabeId aufgabenstellung mbewertung mfile = runMaybeT $ do
bewertung <- MaybeT . return $ mbewertung
student <- MaybeT . return $ mstudent
meinsendung <- lift $ getMaybeEinsendung mfile
einsendung <- MaybeT . return $ meinsendung
lift $ lift $ pack <$> bank (getDefaultParam (entityVal student) (entityKey student) aufgabe aufgabeId) {
P.minstant = Just aufgabenstellung,
P.input = Just $ unpack einsendung,
P.report = Just $ snd bewertung,
P.mresult = Just $ maybe T.No T.ok $ fst bewertung
}
getDefaultParam :: Student -> StudentId -> Aufgabe -> AufgabeId -> P.Type
getDefaultParam student studentId aufgabe aufgabeId =
P.Param { P.makers = [],
P.mmatrikel = Just $ T.MNr $ unpack $ studentMatrikelNummer student,
P.ident = T.SNr $ keyToInt studentId,
P.mpasswort = Nothing,
P.aufgabe = T.Name $ unpack $ aufgabeName aufgabe,
P.typ = T.Typ $ unpack $ aufgabeTyp aufgabe,
P.anr = T.ANr $ keyToInt aufgabeId,
P.vnr = T.VNr $ keyToInt $ aufgabeVorlesungId aufgabe,
P.highscore = aufgabeHighscore aufgabe,
P.minstant = Nothing,
P.input = Nothing,
P.report = Nothing,
P.mresult = Nothing,
P.wahl = "",
P.click = Example,
P.input_width = 80,
P.conf = error "Param.empty.conf",
P.remark = error "Param.empty.remark",
P.variante = error "Param.empty.variante",
P.names = []
}
| marcellussiegburg/autotool | yesod/Handler/EinsendungAnlegen.hs | gpl-2.0 | 10,149 | 0 | 18 | 1,798 | 3,122 | 1,579 | 1,543 | -1 | -1 |
{-# language ParallelListComp #-}
-- | Module 'ErrorProp' is used to calculate error propagation in
-- non-linear systems
module Math.ErrorProp
(Measurement
, Fn, Transf
, mkTransf
, (+-), measurement, measurementCov
, getCovariance, getValues
, variables
, defVar
, x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11
, apply
, linError
, partial
, simplify
)
where
import Control.Applicative
import Data.List
import Data.Function
import Math.Symbolic
import Math.SimpleMx
import Data.List.Split (chunksOf)
type Fn = Expr Double
data Transf = Nt [Fn] [[Fn]] -- ^ non linear transformaton
-- | Measurementment represented by measured value(s) and corresponding
-- covariance matrix
data Measurement = Measurement (Vec Double) (Mx Double)
deriving (Eq)
instance (Show Transf) where
show (Nt fs _) = intercalate "\n" $ zipWith (\a b -> a ++ " = " ++ b)
(map show ys)
(map show fs)
where
ys = map (Symbol.('o':).show) [1..] :: [Fn]
instance (Show Measurement) where
show (Measurement x mSigma)
| mSigma == mD = showv (toList x) d
| otherwise = showm (toList x) mSigma
where
d = takeDiag mSigma
mD = diag d
showv xs sigmas = "measurement [\n" ++
intercalate ",\n"
[ " " ++ show x ++ " +- " ++ show s
| x <- xs
| s <- toList $ fmap ((*3) . sqrt) sigmas] ++ "]"
showm xs sigmas = "measurement [\n" ++
intercalate "\n"
[ " " ++ show x ++ " +- " ++ show s ++ " -- " ++ (show covC)
| x <- xs
| covC <- toLists $ sigmas
| s <- fmap ((*3) . sqrt) $ toList . takeDiag $ sigmas] ++ "\n]"
errorSize x s = error $ "Input length mismatch. length(x) = " ++ show (length x)
++ ", but length(s) or one of its components isn't"
type M = (Double, Double)
(+-) :: Double -> Double -> M
(+-) = (,)
-- | Constructs a measurement from
-- list of values and 3sigma confidence intervals
measurement :: [M] -> Measurement
measurement xs = m (unzip xs)
where m (a,b) = Measurement (fromList a) (diag bb)
where bb = fromList $ fmap ((**2) . (/3)) b
-- | Constructs a measurement from list of values and their covariance matrix
measurementCov :: [Double] -- ^ measurement
-> [[Double]] -- ^ covariance matrix
-> Measurement
measurementCov x sigmas | any (\y -> length y /= length x) sigmas
|| (length sigmas /= length x) =
errorSize x sigmas
| otherwise = Measurement (fromList x) (fromLists sigmas)
-- | extracts covariance matrix from a measurement
getCovariance :: Measurement -> Mx Double
getCovariance (Measurement _ cov) = cov
-- | extracts values from a measurement
getValues :: Measurement -> Vec Double
getValues (Measurement val _) = val
-- | predefined symbolic values to be used in defining expression
xs@[x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11] =
map (Symbol.('x':).show) [1..11] :: [Fn]
-- | Smart constructor of nonlinear transformation
-- e.g. nt [x1*x1, x2, sin(x3)]
mkTransf :: [Fn] -- ^ A list of functions, one for each output parameter
-> Transf
mkTransf fs = Nt fs1 (jacobian fs1)
where
fs1 = map simplify fs
defVar :: String -> Fn
defVar = var
partial (Nt fs fs') env = Nt (map (partEval env) fs) (map (map (partEval env)) fs')
-- | Calculates Jacobian matrix
jacobian :: [Fn] -> [[Fn]]
jacobian fs = chunksOf n [diff s f | f <- fs, s <- xs']
where
n = length xs'
xs' = uniqSym $ concatMap variablesOf fs
variables :: Transf -> [Fn]
variables (Nt fs _) = uniqSym $
concatMap variablesOf fs
uniqSym :: (Eq a, Ord a) => [Expr a] -> [Expr a]
uniqSym fs =
nubBy ((==) `on` getSym) $
sortBy (compare `on` getSym) $ fs
where
getSym (Symbol a) = a
getSym _ = error "not a symbol"
-- | Evaluates non-linear transformation at operation point
operatingPoint :: Transf -> [(Fn, Double)] -> (Vec Double, Mx Double)
operatingPoint (Nt fs fs') env =
(fromList $ map (eval env) fs,
fromLists $ map (map (eval env)) fs')
-- | Applies non-linear transformation to sample
apply :: Transf -> Measurement -> Measurement
apply nlt@(Nt fs _) (Measurement x mS) = Measurement f (mL >< mS >< trans mL)
where (f,mL) = operatingPoint nlt (zip (variables nlt) $ toList x)
-- | Calculates calculation error from linearization of transformation
linError :: Transf -> Measurement -> Vec Double
linError nlt@(Nt fs j) (Measurement x mS) =
f1 - (f0 + (mL >. sigmas))
where
sigmas = fmap sqrt $ takeDiag mS
vars = variables nlt
x' = x + sigmas
(f0, mL) = operatingPoint nlt (zip vars $ toList x)
(f1, _) = operatingPoint nlt (zip vars $ toList x')
| hepek/ErrorProp | src/Math/ErrorProp.hs | gpl-2.0 | 4,975 | 23 | 13 | 1,456 | 1,511 | 845 | 666 | 103 | 2 |
import Probability
model = do
xs <- iid 10 (normal 0.0 1.0)
let ys = map (\x -> x * x) xs
return ["xs" %=% xs, "squares" %=% ys, "sum" %=% sum ys]
main = do
mcmc model
| bredelings/BAli-Phy | tests/prob_prog/demos/2/Main.hs | gpl-2.0 | 197 | 0 | 13 | 67 | 96 | 47 | 49 | 7 | 1 |
{-# LANGUAGE GADTs, NoMonomorphismRestriction, FlexibleInstances, DeriveDataTypeable #-}
module Specify.Expression where
import Autolib.Set
import Autolib.TES.Identifier
import Autolib.ToDoc
import Autolib.Reader
import Autolib.Size
import Text.ParserCombinators.Parsec
import Text.ParserCombinators.Parsec.Expr hiding ( Operator )
import Data.Typeable
data Expression a where
Constant :: ToDoc a => a -> Expression a
Undefined :: Expression a
-- Variable :: Identifier -> Expression Integer
Apply :: Identifier -> [ Expression Integer ] -> Expression Integer
Plus :: Expression Integer -> Expression Integer -> Expression Integer
Minus :: Expression Integer -> Expression Integer -> Expression Integer
Negate :: Expression Integer -> Expression Integer
Times :: Expression Integer -> Expression Integer -> Expression Integer
Quotient :: Expression Integer -> Expression Integer -> Expression Integer
Remainder :: Expression Integer -> Expression Integer -> Expression Integer
-- Forall :: Set Identifier -> Expression Bool -> Expression Bool
Less :: Expression Integer -> Expression Integer -> Expression Bool
LessEqual :: Expression Integer -> Expression Integer -> Expression Bool
Equal :: ( Eq a, ToDoc a ) => Expression a -> Expression a -> Expression Bool
GreaterEqual :: Expression Integer -> Expression Integer -> Expression Bool
Greater :: Expression Integer -> Expression Integer -> Expression Bool
NotEqual :: ( Eq a, ToDoc a ) => Expression a -> Expression a -> Expression Bool
And :: Expression Bool -> Expression Bool -> Expression Bool
Or :: Expression Bool -> Expression Bool -> Expression Bool
Implies :: Expression Bool -> Expression Bool -> Expression Bool
Equiv :: Expression Bool -> Expression Bool -> Expression Bool
Not :: Expression Bool -> Expression Bool
Branch :: Expression Bool -> Expression a -> Expression a -> Expression a
deriving Typeable
instance ToDoc a => ToDoc ( Expression a ) where
toDocPrec p x = case x of
Constant a -> toDoc a
-- Variable v -> toDoc v
Undefined -> text "?"
Apply fun args -> toDoc fun <+> case args of
[] -> empty
_ -> parens ( Autolib.ToDoc.sepBy comma $ map toDoc args )
Plus x y -> docParen ( p > 5 ) $ hsep [ toDocPrec 5 x, text "+", toDocPrec 6 y ]
Minus x y -> docParen ( p > 5 ) $ hsep [ toDocPrec 5 x, text "-", toDocPrec 6 y ]
Negate x -> docParen ( p > 9 ) $ hsep [ text "-", toDocPrec 9 x ]
Times x y -> docParen ( p > 7 ) $ hsep [ toDocPrec 7 x, text "*", toDocPrec 8 y ]
Quotient x y -> docParen ( p > 7 ) $ hsep [ toDocPrec 7 x, text "/", toDocPrec 8 y ]
Remainder x y -> docParen ( p > 7 ) $ hsep [ toDocPrec 7 x, text "%", toDocPrec 8 y ]
-- Forall xs y -> docParen ( p > 1 )
-- $ hsep [ text "forall", hsep $ map toDoc $ setToList xs, text ".", toDocPrec 1 y ]
Branch c y z -> vcat [ text "if" <+> toDoc c, text "then" <+> toDoc y, text "else" <+> toDoc z ]
Less x y -> docParen ( p > 5 ) $ hsep [ toDocPrec 5 x, text "<", toDocPrec 5 y ]
LessEqual x y -> docParen ( p > 5 ) $ hsep [ toDocPrec 5 x, text "<=", toDocPrec 5 y ]
Equal x y -> docParen ( p > 5 ) $ hsep [ toDocPrec 5 x, text "==", toDocPrec 5 y ]
GreaterEqual x y ->docParen (p> 5 ) $ hsep [ toDocPrec 5 x, text ">=", toDocPrec 5 y ]
Greater x y -> docParen ( p > 5 ) $ hsep [ toDocPrec 5 x, text ">", toDocPrec 5 y ]
NotEqual x y -> docParen ( p > 5 ) $ hsep [ toDocPrec 5 x, text "!=", toDocPrec 5 y ]
Or x y -> docParen ( p > 1 ) $ hsep [ toDocPrec 1 x, text "||", toDocPrec 2 y ]
And x y -> docParen ( p > 3 ) $ hsep [ toDocPrec 3 x, text "&&", toDocPrec 4 y ]
Implies x y -> docParen ( p > 2 ) $ hsep [ toDocPrec 2 x, text "==>", toDocPrec 3 y ]
Equiv x y -> docParen ( p > 2 ) $ hsep [ toDocPrec 2 x, text "<==>", toDocPrec 3 y ]
Not x -> docParen ( p > 4 ) $ hsep [ text "!", toDocPrec 8 x ]
instance Size ( Expression a ) where
size x = case x of
Constant a -> 1
Undefined -> 1
Apply fun args -> 1 + sum ( map size args )
Plus x y -> 1 + size x + size y
Minus x y -> 1 + size x + size y
Negate x -> 1 + size x
Times x y -> 1 + size x + size y
Quotient x y -> 1 + size x + size y
Remainder x y -> 1 + size x + size y
-- Forall xs y -> docParen ( p > 1 )
-- $ hsep [ text "forall", hsep $ map toDoc $ setToList xs, text ".", toDocPrec 1 y ]
Branch c y z -> 1 + size c + size y + size z
Less x y -> 1 + size x + size y
LessEqual x y -> 1 + size x + size y
Equal x y -> 1 + size x + size y
GreaterEqual x y ->1 + size x + size y
Greater x y -> 1 + size x + size y
NotEqual x y -> 1 + size x + size y
Or x y -> 1 + size x + size y
And x y -> 1 + size x + size y
Implies x y -> 1 + size x + size y
Not x -> 1 + size x
instance Reader ( Expression Bool ) where
reader =
let binop name f assoc =
Infix ( do { my_symbol name; return $ f } ) assoc
unop name f =
Prefix ( do { my_symbol name; return $ f } )
in buildExpressionParser
[ [ binop "==>" Implies AssocNone ]
, [ binop "<==>" Equiv AssocNone
, binop "!=" NotEqual AssocNone
]
, [ binop "||" Or AssocLeft ]
, [ binop "&&" And AssocLeft ]
, [ unop "!" Not ]
]
( try ( my_parens reader )
<|> do my_symbol "?" ; return Undefined
<|> do my_reserved "true" ; return $ Constant True
<|> do my_reserved "false" ; return $ Constant False
<|> branch
<|> comparison
)
comparison = do
x <- reader
op <- foldr1 (<|>) $ do
( name, val ) <- [ ("<=", LessEqual ), ( "<", Less ) , ("==", Equal )
, ( ">=", GreaterEqual), (">", Greater), ("!=", NotEqual)
]
return $ do
try $ my_symbol name
return val
y <- reader
return $ op x y
instance Reader ( Expression Integer ) where
reader =
let binop name f assoc =
Infix ( do { my_symbol name; return $ f } ) assoc
unop name f =
Prefix ( do { my_symbol name; return $ f } )
in buildExpressionParser
[ [ unop "-" Negate ]
, [ binop "*" Times AssocLeft
, binop "/" Quotient AssocLeft
, binop "%" Remainder AssocLeft
]
, [ binop "+" Plus AssocLeft
, binop "-" Minus AssocLeft
]
]
( my_parens reader
<|> do my_symbol "?" ; return Undefined
<|> do i <- my_integer ; return $ Constant i
<|> application
<|> branch
)
branch = do
my_reserved "if"
c <- reader
my_reserved "then"
y <- reader
my_reserved "else"
z <- reader
return $ Branch c y z
application = do
fun <- ident
args <- option [] $ my_parens $ Autolib.Reader.sepBy reader my_comma
return $ Apply fun args
ident = fmap mkunary my_identifier
| Erdwolf/autotool-bonn | src/Specify/Expression.hs | gpl-2.0 | 7,248 | 163 | 16 | 2,349 | 1,450 | 903 | 547 | 140 | 1 |
module Solver where
import Data.Maybe (mapMaybe, fromJust)
import Data.List (minimumBy)
import Control.Monad (liftM)
import Grid
import Queue
import Relation
import Graph
import Set
newSolve :: Grid -> Maybe [Direction]
newSolve grid = findPath properGraph
where
graph = mapStates (\stateInfo -> (stateInfo, Nothing)) $ toGraph grid
acceptingIds = Queue.fromList $ Graph.getAcceptingStates graph
markStates :: Queue Id -> Graph (StateInfo, Maybe Int) Direction -> Graph (StateInfo, Maybe Int) Direction
markStates queue graph =
case Queue.remove queue of
Nothing -> graph
Just (id, queue') -> markStates queue'' graph'
where
fromIds = Prelude.map (fst . Relation.unpackRelPair) $ Set.toList $ transitionsTo id graph
mark :: (StateInfo, Maybe Int) -> Maybe (StateInfo, Maybe Int)
mark (stateInfo, Nothing) = Just (stateInfo, Just $ 1 + (fromJust $ snd $ fromJust $ dataFromId id graph))
mark _ = Nothing
folder :: Id -> (Queue Id, Graph (StateInfo, Maybe Int) Direction) -> (Queue Id, Graph (StateInfo, Maybe Int) Direction)
folder fromId (q, g) = (if modified then q' else q, g')
where
(modified, g') = modifyState fromId mark g
q' = Queue.insert fromId q
(queue'', graph') = foldr folder (queue', graph) fromIds
properGraph = markStates acceptingIds graph
findPath :: Graph (StateInfo, Maybe Int) Direction -> Maybe [Direction]
findPath graph = search (Graph.getStartingState graph)
where
search :: Id -> Maybe [Direction]
search current =
if current `Prelude.elem` getAcceptingStates graph
then Just []
else
case bestDir of
Nothing -> Nothing
Just (id, dir) -> liftM (dir :) $ search id
where
relPairs = Set.toList $ transitionsFrom current graph
comparator (RelPair (id1, _)) (RelPair (id2, _)) =
case (snd $ fromJust $ dataFromId id1 graph, snd $ fromJust $ dataFromId id2 graph) of
(Nothing, Nothing) -> EQ
(Nothing, _) -> GT
(_, Nothing) -> LT
(Just x, Just y) -> compare x y
bestDir =
case relPairs of
[] -> Nothing
_ ->
case minimumBy comparator relPairs of
RelPair (id, dir) ->
case (snd $ fromJust $ dataFromId id graph) of
Nothing -> Nothing
_ -> Just (id, dir)
solve grid = findPath (getStartingState graph) Set.empty
where
graph = toGraph grid
findPath stateId pathStates
| Graph.isAccepting stateId graph = Just []
| otherwise =
case subResults of
[] -> Nothing
_ -> Just $ minimumBy (\a b -> compare (length a) (length b)) subResults
where
nextTransitions = Prelude.map (\(RelPair (a, b)) -> (a, b)) $ Set.toList $ transitionsFrom stateId graph
nextValidTransitions = filter (\(id, _) -> not $ Set.elem id pathStates) nextTransitions
newPathStates = Set.insert stateId pathStates
subResults = mapMaybe (\(id, dir) -> liftM (dir :) $ findPath id newPathStates) nextValidTransitions | mkm/sokoban | src/Solver.hs | gpl-3.0 | 3,737 | 0 | 21 | 1,460 | 1,129 | 592 | 537 | 65 | 11 |
-- Exercise 3
type Stack = [Char]
type State = Stack
newtype ST a = S (State -> (a, State))
app :: ST a -> State -> (a, State)
app (S st) x = st x
instance Monad ST where
st >>= f = S(\s -> let (x,s') = app st s
in app (f x) s')
instance Functor ST where
fmap g st = do x <- st
return (g x)
instance Applicative ST where
pure x = S (\s -> (x, s))
stf <*> stx = do f <- stf
x <- stx
return (f x)
| mdipirro/functional-languages-homeworks | Week 11/Exercise3.hs | gpl-3.0 | 499 | 0 | 13 | 202 | 251 | 128 | 123 | 16 | 1 |
-- | Alle meine Entchen
module Songs.AlleMeineEntchen where
import Songs.Fun
import Euterpea
-- | Melody of /Alle meine Entchen/ put together
entchenMelody :: Music Pitch
entchenMelody = e1 :+: e2 :+: e3 :+: e4 :+: e5
-- | Melody of /Alle meine Entchen/ as list of primitive values
entchenList :: [Music Pitch]
entchenList = musicToList entchenMelody
-- | Single part of /Alle meine Entchen/'s melody
e1,e2,e3,e4,e5 :: Music Pitch
e1 = addDur qn [c 4, d 4, e 4, f 4]
e2 = g 4 hn :+: g 4 hn
e3 = timesM 4 (a 4 qn) :+: (g 4 wn)
e4 = timesM 4 (f 4 qn) :+: timesM 2 (e 4 hn)
e5 = timesM 4 (g 4 qn) :+: c 4 wn | flofehrenbacher/music-project | EasyNotes/Songs/AlleMeineEntchen.hs | gpl-3.0 | 610 | 0 | 8 | 130 | 227 | 121 | 106 | 13 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{- |
Module : Postmaster.FSM.EventHandler
Copyright : (c) 2004-2008 by Peter Simons
License : GPL2
Maintainer : simons@cryp.to
Stability : provisional
Portability : Haskell 2-pre
-}
module Postmaster.FSM.EventHandler where
import Data.Typeable
import Postmaster.Base
import Text.ParserCombinators.Parsec.Rfc2821
newtype EH = EH EventHandler
deriving (Typeable)
-- |This variable /must/ be initialized in the global
-- environment or Postmaster won't do much.
eventHandler :: Variable
eventHandler = mkVar "eventhandler"
setEventHandler :: EventHandler -> EnvT ()
setEventHandler = setVar eventHandler . EH
getEventHandler :: Smtpd EventHandler
getEventHandler = do
EH f <- local (getVar eventHandler)
>>= maybe (global $ getVar_ eventHandler) return
return f
-- |Trigger the given event.
trigger :: Event -> Smtpd SmtpReply
trigger e = getEventHandler >>= ($ e)
| richardfontana/postmaster | Postmaster/FSM/EventHandler.hs | gpl-3.0 | 968 | 0 | 12 | 191 | 168 | 91 | 77 | 18 | 1 |
{-# LANGUAGE ScopedTypeVariables, TypeFamilies #-}
module Math.Jalla.VectorSpace
( ) where
import Data.VectorSpace
import Math.Vector
import Math.InnerProduct
instance (InnerProduct o f) => InnerSpace o where
Scalar o :: f
a <.> b = innerProduct a b
instance AdditiveGroup (CVector (vec e) e) where
zeroV = -- ... and here is where it breaks. I can not give a zero vector of unknown length.
| cgo/jalla | Math/Jalla/VectorSpace.hs | gpl-3.0 | 406 | 2 | 9 | 77 | 95 | 52 | 43 | -1 | -1 |
module Main where
import Application.FilterStats.FilterStats
import Application.GMM.ConvertPVPGMMConduit
import Control.Monad as M
import Control.Monad.Trans.Resource
import Data.Conduit
import Data.Conduit.Binary as CB
import Data.Conduit.List as CL
import Prelude as P
import System.Environment
main = do
(inputFile:_) <- getArgs
xs <- runResourceT (sourceFile inputFile $$ featureConduit =$= CL.consume)
M.zipWithM_
(\x i ->
plotHist
x
(valueRange x)
100
(show i P.++ " " P.++ show (meanVar x))
(show i P.++ ".png"))
xs
[1 ..]
| XinhuaZhang/PetaVisionHaskell | Application/FilterStats/Main.hs | gpl-3.0 | 786 | 0 | 15 | 325 | 188 | 106 | 82 | 23 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE GeneralisedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
module Schema.UnknownPredictions.V1 where
import Database.Persist.TH (persistUpperCase)
import qualified Database.Persist.TH as TH
import Schema.Utils (EntityDef, ForeignDef)
import qualified Schema.Utils as Utils
import Schema.Algorithm (AlgorithmId)
import Schema.Model (PredictionModelId)
import Schema.Implementation (ImplementationId)
TH.share [TH.mkPersist TH.sqlSettings, TH.mkSave "schema'"] [persistUpperCase|
UnknownPrediction
modelId PredictionModelId
algorithmId AlgorithmId
count Int
deriving Eq Show
UnknownSet
unknownPredId UnknownPredictionId
implId ImplementationId
algorithmId AlgorithmId
Primary unknownPredId implId
deriving Eq Show
|]
schema :: [EntityDef]
schema = Utils.addForeignRef "UnknownPrediction" model
. Utils.addForeignRef "UnknownSet" unknownPred
$ schema'
where
model :: ForeignDef
model = Utils.mkForeignRef "PredictionModel"
[ ("modelId", "id"), ("algorithmId", "algorithmId") ]
unknownPred :: ForeignDef
unknownPred = Utils.mkForeignRef "UnknownPrediction"
[ ("unknownPredId", "id"), ("algorithmId", "algorithmId") ]
| merijn/GPU-benchmarks | benchmark-analysis/src/Schema/UnknownPredictions/V1.hs | gpl-3.0 | 1,615 | 0 | 9 | 247 | 231 | 143 | 88 | 33 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Hie.Language.Haskell.Exts.Pretty
-- Copyright : (c) Niklas Broberg 2004-2009,
-- (c) The GHC Team, Noel Winstanley 1997-2000
-- License : BSD-style (see the file LICENSE.txt)
--
-- Maintainer : Niklas Broberg, d00nibro@chalmers.se
-- Stability : stable
-- Portability : portable
--
-- Pretty printer for Haskell with extensions.
--
-----------------------------------------------------------------------------
module Hie.Language.Haskell.Exts.Pretty (
-- * Pretty printing
Pretty,
prettyPrintStyleMode, prettyPrintWithMode, prettyPrint,
-- * Pretty-printing styles (from "Text.PrettyPrint.HughesPJ")
P.Style(..), P.style, P.Mode(..),
-- * Haskell formatting modes
PPHsMode(..), Indent, PPLayout(..), defaultMode) where
import Hie.Language.Haskell.Exts.Syntax
import qualified Hie.Language.Haskell.Exts.Annotated.Syntax as A
import Hie.Language.Haskell.Exts.Annotated.Simplify
import qualified Hie.Language.Haskell.Exts.ParseSyntax as P
import Hie.Language.Haskell.Exts.SrcLoc
import qualified Text.PrettyPrint as P
import Data.List (intersperse)
infixl 5 $$$
-----------------------------------------------------------------------------
-- | Varieties of layout we can use.
data PPLayout = PPOffsideRule -- ^ classical layout
| PPSemiColon -- ^ classical layout made explicit
| PPInLine -- ^ inline decls, with newlines between them
| PPNoLayout -- ^ everything on a single line
deriving Eq
type Indent = Int
-- | Pretty-printing parameters.
--
-- /Note:/ the 'onsideIndent' must be positive and less than all other indents.
data PPHsMode = PPHsMode {
-- | indentation of a class or instance
classIndent :: Indent,
-- | indentation of a @do@-expression
doIndent :: Indent,
-- | indentation of the body of a
-- @case@ expression
caseIndent :: Indent,
-- | indentation of the declarations in a
-- @let@ expression
letIndent :: Indent,
-- | indentation of the declarations in a
-- @where@ clause
whereIndent :: Indent,
-- | indentation added for continuation
-- lines that would otherwise be offside
onsideIndent :: Indent,
-- | blank lines between statements?
spacing :: Bool,
-- | Pretty-printing style to use
layout :: PPLayout,
-- | add GHC-style @LINE@ pragmas to output?
linePragmas :: Bool
}
-- | The default mode: pretty-print using the offside rule and sensible
-- defaults.
defaultMode :: PPHsMode
defaultMode = PPHsMode{
classIndent = 8,
doIndent = 3,
caseIndent = 4,
letIndent = 4,
whereIndent = 6,
onsideIndent = 2,
spacing = True,
layout = PPOffsideRule,
linePragmas = False
}
-- | Pretty printing monad
newtype DocM s a = DocM (s -> a)
instance Functor (DocM s) where
fmap f xs = do x <- xs; return (f x)
instance Monad (DocM s) where
(>>=) = thenDocM
(>>) = then_DocM
return = retDocM
{-# INLINE thenDocM #-}
{-# INLINE then_DocM #-}
{-# INLINE retDocM #-}
{-# INLINE unDocM #-}
{-# INLINE getPPEnv #-}
thenDocM :: DocM s a -> (a -> DocM s b) -> DocM s b
thenDocM m k = DocM $ (\s -> case unDocM m $ s of a -> unDocM (k a) $ s)
then_DocM :: DocM s a -> DocM s b -> DocM s b
then_DocM m k = DocM $ (\s -> case unDocM m $ s of _ -> unDocM k $ s)
retDocM :: a -> DocM s a
retDocM a = DocM (\_s -> a)
unDocM :: DocM s a -> (s -> a)
unDocM (DocM f) = f
-- all this extra stuff, just for this one function.
getPPEnv :: DocM s s
getPPEnv = DocM id
-- So that pp code still looks the same
-- this means we lose some generality though
-- | The document type produced by these pretty printers uses a 'PPHsMode'
-- environment.
type Doc = DocM PPHsMode P.Doc
-- | Things that can be pretty-printed, including all the syntactic objects
-- in "Hie.Language.Haskell.Exts.Syntax" and "Hie.Language.Haskell.Exts.Annotated.Syntax".
class Pretty a where
-- | Pretty-print something in isolation.
pretty :: a -> Doc
-- | Pretty-print something in a precedence context.
prettyPrec :: Int -> a -> Doc
pretty = prettyPrec 0
prettyPrec _ = pretty
-- The pretty printing combinators
empty :: Doc
empty = return P.empty
nest :: Int -> Doc -> Doc
nest i m = m >>= return . P.nest i
-- Literals
text, ptext :: String -> Doc
text = return . P.text
ptext = return . P.text
char :: Char -> Doc
char = return . P.char
int :: Int -> Doc
int = return . P.int
integer :: Integer -> Doc
integer = return . P.integer
float :: Float -> Doc
float = return . P.float
double :: Double -> Doc
double = return . P.double
rational :: Rational -> Doc
rational = return . P.rational
-- Simple Combining Forms
parens, brackets, braces,quotes,doubleQuotes :: Doc -> Doc
parens d = d >>= return . P.parens
brackets d = d >>= return . P.brackets
braces d = d >>= return . P.braces
quotes d = d >>= return . P.quotes
doubleQuotes d = d >>= return . P.doubleQuotes
parensIf :: Bool -> Doc -> Doc
parensIf True = parens
parensIf False = id
-- Constants
semi,comma,colon,space,equals :: Doc
semi = return P.semi
comma = return P.comma
colon = return P.colon
space = return P.space
equals = return P.equals
lparen,rparen,lbrack,rbrack,lbrace,rbrace :: Doc
lparen = return P.lparen
rparen = return P.rparen
lbrack = return P.lbrack
rbrack = return P.rbrack
lbrace = return P.lbrace
rbrace = return P.rbrace
-- Combinators
(<>),(<+>),($$),($+$) :: Doc -> Doc -> Doc
aM <> bM = do{a<-aM;b<-bM;return (a P.<> b)}
aM <+> bM = do{a<-aM;b<-bM;return (a P.<+> b)}
aM $$ bM = do{a<-aM;b<-bM;return (a P.$$ b)}
aM $+$ bM = do{a<-aM;b<-bM;return (a P.$+$ b)}
hcat,hsep,vcat,sep,cat,fsep,fcat :: [Doc] -> Doc
hcat dl = sequence dl >>= return . P.hcat
hsep dl = sequence dl >>= return . P.hsep
vcat dl = sequence dl >>= return . P.vcat
sep dl = sequence dl >>= return . P.sep
cat dl = sequence dl >>= return . P.cat
fsep dl = sequence dl >>= return . P.fsep
fcat dl = sequence dl >>= return . P.fcat
-- Some More
hang :: Doc -> Int -> Doc -> Doc
hang dM i rM = do{d<-dM;r<-rM;return $ P.hang d i r}
-- Yuk, had to cut-n-paste this one from Pretty.hs
punctuate :: Doc -> [Doc] -> [Doc]
punctuate _ [] = []
punctuate p (d1:ds) = go d1 ds
where
go d [] = [d]
go d (e:es) = (d <> p) : go e es
-- | render the document with a given style and mode.
renderStyleMode :: P.Style -> PPHsMode -> Doc -> String
renderStyleMode ppStyle ppMode d = P.renderStyle ppStyle . unDocM d $ ppMode
-- | render the document with a given mode.
renderWithMode :: PPHsMode -> Doc -> String
renderWithMode = renderStyleMode P.style
-- | render the document with 'defaultMode'.
render :: Doc -> String
render = renderWithMode defaultMode
-- | pretty-print with a given style and mode.
prettyPrintStyleMode :: Pretty a => P.Style -> PPHsMode -> a -> String
prettyPrintStyleMode ppStyle ppMode = renderStyleMode ppStyle ppMode . pretty
-- | pretty-print with the default style and a given mode.
prettyPrintWithMode :: Pretty a => PPHsMode -> a -> String
prettyPrintWithMode = prettyPrintStyleMode P.style
-- | pretty-print with the default style and 'defaultMode'.
prettyPrint :: Pretty a => a -> String
prettyPrint = prettyPrintWithMode defaultMode
fullRenderWithMode :: PPHsMode -> P.Mode -> Int -> Float ->
(P.TextDetails -> a -> a) -> a -> Doc -> a
fullRenderWithMode ppMode m i f fn e mD =
P.fullRender m i f fn e $ (unDocM mD) ppMode
fullRender :: P.Mode -> Int -> Float -> (P.TextDetails -> a -> a)
-> a -> Doc -> a
fullRender = fullRenderWithMode defaultMode
------------------------- Pretty-Print a Module --------------------
instance Pretty Module where
pretty (Module pos m os mbWarn mbExports imp decls) =
markLine pos $
myVcat $ map pretty os ++
(if m == ModuleName "" then id
else \x -> [topLevel (ppModuleHeader m mbWarn mbExports) x])
(map pretty imp ++ map pretty decls)
-------------------------- Module Header ------------------------------
ppModuleHeader :: ModuleName -> Maybe WarningText -> Maybe [ExportSpec] -> Doc
ppModuleHeader m mbWarn mbExportList = mySep [
text "module",
pretty m,
maybePP ppWarnTxt mbWarn,
maybePP (parenList . map pretty) mbExportList,
text "where"]
ppWarnTxt :: WarningText -> Doc
ppWarnTxt (DeprText s) = mySep [text "{-# DEPRECATED", text s, text "#-}"]
ppWarnTxt (WarnText s) = mySep [text "{-# WARNING", text s, text "#-}"]
instance Pretty ModuleName where
pretty (ModuleName modName) = text modName
instance Pretty ExportSpec where
pretty (EVar name) = pretty name
pretty (EAbs name) = pretty name
pretty (EThingAll name) = pretty name <> text "(..)"
pretty (EThingWith name nameList) =
pretty name <> (parenList . map pretty $ nameList)
pretty (EModuleContents m) = text "module" <+> pretty m
instance Pretty ImportDecl where
pretty (ImportDecl pos m qual src mbPkg mbName mbSpecs) =
markLine pos $
mySep [text "import",
if src then text "{-# SOURCE #-}" else empty,
if qual then text "qualified" else empty,
maybePP (\s -> text (show s)) mbPkg,
pretty m,
maybePP (\m' -> text "as" <+> pretty m') mbName,
maybePP exports mbSpecs]
where
exports (b,specList) =
if b then text "hiding" <+> specs else specs
where specs = parenList . map pretty $ specList
instance Pretty ImportSpec where
pretty (IVar name) = pretty name
pretty (IAbs name) = pretty name
pretty (IThingAll name) = pretty name <> text "(..)"
pretty (IThingWith name nameList) =
pretty name <> (parenList . map pretty $ nameList)
------------------------- Declarations ------------------------------
instance Pretty Decl where
pretty (TypeDecl loc name nameList htype) =
blankline $
markLine loc $
mySep ( [text "type", pretty name]
++ map pretty nameList
++ [equals, pretty htype])
pretty (DataDecl loc don context name nameList constrList derives) =
blankline $
markLine loc $
mySep ( [pretty don, ppContext context, pretty name]
++ map pretty nameList)
<+> (myVcat (zipWith (<+>) (equals : repeat (char '|'))
(map pretty constrList))
$$$ ppDeriving derives)
pretty (GDataDecl loc don context name nameList optkind gadtList derives) =
blankline $
markLine loc $
mySep ( [pretty don, ppContext context, pretty name]
++ map pretty nameList ++ ppOptKind optkind ++ [text "where"])
$$$ ppBody classIndent (map pretty gadtList)
$$$ ppBody letIndent [ppDeriving derives]
pretty (TypeFamDecl loc name nameList optkind) =
blankline $
markLine loc $
mySep ([text "type", text "family", pretty name]
++ map pretty nameList
++ ppOptKind optkind)
pretty (DataFamDecl loc context name nameList optkind) =
blankline $
markLine loc $
mySep ( [text "data", text "family", ppContext context, pretty name]
++ map pretty nameList ++ ppOptKind optkind)
pretty (TypeInsDecl loc ntype htype) =
blankline $
markLine loc $
mySep [text "type", text "instance", pretty ntype, equals, pretty htype]
pretty (DataInsDecl loc don ntype constrList derives) =
blankline $
markLine loc $
mySep [pretty don, text "instance", pretty ntype]
<+> (myVcat (zipWith (<+>) (equals : repeat (char '|'))
(map pretty constrList))
$$$ ppDeriving derives)
pretty (GDataInsDecl loc don ntype optkind gadtList derives) =
blankline $
markLine loc $
mySep ( [pretty don, text "instance", pretty ntype]
++ ppOptKind optkind ++ [text "where"])
$$$ ppBody classIndent (map pretty gadtList)
$$$ ppDeriving derives
--m{spacing=False}
-- special case for empty class declaration
pretty (ClassDecl pos context name nameList fundeps []) =
blankline $
markLine pos $
mySep ( [text "class", ppContext context, pretty name]
++ map pretty nameList ++ [ppFunDeps fundeps])
pretty (ClassDecl pos context name nameList fundeps declList) =
blankline $
markLine pos $
mySep ( [text "class", ppContext context, pretty name]
++ map pretty nameList ++ [ppFunDeps fundeps, text "where"])
$$$ ppBody classIndent (map pretty declList)
-- m{spacing=False}
-- special case for empty instance declaration
pretty (InstDecl pos context name args []) =
blankline $
markLine pos $
mySep ( [text "instance", ppContext context, pretty name]
++ map ppAType args)
pretty (InstDecl pos context name args declList) =
blankline $
markLine pos $
mySep ( [text "instance", ppContext context, pretty name]
++ map ppAType args ++ [text "where"])
$$$ ppBody classIndent (map pretty declList)
pretty (DerivDecl pos context name args) =
blankline $
markLine pos $
mySep ( [text "deriving", text "instance", ppContext context, pretty name]
++ map ppAType args)
pretty (DefaultDecl pos htypes) =
blankline $
markLine pos $
text "default" <+> parenList (map pretty htypes)
pretty (SpliceDecl pos splice) =
blankline $
markLine pos $
pretty splice
pretty (TypeSig pos nameList qualType) =
blankline $
markLine pos $
mySep ((punctuate comma . map pretty $ nameList)
++ [text "::", pretty qualType])
pretty (FunBind matches) = do
e <- fmap layout getPPEnv
case e of PPOffsideRule -> foldr ($$$) empty (map pretty matches)
_ -> foldr (\x y -> x <> semi <> y) empty (map pretty matches)
pretty (PatBind pos pat optsig rhs whereBinds) =
markLine pos $
myFsep [pretty pat, maybePP ppSig optsig, pretty rhs] $$$ ppWhere whereBinds
pretty (InfixDecl pos assoc prec opList) =
blankline $
markLine pos $
mySep ([pretty assoc, int prec]
++ (punctuate comma . map pretty $ opList))
pretty (ForImp pos cconv saf str name typ) =
blankline $
markLine pos $
mySep [text "foreign import", pretty cconv, pretty saf,
text (show str), pretty name, text "::", pretty typ]
pretty (ForExp pos cconv str name typ) =
blankline $
markLine pos $
mySep [text "foreign export", pretty cconv,
text (show str), pretty name, text "::", pretty typ]
pretty (RulePragmaDecl pos rules) =
blankline $
markLine pos $
myVcat $ text "{-# RULES" : map pretty rules ++ [text " #-}"]
pretty (DeprPragmaDecl pos deprs) =
blankline $
markLine pos $
myVcat $ text "{-# DEPRECATED" : map ppWarnDepr deprs ++ [text " #-}"]
pretty (WarnPragmaDecl pos deprs) =
blankline $
markLine pos $
myVcat $ text "{-# WARNING" : map ppWarnDepr deprs ++ [text " #-}"]
pretty (InlineSig pos inl activ name) =
blankline $
markLine pos $
mySep [text (if inl then "{-# INLINE" else "{-# NOINLINE"), pretty activ, pretty name, text "#-}"]
pretty (InlineConlikeSig pos activ name) =
blankline $
markLine pos $
mySep [text "{-# INLINE_CONLIKE", pretty activ, pretty name, text "#-}"]
pretty (SpecSig pos name types) =
blankline $
markLine pos $
mySep $ [text "{-# SPECIALISE", pretty name, text "::"]
++ punctuate comma (map pretty types) ++ [text "#-}"]
pretty (SpecInlineSig pos inl activ name types) =
blankline $
markLine pos $
mySep $ [text "{-# SPECIALISE", text (if inl then "INLINE" else "NOINLINE"),
pretty activ, pretty name, text "::"]
++ (punctuate comma $ map pretty types) ++ [text "#-}"]
pretty (InstSig pos context name args) =
blankline $
markLine pos $
mySep $ [text "{-# SPECIALISE", text "instance", ppContext context, pretty name]
++ map ppAType args ++ [text "#-}"]
pretty (AnnPragma pos ann) =
blankline $
markLine pos $
mySep $ [text "{-# ANN", pretty ann, text "#-}"]
instance Pretty Annotation where
pretty (Ann n e) = myFsep [pretty n, pretty e]
pretty (TypeAnn n e) = myFsep [text "type", pretty n, pretty e]
pretty (ModuleAnn e) = myFsep [text "module", pretty e]
instance Pretty DataOrNew where
pretty DataType = text "data"
pretty NewType = text "newtype"
instance Pretty Assoc where
pretty AssocNone = text "infix"
pretty AssocLeft = text "infixl"
pretty AssocRight = text "infixr"
instance Pretty Match where
pretty (Match pos f ps optsig rhs whereBinds) =
markLine pos $
myFsep (lhs ++ [maybePP ppSig optsig, pretty rhs])
$$$ ppWhere whereBinds
where
lhs = case ps of
l:r:ps' | isSymbolName f ->
let hd = [pretty l, ppName f, pretty r] in
if null ps' then hd
else parens (myFsep hd) : map (prettyPrec 2) ps'
_ -> pretty f : map (prettyPrec 2) ps
ppWhere :: Binds -> Doc
ppWhere (BDecls []) = empty
ppWhere (BDecls l) = nest 2 (text "where" $$$ ppBody whereIndent (map pretty l))
ppWhere (IPBinds b) = nest 2 (text "where" $$$ ppBody whereIndent (map pretty b))
ppSig :: Type -> Doc
ppSig t = text "::" <+> pretty t
instance Pretty ClassDecl where
pretty (ClsDecl decl) = pretty decl
pretty (ClsDataFam loc context name nameList optkind) =
markLine loc $
mySep ( [text "data", ppContext context, pretty name]
++ map pretty nameList ++ ppOptKind optkind)
pretty (ClsTyFam loc name nameList optkind) =
markLine loc $
mySep ( [text "type", pretty name]
++ map pretty nameList ++ ppOptKind optkind)
pretty (ClsTyDef loc ntype htype) =
markLine loc $
mySep [text "type", pretty ntype, equals, pretty htype]
instance Pretty InstDecl where
pretty (InsDecl decl) = pretty decl
pretty (InsType loc ntype htype) =
markLine loc $
mySep [text "type", pretty ntype, equals, pretty htype]
pretty (InsData loc don ntype constrList derives) =
markLine loc $
mySep [pretty don, pretty ntype]
<+> (myVcat (zipWith (<+>) (equals : repeat (char '|'))
(map pretty constrList))
$$$ ppDeriving derives)
pretty (InsGData loc don ntype optkind gadtList derives) =
markLine loc $
mySep ( [pretty don, pretty ntype]
++ ppOptKind optkind ++ [text "where"])
$$$ ppBody classIndent (map pretty gadtList)
$$$ ppDeriving derives
-- pretty (InsInline loc inl activ name) =
-- markLine loc $
-- mySep [text (if inl then "{-# INLINE" else "{-# NOINLINE"), pretty activ, pretty name, text "#-}"]
------------------------- FFI stuff -------------------------------------
instance Pretty Safety where
pretty PlayRisky = text "unsafe"
pretty (PlaySafe b) = text $ if b then "threadsafe" else "safe"
instance Pretty CallConv where
pretty StdCall = text "stdcall"
pretty CCall = text "ccall"
------------------------- Pragmas ---------------------------------------
ppWarnDepr :: ([Name], String) -> Doc
ppWarnDepr (names, txt) = mySep $ (punctuate comma $ map pretty names) ++ [text $ show txt]
instance Pretty Rule where
pretty (Rule tag activ rvs rhs lhs) =
mySep $ [text $ show tag, pretty activ,
maybePP ppRuleVars rvs,
pretty rhs, char '=', pretty lhs]
ppRuleVars :: [RuleVar] -> Doc
ppRuleVars [] = empty
ppRuleVars rvs = mySep $ text "forall" : map pretty rvs ++ [char '.']
instance Pretty Activation where
pretty AlwaysActive = empty
pretty (ActiveFrom i) = char '[' <> int i <> char ']'
pretty (ActiveUntil i) = text "[~" <> int i <> char ']'
instance Pretty RuleVar where
pretty (RuleVar n) = pretty n
pretty (TypedRuleVar n t) = parens $ mySep [pretty n, text "::", pretty t]
instance Pretty ModulePragma where
pretty (LanguagePragma _ ns) =
myFsep $ text "{-# LANGUAGE" : punctuate (char ',') (map pretty ns) ++ [text "#-}"]
pretty (OptionsPragma _ (Just tool) s) =
myFsep $ [text "{-# OPTIONS_" <> pretty tool, text s, text "#-}"]
pretty (OptionsPragma _ _ s) =
myFsep $ [text "{-# OPTIONS", text s, text "#-}"]
pretty (AnnModulePragma _ ann) =
myFsep $ [text "{-# ANN", pretty ann, text "#-}"]
instance Pretty Tool where
pretty (UnknownTool s) = text s
pretty t = text $ show t
------------------------- Data & Newtype Bodies -------------------------
instance Pretty QualConDecl where
pretty (QualConDecl _pos tvs ctxt con) =
myFsep [ppForall (Just tvs), ppContext ctxt, pretty con]
instance Pretty GadtDecl where
pretty (GadtDecl _pos name ty) =
myFsep [pretty name, text "::", pretty ty]
instance Pretty ConDecl where
pretty (RecDecl name fieldList) =
pretty name <> (braceList . map ppField $ fieldList)
{- pretty (ConDecl name@(Symbol _) [l, r]) =
myFsep [prettyPrec prec_btype l, ppName name,
prettyPrec prec_btype r] -}
pretty (ConDecl name typeList) =
mySep $ ppName name : map (prettyPrec prec_atype) typeList
pretty (InfixConDecl l name r) =
myFsep [prettyPrec prec_btype l, ppNameInfix name,
prettyPrec prec_btype r]
ppField :: ([Name],BangType) -> Doc
ppField (names, ty) =
myFsepSimple $ (punctuate comma . map pretty $ names) ++
[text "::", pretty ty]
instance Pretty BangType where
prettyPrec _ (BangedTy ty) = char '!' <> ppAType ty
prettyPrec p (UnBangedTy ty) = prettyPrec p ty
prettyPrec p (UnpackedTy ty) = text "{-# UNPACK #-}" <+> char '!' <> prettyPrec p ty
ppDeriving :: [Deriving] -> Doc
ppDeriving [] = empty
ppDeriving [(d, [])] = text "deriving" <+> ppQName d
ppDeriving ds = text "deriving" <+> parenList (map ppDer ds)
where ppDer :: (QName, [Type]) -> Doc
ppDer (n, ts) = mySep (pretty n : map pretty ts)
------------------------- Types -------------------------
ppBType :: Type -> Doc
ppBType = prettyPrec prec_btype
ppAType :: Type -> Doc
ppAType = prettyPrec prec_atype
-- precedences for types
prec_btype, prec_atype :: Int
prec_btype = 1 -- left argument of ->,
-- or either argument of an infix data constructor
prec_atype = 2 -- argument of type or data constructor, or of a class
instance Pretty Type where
prettyPrec p (TyForall mtvs ctxt htype) = parensIf (p > 0) $
myFsep [ppForall mtvs, ppContext ctxt, pretty htype]
prettyPrec p (TyFun a b) = parensIf (p > 0) $
myFsep [ppBType a, text "->", pretty b]
prettyPrec _ (TyTuple bxd l) =
let ds = map pretty l
in case bxd of
Boxed -> parenList ds
Unboxed -> hashParenList ds
prettyPrec _ (TyList t) = brackets $ pretty t
prettyPrec p (TyApp a b) =
{-
| a == list_tycon = brackets $ pretty b -- special case
| otherwise = -} parensIf (p > prec_btype) $
myFsep [pretty a, ppAType b]
prettyPrec _ (TyVar name) = pretty name
prettyPrec _ (TyCon name) = pretty name
prettyPrec _ (TyParen t) = parens (pretty t)
-- prettyPrec _ (TyPred asst) = pretty asst
prettyPrec _ (TyInfix a op b) = myFsep [pretty a, ppQNameInfix op, pretty b]
prettyPrec _ (TyKind t k) = parens (myFsep [pretty t, text "::", pretty k])
prettyPrec _ (TySplice s) = pretty s
instance Pretty TyVarBind where
pretty (KindedVar var kind) = parens $ myFsep [pretty var, text "::", pretty kind]
pretty (UnkindedVar var) = pretty var
ppForall :: Maybe [TyVarBind] -> Doc
ppForall Nothing = empty
ppForall (Just []) = empty
ppForall (Just vs) = myFsep (text "forall" : map pretty vs ++ [char '.'])
---------------------------- Kinds ----------------------------
instance Pretty Kind where
prettyPrec _ KindStar = text "*"
prettyPrec _ KindBang = text "!"
prettyPrec n (KindFn a b) = parensIf (n > 0) $ myFsep [prettyPrec 1 a, text "->", pretty b]
prettyPrec _ (KindParen k) = parens $ pretty k
prettyPrec _ (KindVar n) = pretty n
ppOptKind :: Maybe Kind -> [Doc]
ppOptKind Nothing = []
ppOptKind (Just k) = [text "::", pretty k]
------------------- Functional Dependencies -------------------
instance Pretty FunDep where
pretty (FunDep from to) =
myFsep $ map pretty from ++ [text "->"] ++ map pretty to
ppFunDeps :: [FunDep] -> Doc
ppFunDeps [] = empty
ppFunDeps fds = myFsep $ (char '|':) . punctuate comma . map pretty $ fds
------------------------- Expressions -------------------------
instance Pretty Rhs where
pretty (UnGuardedRhs e) = equals <+> pretty e
pretty (GuardedRhss guardList) = myVcat . map pretty $ guardList
instance Pretty GuardedRhs where
pretty (GuardedRhs _pos guards ppBody) =
myFsep $ [char '|'] ++ (punctuate comma . map pretty $ guards) ++ [equals, pretty ppBody]
instance Pretty Literal where
pretty (Int i) = integer i
pretty (Char c) = text (show c)
pretty (String s) = text (show s)
pretty (Frac r) = double (fromRational r)
-- GHC unboxed literals:
pretty (PrimChar c) = text (show c) <> char '#'
pretty (PrimString s) = text (show s) <> char '#'
pretty (PrimInt i) = integer i <> char '#'
pretty (PrimWord w) = integer w <> text "##"
pretty (PrimFloat r) = float (fromRational r) <> char '#'
pretty (PrimDouble r) = double (fromRational r) <> text "##"
instance Pretty Exp where
prettyPrec _ (Lit l) = pretty l
-- lambda stuff
prettyPrec p (InfixApp a op b) = parensIf (p > 2) $ myFsep [prettyPrec 2 a, pretty op, prettyPrec 1 b]
prettyPrec p (NegApp e) = parensIf (p > 0) $ char '-' <> prettyPrec 4 e
prettyPrec p (App a b) = parensIf (p > 3) $ myFsep [prettyPrec 3 a, prettyPrec 4 b]
prettyPrec p (Lambda _loc patList ppBody) = parensIf (p > 1) $ myFsep $
char '\\' : map pretty patList ++ [text "->", pretty ppBody]
-- keywords
-- two cases for lets
prettyPrec p (Let (BDecls declList) letBody) =
parensIf (p > 1) $ ppLetExp declList letBody
prettyPrec p (Let (IPBinds bindList) letBody) =
parensIf (p > 1) $ ppLetExp bindList letBody
prettyPrec p (If cond thenexp elsexp) = parensIf (p > 1) $
myFsep [text "if", pretty cond,
text "then", pretty thenexp,
text "else", pretty elsexp]
prettyPrec p (Case cond altList) = parensIf (p > 1) $
myFsep [text "case", pretty cond, text "of"]
$$$ ppBody caseIndent (map pretty altList)
prettyPrec p (Do stmtList) = parensIf (p > 1) $
text "do" $$$ ppBody doIndent (map pretty stmtList)
prettyPrec p (MDo stmtList) = parensIf (p > 1) $
text "mdo" $$$ ppBody doIndent (map pretty stmtList)
-- Constructors & Vars
prettyPrec _ (Var name) = pretty name
prettyPrec _ (IPVar ipname) = pretty ipname
prettyPrec _ (Con name) = pretty name
prettyPrec _ (Tuple b expList) = parenList . map pretty $ expList
prettyPrec _ (TupleSection b mExpList) = parenList . map (maybePP pretty) $ mExpList
-- weird stuff
prettyPrec _ (Paren e) = parens . pretty $ e
prettyPrec _ (LeftSection e op) = parens (pretty e <+> pretty op)
prettyPrec _ (RightSection op e) = parens (pretty op <+> pretty e)
prettyPrec _ (RecConstr c fieldList) =
pretty c <> (braceList . map pretty $ fieldList)
prettyPrec _ (RecUpdate e fieldList) =
pretty e <> (braceList . map pretty $ fieldList)
-- Lists
prettyPrec _ (List list) =
bracketList . punctuate comma . map pretty $ list
prettyPrec _ (EnumFrom e) =
bracketList [pretty e, text ".."]
prettyPrec _ (EnumFromTo from to) =
bracketList [pretty from, text "..", pretty to]
prettyPrec _ (EnumFromThen from thenE) =
bracketList [pretty from <> comma, pretty thenE, text ".."]
prettyPrec _ (EnumFromThenTo from thenE to) =
bracketList [pretty from <> comma, pretty thenE,
text "..", pretty to]
prettyPrec _ (ListComp e qualList) =
bracketList ([pretty e, char '|']
++ (punctuate comma . map pretty $ qualList))
prettyPrec _ (ParComp e qualLists) =
bracketList (intersperse (char '|') $
pretty e : (punctuate comma . concatMap (map pretty) $ qualLists))
prettyPrec p (ExpTypeSig _pos e ty) = parensIf (p > 0) $
myFsep [pretty e, text "::", pretty ty]
-- Template Haskell
prettyPrec _ (BracketExp b) = pretty b
prettyPrec _ (SpliceExp s) = pretty s
prettyPrec _ (TypQuote t) = text "\'\'" <> pretty t
prettyPrec _ (VarQuote x) = text "\'" <> pretty x
prettyPrec _ (QuasiQuote n qt) = text ("[$" ++ n ++ "|" ++ qt ++ "|]")
-- Hsx
prettyPrec _ (XTag _ n attrs mattr cs) =
let ax = maybe [] (return . pretty) mattr
in hcat $
(myFsep $ (char '<' <> pretty n): map pretty attrs ++ ax ++ [char '>']):
map pretty cs ++ [myFsep $ [text "</" <> pretty n, char '>']]
prettyPrec _ (XETag _ n attrs mattr) =
let ax = maybe [] (return . pretty) mattr
in myFsep $ (char '<' <> pretty n): map pretty attrs ++ ax ++ [text "/>"]
prettyPrec _ (XPcdata s) = text s
prettyPrec _ (XExpTag e) =
myFsep $ [text "<%", pretty e, text "%>"]
prettyPrec _ (XChildTag _ cs) =
myFsep $ text "<%>" : map pretty cs ++ [text "</%>"]
-- Pragmas
prettyPrec p (CorePragma s e) = myFsep $ map text ["{-# CORE", show s, "#-}"] ++ [pretty e]
prettyPrec _ (SCCPragma s e) = myFsep $ map text ["{-# SCC", show s, "#-}"] ++ [pretty e]
prettyPrec _ (GenPragma s (a,b) (c,d) e) =
myFsep $ [text "{-# GENERATED", text $ show s,
int a, char ':', int b, char '-',
int c, char ':', int d, text "#-}", pretty e]
-- Arrows
prettyPrec p (Proc _ pat e) = parensIf (p > 1) $ myFsep $ [text "proc", pretty pat, text "->", pretty e]
prettyPrec p (LeftArrApp l r) = parensIf (p > 0) $ myFsep $ [pretty l, text "-<", pretty r]
prettyPrec p (RightArrApp l r) = parensIf (p > 0) $ myFsep $ [pretty l, text ">-", pretty r]
prettyPrec p (LeftArrHighApp l r) = parensIf (p > 0) $ myFsep $ [pretty l, text "-<<", pretty r]
prettyPrec p (RightArrHighApp l r) = parensIf (p > 0) $ myFsep $ [pretty l, text ">>-", pretty r]
instance Pretty XAttr where
pretty (XAttr n v) =
myFsep [pretty n, char '=', pretty v]
instance Pretty XName where
pretty (XName n) = text n
pretty (XDomName d n) = text d <> char ':' <> text n
--ppLetExp :: [Decl] -> Exp -> Doc
ppLetExp l b = myFsep [text "let" <+> ppBody letIndent (map pretty l),
text "in", pretty b]
ppWith binds = nest 2 (text "with" $$$ ppBody withIndent (map pretty binds))
withIndent = whereIndent
--------------------- Template Haskell -------------------------
instance Pretty Bracket where
pretty (ExpBracket e) = ppBracket "[|" e
pretty (PatBracket p) = ppBracket "[p|" p
pretty (TypeBracket t) = ppBracket "[t|" t
pretty (DeclBracket d) =
myFsep $ text "[d|" : map pretty d ++ [text "|]"]
ppBracket o x = myFsep [text o, pretty x, text "|]"]
instance Pretty Splice where
pretty (IdSplice s) = char '$' <> text s
pretty (ParenSplice e) =
myFsep [text "$(", pretty e, char ')']
------------------------- Patterns -----------------------------
instance Pretty Pat where
prettyPrec _ (PVar name) = pretty name
prettyPrec _ (PLit lit) = pretty lit
prettyPrec p (PNeg pat) = parensIf (p > 0) $ myFsep [char '-', pretty pat]
prettyPrec p (PInfixApp a op b) = parensIf (p > 0) $
myFsep [prettyPrec 1 a, pretty (QConOp op), prettyPrec 1 b]
prettyPrec p (PApp n ps) = parensIf (p > 1 && not (null ps)) $
myFsep (pretty n : map (prettyPrec 2) ps)
prettyPrec _ (PTuple b ps) = parenList . map pretty $ ps
prettyPrec _ (PList ps) =
bracketList . punctuate comma . map pretty $ ps
prettyPrec _ (PParen pat) = parens . pretty $ pat
prettyPrec _ (PRec c fields) =
pretty c <> (braceList . map pretty $ fields)
-- special case that would otherwise be buggy
prettyPrec _ (PAsPat name (PIrrPat pat)) =
myFsep [pretty name <> char '@', char '~' <> prettyPrec 2 pat]
prettyPrec _ (PAsPat name pat) =
hcat [pretty name, char '@', prettyPrec 2 pat]
prettyPrec _ PWildCard = char '_'
prettyPrec _ (PIrrPat pat) = char '~' <> prettyPrec 2 pat
prettyPrec p (PatTypeSig _pos pat ty) = parensIf (p > 0) $
myFsep [pretty pat, text "::", pretty ty]
prettyPrec p (PViewPat e pat) = parensIf (p > 0) $
myFsep [pretty e, text "->", pretty pat]
prettyPrec p (PNPlusK n k) = parensIf (p > 0) $
myFsep [pretty n, text "+", text $ show k]
-- HaRP
prettyPrec _ (PRPat rs) =
bracketList . punctuate comma . map pretty $ rs
-- Hsx
prettyPrec _ (PXTag _ n attrs mattr cp) =
let ap = maybe [] (return . pretty) mattr
in hcat $ -- TODO: should not introduce blanks
(myFsep $ (char '<' <> pretty n): map pretty attrs ++ ap ++ [char '>']):
map pretty cp ++ [myFsep $ [text "</" <> pretty n, char '>']]
prettyPrec _ (PXETag _ n attrs mattr) =
let ap = maybe [] (return . pretty) mattr
in myFsep $ (char '<' <> pretty n): map pretty attrs ++ ap ++ [text "/>"]
prettyPrec _ (PXPcdata s) = text s
prettyPrec _ (PXPatTag p) =
myFsep $ [text "<%", pretty p, text "%>"]
prettyPrec _ (PXRPats ps) =
myFsep $ text "<[" : map pretty ps ++ [text "%>"]
-- Generics
prettyPrec _ (PExplTypeArg qn t) =
myFsep [pretty qn, text "{|", pretty t, text "|}"]
-- BangPatterns
prettyPrec _ (PBangPat pat) = text "!" <> prettyPrec 2 pat
instance Pretty PXAttr where
pretty (PXAttr n p) =
myFsep [pretty n, char '=', pretty p]
instance Pretty PatField where
pretty (PFieldPat name pat) =
myFsep [pretty name, equals, pretty pat]
pretty (PFieldPun name) = pretty name
pretty (PFieldWildcard) = text ".."
--------------------- Regular Patterns -------------------------
instance Pretty RPat where
pretty (RPOp r op) = pretty r <> pretty op
pretty (RPEither r1 r2) = parens . myFsep $
[pretty r1, char '|', pretty r2]
pretty (RPSeq rs) =
myFsep $ text "(/" : map pretty rs ++ [text "/)"]
pretty (RPGuard r gs) =
myFsep $ text "(|" : pretty r : char '|' : map pretty gs ++ [text "|)"]
-- special case that would otherwise be buggy
pretty (RPCAs n (RPPat (PIrrPat p))) =
myFsep [pretty n <> text "@:", char '~' <> pretty p]
pretty (RPCAs n r) = hcat [pretty n, text "@:", pretty r]
-- special case that would otherwise be buggy
pretty (RPAs n (RPPat (PIrrPat p))) =
myFsep [pretty n <> text "@:", char '~' <> pretty p]
pretty (RPAs n r) = hcat [pretty n, char '@', pretty r]
pretty (RPPat p) = pretty p
pretty (RPParen rp) = parens . pretty $ rp
instance Pretty RPatOp where
pretty RPStar = char '*'
pretty RPStarG = text "*!"
pretty RPPlus = char '+'
pretty RPPlusG = text "+!"
pretty RPOpt = char '?'
pretty RPOptG = text "?!"
------------------------- Case bodies -------------------------
instance Pretty Alt where
pretty (Alt _pos e gAlts binds) =
pretty e <+> pretty gAlts $$$ ppWhere binds
instance Pretty GuardedAlts where
pretty (UnGuardedAlt e) = text "->" <+> pretty e
pretty (GuardedAlts altList) = myVcat . map pretty $ altList
instance Pretty GuardedAlt where
pretty (GuardedAlt _pos guards body) =
myFsep $ char '|': (punctuate comma . map pretty $ guards) ++ [text "->", pretty body]
------------------------- Statements in monads, guards & list comprehensions -----
instance Pretty Stmt where
pretty (Generator _loc e from) =
pretty e <+> text "<-" <+> pretty from
pretty (Qualifier e) = pretty e
-- two cases for lets
pretty (LetStmt (BDecls declList)) =
ppLetStmt declList
pretty (LetStmt (IPBinds bindList)) =
ppLetStmt bindList
pretty (RecStmt stmtList) =
text "rec" $$$ ppBody letIndent (map pretty stmtList)
ppLetStmt l = text "let" $$$ ppBody letIndent (map pretty l)
instance Pretty QualStmt where
pretty (QualStmt s) = pretty s
pretty (ThenTrans f) = myFsep $ [text "then", pretty f]
pretty (ThenBy f e) = myFsep $ [text "then", pretty f, text "by", pretty e]
pretty (GroupBy e) = myFsep $ [text "then", text "group", text "by", pretty e]
pretty (GroupUsing f) = myFsep $ [text "then", text "group", text "using", pretty f]
pretty (GroupByUsing e f) = myFsep $ [text "then", text "group", text "by",
pretty e, text "using", pretty f]
------------------------- Record updates
instance Pretty FieldUpdate where
pretty (FieldUpdate name e) =
myFsep [pretty name, equals, pretty e]
pretty (FieldPun name) = pretty name
pretty (FieldWildcard) = text ".."
------------------------- Names -------------------------
instance Pretty QOp where
pretty (QVarOp n) = ppQNameInfix n
pretty (QConOp n) = ppQNameInfix n
ppQNameInfix :: QName -> Doc
ppQNameInfix name
| isSymbolName (getName name) = ppQName name
| otherwise = char '`' <> ppQName name <> char '`'
instance Pretty QName where
pretty name = case name of
UnQual (Symbol ('#':_)) -> char '(' <+> ppQName name <+> char ')'
_ -> parensIf (isSymbolName (getName name)) (ppQName name)
ppQName :: QName -> Doc
ppQName (UnQual name) = ppName name
ppQName (Qual m name) = pretty m <> char '.' <> ppName name
ppQName (Special sym) = text (specialName sym)
instance Pretty Op where
pretty (VarOp n) = ppNameInfix n
pretty (ConOp n) = ppNameInfix n
ppNameInfix :: Name -> Doc
ppNameInfix name
| isSymbolName name = ppName name
| otherwise = char '`' <> ppName name <> char '`'
instance Pretty Name where
pretty name = case name of
Symbol ('#':_) -> char '(' <+> ppName name <+> char ')'
_ -> parensIf (isSymbolName name) (ppName name)
ppName :: Name -> Doc
ppName (Ident s) = text s
ppName (Symbol s) = text s
instance Pretty IPName where
pretty (IPDup s) = char '?' <> text s
pretty (IPLin s) = char '%' <> text s
instance Pretty IPBind where
pretty (IPBind _loc ipname exp) =
myFsep [pretty ipname, equals, pretty exp]
instance Pretty CName where
pretty (VarName n) = pretty n
pretty (ConName n) = pretty n
instance Pretty SpecialCon where
pretty sc = text $ specialName sc
isSymbolName :: Name -> Bool
isSymbolName (Symbol _) = True
isSymbolName _ = False
getName :: QName -> Name
getName (UnQual s) = s
getName (Qual _ s) = s
getName (Special Cons) = Symbol ":"
getName (Special FunCon) = Symbol "->"
getName (Special s) = Ident (specialName s)
specialName :: SpecialCon -> String
specialName UnitCon = "()"
specialName ListCon = "[]"
specialName FunCon = "->"
specialName (TupleCon b n) = "(" ++ hash ++ replicate (n-1) ',' ++ hash ++ ")"
where hash = if b == Unboxed then "#" else ""
specialName Cons = ":"
ppContext :: Context -> Doc
ppContext [] = empty
ppContext context = mySep [parenList (map pretty context), text "=>"]
-- hacked for multi-parameter type classes
instance Pretty Asst where
pretty (ClassA a ts) = myFsep $ ppQName a : map ppAType ts
pretty (InfixA a op b) = myFsep $ [pretty a, ppQNameInfix op, pretty b]
pretty (IParam i t) = myFsep $ [pretty i, text "::", pretty t]
pretty (EqualP t1 t2) = myFsep $ [pretty t1, text "~", pretty t2]
-- Pretty print a source location, useful for printing out error messages
instance Pretty SrcLoc where
pretty srcLoc =
return $ P.hsep [ colonFollow (P.text $ srcFilename srcLoc)
, colonFollow (P.int $ srcLine srcLoc)
, P.int $ srcColumn srcLoc
]
colonFollow p = P.hcat [ p, P.colon ]
instance Pretty SrcSpan where
pretty srcSpan =
return $ P.hsep [ colonFollow (P.text $ srcSpanFilename srcSpan)
, P.hcat [ P.text "("
, P.int $ srcSpanStartLine srcSpan
, P.colon
, P.int $ srcSpanStartColumn srcSpan
, P.text ")"
]
, P.text "-"
, P.hcat [ P.text "("
, P.int $ srcSpanEndLine srcSpan
, P.colon
, P.int $ srcSpanEndColumn srcSpan
, P.text ")"
]
]
---------------------------------------------------------------------
-- Annotated version
------------------------- Pretty-Print a Module --------------------
instance SrcInfo pos => Pretty (A.Module pos) where
pretty (A.Module pos mbHead os imp decls) =
markLine pos $
myVcat $ map pretty os ++
(case mbHead of
Nothing -> id
Just h -> \x -> [topLevel (pretty h) x])
(map pretty imp ++ map pretty decls)
pretty (A.XmlPage pos _mn os n attrs mattr cs) =
markLine pos $
myVcat $ map pretty os ++
[let ax = maybe [] (return . pretty) mattr
in hcat $
(myFsep $ (char '<' <> pretty n): map pretty attrs ++ ax ++ [char '>']):
map pretty cs ++ [myFsep $ [text "</" <> pretty n, char '>']]]
pretty (A.XmlHybrid pos mbHead os imp decls n attrs mattr cs) =
markLine pos $
myVcat $ map pretty os ++ [text "<%"] ++
(case mbHead of
Nothing -> id
Just h -> \x -> [topLevel (pretty h) x])
(map pretty imp ++ map pretty decls ++
[let ax = maybe [] (return . pretty) mattr
in hcat $
(myFsep $ (char '<' <> pretty n): map pretty attrs ++ ax ++ [char '>']):
map pretty cs ++ [myFsep $ [text "</" <> pretty n, char '>']]])
-------------------------- Module Header ------------------------------
instance Pretty (A.ModuleHead l) where
pretty (A.ModuleHead _ m mbWarn mbExportList) = mySep [
text "module",
pretty m,
maybePP pretty mbWarn,
maybePP pretty mbExportList,
text "where"]
instance Pretty (A.WarningText l) where
pretty = ppWarnTxt. sWarningText
instance Pretty (A.ModuleName l) where
pretty = pretty . sModuleName
instance Pretty (A.ExportSpecList l) where
pretty (A.ExportSpecList _ especs) = parenList $ map pretty especs
instance Pretty (A.ExportSpec l) where
pretty = pretty . sExportSpec
instance SrcInfo pos => Pretty (A.ImportDecl pos) where
pretty = pretty . sImportDecl
instance Pretty (A.ImportSpecList l) where
pretty (A.ImportSpecList _ b ispecs) =
(if b then text "hiding" else empty)
<+> parenList (map pretty ispecs)
instance Pretty (A.ImportSpec l) where
pretty = pretty . sImportSpec
------------------------- Declarations ------------------------------
instance SrcInfo pos => Pretty (A.Decl pos) where
pretty = pretty . sDecl
instance Pretty (A.DeclHead l) where
pretty (A.DHead l n tvs) = mySep (pretty n : map pretty tvs)
pretty (A.DHInfix l tva n tvb) = mySep [pretty tva, pretty n, pretty tvb]
pretty (A.DHParen l dh) = parens (pretty dh)
instance (SrcInfo l) => Pretty (A.InstHead l) where
pretty (A.IHead l qn ts) = mySep (pretty qn : map pretty ts)
pretty (A.IHInfix l ta qn tb) = mySep [pretty ta, pretty qn, pretty tb]
pretty (A.IHParen l ih) = parens (pretty ih)
instance Pretty (A.DataOrNew l) where
pretty = pretty . sDataOrNew
instance Pretty (A.Assoc l) where
pretty = pretty . sAssoc
instance SrcInfo pos => Pretty (A.Match pos) where
pretty = pretty . sMatch
instance SrcInfo loc => Pretty (A.ClassDecl loc) where
pretty = pretty . sClassDecl
instance SrcInfo loc => Pretty (A.InstDecl loc) where
pretty = pretty . sInstDecl
------------------------- FFI stuff -------------------------------------
instance Pretty (A.Safety l) where
pretty = pretty . sSafety
instance Pretty (A.CallConv l) where
pretty = pretty . sCallConv
------------------------- Pragmas ---------------------------------------
instance SrcInfo loc => Pretty (A.Rule loc) where
pretty = pretty . sRule
instance Pretty (A.Activation l) where
pretty = pretty . sActivation
instance (SrcInfo l) => Pretty (A.RuleVar l) where
pretty = pretty . sRuleVar
instance SrcInfo loc => Pretty (A.ModulePragma loc) where
pretty (A.LanguagePragma _ ns) =
myFsep $ text "{-# LANGUAGE" : punctuate (char ',') (map pretty ns) ++ [text "#-}"]
pretty (A.OptionsPragma _ (Just tool) s) =
myFsep $ [text "{-# OPTIONS_" <> pretty tool, text s, text "#-}"]
pretty (A.OptionsPragma _ _ s) =
myFsep $ [text "{-# OPTIONS", text s, text "#-}"]
pretty (A.AnnModulePragma _ ann) =
myFsep $ [text "{-# ANN", pretty ann, text "#-}"]
instance SrcInfo loc => Pretty (A.Annotation loc) where
pretty = pretty . sAnnotation
------------------------- Data & Newtype Bodies -------------------------
instance (SrcInfo l) => Pretty (A.QualConDecl l) where
pretty (A.QualConDecl _pos mtvs ctxt con) =
myFsep [ppForall (fmap (map sTyVarBind) mtvs), ppContext $ maybe [] sContext ctxt, pretty con]
instance (SrcInfo l) => Pretty (A.GadtDecl l) where
pretty (A.GadtDecl _pos name ty) =
myFsep [pretty name, text "::", pretty ty]
instance (SrcInfo l) => Pretty (A.ConDecl l) where
pretty = pretty . sConDecl
instance (SrcInfo l) => Pretty (A.FieldDecl l) where
pretty (A.FieldDecl _ names ty) =
myFsepSimple $ (punctuate comma . map pretty $ names) ++
[text "::", pretty ty]
instance (SrcInfo l) => Pretty (A.BangType l) where
pretty = pretty . sBangType
instance (SrcInfo l) => Pretty (A.Deriving l) where
pretty (A.Deriving _ []) = text "deriving" <+> parenList []
pretty (A.Deriving _ [A.IHead _ d []]) = text "deriving" <+> pretty d
pretty (A.Deriving _ ihs) = text "deriving" <+> parenList (map pretty ihs)
------------------------- Types -------------------------
instance (SrcInfo l) => Pretty (A.Type l) where
pretty = pretty . sType
instance Pretty (A.TyVarBind l) where
pretty = pretty . sTyVarBind
---------------------------- Kinds ----------------------------
instance Pretty (A.Kind l) where
pretty = pretty . sKind
------------------- Functional Dependencies -------------------
instance Pretty (A.FunDep l) where
pretty = pretty . sFunDep
------------------------- Expressions -------------------------
instance SrcInfo loc => Pretty (A.Rhs loc) where
pretty = pretty . sRhs
instance SrcInfo loc => Pretty (A.GuardedRhs loc) where
pretty = pretty . sGuardedRhs
instance Pretty (A.Literal l) where
pretty = pretty . sLiteral
instance SrcInfo loc => Pretty (A.Exp loc) where
pretty = pretty . sExp
instance SrcInfo loc => Pretty (A.XAttr loc) where
pretty = pretty . sXAttr
instance Pretty (A.XName l) where
pretty = pretty . sXName
--------------------- Template Haskell -------------------------
instance SrcInfo loc => Pretty (A.Bracket loc) where
pretty = pretty . sBracket
instance SrcInfo loc => Pretty (A.Splice loc) where
pretty = pretty . sSplice
------------------------- Patterns -----------------------------
instance SrcInfo loc => Pretty (A.Pat loc) where
pretty = pretty . sPat
instance SrcInfo loc => Pretty (A.PXAttr loc) where
pretty = pretty . sPXAttr
instance SrcInfo loc => Pretty (A.PatField loc) where
pretty = pretty . sPatField
--------------------- Regular Patterns -------------------------
instance SrcInfo loc => Pretty (A.RPat loc) where
pretty = pretty . sRPat
instance Pretty (A.RPatOp l) where
pretty = pretty . sRPatOp
------------------------- Case bodies -------------------------
instance SrcInfo loc => Pretty (A.Alt loc) where
pretty = pretty . sAlt
instance SrcInfo loc => Pretty (A.GuardedAlts loc) where
pretty = pretty . sGuardedAlts
instance SrcInfo loc => Pretty (A.GuardedAlt loc) where
pretty = pretty . sGuardedAlt
------------------------- Statements in monads, guards & list comprehensions -----
instance SrcInfo loc => Pretty (A.Stmt loc) where
pretty = pretty . sStmt
instance SrcInfo loc => Pretty (A.QualStmt loc) where
pretty = pretty . sQualStmt
------------------------- Record updates
instance SrcInfo loc => Pretty (A.FieldUpdate loc) where
pretty = pretty . sFieldUpdate
------------------------- Names -------------------------
instance Pretty (A.QOp l) where
pretty = pretty . sQOp
instance Pretty (A.QName l) where
pretty = pretty . sQName
instance Pretty (A.Op l) where
pretty = pretty . sOp
instance Pretty (A.Name l) where
pretty = pretty . sName
instance Pretty (A.IPName l) where
pretty = pretty . sIPName
instance SrcInfo loc => Pretty (A.IPBind loc) where
pretty = pretty . sIPBind
instance Pretty (A.CName l) where
pretty = pretty . sCName
instance (SrcInfo l) => Pretty (A.Context l) where
pretty (A.CxEmpty _) = mySep [text "()", text "=>"]
pretty (A.CxSingle _ asst) = mySep [pretty asst, text "=>"]
pretty (A.CxTuple _ assts) = myFsep $ [parenList (map pretty assts), text "=>"]
pretty (A.CxParen _ asst) = parens (pretty asst)
-- hacked for multi-parameter type classes
instance (SrcInfo l) => Pretty (A.Asst l) where
pretty = pretty . sAsst
------------------------- pp utils -------------------------
maybePP :: (a -> Doc) -> Maybe a -> Doc
maybePP pp Nothing = empty
maybePP pp (Just a) = pp a
parenList :: [Doc] -> Doc
parenList = parens . myFsepSimple . punctuate comma
hashParenList :: [Doc] -> Doc
hashParenList = hashParens . myFsepSimple . punctuate comma
where hashParens = parens . hashes
hashes = \doc -> char '#' <> doc <> char '#'
braceList :: [Doc] -> Doc
braceList = braces . myFsepSimple . punctuate comma
bracketList :: [Doc] -> Doc
bracketList = brackets . myFsepSimple
-- Wrap in braces and semicolons, with an extra space at the start in
-- case the first doc begins with "-", which would be scanned as {-
flatBlock :: [Doc] -> Doc
flatBlock = braces . (space <>) . hsep . punctuate semi
-- Same, but put each thing on a separate line
prettyBlock :: [Doc] -> Doc
prettyBlock = braces . (space <>) . vcat . punctuate semi
-- Monadic PP Combinators -- these examine the env
blankline :: Doc -> Doc
blankline dl = do{e<-getPPEnv;if spacing e && layout e /= PPNoLayout
then space $$ dl else dl}
topLevel :: Doc -> [Doc] -> Doc
topLevel header dl = do
e <- fmap layout getPPEnv
case e of
PPOffsideRule -> header $$ vcat dl
PPSemiColon -> header $$ prettyBlock dl
PPInLine -> header $$ prettyBlock dl
PPNoLayout -> header <+> flatBlock dl
ppBody :: (PPHsMode -> Int) -> [Doc] -> Doc
ppBody f dl = do
e <- fmap layout getPPEnv
case e of PPOffsideRule -> indent
PPSemiColon -> indentExplicit
_ -> flatBlock dl
where
indent = do{i <-fmap f getPPEnv;nest i . vcat $ dl}
indentExplicit = do {i <- fmap f getPPEnv;
nest i . prettyBlock $ dl}
($$$) :: Doc -> Doc -> Doc
a $$$ b = layoutChoice (a $$) (a <+>) b
mySep :: [Doc] -> Doc
mySep = layoutChoice mySep' hsep
where
-- ensure paragraph fills with indentation.
mySep' [x] = x
mySep' (x:xs) = x <+> fsep xs
mySep' [] = error "Internal error: mySep"
myVcat :: [Doc] -> Doc
myVcat = layoutChoice vcat hsep
myFsepSimple :: [Doc] -> Doc
myFsepSimple = layoutChoice fsep hsep
-- same, except that continuation lines are indented,
-- which is necessary to avoid triggering the offside rule.
myFsep :: [Doc] -> Doc
myFsep = layoutChoice fsep' hsep
where fsep' [] = empty
fsep' (d:ds) = do
e <- getPPEnv
let n = onsideIndent e
nest n (fsep (nest (-n) d:ds))
layoutChoice :: (a -> Doc) -> (a -> Doc) -> a -> Doc
layoutChoice a b dl = do e <- getPPEnv
if layout e == PPOffsideRule ||
layout e == PPSemiColon
then a dl else b dl
-- Prefix something with a LINE pragma, if requested.
-- GHC's LINE pragma actually sets the current line number to n-1, so
-- that the following line is line n. But if there's no newline before
-- the line we're talking about, we need to compensate by adding 1.
markLine :: SrcInfo s => s -> Doc -> Doc
markLine loc doc = do
e <- getPPEnv
let y = startLine loc
let line l =
text ("{-# LINE " ++ show l ++ " \"" ++ fileName loc ++ "\" #-}")
if linePragmas e then layoutChoice (line y $$) (line (y+1) <+>) doc
else doc
--------------------------------------------------------------------------------
-- Pretty-printing of internal constructs, for error messages while parsing
instance SrcInfo loc => Pretty (P.PExp loc) where
pretty (P.Lit _ l) = pretty l
pretty (P.InfixApp _ a op b) = myFsep [pretty a, pretty op, pretty b]
pretty (P.NegApp _ e) = myFsep [char '-', pretty e]
pretty (P.App _ a b) = myFsep [pretty a, pretty b]
pretty (P.Lambda _loc expList ppBody) = myFsep $
char '\\' : map pretty expList ++ [text "->", pretty ppBody]
pretty (P.Let _ (A.BDecls _ declList) letBody) =
ppLetExp declList letBody
pretty (P.Let _ (A.IPBinds _ bindList) letBody) =
ppLetExp bindList letBody
pretty (P.If _ cond thenexp elsexp) =
myFsep [text "if", pretty cond,
text "then", pretty thenexp,
text "else", pretty elsexp]
pretty (P.Case _ cond altList) =
myFsep [text "case", pretty cond, text "of"]
$$$ ppBody caseIndent (map pretty altList)
pretty (P.Do _ stmtList) =
text "do" $$$ ppBody doIndent (map pretty stmtList)
pretty (P.MDo _ stmtList) =
text "mdo" $$$ ppBody doIndent (map pretty stmtList)
pretty (P.Var _ name) = pretty name
pretty (P.IPVar _ ipname) = pretty ipname
pretty (P.Con _ name) = pretty name
pretty (P.TupleSection _ b mExpList) = parenList . map (maybePP pretty) $ mExpList
pretty (P.Paren _ e) = parens . pretty $ e
pretty (P.RecConstr _ c fieldList) =
pretty c <> (braceList . map pretty $ fieldList)
pretty (P.RecUpdate _ e fieldList) =
pretty e <> (braceList . map pretty $ fieldList)
pretty (P.List _ list) =
bracketList . punctuate comma . map pretty $ list
pretty (P.EnumFrom _ e) =
bracketList [pretty e, text ".."]
pretty (P.EnumFromTo _ from to) =
bracketList [pretty from, text "..", pretty to]
pretty (P.EnumFromThen _ from thenE) =
bracketList [pretty from <> comma, pretty thenE, text ".."]
pretty (P.EnumFromThenTo _ from thenE to) =
bracketList [pretty from <> comma, pretty thenE,
text "..", pretty to]
pretty (P.ParComp _ e qualLists) =
bracketList (intersperse (char '|') $
pretty e : (punctuate comma . concatMap (map pretty) $ qualLists))
pretty (P.ExpTypeSig _pos e ty) =
myFsep [pretty e, text "::", pretty ty]
pretty (P.BracketExp _ b) = pretty b
pretty (P.SpliceExp _ s) = pretty s
pretty (P.TypQuote _ t) = text "\'\'" <> pretty t
pretty (P.VarQuote _ x) = text "\'" <> pretty x
pretty (P.QuasiQuote _ n qt) = text ("[$" ++ n ++ "|" ++ qt ++ "|]")
pretty (P.XTag _ n attrs mattr cs) =
let ax = maybe [] (return . pretty) mattr
in hcat $
(myFsep $ (char '<' <> pretty n): map pretty attrs ++ ax ++ [char '>']):
map pretty cs ++ [myFsep $ [text "</" <> pretty n, char '>']]
pretty (P.XETag _ n attrs mattr) =
let ax = maybe [] (return . pretty) mattr
in myFsep $ (char '<' <> pretty n): map pretty attrs ++ ax ++ [text "/>"]
pretty (P.XPcdata _ s) = text s
pretty (P.XExpTag _ e) =
myFsep $ [text "<%", pretty e, text "%>"]
pretty (P.XChildTag _ es) =
myFsep $ text "<%>" : map pretty es ++ [text "</%>"]
pretty (P.CorePragma _ s e) = myFsep $ map text ["{-# CORE", show s, "#-}"] ++ [pretty e]
pretty (P.SCCPragma _ s e) = myFsep $ map text ["{-# SCC", show s, "#-}"] ++ [pretty e]
pretty (P.GenPragma _ s (a,b) (c,d) e) =
myFsep $ [text "{-# GENERATED", text $ show s,
int a, char ':', int b, char '-',
int c, char ':', int d, text "#-}", pretty e]
pretty (P.Proc _ p e) = myFsep $ [text "proc", pretty p, text "->", pretty e]
pretty (P.LeftArrApp _ l r) = myFsep $ [pretty l, text "-<", pretty r]
pretty (P.RightArrApp _ l r) = myFsep $ [pretty l, text ">-", pretty r]
pretty (P.LeftArrHighApp _ l r) = myFsep $ [pretty l, text "-<<", pretty r]
pretty (P.RightArrHighApp _ l r) = myFsep $ [pretty l, text ">>-", pretty r]
pretty (P.AsPat _ name (P.IrrPat _ pat)) =
myFsep [pretty name <> char '@', char '~' <> pretty pat]
pretty (P.AsPat _ name pat) =
hcat [pretty name, char '@', pretty pat]
pretty (P.WildCard _) = char '_'
pretty (P.IrrPat _ pat) = char '~' <> pretty pat
pretty (P.PostOp _ e op) = pretty e <+> pretty op
pretty (P.PreOp _ op e) = pretty op <+> pretty e
pretty (P.ViewPat _ e p) =
myFsep [pretty e, text "->", pretty p]
pretty (P.SeqRP _ rs) = myFsep $ text "(/" : map pretty rs ++ [text "/)"]
pretty (P.GuardRP _ r gs) =
myFsep $ text "(|" : pretty r : char '|' : map pretty gs ++ [text "|)"]
pretty (P.EitherRP _ r1 r2) = parens . myFsep $ [pretty r1, char '|', pretty r2]
pretty (P.CAsRP _ n (P.IrrPat _ e)) =
myFsep [pretty n <> text "@:", char '~' <> pretty e]
pretty (P.CAsRP _ n r) = hcat [pretty n, text "@:", pretty r]
pretty (P.XRPats _ ps) =
myFsep $ text "<[" : map pretty ps ++ [text "%>"]
pretty (P.ExplTypeArg _ qn t) =
myFsep [pretty qn, text "{|", pretty t, text "|}"]
pretty (P.BangPat _ e) = text "!" <> pretty e
instance SrcInfo loc => Pretty (P.PFieldUpdate loc) where
pretty (P.FieldUpdate _ name e) =
myFsep [pretty name, equals, pretty e]
pretty (P.FieldPun _ name) = pretty name
pretty (P.FieldWildcard _) = text ".."
instance SrcInfo loc => Pretty (P.ParseXAttr loc) where
pretty (P.XAttr _ n v) =
myFsep [pretty n, char '=', pretty v]
instance SrcInfo loc => Pretty (P.PContext loc) where
pretty (P.CxEmpty _) = mySep [text "()", text "=>"]
pretty (P.CxSingle _ asst) = mySep [pretty asst, text "=>"]
pretty (P.CxTuple _ assts) = myFsep $ [parenList (map pretty assts), text "=>"]
pretty (P.CxParen _ asst) = parens (pretty asst)
instance SrcInfo loc => Pretty (P.PAsst loc) where
pretty (P.ClassA _ a ts) = myFsep $ ppQName (sQName a) : map (prettyPrec prec_atype) ts
pretty (P.InfixA _ a op b) = myFsep $ [pretty a, ppQNameInfix (sQName op), pretty b]
pretty (P.IParam _ i t) = myFsep $ [pretty i, text "::", pretty t]
pretty (P.EqualP _ t1 t2) = myFsep $ [pretty t1, text "~", pretty t2]
instance SrcInfo loc => Pretty (P.PType loc) where
prettyPrec p (P.TyForall _ mtvs ctxt htype) = parensIf (p > 0) $
myFsep [ppForall (fmap (map sTyVarBind) mtvs), maybePP pretty ctxt, pretty htype]
prettyPrec p (P.TyFun _ a b) = parensIf (p > 0) $
myFsep [prettyPrec prec_btype a, text "->", pretty b]
prettyPrec _ (P.TyTuple _ bxd l) =
let ds = map pretty l
in case bxd of
Boxed -> parenList ds
Unboxed -> hashParenList ds
prettyPrec _ (P.TyList _ t) = brackets $ pretty t
prettyPrec p (P.TyApp _ a b) =
{-
| a == list_tycon = brackets $ pretty b -- special case
| otherwise = -} parensIf (p > prec_btype) $
myFsep [pretty a, prettyPrec prec_atype b]
prettyPrec _ (P.TyVar _ name) = pretty name
prettyPrec _ (P.TyCon _ name) = pretty name
prettyPrec _ (P.TyParen _ t) = parens (pretty t)
prettyPrec _ (P.TyPred _ asst) = pretty asst
prettyPrec _ (P.TyInfix _ a op b) = myFsep [pretty a, ppQNameInfix (sQName op), pretty b]
prettyPrec _ (P.TyKind _ t k) = parens (myFsep [pretty t, text "::", pretty k])
prettyPrec _ (P.TySplice _ s) = pretty s
| monsanto/hie | Hie/Language/Haskell/Exts/Pretty.hs | gpl-3.0 | 67,585 | 0 | 23 | 22,417 | 22,654 | 11,298 | 11,356 | 1,208 | 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.BigQuery.Jobs.GetQueryResults
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Retrieves the results of a query job.
--
-- /See:/ <https://cloud.google.com/bigquery/ BigQuery API Reference> for @bigquery.jobs.getQueryResults@.
module Network.Google.Resource.BigQuery.Jobs.GetQueryResults
(
-- * REST Resource
JobsGetQueryResultsResource
-- * Creating a Request
, jobsGetQueryResults
, JobsGetQueryResults
-- * Request Lenses
, jgqrJobId
, jgqrTimeoutMs
, jgqrPageToken
, jgqrProjectId
, jgqrStartIndex
, jgqrMaxResults
) where
import Network.Google.BigQuery.Types
import Network.Google.Prelude
-- | A resource alias for @bigquery.jobs.getQueryResults@ method which the
-- 'JobsGetQueryResults' request conforms to.
type JobsGetQueryResultsResource =
"bigquery" :>
"v2" :>
"projects" :>
Capture "projectId" Text :>
"queries" :>
Capture "jobId" Text :>
QueryParam "timeoutMs" (Textual Word32) :>
QueryParam "pageToken" Text :>
QueryParam "startIndex" (Textual Word64) :>
QueryParam "maxResults" (Textual Word32) :>
QueryParam "alt" AltJSON :>
Get '[JSON] GetQueryResultsResponse
-- | Retrieves the results of a query job.
--
-- /See:/ 'jobsGetQueryResults' smart constructor.
data JobsGetQueryResults = JobsGetQueryResults'
{ _jgqrJobId :: !Text
, _jgqrTimeoutMs :: !(Maybe (Textual Word32))
, _jgqrPageToken :: !(Maybe Text)
, _jgqrProjectId :: !Text
, _jgqrStartIndex :: !(Maybe (Textual Word64))
, _jgqrMaxResults :: !(Maybe (Textual Word32))
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'JobsGetQueryResults' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'jgqrJobId'
--
-- * 'jgqrTimeoutMs'
--
-- * 'jgqrPageToken'
--
-- * 'jgqrProjectId'
--
-- * 'jgqrStartIndex'
--
-- * 'jgqrMaxResults'
jobsGetQueryResults
:: Text -- ^ 'jgqrJobId'
-> Text -- ^ 'jgqrProjectId'
-> JobsGetQueryResults
jobsGetQueryResults pJgqrJobId_ pJgqrProjectId_ =
JobsGetQueryResults'
{ _jgqrJobId = pJgqrJobId_
, _jgqrTimeoutMs = Nothing
, _jgqrPageToken = Nothing
, _jgqrProjectId = pJgqrProjectId_
, _jgqrStartIndex = Nothing
, _jgqrMaxResults = Nothing
}
-- | [Required] Job ID of the query job
jgqrJobId :: Lens' JobsGetQueryResults Text
jgqrJobId
= lens _jgqrJobId (\ s a -> s{_jgqrJobId = a})
-- | How long to wait for the query to complete, in milliseconds, before
-- returning. Default is 10 seconds. If the timeout passes before the job
-- completes, the \'jobComplete\' field in the response will be false
jgqrTimeoutMs :: Lens' JobsGetQueryResults (Maybe Word32)
jgqrTimeoutMs
= lens _jgqrTimeoutMs
(\ s a -> s{_jgqrTimeoutMs = a})
. mapping _Coerce
-- | Page token, returned by a previous call, to request the next page of
-- results
jgqrPageToken :: Lens' JobsGetQueryResults (Maybe Text)
jgqrPageToken
= lens _jgqrPageToken
(\ s a -> s{_jgqrPageToken = a})
-- | [Required] Project ID of the query job
jgqrProjectId :: Lens' JobsGetQueryResults Text
jgqrProjectId
= lens _jgqrProjectId
(\ s a -> s{_jgqrProjectId = a})
-- | Zero-based index of the starting row
jgqrStartIndex :: Lens' JobsGetQueryResults (Maybe Word64)
jgqrStartIndex
= lens _jgqrStartIndex
(\ s a -> s{_jgqrStartIndex = a})
. mapping _Coerce
-- | Maximum number of results to read
jgqrMaxResults :: Lens' JobsGetQueryResults (Maybe Word32)
jgqrMaxResults
= lens _jgqrMaxResults
(\ s a -> s{_jgqrMaxResults = a})
. mapping _Coerce
instance GoogleRequest JobsGetQueryResults where
type Rs JobsGetQueryResults = GetQueryResultsResponse
type Scopes JobsGetQueryResults =
'["https://www.googleapis.com/auth/bigquery",
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/cloud-platform.read-only"]
requestClient JobsGetQueryResults'{..}
= go _jgqrProjectId _jgqrJobId _jgqrTimeoutMs
_jgqrPageToken
_jgqrStartIndex
_jgqrMaxResults
(Just AltJSON)
bigQueryService
where go
= buildClient
(Proxy :: Proxy JobsGetQueryResultsResource)
mempty
| rueshyna/gogol | gogol-bigquery/gen/Network/Google/Resource/BigQuery/Jobs/GetQueryResults.hs | mpl-2.0 | 5,267 | 0 | 18 | 1,285 | 767 | 443 | 324 | 113 | 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.MapsEngine.Assets.Parents.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Return all parent ids of the specified asset.
--
-- /See:/ <https://developers.google.com/maps-engine/ Google Maps Engine API Reference> for @mapsengine.assets.parents.list@.
module Network.Google.Resource.MapsEngine.Assets.Parents.List
(
-- * REST Resource
AssetsParentsListResource
-- * Creating a Request
, assetsParentsList
, AssetsParentsList
-- * Request Lenses
, aplId
, aplPageToken
, aplMaxResults
) where
import Network.Google.MapsEngine.Types
import Network.Google.Prelude
-- | A resource alias for @mapsengine.assets.parents.list@ method which the
-- 'AssetsParentsList' request conforms to.
type AssetsParentsListResource =
"mapsengine" :>
"v1" :>
"assets" :>
Capture "id" Text :>
"parents" :>
QueryParam "pageToken" Text :>
QueryParam "maxResults" (Textual Word32) :>
QueryParam "alt" AltJSON :>
Get '[JSON] ParentsListResponse
-- | Return all parent ids of the specified asset.
--
-- /See:/ 'assetsParentsList' smart constructor.
data AssetsParentsList = AssetsParentsList'
{ _aplId :: !Text
, _aplPageToken :: !(Maybe Text)
, _aplMaxResults :: !(Maybe (Textual Word32))
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'AssetsParentsList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'aplId'
--
-- * 'aplPageToken'
--
-- * 'aplMaxResults'
assetsParentsList
:: Text -- ^ 'aplId'
-> AssetsParentsList
assetsParentsList pAplId_ =
AssetsParentsList'
{ _aplId = pAplId_
, _aplPageToken = Nothing
, _aplMaxResults = Nothing
}
-- | The ID of the asset whose parents will be listed.
aplId :: Lens' AssetsParentsList Text
aplId = lens _aplId (\ s a -> s{_aplId = a})
-- | The continuation token, used to page through large result sets. To get
-- the next page of results, set this parameter to the value of
-- nextPageToken from the previous response.
aplPageToken :: Lens' AssetsParentsList (Maybe Text)
aplPageToken
= lens _aplPageToken (\ s a -> s{_aplPageToken = a})
-- | The maximum number of items to include in a single response page. The
-- maximum supported value is 50.
aplMaxResults :: Lens' AssetsParentsList (Maybe Word32)
aplMaxResults
= lens _aplMaxResults
(\ s a -> s{_aplMaxResults = a})
. mapping _Coerce
instance GoogleRequest AssetsParentsList where
type Rs AssetsParentsList = ParentsListResponse
type Scopes AssetsParentsList =
'["https://www.googleapis.com/auth/mapsengine",
"https://www.googleapis.com/auth/mapsengine.readonly"]
requestClient AssetsParentsList'{..}
= go _aplId _aplPageToken _aplMaxResults
(Just AltJSON)
mapsEngineService
where go
= buildClient
(Proxy :: Proxy AssetsParentsListResource)
mempty
| rueshyna/gogol | gogol-maps-engine/gen/Network/Google/Resource/MapsEngine/Assets/Parents/List.hs | mpl-2.0 | 3,853 | 0 | 15 | 922 | 492 | 291 | 201 | 74 | 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.TagManager.Accounts.Containers.Workspaces.Triggers.Update
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Updates a GTM Trigger.
--
-- /See:/ <https://developers.google.com/tag-manager Tag Manager API Reference> for @tagmanager.accounts.containers.workspaces.triggers.update@.
module Network.Google.Resource.TagManager.Accounts.Containers.Workspaces.Triggers.Update
(
-- * REST Resource
AccountsContainersWorkspacesTriggersUpdateResource
-- * Creating a Request
, accountsContainersWorkspacesTriggersUpdate
, AccountsContainersWorkspacesTriggersUpdate
-- * Request Lenses
, acwtuXgafv
, acwtuUploadProtocol
, acwtuPath
, acwtuFingerprint
, acwtuAccessToken
, acwtuUploadType
, acwtuPayload
, acwtuCallback
) where
import Network.Google.Prelude
import Network.Google.TagManager.Types
-- | A resource alias for @tagmanager.accounts.containers.workspaces.triggers.update@ method which the
-- 'AccountsContainersWorkspacesTriggersUpdate' request conforms to.
type AccountsContainersWorkspacesTriggersUpdateResource
=
"tagmanager" :>
"v2" :>
Capture "path" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "fingerprint" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] Trigger :> Put '[JSON] Trigger
-- | Updates a GTM Trigger.
--
-- /See:/ 'accountsContainersWorkspacesTriggersUpdate' smart constructor.
data AccountsContainersWorkspacesTriggersUpdate =
AccountsContainersWorkspacesTriggersUpdate'
{ _acwtuXgafv :: !(Maybe Xgafv)
, _acwtuUploadProtocol :: !(Maybe Text)
, _acwtuPath :: !Text
, _acwtuFingerprint :: !(Maybe Text)
, _acwtuAccessToken :: !(Maybe Text)
, _acwtuUploadType :: !(Maybe Text)
, _acwtuPayload :: !Trigger
, _acwtuCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'AccountsContainersWorkspacesTriggersUpdate' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'acwtuXgafv'
--
-- * 'acwtuUploadProtocol'
--
-- * 'acwtuPath'
--
-- * 'acwtuFingerprint'
--
-- * 'acwtuAccessToken'
--
-- * 'acwtuUploadType'
--
-- * 'acwtuPayload'
--
-- * 'acwtuCallback'
accountsContainersWorkspacesTriggersUpdate
:: Text -- ^ 'acwtuPath'
-> Trigger -- ^ 'acwtuPayload'
-> AccountsContainersWorkspacesTriggersUpdate
accountsContainersWorkspacesTriggersUpdate pAcwtuPath_ pAcwtuPayload_ =
AccountsContainersWorkspacesTriggersUpdate'
{ _acwtuXgafv = Nothing
, _acwtuUploadProtocol = Nothing
, _acwtuPath = pAcwtuPath_
, _acwtuFingerprint = Nothing
, _acwtuAccessToken = Nothing
, _acwtuUploadType = Nothing
, _acwtuPayload = pAcwtuPayload_
, _acwtuCallback = Nothing
}
-- | V1 error format.
acwtuXgafv :: Lens' AccountsContainersWorkspacesTriggersUpdate (Maybe Xgafv)
acwtuXgafv
= lens _acwtuXgafv (\ s a -> s{_acwtuXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
acwtuUploadProtocol :: Lens' AccountsContainersWorkspacesTriggersUpdate (Maybe Text)
acwtuUploadProtocol
= lens _acwtuUploadProtocol
(\ s a -> s{_acwtuUploadProtocol = a})
-- | GTM Trigger\'s API relative path. Example:
-- accounts\/{account_id}\/containers\/{container_id}\/workspaces\/{workspace_id}\/triggers\/{trigger_id}
acwtuPath :: Lens' AccountsContainersWorkspacesTriggersUpdate Text
acwtuPath
= lens _acwtuPath (\ s a -> s{_acwtuPath = a})
-- | When provided, this fingerprint must match the fingerprint of the
-- trigger in storage.
acwtuFingerprint :: Lens' AccountsContainersWorkspacesTriggersUpdate (Maybe Text)
acwtuFingerprint
= lens _acwtuFingerprint
(\ s a -> s{_acwtuFingerprint = a})
-- | OAuth access token.
acwtuAccessToken :: Lens' AccountsContainersWorkspacesTriggersUpdate (Maybe Text)
acwtuAccessToken
= lens _acwtuAccessToken
(\ s a -> s{_acwtuAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
acwtuUploadType :: Lens' AccountsContainersWorkspacesTriggersUpdate (Maybe Text)
acwtuUploadType
= lens _acwtuUploadType
(\ s a -> s{_acwtuUploadType = a})
-- | Multipart request metadata.
acwtuPayload :: Lens' AccountsContainersWorkspacesTriggersUpdate Trigger
acwtuPayload
= lens _acwtuPayload (\ s a -> s{_acwtuPayload = a})
-- | JSONP
acwtuCallback :: Lens' AccountsContainersWorkspacesTriggersUpdate (Maybe Text)
acwtuCallback
= lens _acwtuCallback
(\ s a -> s{_acwtuCallback = a})
instance GoogleRequest
AccountsContainersWorkspacesTriggersUpdate
where
type Rs AccountsContainersWorkspacesTriggersUpdate =
Trigger
type Scopes
AccountsContainersWorkspacesTriggersUpdate
=
'["https://www.googleapis.com/auth/tagmanager.edit.containers"]
requestClient
AccountsContainersWorkspacesTriggersUpdate'{..}
= go _acwtuPath _acwtuXgafv _acwtuUploadProtocol
_acwtuFingerprint
_acwtuAccessToken
_acwtuUploadType
_acwtuCallback
(Just AltJSON)
_acwtuPayload
tagManagerService
where go
= buildClient
(Proxy ::
Proxy
AccountsContainersWorkspacesTriggersUpdateResource)
mempty
| brendanhay/gogol | gogol-tagmanager/gen/Network/Google/Resource/TagManager/Accounts/Containers/Workspaces/Triggers/Update.hs | mpl-2.0 | 6,406 | 0 | 18 | 1,398 | 863 | 503 | 360 | 132 | 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.DLP.Organizations.StoredInfoTypes.Delete
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Deletes a stored infoType. See
-- https:\/\/cloud.google.com\/dlp\/docs\/creating-stored-infotypes to
-- learn more.
--
-- /See:/ <https://cloud.google.com/dlp/docs/ Cloud Data Loss Prevention (DLP) API Reference> for @dlp.organizations.storedInfoTypes.delete@.
module Network.Google.Resource.DLP.Organizations.StoredInfoTypes.Delete
(
-- * REST Resource
OrganizationsStoredInfoTypesDeleteResource
-- * Creating a Request
, organizationsStoredInfoTypesDelete
, OrganizationsStoredInfoTypesDelete
-- * Request Lenses
, ositdXgafv
, ositdUploadProtocol
, ositdAccessToken
, ositdUploadType
, ositdName
, ositdCallback
) where
import Network.Google.DLP.Types
import Network.Google.Prelude
-- | A resource alias for @dlp.organizations.storedInfoTypes.delete@ method which the
-- 'OrganizationsStoredInfoTypesDelete' request conforms to.
type OrganizationsStoredInfoTypesDeleteResource =
"v2" :>
Capture "name" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Delete '[JSON] GoogleProtobufEmpty
-- | Deletes a stored infoType. See
-- https:\/\/cloud.google.com\/dlp\/docs\/creating-stored-infotypes to
-- learn more.
--
-- /See:/ 'organizationsStoredInfoTypesDelete' smart constructor.
data OrganizationsStoredInfoTypesDelete =
OrganizationsStoredInfoTypesDelete'
{ _ositdXgafv :: !(Maybe Xgafv)
, _ositdUploadProtocol :: !(Maybe Text)
, _ositdAccessToken :: !(Maybe Text)
, _ositdUploadType :: !(Maybe Text)
, _ositdName :: !Text
, _ositdCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'OrganizationsStoredInfoTypesDelete' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ositdXgafv'
--
-- * 'ositdUploadProtocol'
--
-- * 'ositdAccessToken'
--
-- * 'ositdUploadType'
--
-- * 'ositdName'
--
-- * 'ositdCallback'
organizationsStoredInfoTypesDelete
:: Text -- ^ 'ositdName'
-> OrganizationsStoredInfoTypesDelete
organizationsStoredInfoTypesDelete pOsitdName_ =
OrganizationsStoredInfoTypesDelete'
{ _ositdXgafv = Nothing
, _ositdUploadProtocol = Nothing
, _ositdAccessToken = Nothing
, _ositdUploadType = Nothing
, _ositdName = pOsitdName_
, _ositdCallback = Nothing
}
-- | V1 error format.
ositdXgafv :: Lens' OrganizationsStoredInfoTypesDelete (Maybe Xgafv)
ositdXgafv
= lens _ositdXgafv (\ s a -> s{_ositdXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
ositdUploadProtocol :: Lens' OrganizationsStoredInfoTypesDelete (Maybe Text)
ositdUploadProtocol
= lens _ositdUploadProtocol
(\ s a -> s{_ositdUploadProtocol = a})
-- | OAuth access token.
ositdAccessToken :: Lens' OrganizationsStoredInfoTypesDelete (Maybe Text)
ositdAccessToken
= lens _ositdAccessToken
(\ s a -> s{_ositdAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
ositdUploadType :: Lens' OrganizationsStoredInfoTypesDelete (Maybe Text)
ositdUploadType
= lens _ositdUploadType
(\ s a -> s{_ositdUploadType = a})
-- | Required. Resource name of the organization and storedInfoType to be
-- deleted, for example
-- \`organizations\/433245324\/storedInfoTypes\/432452342\` or
-- projects\/project-id\/storedInfoTypes\/432452342.
ositdName :: Lens' OrganizationsStoredInfoTypesDelete Text
ositdName
= lens _ositdName (\ s a -> s{_ositdName = a})
-- | JSONP
ositdCallback :: Lens' OrganizationsStoredInfoTypesDelete (Maybe Text)
ositdCallback
= lens _ositdCallback
(\ s a -> s{_ositdCallback = a})
instance GoogleRequest
OrganizationsStoredInfoTypesDelete
where
type Rs OrganizationsStoredInfoTypesDelete =
GoogleProtobufEmpty
type Scopes OrganizationsStoredInfoTypesDelete =
'["https://www.googleapis.com/auth/cloud-platform"]
requestClient OrganizationsStoredInfoTypesDelete'{..}
= go _ositdName _ositdXgafv _ositdUploadProtocol
_ositdAccessToken
_ositdUploadType
_ositdCallback
(Just AltJSON)
dLPService
where go
= buildClient
(Proxy ::
Proxy OrganizationsStoredInfoTypesDeleteResource)
mempty
| brendanhay/gogol | gogol-dlp/gen/Network/Google/Resource/DLP/Organizations/StoredInfoTypes/Delete.hs | mpl-2.0 | 5,431 | 0 | 15 | 1,139 | 702 | 413 | 289 | 107 | 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.AdExchangeBuyer2.Bidders.Accounts.FilterSets.FilteredBidRequests.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- List all reasons that caused a bid request not to be sent for an
-- impression, with the number of bid requests not sent for each reason.
--
-- /See:/ <https://developers.google.com/authorized-buyers/apis/reference/rest/ Ad Exchange Buyer API II Reference> for @adexchangebuyer2.bidders.accounts.filterSets.filteredBidRequests.list@.
module Network.Google.Resource.AdExchangeBuyer2.Bidders.Accounts.FilterSets.FilteredBidRequests.List
(
-- * REST Resource
BiddersAccountsFilterSetsFilteredBidRequestsListResource
-- * Creating a Request
, biddersAccountsFilterSetsFilteredBidRequestsList
, BiddersAccountsFilterSetsFilteredBidRequestsList
-- * Request Lenses
, bafsfbrlXgafv
, bafsfbrlUploadProtocol
, bafsfbrlFilterSetName
, bafsfbrlAccessToken
, bafsfbrlUploadType
, bafsfbrlPageToken
, bafsfbrlPageSize
, bafsfbrlCallback
) where
import Network.Google.AdExchangeBuyer2.Types
import Network.Google.Prelude
-- | A resource alias for @adexchangebuyer2.bidders.accounts.filterSets.filteredBidRequests.list@ method which the
-- 'BiddersAccountsFilterSetsFilteredBidRequestsList' request conforms to.
type BiddersAccountsFilterSetsFilteredBidRequestsListResource
=
"v2beta1" :>
Capture "filterSetName" Text :>
"filteredBidRequests" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "pageToken" Text :>
QueryParam "pageSize" (Textual Int32) :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] ListFilteredBidRequestsResponse
-- | List all reasons that caused a bid request not to be sent for an
-- impression, with the number of bid requests not sent for each reason.
--
-- /See:/ 'biddersAccountsFilterSetsFilteredBidRequestsList' smart constructor.
data BiddersAccountsFilterSetsFilteredBidRequestsList =
BiddersAccountsFilterSetsFilteredBidRequestsList'
{ _bafsfbrlXgafv :: !(Maybe Xgafv)
, _bafsfbrlUploadProtocol :: !(Maybe Text)
, _bafsfbrlFilterSetName :: !Text
, _bafsfbrlAccessToken :: !(Maybe Text)
, _bafsfbrlUploadType :: !(Maybe Text)
, _bafsfbrlPageToken :: !(Maybe Text)
, _bafsfbrlPageSize :: !(Maybe (Textual Int32))
, _bafsfbrlCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'BiddersAccountsFilterSetsFilteredBidRequestsList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'bafsfbrlXgafv'
--
-- * 'bafsfbrlUploadProtocol'
--
-- * 'bafsfbrlFilterSetName'
--
-- * 'bafsfbrlAccessToken'
--
-- * 'bafsfbrlUploadType'
--
-- * 'bafsfbrlPageToken'
--
-- * 'bafsfbrlPageSize'
--
-- * 'bafsfbrlCallback'
biddersAccountsFilterSetsFilteredBidRequestsList
:: Text -- ^ 'bafsfbrlFilterSetName'
-> BiddersAccountsFilterSetsFilteredBidRequestsList
biddersAccountsFilterSetsFilteredBidRequestsList pBafsfbrlFilterSetName_ =
BiddersAccountsFilterSetsFilteredBidRequestsList'
{ _bafsfbrlXgafv = Nothing
, _bafsfbrlUploadProtocol = Nothing
, _bafsfbrlFilterSetName = pBafsfbrlFilterSetName_
, _bafsfbrlAccessToken = Nothing
, _bafsfbrlUploadType = Nothing
, _bafsfbrlPageToken = Nothing
, _bafsfbrlPageSize = Nothing
, _bafsfbrlCallback = Nothing
}
-- | V1 error format.
bafsfbrlXgafv :: Lens' BiddersAccountsFilterSetsFilteredBidRequestsList (Maybe Xgafv)
bafsfbrlXgafv
= lens _bafsfbrlXgafv
(\ s a -> s{_bafsfbrlXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
bafsfbrlUploadProtocol :: Lens' BiddersAccountsFilterSetsFilteredBidRequestsList (Maybe Text)
bafsfbrlUploadProtocol
= lens _bafsfbrlUploadProtocol
(\ s a -> s{_bafsfbrlUploadProtocol = a})
-- | Name of the filter set that should be applied to the requested metrics.
-- For example: - For a bidder-level filter set for bidder 123:
-- \`bidders\/123\/filterSets\/abc\` - For an account-level filter set for
-- the buyer account representing bidder 123:
-- \`bidders\/123\/accounts\/123\/filterSets\/abc\` - For an account-level
-- filter set for the child seat buyer account 456 whose bidder is 123:
-- \`bidders\/123\/accounts\/456\/filterSets\/abc\`
bafsfbrlFilterSetName :: Lens' BiddersAccountsFilterSetsFilteredBidRequestsList Text
bafsfbrlFilterSetName
= lens _bafsfbrlFilterSetName
(\ s a -> s{_bafsfbrlFilterSetName = a})
-- | OAuth access token.
bafsfbrlAccessToken :: Lens' BiddersAccountsFilterSetsFilteredBidRequestsList (Maybe Text)
bafsfbrlAccessToken
= lens _bafsfbrlAccessToken
(\ s a -> s{_bafsfbrlAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
bafsfbrlUploadType :: Lens' BiddersAccountsFilterSetsFilteredBidRequestsList (Maybe Text)
bafsfbrlUploadType
= lens _bafsfbrlUploadType
(\ s a -> s{_bafsfbrlUploadType = a})
-- | A token identifying a page of results the server should return.
-- Typically, this is the value of
-- ListFilteredBidRequestsResponse.nextPageToken returned from the previous
-- call to the filteredBidRequests.list method.
bafsfbrlPageToken :: Lens' BiddersAccountsFilterSetsFilteredBidRequestsList (Maybe Text)
bafsfbrlPageToken
= lens _bafsfbrlPageToken
(\ s a -> s{_bafsfbrlPageToken = a})
-- | Requested page size. The server may return fewer results than requested.
-- If unspecified, the server will pick an appropriate default.
bafsfbrlPageSize :: Lens' BiddersAccountsFilterSetsFilteredBidRequestsList (Maybe Int32)
bafsfbrlPageSize
= lens _bafsfbrlPageSize
(\ s a -> s{_bafsfbrlPageSize = a})
. mapping _Coerce
-- | JSONP
bafsfbrlCallback :: Lens' BiddersAccountsFilterSetsFilteredBidRequestsList (Maybe Text)
bafsfbrlCallback
= lens _bafsfbrlCallback
(\ s a -> s{_bafsfbrlCallback = a})
instance GoogleRequest
BiddersAccountsFilterSetsFilteredBidRequestsList
where
type Rs
BiddersAccountsFilterSetsFilteredBidRequestsList
= ListFilteredBidRequestsResponse
type Scopes
BiddersAccountsFilterSetsFilteredBidRequestsList
=
'["https://www.googleapis.com/auth/adexchange.buyer"]
requestClient
BiddersAccountsFilterSetsFilteredBidRequestsList'{..}
= go _bafsfbrlFilterSetName _bafsfbrlXgafv
_bafsfbrlUploadProtocol
_bafsfbrlAccessToken
_bafsfbrlUploadType
_bafsfbrlPageToken
_bafsfbrlPageSize
_bafsfbrlCallback
(Just AltJSON)
adExchangeBuyer2Service
where go
= buildClient
(Proxy ::
Proxy
BiddersAccountsFilterSetsFilteredBidRequestsListResource)
mempty
| brendanhay/gogol | gogol-adexchangebuyer2/gen/Network/Google/Resource/AdExchangeBuyer2/Bidders/Accounts/FilterSets/FilteredBidRequests/List.hs | mpl-2.0 | 7,898 | 0 | 18 | 1,612 | 892 | 521 | 371 | 138 | 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.People.OtherContacts.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- List all \"Other contacts\", that is contacts that are not in a contact
-- group. \"Other contacts\" are typically auto created contacts from
-- interactions. Sync tokens expire 7 days after the full sync. A request
-- with an expired sync token will result in a 410 error. In the case of
-- such an error clients should make a full sync request without a
-- \`sync_token\`. The first page of a full sync request has an additional
-- quota. If the quota is exceeded, a 429 error will be returned. This
-- quota is fixed and can not be increased. When the \`sync_token\` is
-- specified, resources deleted since the last sync will be returned as a
-- person with \`PersonMetadata.deleted\` set to true. When the
-- \`page_token\` or \`sync_token\` is specified, all other request
-- parameters must match the first call. Writes may have a propagation
-- delay of several minutes for sync requests. Incremental syncs are not
-- intended for read-after-write use cases. See example usage at [List the
-- user\'s other contacts that have
-- changed](\/people\/v1\/other-contacts#list_the_users_other_contacts_that_have_changed).
--
-- /See:/ <https://developers.google.com/people/ People API Reference> for @people.otherContacts.list@.
module Network.Google.Resource.People.OtherContacts.List
(
-- * REST Resource
OtherContactsListResource
-- * Creating a Request
, otherContactsList
, OtherContactsList
-- * Request Lenses
, oclSyncToken
, oclXgafv
, oclUploadProtocol
, oclRequestSyncToken
, oclAccessToken
, oclUploadType
, oclReadMask
, oclSources
, oclPageToken
, oclPageSize
, oclCallback
) where
import Network.Google.People.Types
import Network.Google.Prelude
-- | A resource alias for @people.otherContacts.list@ method which the
-- 'OtherContactsList' request conforms to.
type OtherContactsListResource =
"v1" :>
"otherContacts" :>
QueryParam "syncToken" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "requestSyncToken" Bool :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "readMask" GFieldMask :>
QueryParams "sources" OtherContactsListSources :>
QueryParam "pageToken" Text :>
QueryParam "pageSize" (Textual Int32) :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] ListOtherContactsResponse
-- | List all \"Other contacts\", that is contacts that are not in a contact
-- group. \"Other contacts\" are typically auto created contacts from
-- interactions. Sync tokens expire 7 days after the full sync. A request
-- with an expired sync token will result in a 410 error. In the case of
-- such an error clients should make a full sync request without a
-- \`sync_token\`. The first page of a full sync request has an additional
-- quota. If the quota is exceeded, a 429 error will be returned. This
-- quota is fixed and can not be increased. When the \`sync_token\` is
-- specified, resources deleted since the last sync will be returned as a
-- person with \`PersonMetadata.deleted\` set to true. When the
-- \`page_token\` or \`sync_token\` is specified, all other request
-- parameters must match the first call. Writes may have a propagation
-- delay of several minutes for sync requests. Incremental syncs are not
-- intended for read-after-write use cases. See example usage at [List the
-- user\'s other contacts that have
-- changed](\/people\/v1\/other-contacts#list_the_users_other_contacts_that_have_changed).
--
-- /See:/ 'otherContactsList' smart constructor.
data OtherContactsList =
OtherContactsList'
{ _oclSyncToken :: !(Maybe Text)
, _oclXgafv :: !(Maybe Xgafv)
, _oclUploadProtocol :: !(Maybe Text)
, _oclRequestSyncToken :: !(Maybe Bool)
, _oclAccessToken :: !(Maybe Text)
, _oclUploadType :: !(Maybe Text)
, _oclReadMask :: !(Maybe GFieldMask)
, _oclSources :: !(Maybe [OtherContactsListSources])
, _oclPageToken :: !(Maybe Text)
, _oclPageSize :: !(Maybe (Textual Int32))
, _oclCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'OtherContactsList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'oclSyncToken'
--
-- * 'oclXgafv'
--
-- * 'oclUploadProtocol'
--
-- * 'oclRequestSyncToken'
--
-- * 'oclAccessToken'
--
-- * 'oclUploadType'
--
-- * 'oclReadMask'
--
-- * 'oclSources'
--
-- * 'oclPageToken'
--
-- * 'oclPageSize'
--
-- * 'oclCallback'
otherContactsList
:: OtherContactsList
otherContactsList =
OtherContactsList'
{ _oclSyncToken = Nothing
, _oclXgafv = Nothing
, _oclUploadProtocol = Nothing
, _oclRequestSyncToken = Nothing
, _oclAccessToken = Nothing
, _oclUploadType = Nothing
, _oclReadMask = Nothing
, _oclSources = Nothing
, _oclPageToken = Nothing
, _oclPageSize = Nothing
, _oclCallback = Nothing
}
-- | Optional. A sync token, received from a previous response
-- \`next_sync_token\` Provide this to retrieve only the resources changed
-- since the last request. When syncing, all other parameters provided to
-- \`otherContacts.list\` must match the first call that provided the sync
-- token. More details about sync behavior at \`otherContacts.list\`.
oclSyncToken :: Lens' OtherContactsList (Maybe Text)
oclSyncToken
= lens _oclSyncToken (\ s a -> s{_oclSyncToken = a})
-- | V1 error format.
oclXgafv :: Lens' OtherContactsList (Maybe Xgafv)
oclXgafv = lens _oclXgafv (\ s a -> s{_oclXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
oclUploadProtocol :: Lens' OtherContactsList (Maybe Text)
oclUploadProtocol
= lens _oclUploadProtocol
(\ s a -> s{_oclUploadProtocol = a})
-- | Optional. Whether the response should return \`next_sync_token\` on the
-- last page of results. It can be used to get incremental changes since
-- the last request by setting it on the request \`sync_token\`. More
-- details about sync behavior at \`otherContacts.list\`.
oclRequestSyncToken :: Lens' OtherContactsList (Maybe Bool)
oclRequestSyncToken
= lens _oclRequestSyncToken
(\ s a -> s{_oclRequestSyncToken = a})
-- | OAuth access token.
oclAccessToken :: Lens' OtherContactsList (Maybe Text)
oclAccessToken
= lens _oclAccessToken
(\ s a -> s{_oclAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
oclUploadType :: Lens' OtherContactsList (Maybe Text)
oclUploadType
= lens _oclUploadType
(\ s a -> s{_oclUploadType = a})
-- | Required. A field mask to restrict which fields on each person are
-- returned. Multiple fields can be specified by separating them with
-- commas. Valid values are: * emailAddresses * metadata * names *
-- phoneNumbers * photos
oclReadMask :: Lens' OtherContactsList (Maybe GFieldMask)
oclReadMask
= lens _oclReadMask (\ s a -> s{_oclReadMask = a})
-- | Optional. A mask of what source types to return. Defaults to
-- READ_SOURCE_TYPE_CONTACT if not set.
oclSources :: Lens' OtherContactsList [OtherContactsListSources]
oclSources
= lens _oclSources (\ s a -> s{_oclSources = a}) .
_Default
. _Coerce
-- | Optional. A page token, received from a previous response
-- \`next_page_token\`. Provide this to retrieve the subsequent page. When
-- paginating, all other parameters provided to \`otherContacts.list\` must
-- match the first call that provided the page token.
oclPageToken :: Lens' OtherContactsList (Maybe Text)
oclPageToken
= lens _oclPageToken (\ s a -> s{_oclPageToken = a})
-- | Optional. The number of \"Other contacts\" to include in the response.
-- Valid values are between 1 and 1000, inclusive. Defaults to 100 if not
-- set or set to 0.
oclPageSize :: Lens' OtherContactsList (Maybe Int32)
oclPageSize
= lens _oclPageSize (\ s a -> s{_oclPageSize = a}) .
mapping _Coerce
-- | JSONP
oclCallback :: Lens' OtherContactsList (Maybe Text)
oclCallback
= lens _oclCallback (\ s a -> s{_oclCallback = a})
instance GoogleRequest OtherContactsList where
type Rs OtherContactsList = ListOtherContactsResponse
type Scopes OtherContactsList =
'["https://www.googleapis.com/auth/contacts.other.readonly"]
requestClient OtherContactsList'{..}
= go _oclSyncToken _oclXgafv _oclUploadProtocol
_oclRequestSyncToken
_oclAccessToken
_oclUploadType
_oclReadMask
(_oclSources ^. _Default)
_oclPageToken
_oclPageSize
_oclCallback
(Just AltJSON)
peopleService
where go
= buildClient
(Proxy :: Proxy OtherContactsListResource)
mempty
| brendanhay/gogol | gogol-people/gen/Network/Google/Resource/People/OtherContacts/List.hs | mpl-2.0 | 9,871 | 0 | 21 | 2,141 | 1,182 | 698 | 484 | 156 | 1 |
module Tests.Command where
import Condition(Value(..),ScopeType(..),Condition(..))
import Command
import Duration(Duration(..))
import Scoped(Error())
import Tests.QuickMaker(quickMake)
import Data.Text(Text,unlines)
import Data.Either(isLeft)
import Test.Tasty
import Test.Tasty.HUnit
import Prelude hiding (unlines)
commandUnitTests = testGroup "Command Unit Tests"
[ commandSuccessTests, commandFailTests]
commandSuccessTests = testGroup "Command Success Tests"
[ successTest "A simple concrete command"
"set_coa = e_byzantium" $ Concrete "set_coa" (Id "e_byzantium")
, successTest "Boolean command"
"abandon_heresy = yes" $ BooleanCommand "abandon_heresy" True
, successTest "Numeric command"
"change_diplomacy = 3" $ NumericCommand "change_diplomacy" 3
, successTest "Adding a trait"
"add_trait = diligent" $ AddTrait "diligent"
, successTest "Removing a trait"
"remove_trait = wroth" $ RemoveTrait "wroth"
, successTest "Set Character Flag"
"set_character_flag = char_flag" $ SetFlag Character "char_flag"
, successTest "Clear Province Flag"
"clr_province_flag = prov_flag" $ ClrFlag Province "prov_flag"
, successTest "Set a variable"
"set_variable = { which = a which = b }" $ VarOpVar "a" Set "b"
, successTest "Add two variables"
"change_variable = { which = a which = b }" $ VarOpVar "a" Change "b"
, successTest "Check a variable against constant"
"check_variable = { which = a_variable value = 10 }"
$ VarOpLit "a_variable" Check 10
, successTest "Divide a variable by a constant"
"divide_variable = { which = a value = 4 } "
$ VarOpLit "a" Divide 4
, successTest "Check variable strict equality"
"is_variable_equal = { which = a which = b }"
$ VarOpVar "a" Equal "b"
, successTest "Subtract constant from variable"
"subtract_variable = { which = a value = 4 }" $ VarOpLit "a" Subtract 4
, successTest "Multiply two variables"
"multiply_variable = { which = \"quoted_variable\" which = b }"
$ VarOpVar "quoted_variable" Multiply "b"
, successTest "Spawn a unit"
"spawn_unit = { province = 342 owner = THIS leader = FROM home = PREV attrition = 1 troops = { archers = { 100 100 } pikemen = { 200 300 }} earmark = test_troops }"
$ SpawnUnit {
province = Left 342
, owner = Just This
, leader = Just From
, home = Just Prev
, attrition = Just 1
, composition = FixedSpec [("archers",100,100)
,("pikemen",200,300)]
, earmark = Just "test_troops"
, disbandOnPeace = Nothing, cannotInherit = Nothing
, maintenanceMultiplier = Nothing
, scaledByBiggestGarrison = Nothing, merge = Nothing
}
, successTest "Spawn a unit - province is scopetype"
"spawn_unit = { province = FROMFROM owner = THIS leader = FROM home = PREV attrition = 1 troops = { archers = { 100 100 } pikemen = { 200 300 }} earmark = test_troops }"
$ SpawnUnit {
province = Right FromFrom
, owner = Just This
, leader = Just From
, home = Just Prev
, attrition = Just 1
, composition = FixedSpec [("archers",100,100)
,("pikemen",200,300)]
, earmark = Just "test_troops"
, disbandOnPeace = Nothing, cannotInherit = Nothing
, maintenanceMultiplier = Nothing
, scaledByBiggestGarrison = Nothing, merge = Nothing
}
, successTest "Spawn a unit - matching composition"
"spawn_unit = { province = 101 home = ROOT owner = ROOT leader = ROOT earmark = test_army match_character = THIS match_mult = 2 match_max = 10000 match_min = 100 disband_on_peace = no cannot_inherit = no attrition = 0.1 maintenance_multiplier = 0.1 scaled_by_biggest_garrison = 2.0 merge = yes }"
SpawnUnit {
province = Left 101, home = Just Root, owner = Just Root
, leader = Just Root, earmark = Just "test_army"
, composition = MatchSpec { matchCharacter = This, matchMultiplier = 2
, matchMax = Just 10000, matchMin = Just 100 }
, disbandOnPeace = Just False, cannotInherit = Just False
, attrition = Just 0.1, maintenanceMultiplier = Just 0.1
, scaledByBiggestGarrison = Just 2, merge = Just True }
, successTest "Spawn a unit - matching composition - no min/max"
"spawn_unit = { province = 101 home = ROOT owner = ROOT leader = ROOT earmark = test_army match_character = THIS match_mult = 2 disband_on_peace = no cannot_inherit = no attrition = 0.1 maintenance_multiplier = 0.1 scaled_by_biggest_garrison = 2.0 merge = yes }"
SpawnUnit {
province = Left 101, home = Just Root, owner = Just Root
, leader = Just Root, earmark = Just "test_army"
, composition = MatchSpec { matchCharacter = This, matchMultiplier = 2
, matchMax = Nothing, matchMin = Nothing }
, disbandOnPeace = Just False, cannotInherit = Just False
, attrition = Just 0.1, maintenanceMultiplier = Just 0.1
, scaledByBiggestGarrison = Just 2, merge = Just True }
, successTest "Break"
"break = yes"
Break
, successTest "Random Break"
"random = { chance = 20 modifier = { factor = 0.5 trait = sloth } modifier = { factor = 2 trait = diligent } break = yes }"
$ Random 20 [Modifier 0.5 [Trait "sloth"], Modifier 2 [Trait "diligent"]] [Break]
, successTest "If"
"if = { limit = { trait = humble prestige = 5 } change_diplomacy = 2 add_trait = monk}"
$ If [Trait "humble", NumericCondition "prestige" 5] [NumericCommand "change_diplomacy" 2, AddTrait "monk"]
, successTest "Random List"
"random_list = { 10 = { wealth = 10 } 20 = { unsafe_religion = catholic modifier = { factor = 2 trait = cynical }} 70 = { prestige = 30 } }"
$ RandomList [(10,[],[Concrete "wealth" $ NumValue 10]),
(20,[Modifier 2 [Trait "cynical"]],[StringCommand "unsafe_religion" "catholic"]),
(70,[],[NumericCommand "prestige" 30])]
, successTest "Create Character"
(unlines ["create_character = {"
, "random_traits = no"
, "name = \"Hassan\""
, "dynasty = random"
, "religion = ROOT"
, "culture = persian"
, "female = no"
, "age = 40"
, "has_nickname = the_testy"
, "attributes = {"
, "martial = 6"
, "diplomacy = 8"
, "stewardship = 9"
, "intrigue = 12"
, "learning = 12"
, "}"
, "health = 6"
, "fertility = 0.8"
, "mother = FROM"
, "father = FROMFROM"
, "race = testish"
, "dna = DNA"
, "flag = \"test_flag\""
, "employer = THIS"
, "trait = elusive_shadow"
, "trait = patient"
, "trait = zealous"
, "trait = scholar"
, "trait = chaste"
, "trait = temperate }"])
(CreateCharacter {
age = Just 40
, name = "Hassan"
, hasNickName = Just "the_testy"
, attributes = [6,8,9,12,12]
, traits = ["elusive_shadow","patient","zealous",
"scholar","chaste","temperate"]
, health = Just 6
, fertility = Just 0.8
, randomTraits = Just False
, female = False
, employer = Just This
, religion = Just Root
, culture = IdScope "persian"
, dynasty = Just $ Left "random"
, dna = Just "DNA"
, flag = Just "test_flag"
, mother = Just From
, father = Just FromFrom
, race = Just $ IdScope "testish"
})
, successTest "Create Character"
(unlines ["create_random_intriguer = {"
, "random_traits = no"
, "name = \"Hassan\""
, "dynasty = random"
, "religion = ROOT"
, "culture = persian"
, "female = no"
, "age = 40"
, "has_nickname = the_testy"
, "attributes = {"
, "martial = 6"
, "diplomacy = 8"
, "stewardship = 9"
, "intrigue = 12"
, "learning = 12"
, "}"
, "health = 6"
, "fertility = 0.8"
, "mother = FROM"
, "father = FROMFROM"
, "race = testish"
, "dna = DNA"
, "flag = \"test_flag\""
, "employer = THIS"
, "trait = elusive_shadow"
, "trait = patient"
, "trait = zealous"
, "trait = scholar"
, "trait = chaste"
, "trait = temperate }"])
(CreateCharacter {
age = Just 40
, name = "Hassan"
, hasNickName = Just "the_testy"
, attributes = [6,8,9,12,12]
, traits = ["elusive_shadow","patient","zealous",
"scholar","chaste","temperate"]
, health = Just 6
, fertility = Just 0.8
, randomTraits = Just False
, female = False
, employer = Just This
, religion = Just Root
, culture = IdScope "persian"
, dynasty = Just $ Left "random"
, dna = Just "DNA"
, flag = Just "test_flag"
, mother = Just From
, father = Just FromFrom
, race = Just $ IdScope "testish"
})
, successTest "activate title"
"activate_title = { title = e_persia status = yes }"
$ ActivateTitle "e_persia" True
, successTest "Add Character Modifier"
"add_character_modifier = { name = test_mod duration = 180 }"
$ ScopedModifier "test_mod" $ Days 180
, successTest "Add province modifier"
"add_province_modifier = { name = test_mod years = 3 }"
$ ScopedModifier "test_mod" $ Years 3
, successTest "deactivate title"
"activate_title = { title = b_rome status = no }"
$ ActivateTitle "b_rome" False
, successTest "character event"
"character_event = { id = test.12 days = 5 tooltip = \"An event\" }"
$ TriggerEvent ("test",12) (Just $ Days 5) (Just "An event")
, successTest "Build holding"
"build_holding = { title = b_masyaf type = castle holder = ROOT }"
$ BuildHolding (Just "b_masyaf") "castle" Root
, successTest "Build holding - no holder"
"build_holding = { type = castle }"
$ BuildHolding Nothing "castle" This
, successTest "Change legalism"
"change_tech = { technology = TECH_LEGALISM value = 1 }"
$ ChangeTech "TECH_LEGALISM" 1
, successTest "Best Fit Character"
(unlines ["best_fit_character_for_title = {",
"title = PREV",
"perspective = ROOT",
"index = 1",
"grant_title = PREV",
"}"])
$ BestFitCharacterForTitle {
title = Prev
, perspective = Root
, index = 1
, grantTitle = Prev }
, successTest "Create title" "create_title = { tier = DUKE name = \"SHEPHERDS_CRUSADE\" holder = THIS }"
$ CreateTitle { tier = "DUKE"
, landless = Nothing
, temporary = Nothing
, rebel = Nothing
, titleCulture = Nothing
, name = "SHEPHERDS_CRUSADE"
, holder = This
, customCreated = Nothing
, baseTitle = Nothing
, copyTitleLaws = Nothing }
, successTest "Create title - no name"
"create_title = { tier = DUKE holder = THIS }"
CreateTitle { tier = "DUKE"
, landless = Nothing
, temporary = Nothing
, rebel = Nothing
, titleCulture = Nothing
, name = ""
, holder = This
, customCreated = Nothing
, baseTitle = Nothing
, copyTitleLaws = Nothing }
, successTest "Death" "death = { death_reason = death_disease killer = FROMFROMFROM }"
$ Death { deathReason = "death_disease"
, killer = Just FromFromFrom }
, successTest "Death (no killer)" "death = { death_reason = death_mystery }"
$ Death { deathReason = "death_mystery", killer = Nothing }
, successTest "Gain Settlements"
"gain_settlements_under_title = { title = PREV enemy = ROOT }"
GainSettlementsUnderTitle { title = Prev, enemy = Root }
, successTest "Letter Event with tooltip"
"letter_event = { id = 40 months = 3 tooltip = EVTTESTTOOLTIP }"
$ TriggerEvent ("",40) (Just $ Months 3) $ Just "EVTTESTTOOLTIP"
, successTest "Minimal letter event"
"letter_event = { id = test.3 }"
$ TriggerEvent ("test",3) Nothing Nothing
, successTest "Opinion modifier"
"opinion = { modifier = test_modifier years = 5 who = PREVPREV }"
$ OpinionModifier { opinionModifier = "test_modifier"
, who = PrevPrev
, me = This
, dur = Years 5 }
, successTest "Province event"
"province_event = { id = 2254 }"
$ TriggerEvent ("",2254) Nothing Nothing
, successTest "Religion authority - Numeric"
"religion_authority = 10"
$ ReligionAuthority $ Left 10
, successTest "Religion authority - Modifier"
"religion_authority = { modifier = test_mod }"
$ ReligionAuthority $ Right "test_mod"
, successTest "Remove opinion"
"remove_opinion = { who = FROM modifier = opinion_friend }"
$ RemoveOpinion { opinionModifier = "opinion_friend"
, who = From, me = This }
, successTest "Repeat event"
"repeat_event = { id = WoL.5502 days = 30 }"
$ TriggerEvent ("WoL",5502) (Just $ Days 30) Nothing
, successTest "Reverse opinion"
"reverse_opinion = { modifier = test_modifier years = 5 who = PREVPREV }"
$ OpinionModifier { opinionModifier = "test_modifier"
, who = This
, me = PrevPrev
, dur = Years 5 }
, successTest "Reverse remove opinion"
"reverse_remove_opinion = { modifier = opinion_friend who = FROM }"
$ RemoveOpinion { opinionModifier = "opinion_friend"
, who = This, me = From }
, successTest "Declare war"
"war = { target = PREVPREV casus_belli = duchy_adventure thirdparty_title = PREV tier = DUKE }"
$ War { attacker = This, target = PrevPrev
, casusBelli = "duchy_adventure"
, thirdparty = Just Prev, targetTier = Just "DUKE" }
, successTest "Declare reverse war"
"reverse_war = { target = FROM casus_belli = other_claim thirdparty = ROOT }"
$ War { attacker = From, target = This
, casusBelli = "other_claim"
, thirdparty = Just Root, targetTier = Nothing }
, successTest "Add piety modifier"
"add_piety_modifier = 0.3"
$ NumericCommand "add_piety_modifier" 0.3
, successTest "Remove building"
"remove_building = castle_town"
$ StringCommand "remove_building" "castle_town"
, successTest "Character with unspecified age"
(unlines ["create_random_soldier = {"
, "random_traits = no"
, "name = \"Hassan\""
, "dynasty = random"
, "religion = ROOT"
, "culture = persian"
, "female = no"
, "has_nickname = the_testy"
, "attributes = {"
, "martial = 6"
, "diplomacy = 8"
, "stewardship = 9"
, "intrigue = 12"
, "learning = 12"
, "}"
, "health = 6"
, "fertility = 0.8"
, "mother = FROM"
, "father = FROMFROM"
, "race = testish"
, "dna = DNA"
, "flag = \"test_flag\""
, "employer = THIS"
, "trait = elusive_shadow"
, "trait = patient"
, "trait = zealous"
, "trait = scholar"
, "trait = chaste"
, "trait = temperate }"])
(CreateCharacter {
age = Nothing
, name = "Hassan"
, hasNickName = Just "the_testy"
, attributes = [6,8,9,12,12]
, traits = ["elusive_shadow","patient","zealous",
"scholar","chaste","temperate"]
, health = Just 6
, fertility = Just 0.8
, randomTraits = Just False
, female = False
, employer = Just This
, religion = Just Root
, culture = IdScope "persian"
, dynasty = Just $ Left "random"
, dna = Just "DNA"
, flag = Just "test_flag"
, mother = Just From
, father = Just FromFrom
, race = Just $ IdScope "testish"
})
, successTest "Character with unspecified religion"
(unlines ["create_random_soldier = {"
, "random_traits = no"
, "name = \"Hassan\""
, "dynasty = random"
, "culture = persian"
, "female = no"
, "has_nickname = the_testy"
, "attributes = {"
, "martial = 6"
, "diplomacy = 8"
, "stewardship = 9"
, "intrigue = 12"
, "learning = 12"
, "}"
, "health = 6"
, "fertility = 0.8"
, "mother = FROM"
, "father = FROMFROM"
, "race = testish"
, "dna = DNA"
, "flag = \"test_flag\""
, "employer = THIS"
, "trait = elusive_shadow"
, "trait = patient"
, "trait = zealous"
, "trait = scholar"
, "trait = chaste"
, "trait = temperate }"])
(CreateCharacter {
age = Nothing
, name = "Hassan"
, hasNickName = Just "the_testy"
, attributes = [6,8,9,12,12]
, traits = ["elusive_shadow","patient","zealous",
"scholar","chaste","temperate"]
, health = Just 6
, fertility = Just 0.8
, randomTraits = Just False
, female = False
, employer = Just This
, religion = Nothing
, culture = IdScope "persian"
, dynasty = Just $ Left "random"
, dna = Just "DNA"
, flag = Just "test_flag"
, mother = Just From
, father = Just FromFrom
, race = Just $ IdScope "testish"
})
, successTest "Character with unspecified gender"
(unlines ["create_random_soldier = {"
, "random_traits = no"
, "name = \"Hassan\""
, "dynasty = random"
, "culture = persian"
, "has_nickname = the_testy"
, "attributes = {"
, "martial = 6"
, "diplomacy = 8"
, "stewardship = 9"
, "intrigue = 12"
, "learning = 12"
, "}"
, "health = 6"
, "fertility = 0.8"
, "mother = FROM"
, "father = FROMFROM"
, "race = testish"
, "dna = DNA"
, "flag = \"test_flag\""
, "employer = THIS"
, "trait = elusive_shadow"
, "trait = patient"
, "trait = zealous"
, "trait = scholar"
, "trait = chaste"
, "trait = temperate }"])
(CreateCharacter {
age = Nothing
, name = "Hassan"
, hasNickName = Just "the_testy"
, attributes = [6,8,9,12,12]
, traits = ["elusive_shadow","patient","zealous",
"scholar","chaste","temperate"]
, health = Just 6
, fertility = Just 0.8
, randomTraits = Just False
, female = False
, employer = Just This
, religion = Nothing
, culture = IdScope "persian"
, dynasty = Just $ Left "random"
, dna = Just "DNA"
, flag = Just "test_flag"
, mother = Just From
, father = Just FromFrom
, race = Just $ IdScope "testish"
})
, successTest "Character with unspecified name"
(unlines ["create_random_soldier = {"
, "random_traits = no"
, "dynasty = random"
, "culture = persian"
, "has_nickname = the_testy"
, "attributes = {"
, "martial = 6"
, "diplomacy = 8"
, "stewardship = 9"
, "intrigue = 12"
, "learning = 12"
, "}"
, "health = 6"
, "fertility = 0.8"
, "mother = FROM"
, "father = FROMFROM"
, "race = testish"
, "dna = DNA"
, "flag = \"test_flag\""
, "employer = THIS"
, "trait = elusive_shadow"
, "trait = patient"
, "trait = zealous"
, "trait = scholar"
, "trait = chaste"
, "trait = temperate }"])
(CreateCharacter {
age = Nothing
, name = ""
, hasNickName = Just "the_testy"
, attributes = [6,8,9,12,12]
, traits = ["elusive_shadow","patient","zealous",
"scholar","chaste","temperate"]
, health = Just 6
, fertility = Just 0.8
, randomTraits = Just False
, female = False
, employer = Just This
, religion = Nothing
, culture = IdScope "persian"
, dynasty = Just $ Left "random"
, dna = Just "DNA"
, flag = Just "test_flag"
, mother = Just From
, father = Just FromFrom
, race = Just $ IdScope "testish"
})
, successTest "Character with unspecified health"
(unlines ["create_random_soldier = {"
, "random_traits = no"
, "dynasty = random"
, "culture = persian"
, "has_nickname = the_testy"
, "attributes = {"
, "martial = 6"
, "diplomacy = 8"
, "stewardship = 9"
, "intrigue = 12"
, "learning = 12"
, "}"
, "fertility = 0.8"
, "mother = FROM"
, "father = FROMFROM"
, "race = testish"
, "dna = DNA"
, "flag = \"test_flag\""
, "employer = THIS"
, "trait = elusive_shadow"
, "trait = patient"
, "trait = zealous"
, "trait = scholar"
, "trait = chaste"
, "trait = temperate }"])
(CreateCharacter {
age = Nothing
, name = ""
, hasNickName = Just "the_testy"
, attributes = [6,8,9,12,12]
, traits = ["elusive_shadow","patient","zealous",
"scholar","chaste","temperate"]
, health = Nothing
, fertility = Just 0.8
, randomTraits = Just False
, female = False
, employer = Just This
, religion = Nothing
, culture = IdScope "persian"
, dynasty = Just $ Left "random"
, dna = Just "DNA"
, flag = Just "test_flag"
, mother = Just From
, father = Just FromFrom
, race = Just $ IdScope "testish"
})
, successTest "Character with unspecified attributes"
(unlines ["create_random_soldier = {"
, "random_traits = no"
, "dynasty = random"
, "culture = persian"
, "has_nickname = the_testy"
, "fertility = 0.8"
, "mother = FROM"
, "father = FROMFROM"
, "race = testish"
, "dna = DNA"
, "flag = \"test_flag\""
, "employer = THIS"
, "trait = elusive_shadow"
, "trait = patient"
, "trait = zealous"
, "trait = scholar"
, "trait = chaste"
, "trait = temperate }"])
(CreateCharacter {
age = Nothing
, name = ""
, hasNickName = Just "the_testy"
, attributes = []
, traits = ["elusive_shadow","patient","zealous",
"scholar","chaste","temperate"]
, health = Nothing
, fertility = Just 0.8
, randomTraits = Just False
, female = False
, employer = Just This
, religion = Nothing
, culture = IdScope "persian"
, dynasty = Just $ Left "random"
, dna = Just "DNA"
, flag = Just "test_flag"
, mother = Just From
, father = Just FromFrom
, race = Just $ IdScope "testish"
})
, successTest "Opinion modifier with no duration"
"opinion = { modifier = test_modifier who = PREV }"
$ OpinionModifier {
opinionModifier = "test_modifier"
, who = Prev
, me = This
, dur = Days (-1)}
, successTest "Character with unspecified culture"
(unlines ["create_random_soldier = {"
, "random_traits = no"
, "dynasty = random"
, "has_nickname = the_testy"
, "attributes = {"
, "martial = 6"
, "diplomacy = 8"
, "stewardship = 9"
, "intrigue = 12"
, "learning = 12"
, "}"
, "fertility = 0.8"
, "mother = FROM"
, "father = FROMFROM"
, "race = testish"
, "dna = DNA"
, "flag = \"test_flag\""
, "employer = THIS"
, "trait = elusive_shadow"
, "trait = patient"
, "trait = zealous"
, "trait = scholar"
, "trait = chaste"
, "trait = temperate }"])
(CreateCharacter {
age = Nothing
, name = ""
, hasNickName = Just "the_testy"
, attributes = [6,8,9,12,12]
, traits = ["elusive_shadow","patient","zealous",
"scholar","chaste","temperate"]
, health = Nothing
, fertility = Just 0.8
, randomTraits = Just False
, female = False
, employer = Just This
, religion = Nothing
, culture = This
, dynasty = Just $ Left "random"
, dna = Just "DNA"
, flag = Just "test_flag"
, mother = Just From
, father = Just FromFrom
, race = Just $ IdScope "testish"
})
, successTest "Character with unspecified dynasty"
(unlines ["create_random_soldier = {"
, "random_traits = no"
, "has_nickname = the_testy"
, "attributes = {"
, "martial = 6"
, "diplomacy = 8"
, "stewardship = 9"
, "intrigue = 12"
, "learning = 12"
, "}"
, "fertility = 0.8"
, "mother = FROM"
, "father = FROMFROM"
, "race = testish"
, "dna = DNA"
, "flag = \"test_flag\""
, "employer = THIS"
, "trait = elusive_shadow"
, "trait = patient"
, "trait = zealous"
, "trait = scholar"
, "trait = chaste"
, "trait = temperate }"])
(CreateCharacter {
age = Nothing
, name = ""
, hasNickName = Just "the_testy"
, attributes = [6,8,9,12,12]
, traits = ["elusive_shadow","patient","zealous",
"scholar","chaste","temperate"]
, health = Nothing
, fertility = Just 0.8
, randomTraits = Just False
, female = False
, employer = Just This
, religion = Nothing
, culture = This
, dynasty = Nothing
, dna = Just "DNA"
, flag = Just "test_flag"
, mother = Just From
, father = Just FromFrom
, race = Just $ IdScope "testish"
})
, successTest "Add province modifier (with 'modifier' instead of 'name')"
"add_province_modifier = { modifier = test }"
$ ScopedModifier "test" (Days $ -1)
, successTest "Character with numeric dynasty"
(unlines ["create_random_soldier = {"
, "random_traits = no"
, "has_nickname = the_testy"
, "attributes = {"
, "martial = 6"
, "diplomacy = 8"
, "stewardship = 9"
, "intrigue = 12"
, "learning = 12"
, "}"
, "fertility = 0.8"
, "mother = FROM"
, "father = FROMFROM"
, "race = testish"
, "dna = DNA"
, "flag = \"test_flag\""
, "dynasty = 1000"
, "employer = THIS"
, "trait = elusive_shadow"
, "trait = patient"
, "trait = zealous"
, "trait = scholar"
, "trait = chaste"
, "trait = temperate }"])
(CreateCharacter {
age = Nothing
, name = ""
, hasNickName = Just "the_testy"
, attributes = [6,8,9,12,12]
, traits = ["elusive_shadow","patient","zealous",
"scholar","chaste","temperate"]
, health = Nothing
, fertility = Just 0.8
, randomTraits = Just False
, female = False
, employer = Just This
, religion = Nothing
, culture = This
, dynasty = Just $ Right 1000
, dna = Just "DNA"
, flag = Just "test_flag"
, mother = Just From
, father = Just FromFrom
, race = Just $ IdScope "testish"
})
, successTest "Disable viceroyalties"
"set_allow_vice_royalties = no"
$ SetAllowViceRoyalties (Left False)
, successTest "Allow kingdom viceroyalties"
"set_allow_vice_royalties = king"
$ SetAllowViceRoyalties (Right "king")
, successTest "Clear wealth - boolean arg"
"clear_wealth = yes"
$ ClearWealth (Left True)
, successTest "Clear wealth - character arg"
"clear_wealth = PREV"
$ ClearWealth (Right Prev)
, successTest "Scaled wealth - simple"
"scaled_wealth = 5"
$ ScaledWealth 5
, successTest "Scaled wealth - min bound"
"scaled_wealth = { value = 2 min = 10 }"
$ ScaledWealthBounded 2 (Just 10) Nothing
, successTest "Scaled wealth - max bound"
"scaled_wealth = { value = 5 max = 1000 }"
$ ScaledWealthBounded 5 Nothing (Just 1000)
, successTest "Opinion - Default Target"
"opinion = { modifier = claim_refused years = 5}"
$ OpinionModifier { opinionModifier = "claim_refused"
, who = Root
, me = This
, dur = Years 5 }
, successTest "Destroy random building - boolean"
"destroy_random_building = yes"
$ Concrete "destroy_random_building" (BooleanValue True)
, successTest "Destroy random building - scope"
"destroy_random_building = this"
$ Concrete "destroy_random_building" (Id "this")
]
commandFailTests =
testGroup "Failing tests"
[ failTest "Missing brace" "opinion = { who = ROOT modifier = test years = 4"
, failTest "Ill-formed opinion" "opinion = { who = ROOT }"
, failTest "Event missing id" "letter_event = { days = 5 }"
, failTest "War missing target" "war = { casus_belli = duchy }"
, failTest "War missing CB" "war = { target = ROOT }"
, failTest "Empty clause" "war = { }"
, failTest "Numeric commands can't have string args" "change_diplomacy = more"
, failTest "Numeric commands can't have clause args" "reduce_disease = { value = 3 }"
, failTest "String commands don't take numbers" "unsafe_religion = 5"
]
makeCommand :: Text -> Either Error Command
makeCommand = quickMake command
successTest :: TestName -> Text -> Command -> TestTree
successTest name command result = testCase name $ makeCommand command @?= Right result
failTest name command = testCase name $ isLeft (makeCommand command) @?= True
| joelwilliamson/validator | Tests/Command.hs | agpl-3.0 | 46,805 | 0 | 14 | 26,556 | 5,632 | 3,266 | 2,366 | 803 | 1 |
--
-- Copyright (c) 2013 Stefan Wehr - http://www.stefanwehr.de
--
-- 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.
--
import Test.Framework.ThreadPool
import System.Environment
import System.Exit
import Control.Monad
main :: IO ()
main =
do args <- getArgs
when ("-h" `elem` args || "--help" `elem` args) usage
(i, nEntries) <- case args of
[] -> return (200, 100)
[x] -> return (read x, 100)
[x, y] -> return (read x, read y)
_ -> usage
threadPoolTest (1, i) nEntries
return ()
where
usage =
do putStrLn "USAGE: ThreadPoolTest [N_THREADS [N_ENTRIES]]"
exitWith (ExitFailure 1)
| skogsbaer/HTF | tests/ThreadPoolTest.hs | lgpl-2.1 | 1,419 | 0 | 13 | 385 | 225 | 124 | 101 | 18 | 4 |
{-# OPTIONS_GHC -Wno-missing-signatures #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE RankNTypes #-}
module X05 where
import Data.Proxy
import Data.Tagged
import Data.Typeable
import Protolude
import Test.Hspec
type Length u = Tagged u Double
oneHalfInch :: Length "inches"
oneHalfInch = Tagged 0.5
fourCentimeters :: Length "centimeters"
fourCentimeters = Tagged 4.0
add0 :: Length "inches"
-> Length "centimeters"
-> Length a
add0 (Tagged x) (Tagged y) = Tagged (x + y)
x1 :: Length a
x1 = add0 oneHalfInch fourCentimeters
x2 :: Length "ounces"
x2 = add0 oneHalfInch fourCentimeters
typeOfLengthCentimeters :: TypeRep
typeOfLengthCentimeters = typeOf fourCentimeters
typeOfProxyLengthCentimeters :: TypeRep
typeOfProxyLengthCentimeters = typeRep (Proxy :: Proxy (Proxy (Length "centimeters")))
typeOfLengthInches :: TypeRep
typeOfLengthInches = typeOf oneHalfInch
typeOfProxyLengthInches :: TypeRep
typeOfProxyLengthInches = typeRep (Proxy :: Proxy (Proxy (Length "inches")))
add :: forall k (a :: k) (b :: k) (c :: k)
. (Typeable a, Typeable b, Typeable c, Typeable k)
=> Length a
-> Length b
-> Proxy (Length c)
-> Maybe (Length c)
add x y p = do
Tagged x' <- toCentimeters x
Tagged y' <- toCentimeters y
let xy = x' + y'
if | typeOf p == typeOfProxyLengthCentimeters -> Just (Tagged xy)
| typeOf p == typeOfProxyLengthInches -> Just (Tagged (xy/2.54))
| otherwise -> Nothing
toCentimeters
:: forall k (a :: k)
. (Typeable a, Typeable k)
=> Length a
-> Maybe (Length "centimeters")
toCentimeters la@(Tagged a) =
if | typeOf la == typeOfLengthCentimeters ->
cast la
| typeOf la == typeOfLengthInches ->
Just (Tagged (a * 2.54))
| otherwise -> Nothing
ic = add oneHalfInch fourCentimeters (Proxy::Proxy (Length "inches"))
cc = add fourCentimeters fourCentimeters (Proxy::Proxy (Length "centimeters"))
x05 :: Spec
x05 = describe "X05" $ do
it "ic" $ ic `shouldBe` Just (Tagged 2.074803149606299)
it "cc" $ cc `shouldBe` Just (Tagged 8.0)
| haroldcarr/learn-haskell-coq-ml-etc | haskell/topic/phantoms/hc-phantom/src/X05.hs | unlicense | 2,285 | 0 | 13 | 563 | 721 | 367 | 354 | 63 | 3 |
import Data.Char
ans = map chr . map (\x -> if x >= (ord 'D')
then x - 3
else x - (ord 'A') + (ord 'X') ) . map ord
main = do
l <- getLine
let o = ans l
putStrLn o
| a143753/AOJ | 0512.hs | apache-2.0 | 225 | 1 | 14 | 105 | 111 | 53 | 58 | 8 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module NLP.TAG.Vanilla.Earley.TreeGen.Tests where
import qualified Data.Set as S
import Test.Tasty (TestTree)
import qualified NLP.TAG.Vanilla.Earley.TreeGen as E
import qualified NLP.TAG.Vanilla.Tree as E
import qualified NLP.TAG.Vanilla.Tests as T
-- | All the tests of the parsing algorithm.
tests :: TestTree
tests = T.testTree "NLP.TAG.Vanilla.Earley.TreeGen"
E.recognize (Just E.parse) Nothing
--------------------------------------------------
-- Testing by Hand
--------------------------------------------------
-- -- | A local test.
-- localTest1 :: IO ()
-- localTest1 = do
-- gram <- T.mkGram1
-- treeSet <- E.parse gram "S"
-- (words "Tom almost caught a mouse")
-- putStrLn ""
-- mapM_ (putStrLn . E.showTree') (S.toList treeSet)
-- -- mapM_ (putStrLn . show) (S.toList treeSet)
--
--
-- -- | A local test.
-- localTest2 :: IO ()
-- localTest2 = do
-- gram <- T.mkGram2
-- treeSet <- E.parse gram "S"
-- (words "a b a b e a b a b")
-- putStrLn ""
-- mapM_ (putStrLn . E.showTree') (S.toList treeSet)
--
--
-- -- | A local test.
-- localTest3 :: IO ()
-- localTest3 = do
-- gram <- T.mkGram4
-- treeSet <- E.parse gram "S"
-- ["make", "a", "cat", "drink"]
-- putStrLn ""
-- mapM_ (putStrLn . E.showTree') (S.toList treeSet)
| kawu/tag-vanilla | src/NLP/TAG/Vanilla/Earley/TreeGen/Tests.hs | bsd-2-clause | 1,378 | 0 | 8 | 302 | 124 | 95 | 29 | 10 | 1 |
{-# LANGUAGE CPP #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
-- |
-- Module: $HEADER$
-- Description: FromAscii instances for Text
-- Copyright: (c) 2013 Peter Trsko
-- License: BSD3
--
-- Maintainer: peter.trsko@gmail.com
-- Stability: stable
-- Portability: non-portable (CPP)
--
-- 'FromAscii' instances for Text.
module Text.Pwgen.FromAscii.Text (FromAscii(..))
where
import qualified Data.Text as Text (Text, singleton)
import qualified Data.Text.Lazy as LazyText (Text, singleton)
-- Text Builder, introduced in version 0.8.0.0.
#if MIN_VERSION_text(0, 8, 0)
import qualified Data.Text.Lazy.Builder as TextBuilder (Builder, singleton)
#endif
import Text.Pwgen.FromAscii.Class (FromAscii(..))
instance FromAscii Text.Text where
fromAscii = Text.singleton . fromAscii
{-# INLINE fromAscii #-}
instance FromAscii LazyText.Text where
fromAscii = LazyText.singleton . fromAscii
{-# INLINE fromAscii #-}
#if MIN_VERSION_text(0, 8, 0)
instance FromAscii TextBuilder.Builder where
fromAscii = TextBuilder.singleton . fromAscii
{-# INLINE fromAscii #-}
#endif
| trskop/hpwgen | src/Text/Pwgen/FromAscii/Text.hs | bsd-3-clause | 1,111 | 0 | 7 | 185 | 168 | 113 | 55 | 12 | 0 |
module System.Systemd.Config.Networkd.Network where
import Data.Monoid ((<>), Last)
import Data.Text (Text, unpack)
import Data.Text.IO (writeFile)
import GHC.Generics (Generic)
import Generics.Deriving.Monoid (GMonoid, gmempty, gmappend)
import qualified Net.Mac.Text as Mac
import qualified Net.IPv4.Text as IPv4
import qualified Net.IPv4.Range as IPv4.Range
import qualified Net.IPv4.Range.Text as IPv4.Range.Text
import Net.Types (Mac, IPv4, IPv4Range)
import Path (Abs, Dir, File, fromAbsFile, mkAbsDir, Path, (</>), parseRelFile)
import Prelude hiding (writeFile)
import System.Systemd.Config.Unit (showBool, Unit, section, printUnit, pattern Value)
data Match = Match
{ matchArchitecture :: Last Architecture
, matchDriver :: Last Text
, matchHost :: Last Text
, matchKernelCommandLine :: Last Text
, matchMacAddress :: Last Mac
, matchName :: Last Text
, matchPath :: Last Text
, matchTypeOfDevice :: Last Text
, matchVirtualization :: Last Bool
}
deriving (Generic, GMonoid, Show)
instance Monoid Match where
mempty = gmempty
mappend = gmappend
matchSection :: Match -> Unit
matchSection Match {..} =
section "Match" options
where
options =
[ ("Architecture", showArchitecture <$> matchArchitecture)
, ("Driver", matchDriver)
, ("Host", matchHost)
, ("KernelCommandLine", matchKernelCommandLine)
, ("MACAddress", Mac.encode <$> matchMacAddress)
, ("Name", matchName)
, ("Path", matchPath)
, ("Type", matchTypeOfDevice)
, ("Virtualization", showBool <$> matchVirtualization)
]
-- Accepts "yes", "no", "ipv4", or "ipv6".
data NetworkDHCP = EnableDHCP | DisableDHCP | EnableIPv4DHCP | EnableIPv6DHCP
showNetworkDHCP :: NetworkDHCP -> Text
showNetworkDHCP EnableDHCP = "yes"
showNetworkDHCP DisableDHCP = "no"
showNetworkDHCP EnableIPv4DHCP = "ipv4"
showNetworkDHCP EnableIPv6DHCP = "ipv6"
-- XXX: handle IPv6 setup...
data Network = Network
{ networkDescription :: Last Text
, networkAddress :: Last IPv4Range
, networkGateway :: Last IPv4
, networkDNS :: [IPv4]
, networkDHCP :: Last NetworkDHCP
, networkBridge :: Last Text
, networkMACVLAN :: Last Text
}
deriving (Generic, GMonoid)
instance Monoid Network where
mempty = gmempty
mappend = gmappend
networkSection :: Network -> Unit
networkSection Network {..} =
section "Network" options
where
options =
[ ("Address", (IPv4.Range.Text.encode . IPv4.Range.normalize) <$> networkAddress)
, ("Bridge", networkBridge)
, ("Description", networkDescription)
, ("DHCP", showNetworkDHCP <$> networkDHCP)
] <>
map (\dns -> ("DNS", Value . IPv4.encode $ dns)) networkDNS <>
[ ("Gateway", IPv4.encode <$> networkGateway)
, ("MACVLAN", networkMACVLAN)
]
data NetworkConfig = NetworkConfig
{ match :: Match
, network :: Network
}
deriving (Generic, GMonoid)
instance Monoid NetworkConfig where
mempty = gmempty
mappend = gmappend
toUnit :: NetworkConfig -> Unit
toUnit NetworkConfig {..} = matchSection match <> networkSection network
type NetworkDir = Path Abs Dir
type NetworkName = Text
writeNetwork :: NetworkName -> NetworkDir -> NetworkConfig -> IO (Path Abs File)
writeNetwork networkName networkDir net = do
networkFileName <- parseRelFile (unpack networkName <> ".network")
let networkFile = networkDir </> networkFileName
writeFile (fromAbsFile networkFile) config
return networkFile
where
config = printUnit . toUnit $ net
writeNetwork' :: NetworkName -> NetworkConfig -> IO (Path Abs File)
writeNetwork' name = writeNetwork name $(mkAbsDir "/etc/systemd/network/")
data Architecture
= X86
| X86_64
| Ppc
| Ppc_le
| Ppc64
| Ppc64_le
| Ia64
| Parisc
| Parisc64
| S390
| S390x
| Sparc
| Sparc64
| Mips
| Mips_le
| Mips64
| Mips64_le
| Alpha
| Arm
| Arm_be
| Arm64
| Arm64_be
| Sh
| Sh64
| M86k
| Tilegx
| Cris
deriving (Generic, Show)
showArchitecture :: Architecture -> Text
showArchitecture X86 = "x86"
showArchitecture X86_64 = "x86-64"
showArchitecture Ppc = "ppc"
showArchitecture Ppc_le = "ppc-le"
showArchitecture Ppc64 = "ppc64"
showArchitecture Ppc64_le = "ppc64-le"
showArchitecture Ia64 = "ia64"
showArchitecture Parisc = "parisc"
showArchitecture Parisc64 = "parisc64"
showArchitecture S390 = "s390"
showArchitecture S390x = "s390x"
showArchitecture Sparc = "sparc"
showArchitecture Sparc64 = "sparc64"
showArchitecture Mips = "mips"
showArchitecture Mips_le = "mips-le"
showArchitecture Mips64 = "mips64"
showArchitecture Mips64_le = "mips64-le"
showArchitecture Alpha = "alpha"
showArchitecture Arm = "arm"
showArchitecture Arm_be = "arm-be"
showArchitecture Arm64 = "arm64"
showArchitecture Arm64_be = "arm64-be"
showArchitecture Sh = "sh"
showArchitecture Sh64 = "sh64"
showArchitecture M86k = "m86k"
showArchitecture Tilegx = "tilegx"
showArchitecture Cris = "cris"
| paluh/systemd-config | src/System/Systemd/Config/Networkd/Network.hs | bsd-3-clause | 4,868 | 0 | 15 | 845 | 1,339 | 764 | 575 | -1 | -1 |
{-# language CPP #-}
{-# language QuasiQuotes #-}
{-# language TemplateHaskell #-}
#if __GLASGOW_HASKELL__ >= 800
{-# options_ghc -Wno-redundant-constraints #-}
#endif
module OpenCV.ImgProc.MiscImgTransform
( -- * Color conversion
cvtColor
, module OpenCV.ImgProc.MiscImgTransform.ColorCodes
-- * Flood filling
, floodFill
, FloodFillOperationFlags(..)
, defaultFloodFillOperationFlags
-- * Thresholding
, ThreshType(..)
, ThreshValue(..)
, threshold
-- * Watershed
, watershed
) where
import "base" Data.Bits
import "base" Data.Int
import "base" Data.Proxy ( Proxy(..) )
import "base" Data.Word
import "base" Foreign.Marshal.Alloc ( alloca )
import "base" Foreign.Storable ( peek )
import "base" GHC.TypeLits
import "primitive" Control.Monad.Primitive ( PrimMonad, PrimState, unsafePrimToPrim )
import qualified "inline-c" Language.C.Inline as C
import qualified "inline-c-cpp" Language.C.Inline.Cpp as C
import "linear" Linear.V4 ( V4 )
import "this" OpenCV.Core.Types
import "this" OpenCV.ImgProc.MiscImgTransform.ColorCodes
import "this" OpenCV.Internal.C.Inline ( openCvCtx )
import "this" OpenCV.Internal.C.Types
import "this" OpenCV.Internal.Exception
import "this" OpenCV.Internal.Core.Types.Mat
import "this" OpenCV.Internal.ImgProc.MiscImgTransform
import "this" OpenCV.Internal.ImgProc.MiscImgTransform.TypeLevel
import "this" OpenCV.Internal.ImgProc.MiscImgTransform.ColorCodes ( colorConversionCode )
import "this" OpenCV.TypeLevel
--------------------------------------------------------------------------------
C.context openCvCtx
C.include "opencv2/core.hpp"
C.include "opencv2/imgproc.hpp"
C.using "namespace cv"
--------------------------------------------------------------------------------
-- ignore next Haddock code block, because of the hash sign in the link at the end of the comment.
{- | Converts an image from one color space to another
The function converts an input image from one color space to
another. In case of a transformation to-from RGB color space, the
order of the channels should be specified explicitly (RGB or
BGR). Note that the default color format in OpenCV is often
referred to as RGB but it is actually BGR (the bytes are
reversed). So the first byte in a standard (24-bit) color image
will be an 8-bit Blue component, the second byte will be Green, and
the third byte will be Red. The fourth, fifth, and sixth bytes
would then be the second pixel (Blue, then Green, then Red), and so
on.
The conventional ranges for R, G, and B channel values are:
* 0 to 255 for 'Word8' images
* 0 to 65535 for 'Word16' images
* 0 to 1 for 'Float' images
In case of linear transformations, the range does not matter. But
in case of a non-linear transformation, an input RGB image should
be normalized to the proper value range to get the correct results,
for example, for RGB to L*u*v* transformation. For example, if you
have a 32-bit floating-point image directly converted from an 8-bit
image without any scaling, then it will have the 0..255 value range
instead of 0..1 assumed by the function. So, before calling
'cvtColor', you need first to scale the image down:
> cvtColor (img * 1/255) 'ColorConvBGR2Luv'
If you use 'cvtColor' with 8-bit images, the conversion will have
some information lost. For many applications, this will not be
noticeable but it is recommended to use 32-bit images in
applications that need the full range of colors or that convert an
image before an operation and then convert back.
If conversion adds the alpha channel, its value will set to the
maximum of corresponding channel range: 255 for 'Word8', 65535 for
'Word16', 1 for 'Float'.
Example:
@
cvtColorImg
:: forall (width :: Nat)
(width2 :: Nat)
(height :: Nat)
(channels :: Nat)
(depth :: *)
. ( Mat (ShapeT [height, width]) ('S channels) ('S depth) ~ Birds_512x341
, width2 ~ (width + width)
)
=> Mat (ShapeT [height, width2]) ('S channels) ('S depth)
cvtColorImg = exceptError $
withMatM ((Proxy :: Proxy height) ::: (Proxy :: Proxy width2) ::: Z)
(Proxy :: Proxy channels)
(Proxy :: Proxy depth)
white $ \imgM -> do
birds_gray <- pureExcept $ cvtColor gray bgr
=<< cvtColor bgr gray birds_512x341
matCopyToM imgM (V2 0 0) birds_512x341 Nothing
matCopyToM imgM (V2 w 0) birds_gray Nothing
lift $ arrowedLine imgM (V2 startX midY) (V2 pointX midY) red 4 LineType_8 0 0.15
where
h, w :: Int32
h = fromInteger $ natVal (Proxy :: Proxy height)
w = fromInteger $ natVal (Proxy :: Proxy width)
startX, pointX :: Int32
startX = round $ fromIntegral w * (0.95 :: Double)
pointX = round $ fromIntegral w * (1.05 :: Double)
midY = h \`div\` 2
@
<<doc/generated/examples/cvtColorImg.png cvtColorImg>>
<http://goo.gl/3rfrhu OpenCV Sphinx Doc>
-}
-- the link avove is minified because it includes a hash, which the CPP tries to parse and fails
-- TODO (RvD): Allow value level color codes
-- Allow statically unknown color codes: fromColor :: DS ColorCode
cvtColor :: forall (fromColor :: ColorCode)
(toColor :: ColorCode)
(shape :: DS [DS Nat])
(srcChannels :: DS Nat)
(dstChannels :: DS Nat)
(srcDepth :: DS *)
(dstDepth :: DS *)
. ( ColorConversion fromColor toColor
, ColorCodeMatchesChannels fromColor srcChannels
, dstChannels ~ 'S (ColorCodeChannels toColor)
, srcDepth `In` ['D, 'S Word8, 'S Word16, 'S Float]
, dstDepth ~ ColorCodeDepth fromColor toColor srcDepth
)
=> Proxy fromColor -- ^ Convert from 'ColorCode'. Make sure the source image has this 'ColorCode'
-> Proxy toColor -- ^ Convert to 'ColorCode'.
-> Mat shape srcChannels srcDepth -- ^ Source image
-> CvExcept (Mat shape dstChannels dstDepth)
cvtColor fromColor toColor src = unsafeWrapException $ do
dst <- newEmptyMat
handleCvException (pure $ unsafeCoerceMat dst) $
withPtr src $ \srcPtr ->
withPtr dst $ \dstPtr ->
[cvExcept|
cv::cvtColor( *$(Mat * srcPtr)
, *$(Mat * dstPtr)
, $(int32_t c'code)
, 0
);
|]
where
c'code = colorConversionCode fromColor toColor
{- | The function 'floodFill' fills a connected component starting from the seed point with the specified color.
The connectivity is determined by the color/brightness closeness of the neighbor pixels. See the OpenCV
documentation for details on the algorithm.
Example:
@
floodFillImg
:: forall (width :: Nat)
(width2 :: Nat)
(height :: Nat)
(channels :: Nat)
(depth :: *)
. ( Mat (ShapeT [height, width]) ('S channels) ('S depth) ~ Sailboat_768x512
, width2 ~ (width + width)
)
=> Mat (ShapeT [height, width2]) ('S channels) ('S depth)
floodFillImg = exceptError $
withMatM ((Proxy :: Proxy height) ::: (Proxy :: Proxy width2) ::: Z)
(Proxy :: Proxy channels)
(Proxy :: Proxy depth)
white $ \imgM -> do
sailboatEvening_768x512 <- thaw sailboat_768x512
mask <- mkMatM (Proxy :: Proxy [height + 2, width + 2])
(Proxy :: Proxy 1)
(Proxy :: Proxy Word8)
black
circle mask (V2 450 120 :: V2 Int32) 45 white (-1) LineType_AA 0
rect <- floodFill sailboatEvening_768x512 (Just mask) seedPoint eveningRed (Just tolerance) (Just tolerance) defaultFloodFillOperationFlags
rectangle sailboatEvening_768x512 rect blue 2 LineType_8 0
frozenSailboatEvening_768x512 <- freeze sailboatEvening_768x512
matCopyToM imgM (V2 0 0) sailboat_768x512 Nothing
matCopyToM imgM (V2 w 0) frozenSailboatEvening_768x512 Nothing
lift $ arrowedLine imgM (V2 startX midY) (V2 pointX midY) red 4 LineType_8 0 0.15
where
h, w :: Int32
h = fromInteger $ natVal (Proxy :: Proxy height)
w = fromInteger $ natVal (Proxy :: Proxy width)
startX, pointX :: Int32
startX = round $ fromIntegral w * (0.95 :: Double)
pointX = round $ fromIntegral w * (1.05 :: Double)
midY = h \`div\` 2
seedPoint :: V2 Int32
seedPoint = V2 100 50
eveningRed :: V4 Double
eveningRed = V4 0 100 200 255
tolerance :: V4 Double
tolerance = pure 7
@
<<doc/generated/examples/floodFillImg.png floodFillImg>>
<http://goo.gl/9XIIne OpenCV Sphinx Doc>
-}
floodFill
:: ( PrimMonad m
, channels `In` '[ 'S 1, 'S 3 ]
, depth `In` '[ 'D, 'S Word8, 'S Float, 'S Double ]
, IsPoint2 point2 Int32
, ToScalar color
)
=> Mut (Mat shape channels depth) (PrimState m)
-- ^ Input/output 1- or 3-channel, 8-bit, or floating-point image. It is modified by the function unless the FLOODFILL_MASK_ONLY flag is set.
-> Maybe (Mut (Mat (WidthAndHeightPlusTwo shape) ('S 1) ('S Word8)) (PrimState m))
-- ^ Operation mask that should be a single-channel 8-bit image, 2 pixels wider and 2 pixels taller than image. Since this is both an input and output parameter, you must take responsibility of initializing it. Flood-filling cannot go across non-zero pixels in the input mask. For example, an edge detector output can be used as a mask to stop filling at edges. On output, pixels in the mask corresponding to filled pixels in the image are set to 1 or to the a value specified in flags as described below. It is therefore possible to use the same mask in multiple calls to the function to make sure the filled areas do not overlap.
-- Note: Since the mask is larger than the filled image, a pixel (x, y) in image corresponds to the pixel (x+1, y+1) in the mask.
-> point2 Int32
-- ^ Starting point.
-> color
-- ^ New value of the repainted domain pixels.
-> Maybe color
-- ^ Maximal lower brightness/color difference between the currently observed pixel and one of its neighbors belonging to the component, or a seed pixel being added to the component. Zero by default.
-> Maybe color
-- ^ Maximal upper brightness/color difference between the currently observed pixel and one of its neighbors belonging to the component, or a seed pixel being added to the component. Zero by default.
-> FloodFillOperationFlags
-> m Rect2i
floodFill img mbMask seedPoint color mLoDiff mUpDiff opFlags =
unsafePrimToPrim $
withPtr img $ \matPtr ->
withPtr mbMask $ \maskPtr ->
withPtr (toPoint seedPoint) $ \seedPointPtr ->
withPtr (toScalar color) $ \colorPtr ->
withPtr loDiff $ \loDiffPtr ->
withPtr upDiff $ \upDiffPtr ->
withPtr rect $ \rectPtr -> do
[C.block|void {
cv::Mat * maskPtr = $(Mat * maskPtr);
cv::floodFill( *$(Mat * matPtr)
, maskPtr ? cv::_InputOutputArray(*maskPtr) : cv::_InputOutputArray(noArray())
, *$(Point2i * seedPointPtr)
, *$(Scalar * colorPtr)
, $(Rect2i * rectPtr)
, *$(Scalar * loDiffPtr)
, *$(Scalar * upDiffPtr)
, $(int32_t c'opFlags)
);
}|]
pure rect
where
rect :: Rect2i
rect = toRect HRect{ hRectTopLeft = pure 0
, hRectSize = pure 0
}
c'opFlags = marshalFloodFillOperationFlags opFlags
zeroScalar = toScalar (pure 0 :: V4 Double)
loDiff = maybe zeroScalar toScalar mLoDiff
upDiff = maybe zeroScalar toScalar mUpDiff
data FloodFillOperationFlags
= FloodFillOperationFlags
{ floodFillConnectivity :: Word8
-- ^ Connectivity value. The default value of 4 means that only the four nearest neighbor pixels (those that share
-- an edge) are considered. A connectivity value of 8 means that the eight nearest neighbor pixels (those that share
-- a corner) will be considered.
, floodFillMaskFillColor :: Word8
-- ^ Value between 1 and 255 with which to fill the mask (the default value is 1).
, floodFillFixedRange :: Bool
-- ^ If set, the difference between the current pixel and seed pixel is considered. Otherwise, the difference
-- between neighbor pixels is considered (that is, the range is floating).
, floodFillMaskOnly :: Bool
-- ^ If set, the function does not change the image ( newVal is ignored), and only fills the mask with the
-- value specified in bits 8-16 of flags as described above. This option only make sense in function variants
-- that have the mask parameter.
}
defaultFloodFillOperationFlags :: FloodFillOperationFlags
defaultFloodFillOperationFlags =
FloodFillOperationFlags
{ floodFillConnectivity = 4
, floodFillMaskFillColor = 1
, floodFillFixedRange = False
, floodFillMaskOnly = False
}
marshalFloodFillOperationFlags :: FloodFillOperationFlags -> Int32
marshalFloodFillOperationFlags opFlags =
let connectivityBits = fromIntegral (floodFillConnectivity opFlags)
maskFillColorBits = fromIntegral (floodFillMaskFillColor opFlags) `shiftL` 8
fixedRangeBits = if floodFillFixedRange opFlags then c'FLOODFILL_FIXED_RANGE else 0
fillMaskOnlyBits = if floodFillMaskOnly opFlags then c'FLOODFILL_MASK_ONLY else 0
in connectivityBits .|. maskFillColorBits .|. fixedRangeBits .|. fillMaskOnlyBits
-- TODO (RvD): Otsu and triangle are only implemented for 8 bit images.
{- | Applies a fixed-level threshold to each array element
The function applies fixed-level thresholding to a single-channel array. The
function is typically used to get a bi-level (binary) image out of a
grayscale image or for removing a noise, that is, filtering out pixels with
too small or too large values. There are several types of thresholding
supported by the function.
<http://docs.opencv.org/3.0-last-rst/modules/imgproc/doc/miscellaneous_transformations.html#threshold OpenCV Sphinx doc>
-}
threshold
:: (depth `In` [Word8, Float])
=> ThreshValue -- ^
-> ThreshType
-> (Mat shape ('S 1) ('S depth))
-> CvExcept (Mat shape ('S 1) ('S depth), Double)
threshold threshVal threshType src = unsafeWrapException $ do
dst <- newEmptyMat
alloca $ \calcThreshPtr ->
handleCvException ((unsafeCoerceMat dst, ) . realToFrac <$> peek calcThreshPtr) $
withPtr src $ \srcPtr ->
withPtr dst $ \dstPtr ->
[cvExcept|
*$(double * calcThreshPtr) =
cv::threshold( *$(Mat * srcPtr)
, *$(Mat * dstPtr)
, $(double c'threshVal)
, $(double c'maxVal)
, $(int32_t c'type)
);
|]
where
c'type = c'threshType .|. c'threshValMode
(c'threshType, c'maxVal) = marshalThreshType threshType
(c'threshValMode, c'threshVal) = marshalThreshValue threshVal
{- | Performs a marker-based image segmentation using the watershed algorithm.
The function implements one of the variants of watershed, non-parametric marker-based segmentation algorithm, described in [Meyer, F. Color Image Segmentation, ICIP92, 1992].
Before passing the image to the function, you have to roughly outline the desired regions in the image markers with positive (>0) indices. So, every region is represented as one or more connected components with the pixel values 1, 2, 3, and so on. Such markers can be retrieved from a binary mask using 'findContours' and 'drawContours'. The markers are “seeds” of the future image regions. All the other pixels in markers , whose relation to the outlined regions is not known and should be defined by the algorithm, should be set to 0’s. In the function output, each pixel in markers is set to a value of the “seed” components or to -1 at boundaries between the regions.
<http://docs.opencv.org/3.0-last-rst/modules/imgproc/doc/miscellaneous_transformations.html#watershed OpenCV Sphinx doc>
-}
watershed
:: (PrimMonad m)
=> Mat ('S [h, w]) ('S 3) ('S Word8) -- ^ Input 8-bit 3-channel image
-> Mut (Mat ('S [h, w]) ('S 1) ('S Int32)) (PrimState m) -- ^ Input/output 32-bit single-channel image (map) of markers
-> CvExceptT m ()
watershed img markers =
unsafePrimToPrim $
withPtr img $ \imgPtr ->
withPtr markers $ \markersPtr ->
[C.exp|void {
cv::watershed( *$(Mat * imgPtr)
, *$(Mat * markersPtr)
)
}|]
| Cortlandd/haskell-opencv | src/OpenCV/ImgProc/MiscImgTransform.hs | bsd-3-clause | 16,774 | 0 | 21 | 4,155 | 1,611 | 905 | 706 | -1 | -1 |
-- TODO: check that every occurrence of "die" should really be a death, and not just a "fix-it-up-and-warn"
-- boilerplate {{{
{-# LANGUAGE NoMonomorphismRestriction, FlexibleContexts #-}
module Data.SGF.Parse (
collection,
clipDate,
PropertyType(..),
properties,
extraProperties,
Property(..),
Warning(..),
ErrorType(..),
Error(..)
) where
import Control.Applicative
import Control.Arrow
import Control.Monad
import Control.Monad.Reader
import Control.Monad.State
import Control.Monad.Writer
import Data.Bits
import Data.Char
import Data.Default
import Data.Encoding
import Data.Function
import Data.List
import Data.List.Split
import Data.Maybe
import Data.Ord
import Data.Time.Calendar
import Data.Tree
import Data.Word
import Prelude hiding (round)
import Text.Parsec hiding (newline)
import Text.Parsec.Pos (newPos)
import qualified Data.Map as Map
import qualified Data.Set as Set
import Data.SGF.Parse.Encodings
import Data.SGF.Parse.Raw hiding (collection)
import Data.SGF.Types hiding (Game(..), GameInfo(..), GameNode(..), Setup(..), Move(..))
import Data.SGF.Types (Game(Game), GameNode(GameNode))
import Data.SGF.Parse.Util
import qualified Data.SGF.Parse.Raw as Raw
import qualified Data.SGF.Types as T
-- }}}
-- top level/testing {{{
translate trans state = case runStateT (runWriterT trans) state of
Left (UnknownError Nothing ) -> fail ""
Left (UnknownError (Just e)) -> fail e
Left e -> setPosition (errorPosition e) >> fail (show e)
Right ((a, warnings), _) -> return (a, warnings)
-- TODO: delete "test"
test = runParser collection () "<interactive>" . map enum
-- |
-- Parse a 'Word8' stream into an SGF collection. A collection is a list of
-- games; the documentation for 'Game' has more details. There are generally
-- two kinds of errors in SGF files: recoverable ones (which will be
-- accumulated in the ['Warning'] return) and unrecoverable ones (which will
-- result in parse errors).
collection :: Stream s m Word8 => ParsecT s u m (Collection, [Warning])
collection = second concat . unzip <$> (mapM (translate gameTree) =<< Raw.collection)
gameTree = do
hea <- parseHeader
app <- application hea
gam <- gameType
var <- variationType
siz <- size gam
fmap (Game app var siz) (parse hea gam siz False)
where
parse h g s = case g of
Go -> fmap TreeGo . nodeGo h s
Backgammon -> fmap TreeBackgammon . nodeBackgammon h
LinesOfAction -> fmap TreeLinesOfAction . nodeLinesOfAction h
Hex -> gameHex h
Octi -> fmap TreeOcti . nodeOcti h
other -> fmap (TreeOther other) . nodeOther h
-- }}}
warnAll w ps = mapM_ (\p -> maybe (return ()) (tell . (:[]) . w) =<< consume p) ps
dieEarliest e ps = dieWith e . head . sortBy (comparing position) . catMaybes =<< mapM consume ps
-- game header information {{{
getFormat = do
prop <- consumeSingle "FF"
ff <- maybe (return 1) number prop
when (ff /= 4) (dieWithPos FormatUnsupported (maybe (newPos "FF_missing" 1 1) position prop))
return ff
getEncoding = do
ws <- consumeSingle "CA"
case maybe [encodingFromString "latin1"] (guessEncoding . head . values) ws of
[encoding] -> return encoding
[] -> dieWithJust UnknownEncoding ws
_ -> dieWithJust AmbiguousEncoding ws -- pretty much guaranteed not to happen
parseHeader = liftM2 Header getFormat getEncoding
application = flip transMap "AP" . join compose . simple
gameType = do
property <- consumeSingle "GM"
gameType <- maybe (return 1) number property
if enum (minBound :: GameType) <= gameType && gameType <= enum (maxBound :: GameType)
then return (enum gameType)
else dieWithJust OutOfBounds property
variationType = transMap (\p -> number p >>= variationType' p) "ST" where
variationType' property 0 = return (T.Children, True )
variationType' property 1 = return (T.Siblings, True )
variationType' property 2 = return (T.Children, False)
variationType' property 3 = return (T.Siblings, False)
variationType' property _ = dieWith OutOfBounds property
size gameType = do
property <- consumeSingle "SZ"
case property of
Nothing -> return $ lookup gameType defaultSize
Just p -> if enum ':' `elem` head (values p)
then do
(m, n) <- join compose number p
when (m == n) . tell . return . SquareSizeSpecifiedAsRectangle . position $ p
checkValidity gameType m n property
else do
m <- number p
checkValidity gameType m m property
where
invalid t m n = or [t == Go && (m > 52 || n > 52), m < 1, n < 1]
checkValidity t m n p = when (invalid t m n) (dieWithJust OutOfBounds p) >> return (Just (m, n))
-- }}}
-- game-info properties {{{
gameInfo header =
consumeFreeformGameInfo header
>>= consumeUpdateGameInfo rank (\g v -> g { T.rankBlack = v }) "BR" header
>>= consumeUpdateGameInfo rank (\g v -> g { T.rankWhite = v }) "WR" header
>>= consumeUpdateGameInfo round (\g v -> g { T.round = v }) "RO" header
>>= consumeUpdateGameInfoMaybe result (\g v -> g { T.result = v }) "RE" header
>>= consumeUpdateGameInfoMaybe date dateUpdate "DT" header
>>= warnClipDate
>>= timeLimit
freeformGameInfo = [
("AN", T.Annotator ),
("BT", T.TeamName Black ),
("CP", T.Copyright ),
("EV", T.Event ),
("GN", T.GameName ),
("GC", T.Context ),
("ON", T.Opening ),
("OT", T.Overtime ),
("PB", T.PlayerName Black),
("PC", T.Location ),
("PW", T.PlayerName White),
("SO", T.Source ),
("US", T.User ),
("WT", T.TeamName White )
]
consumeFreeformGameInfo :: Header -> Translator (T.GameInfo ruleSet ())
consumeFreeformGameInfo header = fmap gameInfo tagValues where
(tags, types) = unzip freeformGameInfo
tagValues = mapM (transMap (simple header)) tags
gameInfo vals = (\m -> def { T.freeform = m })
. Map.fromList . catMaybes
$ zipWith (fmap . (,)) types vals
consumeUpdateGameInfo = consumeUpdateGameInfoMaybe . (return .)
consumeUpdateGameInfoMaybe fromString update property header gameInfo = do
maybeProp <- consumeSingle property
maybeString <- transMap' (simple header) maybeProp
case (maybeProp, maybeString >>= fromString) of
(Nothing, _) -> return gameInfo
(_, Nothing) -> dieWithJust BadlyFormattedValue maybeProp
(_, v) -> return (update gameInfo v)
abbreviateList xs = xs >>= \(n, v) -> [(n, v), (take 1 n, v)]
-- TODO: can we unify this with the other implementation of reading a rational?
readRational s = liftM3 (\s n d -> s * (fromInteger n + d)) maybeSign maybeNum maybeDen where
(sign, rest) = span (`elem` "+-") s
(numerator, rest') = span isDigit rest
denominator' = drop 1 rest' ++ "0"
denominator = fromInteger (read denominator') / 10 ^ length denominator'
maybeSign = lookup sign [("", 1), ("+", 1), ("-", -1)]
maybeNum = listToMaybe numerator >> return (read numerator)
maybeDen = guard (take 1 rest' `isPrefixOf` "." && all isDigit denominator') >> return denominator
rank s = fromMaybe (OtherRank s) maybeRanked where
(rank, rest) = span isDigit s
(scale, certainty) = span isAlpha rest
maybeRank = listToMaybe rank >> return (read rank)
maybeScale = lookup (map toLower scale) scales
maybeCertainty = lookup certainty certainties
maybeRanked = liftM3 Ranked maybeRank maybeScale maybeCertainty
certainties = [("", Nothing), ("?", Just Uncertain), ("*", Just Certain)]
scales = abbreviateList [("kyu", Kyu), ("dan", Dan), ("pro", Pro)]
result (c:'+':score) = liftM2 Win maybeColor maybeWinType where
maybeColor = lookup (toLower c) [('b', Black), ('w', White)]
maybeWinType = lookup (map toLower score) winTypes `mplus` fmap Score (readRational score)
winTypes = abbreviateList [("", OtherWinType), ("forfeit", Forfeit), ("time", Time), ("resign", Resign)]
result s = lookup (map toLower s) [("0", Draw), ("draw", Draw), ("void", Void), ("?", Unknown)]
timeLimit gameInfo = fmap (\v -> gameInfo { T.timeLimit = v }) (transMap real "TM")
date = expect [] . splitWhen (== ',') where
expect parsers [] = return []
expect parsers (pd:pds) = do
parsed <- msum . sequence ([parseYMD, parseYM, parseY] ++ parsers) . splitWhen (== '-') $ pd
liftM (parsed:) . ($ pds) $ case parsed of
Year {} -> expect []
Month { year = y } -> expect [parseMD y, parseM y]
Day { year = y, month = m } -> expect [parseMD y, parseD y m]
ensure p x = guard (p x) >> return x
hasLength n xs = n >= 0 && hasLength' n xs where
hasLength' n [] = n == 0
hasLength' 0 (x:xs) = False
hasLength' n (x:xs) = hasLength' (n-1) xs
ensureLength = ensure . hasLength
parseYMD ss = ensureLength 3 ss >>= \[y, m, d] -> liftM3 Day (checkY y) (checkMD m) (checkMD d)
parseYM ss = ensureLength 2 ss >>= \[y, m ] -> liftM2 Month (checkY y) (checkMD m)
parseY ss = ensureLength 1 ss >>= \[y ] -> liftM Year (checkY y)
parseMD y ss = ensureLength 2 ss >>= \[ m, d] -> liftM2 (Day y) (checkMD m) (checkMD d)
parseM y ss = ensureLength 1 ss >>= \[ m ] -> liftM (Month y) (checkMD m)
parseD y m ss = ensureLength 1 ss >>= \[ d] -> liftM (Day y m) (checkMD d)
checkY y = ensureLength 4 y >>= readM
checkMD md = ensureLength 2 md >>= readM
readM = listToMaybe . map fst . filter (null . snd) . reads
-- |
-- Clip to a valid, representable date. Years are clipped to the 0000-9999
-- range; months are clipped to the 1-12 range, and days are clipped to the
-- 1-\<number of days in the given month\> range (accounting for leap years in
-- the case of February).
--
-- If a parsed date is changed by this function, a warning is emitted.
clipDate :: PartialDate -> PartialDate
clipDate (y@Year {}) = Year . min 9999 . max 0 . year $ y
clipDate (Month { year = y, month = m }) = Month {
year = year . clipDate . Year $ y,
month = min 12 . max 1 $ m
}
clipDate (Day { year = y, month = m, day = d }) = let m' = clipDate (Month y m) in Day {
year = year m', month = month m',
day = max 1 . min (fromIntegral (gregorianMonthLength (year m') (fromIntegral (month m')))) $ d
}
warnClipDate gameInfo@(T.GameInfo { T.date = d }) = let d' = Set.map clipDate d in do
when (d /= d') (tell [InvalidDatesClipped d])
return gameInfo { T.date = d' }
dateUpdate g v = g { T.date = maybe def Set.fromList v }
round s = case words s of
[roundNumber@(_:_)] | all isDigit roundNumber
-> SimpleRound (read roundNumber)
[roundNumber@(_:_), '(':roundType] | all isDigit roundNumber && last roundType == ')'
-> FormattedRound (read roundNumber) (init roundType)
_ -> OtherRound s
-- }}}
-- move properties {{{
move move = do
color_ <- mapM has ["B", "W"]
[number_, overtimeMovesBlack_, overtimeMovesWhite_] <- mapM (transMap number) ["MN", "OB", "OW"]
[timeBlack_, timeWhite_] <- mapM (transMap real ) ["BL", "WL"]
let partialMove = def {
T.number = number_,
T.timeBlack = timeBlack_,
T.timeWhite = timeWhite_,
T.overtimeMovesBlack = overtimeMovesBlack_,
T.overtimeMovesWhite = overtimeMovesWhite_
}
case color_ of
[False, False] -> warnAll MovelessAnnotationOmitted ["KO", "BM", "DO", "IT", "TE"] >> return partialMove
[True , True ] -> dieEarliest ConcurrentBlackAndWhiteMove ["B", "W"]
[black, white] -> let color = if black then Black else White in do
Just move <- fmap msum . mapM (transMap move) $ ["B", "W"]
illegal <- fmap (maybe Possibly (const Definitely)) (transMap none "KO")
annotations <- mapM has ["BM", "DO", "IT", "TE"]
quality <- case annotations of
[False, False, False, False] -> return Nothing
[True , False, False, False] -> fmap (fmap Bad ) (transMap double "BM")
[False, False, False, True ] -> fmap (fmap Good) (transMap double "TE")
[False, True , False, False] -> transMap none "DO" >> return (Just Doubtful )
[False, False, True , False] -> transMap none "IT" >> return (Just Interesting)
_ -> dieEarliest ConcurrentAnnotations ["BM", "DO", "IT", "TE"]
return partialMove { T.move = Just (color, move), T.illegal = illegal, T.quality = quality }
-- }}}
-- setup properties {{{
setupPoint point = do
points <- mapM (transMapList (listOfPoint point)) ["AB", "AW", "AE"]
let [addBlack, addWhite, remove] = map Set.fromList points
allPoints = addBlack `Set.union` addWhite `Set.union` remove
duplicates = concat points \\ Set.elems allPoints
addWhite' = addWhite Set.\\ addBlack
remove' = remove Set.\\ (addBlack `Set.union` addWhite')
unless (null duplicates) (tell [DuplicateSetupOperationsOmitted duplicates])
setupFinish addBlack addWhite' remove'
-- note: does not (cannot, in general) check the constraint that addBlack,
-- addWhite, and remove specify disjoint sets of points
-- TODO: what, really, cannot? even if we allow ourselves a class constraint or something?
setupPointStone point stone = do
addBlack <- transMapList (listOf stone) "AB"
addWhite <- transMapList (listOf stone) "AW"
remove <- transMapList (listOfPoint point) "AE"
setupFinish (Set.fromList addBlack) (Set.fromList addWhite) (Set.fromList remove)
setupFinish addBlack addWhite remove =
liftM (T.Setup addBlack addWhite remove) (transMap color "PL")
-- }}}
-- none properties {{{
annotation :: Header -> Translator (Annotation ())
annotation header = do
comment <- transMap (text header) "C"
name <- transMap (simple header) "N"
hotspot <- transMap double "HO"
value <- transMap real "V"
judgments' <- mapM (transMap double) ["GW", "GB", "DM", "UC"]
let judgments = [(j, e) | (j, Just e) <- zip [GoodForWhite ..] judgments']
tell . map ExtraPositionalJudgmentOmitted . drop 1 $ judgments
return def {
T.comment = comment,
T.name = name,
T.hotspot = hotspot,
T.value = value,
T.judgment = listToMaybe judgments
}
addMarks marks (mark, points) = tell warning >> return result where
(ignored, inserted) = partition (`Map.member` marks) points
warning = map (DuplicateMarkupOmitted . (,) mark) ignored
result = marks `Map.union` Map.fromList [(i, mark) | i <- inserted]
markup header point = do
markedPoints <- mapM (transMapList (listOfPoint point)) ["CR", "MA", "SL", "SQ", "TR"]
marks <- foldM addMarks def . zip [Circle ..] $ markedPoints
labels <- transMapList (listOf (compose point (simple header))) "LB"
arrows <- consumePointPairs "AR"
lines <- consumePointPairs "LN"
dim <- transMapMulti ( listOfPoint point) "DD"
visible <- transMapMulti (elistOfPoint point) "VW"
numbering <- transMap number "PM"
figure <- transMap (figurePTranslator header) "FG"
tell . map DuplicateLabelOmitted $ labels \\ nubBy (on (==) fst) labels
tell [UnknownNumberingIgnored n | Just n <- [numbering], n < 0 || n > 2]
-- TODO: some kind of warning when omitting arrows and lines
return Markup {
T.marks = marks,
T.labels = Map.fromList labels,
T.arrows = prune arrows,
T.lines = prune . map canonicalize $ lines,
T.dim = fmap Set.fromList dim,
T.visible = fmap Set.fromList visible,
T.numbering = numbering >>= flip lookup (zip [0..] [Unnumbered ..]),
T.figure = figure
}
where
consumePointPairs = transMapList (listOf (join compose point))
prune = Set.fromList . filter (uncurry (/=))
canonicalize (x, y) = (min x y, max x y)
figurePTranslator header (Property { values = [[]] }) = return DefaultFigure
figurePTranslator header p = do
(flags, name) <- compose number (simple header) p
return $ if testBit flags 16
then NamedDefaultFigure name
else NamedFigure name (not . testBit flags . fromEnum)
-- }}}
-- known properties list {{{
-- |
-- Types of properties, as given in the SGF specification.
data PropertyType
= Move
| Setup
| Root
| GameInfo
| Inherit -- ^
-- Technically, these properties have type \"none\" and
-- /attribute/ \"inherit\", but the property index lists them as
-- properties of type \"inherit\" with no attributes, so we
-- follow that lead.
| None
deriving (Eq, Ord, Show, Read, Enum, Bounded)
-- |
-- All properties of each type listed in the SGF specification.
properties :: GameType -> PropertyType -> [String]
properties = liftM2 (++) properties' . extraProperties where
properties' Move = ["B", "KO", "MN", "W", "BM", "DO", "IT", "TE", "BL", "OB", "OW", "WL"]
properties' Setup = ["AB", "AE", "AW", "PL"]
properties' Root = ["AP", "CA", "FF", "GM", "ST", "SZ"]
properties' GameInfo = ["AN", "BR", "BT", "CP", "DT", "EV", "GN", "GC", "ON", "OT", "PB", "PC", "PW", "RE", "RO", "RU", "SO", "TM", "US", "WR", "WT"]
properties' Inherit = ["DD", "PM", "VW"]
properties' None = ["C", "DM", "GB", "GW", "HO", "N", "UC", "V", "AR", "CR", "LB", "LN", "MA", "SL", "SQ", "TR", "FG"]
-- }}}
-- game-specific stuff {{{
defaultSize = [
(Go , (19, 19)),
(Chess , ( 8, 8)),
(LinesOfAction , ( 8, 8)),
(Hex , (11, 11)),
(Amazons , (10, 10)),
(Gess , (20, 20))
]
ruleSetLookup rs = flip lookup rs . map toLower
ruleSetGo = ruleSetLookup [
("aga" , AGA),
("goe" , GOE),
("chinese" , Chinese),
("japanese" , Japanese),
("nz" , NewZealand)
]
ruleSetBackgammon = ruleSetLookup [
("crawford" , Crawford),
("crawford:crawfordgame" , CrawfordGame),
("jacoby" , Jacoby)
]
ruleSetOcti s = case break (== ':') s of
(major, ':':minors) -> liftM (flip OctiRuleSet (minorVariations minors )) (majorVariation major )
(majorOrMinors, "") -> liftM (flip OctiRuleSet (def )) (majorVariation majorOrMinors)
`mplus` return (OctiRuleSet Full (minorVariations majorOrMinors))
where
majorVariation = ruleSetLookup [("full", Full), ("fast", Fast), ("kids", Kids)]
minorVariation s = fromMaybe (OtherMinorVariation s) . ruleSetLookup [("edgeless", Edgeless), ("superprong", Superprong)] $ s
minorVariations = Set.fromList . map minorVariation . splitWhen (== ',')
ruleSet read maybeDefault header = do
maybeRulesetString <- transMap (simple header) "RU"
return $ case (maybeRulesetString, maybeRulesetString >>= read) of
(Nothing, _ ) -> fmap Known maybeDefault
(Just s , Nothing) -> Just (OtherRuleSet s)
(_ , Just rs) -> Just (Known rs)
ruleSetDefault = ruleSet (const Nothing) Nothing
-- |
-- Just the properties associated with specific games.
extraProperties :: GameType -> PropertyType -> [String]
extraProperties Go GameInfo = ["HA", "KM"]
extraProperties Go None = ["TB", "TW"]
extraProperties Backgammon Setup = ["CO", "CV", "DI"]
extraProperties Backgammon GameInfo = ["MI", "RE", "RU"]
extraProperties LinesOfAction GameInfo = ["IP", "IY", "SU"]
extraProperties LinesOfAction None = ["AS", "SE"]
extraProperties Hex Root = ["IS"]
extraProperties Hex GameInfo = ["IP"]
extraProperties Amazons Setup = ["AA"]
extraProperties Octi Setup = ["RP"]
extraProperties Octi GameInfo = ["BO", "WO", "NP", "NR", "NS"]
extraProperties Octi None = ["AS", "CS", "MS", "SS", "TS"]
extraProperties _ _ = []
gameInfoGo = liftM2 GameInfoGo (transMap number "HA") (transMap real "KM")
pointGo (Property { values = [[x, y]] }) | valid x && valid y = return (translate x, translate y)
where
valid x = (enum 'a' <= x && x <= enum 'z') || (enum 'A' <= x && x <= enum 'Z')
translate x = enum x - enum (if x < enum 'a' then 'A' else 'a')
pointGo p = dieWith BadlyFormattedValue p
moveGo _ (Property { values = [[]] }) = return Pass
moveGo (Just (w, h)) p = pointGo p >>= \v@(x, y) -> return $ if x >= w || y >= h then Pass else Play v
moveGo _ p = fmap Play (pointGo p)
annotationGo = do
territories <- mapM (transMap (elistOfPoint pointGo)) ["TB", "TW"]
return . Map.fromList $ [(c, Set.fromList t) | (c, Just t) <- zip [Black, White] territories]
gameHex header seenGameInfo = fmap (TreeHex []) (nodeHex header seenGameInfo)
nodeGo header size seenGameInfo = do
[hasGameInfo, hasRoot, hasSetup, hasMove] <- mapM (hasAny . properties Go) [GameInfo, Root, Setup, Move]
let setGameInfo = hasGameInfo && not seenGameInfo
duplicateGameInfo = hasGameInfo && seenGameInfo
when (hasSetup && hasMove) dieSetupAndMove
when duplicateGameInfo warnGameInfo
when hasRoot warnRoot
mGameInfo <- liftM (\x -> guard setGameInfo >> Just x) (gameInfo header)
otherGameInfo <- gameInfoGo
ruleSet_ <- ruleSet ruleSetGo Nothing header
action_ <- if hasMove then liftM Right $ move (moveGo size) else liftM Left $ setupPoint pointGo
annotation_ <- annotation header
otherAnnotation <- annotationGo
markup_ <- markup header pointGo
unknown_ <- unknownProperties
children <- gets subForest >>= mapM (\s -> put s >> nodeGo header size (seenGameInfo || hasGameInfo))
return (Node (GameNode (fmap (\gi -> gi { T.ruleSet = ruleSet_, T.otherGameInfo = otherGameInfo }) mGameInfo) action_ annotation_ { T.otherAnnotation = otherAnnotation } markup_ unknown_) children)
where
dieSetupAndMove = dieEarliest ConcurrentMoveAndSetup (properties Go =<< [Setup, Move])
warnGameInfo = warnAll ExtraGameInfoOmitted (properties Go GameInfo)
warnRoot = warnAll NestedRootPropertyOmitted (properties Go Root)
nodeBackgammon = nodeOther -- TODO
nodeLinesOfAction = nodeOther -- TODO
nodeHex = nodeOther -- TODO
nodeOcti = nodeOther -- TODO
nodeOther header seenGameInfo = return def -- TODO
-- }}}
| dmwit/sgf | Data/SGF/Parse.hs | bsd-3-clause | 23,384 | 0 | 21 | 6,411 | 7,864 | 4,185 | 3,679 | 397 | 9 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Time.Corpus
( datetime
, datetimeHoliday
, datetimeInterval
, datetimeIntervalHoliday
, datetimeOpenInterval
, examples
) where
import Data.Aeson
import qualified Data.HashMap.Strict as H
import Data.Text (Text)
import qualified Data.Time.LocalTime.TimeZone.Series as Series
import Prelude
import Data.String
import Duckling.Resolve
import Duckling.Testing.Types hiding (examples)
import Duckling.Time.Types hiding (Month)
import Duckling.TimeGrain.Types hiding (add)
import Duckling.Types hiding (Entity(..))
datetime :: Datetime -> Grain -> Context -> TimeValue
datetime d g ctx = datetimeIntervalHolidayHelper (d, Nothing) g Nothing ctx
datetimeHoliday :: Datetime -> Grain -> Text -> Context -> TimeValue
datetimeHoliday d g h ctx =
datetimeIntervalHolidayHelper (d, Nothing) g (Just h) ctx
datetimeInterval :: (Datetime, Datetime) -> Grain -> Context -> TimeValue
datetimeInterval (d1, d2) g ctx =
datetimeIntervalHolidayHelper (d1, Just d2) g Nothing ctx
datetimeIntervalHoliday ::
(Datetime, Datetime) -> Grain -> Text -> Context -> TimeValue
datetimeIntervalHoliday (d1, d2) g h ctx =
datetimeIntervalHolidayHelper (d1, Just d2) g (Just h) ctx
datetimeIntervalHolidayHelper ::
(Datetime, Maybe Datetime) -> Grain -> Maybe Text -> Context -> TimeValue
datetimeIntervalHolidayHelper (d1, md2) g hol ctx = TimeValue tv [tv] hol
where
DucklingTime (Series.ZoneSeriesTime _ tzSeries) = referenceTime ctx
tv = timeValue tzSeries TimeObject {start = dt d1, end = d, grain = g}
d = case md2 of
Nothing -> Nothing
Just d2 -> Just $ dt d2
datetimeOpenInterval
:: IntervalDirection -> Datetime -> Grain -> Context -> TimeValue
datetimeOpenInterval dir d g ctx = TimeValue tv [tv] Nothing
where
DucklingTime (Series.ZoneSeriesTime _ tzSeries) = referenceTime ctx
tv = openInterval tzSeries dir TimeObject
{start = dt d, end = Nothing, grain = g}
check :: ToJSON a => (Context -> a) -> TestPredicate
check f context Resolved{rval = RVal _ v} = case toJSON v of
Object o -> deleteValues (toJSON (f context)) == deleteValues (Object o)
_ -> False
where
deleteValues :: Value -> Value
deleteValues (Object o) = Object $ H.delete "values" o
deleteValues _ = Object H.empty
examples :: ToJSON a => (Context -> a) -> [Text] -> [Example]
examples f = examplesCustom (check f)
| facebookincubator/duckling | Duckling/Time/Corpus.hs | bsd-3-clause | 2,652 | 0 | 13 | 473 | 816 | 444 | 372 | 55 | 3 |
{-# LANGUAGE DeriveDataTypeable, RecordWildCards, OverloadedStrings #-}
module Network.IRC.Bot.Types
( User(..)
, nullUser
) where
import Data.ByteString (ByteString)
import Data.Data (Data, Typeable)
import Network.IRC as I
import Network (HostName)
data User = User
{ username :: ByteString -- ^ username on client system
, hostname :: HostName -- ^ hostname of client system
, servername :: HostName -- ^ irc server client is connected to
, realname :: ByteString -- ^ client's real name
}
deriving (Data, Typeable, Eq, Ord, Read, Show)
nullUser :: User
nullUser = User { username = ""
, hostname = "."
, servername = "."
, realname = ""
}
| eigengrau/haskell-ircbot | Network/IRC/Bot/Types.hs | bsd-3-clause | 820 | 0 | 8 | 281 | 159 | 101 | 58 | 19 | 1 |
----------------------------------------------------------------------------
-- |
-- Module : Haskell.Language.Lexer.Preprocessor.Tests
-- Copyright : (c) Sergey Vinokurov 2017
-- License : BSD3-style (see LICENSE)
-- Maintainer : serg.foo@gmail.com
-- Created : 29 May 2017
----------------------------------------------------------------------------
{-# LANGUAGE OverloadedStrings #-}
module Haskell.Language.Lexer.Preprocessor.Tests (tests) where
import Test.Tasty
import Test.Tasty.HUnit (testCase)
import Control.Arrow (left)
import Data.Text (Text)
import qualified Data.Text.Prettyprint.Doc.Ext as PP
import Data.ErrorMessage
import Data.Symbols.MacroName (mkMacroName)
import Haskell.Language.Lexer.Preprocessor
import TestUtils
tests :: TestTree
tests = testGroup "Preprocessor parsing tests"
[ defineTests
, undefTests
]
mkConstantMacroDef :: Text -> Text -> ConstantMacroDef
mkConstantMacroDef name body = ConstantMacroDef
{ cmdName = mkMacroName name
, cmdBody = body
}
mkFunctionMacroDef :: Text -> [Text] -> Text -> FunctionMacroDef
mkFunctionMacroDef name args body = FunctionMacroDef
{ fmdName = mkMacroName name
, fmdArgs = map mkMacroName args
, fmdBody = body
}
defineTests :: TestTree
defineTests = testGroup "#define"
[ testGroup "Constants"
[ testCase "Vanilla define" $
"#define foo bar"
==> PreprocessorConstant (mkConstantMacroDef "foo" "bar")
, testCase "Define with some spaces" $
"# define FOO qu ux"
==> PreprocessorConstant (mkConstantMacroDef "FOO" "qu ux")
, testCase "Define with lots of continuation lines" $
"# \\\n\
\ define \\\n\
\ FOO \\\n\
\ qu \\\n\
\ ux"
==> PreprocessorConstant (mkConstantMacroDef "FOO" "qu ux")
, testCase "Define with name split by continuation line" $
"#define FO\\\n\
\O bar"
==> PreprocessorConstant (mkConstantMacroDef "FOO" "bar")
, testCase "Malformed define starting with a number" $
"#define 1foo bar"
!=> Left "defined name > first cpp identifier char: Failed reading: satisfy"
, testGroup "Haskell-style names"
[ testCase "primes and backticks in the body" $
"#define foo'_bar` baz"
==> PreprocessorConstant (mkConstantMacroDef "foo'_bar`" "baz")
, testCase "prime at the start" $
"#define 'foo_bar baz"
==> PreprocessorConstant (mkConstantMacroDef "'foo_bar" "baz")
, testCase "backtick at the start" $
"#define `foo_bar baz"
==> PreprocessorConstant (mkConstantMacroDef "`foo_bar" "baz")
]
]
, testGroup "Macro functions"
[ testGroup "Single argument"
[ testCase "Vanilla define" $
"#define FOO(x) x"
==> PreprocessorFunction (mkFunctionMacroDef "FOO" ["x"] "x")
, testCase "Define with some spaces" $
"# define FOO( x ) x"
==> PreprocessorFunction (mkFunctionMacroDef "FOO" ["x"] "x")
]
, testGroup "Two arguments"
[ testCase "Vanilla define" $
"#define FOO(x, y) (x < y)"
==> PreprocessorFunction (mkFunctionMacroDef "FOO" ["x", "y"] "(x < y)")
, testCase "Define with with some spaces" $
"# define FOO( x , y ) ( x < y )"
==> PreprocessorFunction (mkFunctionMacroDef "FOO" ["x", "y"] "( x < y )")
, testCase "Define with lots of continuation lines" $
"# \\\n\
\ define \\\n\
\ FOO( \\\n\
\ x \\\n\
\ , \\\n\
\ y \\\n\
\ ) \\\n\
\ ( x < \\\n\
\ y )"
==> PreprocessorFunction (mkFunctionMacroDef "FOO" ["x", "y"] "( x < y )")
, testCase "Define with name split by continuation line" $
"#define FO\\\n\
\O(x \\\n\
\ , \\\n\
\ y) \\\n\
\ (y -\\\n\
\x)"
==> PreprocessorFunction (mkFunctionMacroDef "FOO" ["x", "y"] "(y -x)")
]
]
]
where
(==>) = makeAssertion' parsePreprocessorDefine
(!=>) = makeAssertion (left (PP.displayDocString . errorMessageBody) . parsePreprocessorDefine)
undefTests :: TestTree
undefTests = testGroup "#undef"
[ testCase "Vanilla undef" $
"#undef FOO"
==> mkMacroName "FOO"
, testCase "Undef with some spaces" $
"# undef FOO"
==> mkMacroName "FOO"
, testCase "Undef with lots of continuation lines" $
"# \\\n\
\ undef \\\n\
\ F\\\n\
\OO"
==> mkMacroName "FOO"
]
where
(==>) = makeAssertion' parsePreprocessorUndef
| sergv/tags-server | tests/Haskell/Language/Lexer/Preprocessor/Tests.hs | bsd-3-clause | 4,822 | 0 | 15 | 1,456 | 775 | 414 | 361 | 87 | 1 |
module Main (main) where
import Control.Monad
import System.Environment(getArgs)
import System.Exit
import Data.Char
import Data.Map (Map, (!))
import qualified Data.Map as M
import Util.Command
import Genome.Dna.Kmer
import Genome.Dna.Dna
main :: IO ()
main = do
args <- getArgs
dispatch args
dispatch :: [String] -> IO ()
dispatch ["-h"] = cltoolsUsage >> exit
dispatch ["-v"] = version >> exit
dispatch (u:("-h"):_) = putStrLn (usage u) >> exit
dispatch args = execute (readCommand args)
version = putStrLn "version 0.1"
exit = exitWith ExitSuccess
die = exitWith (ExitFailure 1)
| visood/bioalgo | app/cltools/Main.hs | bsd-3-clause | 631 | 0 | 9 | 133 | 231 | 127 | 104 | 22 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
module Api.Invoice
( Identifier (..)
, WithInvoice
, resource
, invoiceFromIdentifier
) where
import Control.Applicative
import Control.Concurrent.STM (STM, TVar, atomically, modifyTVar, readTVar)
import Control.Monad (unless)
import Control.Monad.Error (ErrorT, throwError)
import Control.Monad.Reader (ReaderT, asks)
import Control.Monad.Trans (lift, liftIO)
import Data.List (sortBy)
import Data.Ord (comparing)
import Data.Set (Set)
import Data.Time
import Data.Typeable
import Safe
import qualified Data.Foldable as F
import qualified Data.Set as Set
import qualified Data.Text as T
import Rest
import Rest.Info
import Rest.ShowUrl
import qualified Rest.Resource as R
import ApiTypes
import Type.CreateInvoice (CreateInvoice)
import Type.Invoice (Invoice (Invoice))
import Type.InvoiceError (InvoiceError (..))
import Type.Customer (Customer)
import Type.CustomerInvoice (CustomerInvoice (CustomerInvoice))
import qualified Type.CreateInvoice as CreateInvoice
import qualified Type.Invoice as Invoice
import qualified Type.Customer as Customer
data Identifier
= Latest
| ById Int
deriving (Eq, Show, Read, Typeable)
instance Info Identifier where
describe _ = "identifier"
instance ShowUrl Identifier where
showUrl Latest = "latest"
showUrl (ById i) = show i
-- | Invoice extends the root of the API with a reader containing the ways to identify a Invoice in our URLs.
-- Currently only by the title of the invoice.
type WithInvoice = ReaderT Identifier BlogApi
-- | Defines the /invoice api end-point.
resource :: Resource BlogApi WithInvoice Identifier () Void
resource = mkResourceReader
{ R.name = "invoice" -- Name of the HTTP path segment.
, R.schema = withListing () $ named [("id", singleRead ById), ("latest", single Latest)]
, R.list = const list -- list is requested by GET /invoice which gives a listing of invoices.
, R.create = Just create -- PUT /invoice to create a new Invoice.
, R.get = Just get
, R.remove = Just remove
}
invoiceFromIdentifier :: Identifier -> TVar (Set Invoice) -> STM (Maybe Invoice)
invoiceFromIdentifier i pv = finder <$> readTVar pv
where
finder = case i of
ById ident -> F.find ((== ident) . Invoice.id) . Set.toList
Latest -> headMay . sortBy (flip $ comparing Invoice.createdTime) . Set.toList
{--
-- See Tutorial
get :: Handler (ReaderT Title IO)
get :: mkIdHandler xmlJsonO $ \_ title -> liftIO readInvoiceFromDb title
--}
get :: Handler WithInvoice
get = mkIdHandler xmlJsonO $ \_ i -> do
minvoice <- liftIO . atomically . invoiceFromIdentifier i =<< (lift . lift) (asks invoices)
case minvoice of
Nothing -> throwError NotFound
Just a -> return a
-- | List Invoices with the most recent invoices first.
list :: ListHandler BlogApi
list = mkListing xmlJsonO $ \r -> do
psts <- liftIO . atomically . readTVar =<< asks invoices
return . take (count r) . drop (offset r) . sortBy (flip $ comparing Invoice.createdTime) . Set.toList $ psts
create :: Handler BlogApi
create = mkInputHandler (xmlJsonE . xmlJson) $ \(CustomerInvoice usr pst) -> do
-- Make sure the credentials are valid
checkLogin usr
pstsVar <- asks invoices
psts <- liftIO . atomically . readTVar $ pstsVar
invoice <- liftIO $ toInvoice (Set.size psts + 1) usr pst
-- Validate and save the invoice in the same transaction.
merr <- liftIO . atomically $ do
let vt = validTitle pst psts
if not vt
then return . Just $ domainReason InvalidTitle
else if not (validContent pst)
then return . Just $ domainReason InvalidContent
else modifyTVar pstsVar (Set.insert invoice) >> return Nothing
maybe (return invoice) throwError merr
remove :: Handler WithInvoice
remove = mkIdHandler id $ \_ i -> do
pstsVar <- lift . lift $ asks invoices
merr <- liftIO . atomically $ do
minvoice <- invoiceFromIdentifier i pstsVar
case minvoice of
Nothing -> return . Just $ NotFound
Just invoice -> modifyTVar pstsVar (Set.delete invoice) >> return Nothing
maybe (return ()) throwError merr
-- | Convert a Customer and CreateInvoice into a Invoice that can be saved.
toInvoice :: Int -> Customer -> CreateInvoice -> IO Invoice
toInvoice i u p = do
t <- getCurrentTime
return Invoice
{ Invoice.id = i
, Invoice.author = Customer.name u
, Invoice.createdTime = t
, Invoice.title = CreateInvoice.title p
, Invoice.content = CreateInvoice.content p
}
-- | A Invoice's title must be unique and non-empty.
validTitle :: CreateInvoice -> Set Invoice -> Bool
validTitle p psts =
let pt = CreateInvoice.title p
nonEmpty = (>= 1) . T.length $ pt
available = F.all ((pt /=) . Invoice.title) psts
in available && nonEmpty
-- | A Invoice's content must be non-empty.
validContent :: CreateInvoice -> Bool
validContent = (>= 1) . T.length . CreateInvoice.content
-- | Throw an error if the customer isn't logged in.
checkLogin :: Customer -> ErrorT (Reason e) BlogApi ()
checkLogin usr = do
usrs <- liftIO . atomically . readTVar =<< asks customers
unless (usr `F.elem` usrs) $ throwError NotAllowed
| tinkerthaler/basic-invoice-rest | example-api/Api/Invoice.hs | bsd-3-clause | 5,195 | 0 | 20 | 1,044 | 1,492 | 792 | 700 | 111 | 3 |
-- | This is a parser for HTML documents. Unlike for XML documents, it
-- must include a certain amount of error-correction to account for
-- HTML features like self-terminating tags, unterminated tags, and
-- incorrect nesting. The input is tokenised by the
-- XML lexer (a separate lexer is not required for HTML).
-- It uses a slightly extended version of the Hutton/Meijer parser
-- combinators.
module Text.XML.HaXml.Html.Parse
( htmlParse
) where
import Prelude hiding (either,maybe,sequence)
import qualified Prelude (either)
import Maybe hiding (maybe)
import Char (toLower, isSpace, isDigit, isHexDigit)
import Numeric (readDec,readHex)
import Monad
import Text.XML.HaXml.Types
import Text.XML.HaXml.Lex
import Text.XML.HaXml.Posn
import Text.ParserCombinators.Poly
-- #define DEBUG
#if defined(DEBUG)
# if ( defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ > 502 ) || \
( defined(__NHC__) && __NHC__ > 114 ) || defined(__HUGS__)
import Debug.Trace(trace)
# elif defined(__GLASGOW_HASKELL__)
import IOExts(trace)
# elif defined(__NHC__) || defined(__HBC__)
import NonStdTrace
# endif
debug :: Monad m => String -> m ()
debug s = trace s (return ())
#else
debug :: Monad m => String -> m ()
debug s = return ()
#endif
-- | The first argument is the name of the file, the second is the string
-- contents of the file. The result is the generic representation of
-- an XML document. Any errors cause program failure with message to stderr.
htmlParse :: String -> String -> Document Posn
htmlParse name = Prelude.either error id . htmlParse' name
-- | The first argument is the name of the file, the second is the string
-- contents of the file. The result is the generic representation of
-- an XML document. Any parsing errors are returned in the @Either@ type.
htmlParse' :: String -> String -> Either String (Document Posn)
htmlParse' name = Prelude.either Left (Right . simplify) . fst
. runParser document . xmlLex name
---- Document simplification ----
simplify :: Document i -> Document i
simplify (Document p st (Elem n avs cs) ms) =
Document p st (Elem n avs (deepfilter simp cs)) ms
where
simp (CElem (Elem "null" [] []) _) = False
simp (CElem (Elem n _ []) _) | n `elem` ["font","p","i","b","em"
,"tt","big","small"] = False
-- simp (CString False s _) | all isSpace s = False
simp _ = True
deepfilter p =
filter p . map (\c-> case c of
CElem (Elem n avs cs) i
-> CElem (Elem n avs (deepfilter p cs)) i
_ -> c)
-- opening any of these, they close again immediately
selfclosingtags = ["img","hr","br","meta","col","link","base"
,"param","area","frame","input"]
--closing this, implicitly closes any of those which are contained in it
closeInnerTags =
[ ("ul", ["li"])
, ("ol", ["li"])
, ("dl", ["dt","dd"])
, ("tr", ["th","td"])
, ("div", ["p"])
, ("thead", ["th","tr","td"])
, ("tfoot", ["th","tr","td"])
, ("tbody", ["th","tr","td"])
, ("table", ["th","tr","td","thead","tfoot","tbody"])
, ("caption", ["p"])
, ("th", ["p"])
, ("td", ["p"])
, ("li", ["p"])
, ("dt", ["p"])
, ("dd", ["p"])
, ("object", ["p"])
, ("map", ["p"])
, ("body", ["p"])
]
--opening this, implicitly closes that
closes :: Name -> Name -> Bool
"a" `closes` "a" = True
"li" `closes` "li" = True
"th" `closes` t | t `elem` ["th","td"] = True
"td" `closes` t | t `elem` ["th","td"] = True
"tr" `closes` t | t `elem` ["th","td","tr"] = True
"dt" `closes` t | t `elem` ["dt","dd"] = True
"dd" `closes` t | t `elem` ["dt","dd"] = True
"form" `closes` "form" = True
"label" `closes` "label" = True
_ `closes` "option" = True
"thead" `closes` t | t `elem` ["colgroup"] = True
"tfoot" `closes` t | t `elem` ["thead","colgroup"] = True
"tbody" `closes` t | t `elem` ["tbody","tfoot","thead","colgroup"] = True
"colgroup" `closes` "colgroup" = True
t `closes` "p"
| t `elem` ["p","h1","h2","h3","h4","h5","h6"
,"hr","div","ul","dl","ol","table"] = True
_ `closes` _ = False
---- Misc ----
fst3 (a,_,_) = a
snd3 (_,a,_) = a
thd3 (_,_,a) = a
---- Auxiliary Parsing Functions ----
type HParser a = Parser (Posn,TokenT) a
tok :: TokenT -> HParser TokenT
tok t = do (p,t') <- next
case t' of TokError s -> report failBad (show t) p t'
_ | t'==t -> return t
| otherwise -> report fail (show t) p t'
name :: HParser Name
--name = do {(p,TokName s) <- next; return s}
name = do (p,tok) <- next
case tok of
TokName s -> return s
TokError s -> report failBad "a name" p tok
_ -> report fail "a name" p tok
string, freetext :: HParser String
string = do (p,t) <- next
case t of TokName s -> return s
_ -> report fail "text" p t
freetext = do (p,t) <- next
case t of TokFreeText s -> return s
_ -> report fail "text" p t
maybe :: HParser a -> HParser (Maybe a)
maybe p =
( p >>= return . Just) `onFail`
( return Nothing)
either :: HParser a -> HParser b -> HParser (Either a b)
either p q =
( p >>= return . Left) `onFail`
( q >>= return . Right)
word :: String -> HParser ()
word s = do { x <- next
; case x of
(p,TokName n) | s==n -> return ()
(p,TokFreeText n) | s==n -> return ()
(p,t@(TokError _)) -> report failBad (show s) p t
(p,t) -> report fail (show s) p t
}
posn :: HParser Posn
posn = do { x@(p,_) <- next
; reparse [x]
; return p
} `onFail` return noPos
nmtoken :: HParser NmToken
nmtoken = (string `onFail` freetext)
failP, failBadP :: String -> HParser a
failP msg = do { p <- posn; fail (msg++"\n at "++show p) }
failBadP msg = do { p <- posn; failBad (msg++"\n at "++show p) }
report :: (String->HParser a) -> String -> Posn -> TokenT -> HParser a
report fail exp p t = fail ("Expected "++show exp++" but found "++show t
++"\n at "++show p)
adjustErrP :: HParser a -> (String->String) -> HParser a
p `adjustErrP` f = p `onFail` do pn <- posn
(p `adjustErr` f) `adjustErr` (++show pn)
---- XML Parsing Functions ----
document :: HParser (Document Posn)
document = do
p <- prolog `adjustErr` ("unrecognisable XML prolog\n"++)
es <- many1 (element "HTML document")
ms <- many misc
return (Document p emptyST (case map snd es of
[e] -> e
es -> Elem "html" [] (map mkCElem es))
ms)
where mkCElem e = CElem e noPos
comment :: HParser Comment
comment = do
bracket (tok TokCommentOpen) (tok TokCommentClose) freetext
processinginstruction :: HParser ProcessingInstruction
processinginstruction = do
tok TokPIOpen
commit $ do
n <- string `onFail` failP "processing instruction has no target"
f <- freetext
(tok TokPIClose `onFail` tok TokAnyClose) `onFail` failP "missing ?> or >"
return (n, f)
cdsect :: HParser CDSect
cdsect = do
tok TokSectionOpen
bracket (tok (TokSection CDATAx)) (tok TokSectionClose) chardata
prolog :: HParser Prolog
prolog = do
x <- maybe xmldecl
m1 <- many misc
dtd <- maybe doctypedecl
m2 <- many misc
return (Prolog x m1 dtd m2)
xmldecl :: HParser XMLDecl
xmldecl = do
tok TokPIOpen
(word "xml" `onFail` word "XML")
p <- posn
s <- freetext
tok TokPIClose `onFail` failBadP "missing ?> in <?xml ...?>"
(Prelude.either failP return . fst . runParser aux . xmlReLex p) s
where
aux = do
v <- versioninfo `onFail` failP "missing XML version info"
e <- maybe encodingdecl
s <- maybe sddecl
return (XMLDecl v e s)
versioninfo :: HParser VersionInfo
versioninfo = do
(word "version" `onFail` word "VERSION")
tok TokEqual
bracket (tok TokQuote) (tok TokQuote) freetext
misc :: HParser Misc
misc =
oneOf' [ ("<!--comment-->", comment >>= return . Comment)
, ("<?PI?>", processinginstruction >>= return . PI)
]
-- Question: for HTML, should we disallow in-line DTDs, allowing only externals?
-- Answer: I think so.
doctypedecl :: HParser DocTypeDecl
doctypedecl = do
tok TokSpecialOpen
tok (TokSpecial DOCTYPEx)
commit $ do
n <- name
eid <- maybe externalid
-- es <- maybe (bracket (tok TokSqOpen) (tok TokSqClose)) (many markupdecl)
tok TokAnyClose `onFail` failP "missing > in DOCTYPE decl"
-- return (DTD n eid (case es of { Nothing -> []; Just e -> e }))
return (DTD n eid [])
--markupdecl :: HParser MarkupDecl
--markupdecl =
-- ( elementdecl >>= return . Element) `onFail`
-- ( attlistdecl >>= return . AttList) `onFail`
-- ( entitydecl >>= return . Entity) `onFail`
-- ( notationdecl >>= return . Notation) `onFail`
-- ( misc >>= return . MarkupMisc) `onFail`
-- PEREF(MarkupPE,markupdecl)
--
--extsubset :: HParser ExtSubset
--extsubset = do
-- td <- maybe textdecl
-- ds <- many extsubsetdecl
-- return (ExtSubset td ds)
--
--extsubsetdecl :: HParser ExtSubsetDecl
--extsubsetdecl =
-- ( markupdecl >>= return . ExtMarkupDecl) `onFail`
-- ( conditionalsect >>= return . ExtConditionalSect) `onFail`
-- PEREF(ExtPEReference,extsubsetdecl)
sddecl :: HParser SDDecl
sddecl = do
(word "standalone" `onFail` word "STANDALONE")
commit $ do
tok TokEqual `onFail` failP "missing = in 'standalone' decl"
bracket (tok TokQuote) (tok TokQuote)
( (word "yes" >> return True) `onFail`
(word "no" >> return False) `onFail`
failP "'standalone' decl requires 'yes' or 'no' value" )
----
-- VERY IMPORTANT NOTE: The stack returned here contains those tags which
-- have been closed implicitly and need to be reopened again at the
-- earliest opportunity.
type Stack = [(Name,[Attribute])]
element :: Name -> HParser (Stack,Element Posn)
element ctx =
do
tok TokAnyOpen
(ElemTag e avs) <- elemtag
( if e `closes` ctx then
-- insert the missing close-tag, fail forward, and reparse.
( do debug ("/")
unparse ([TokEndOpen, TokName ctx, TokAnyClose,
TokAnyOpen, TokName e] ++ reformatAttrs avs)
return ([], Elem "null" [] []))
else if e `elem` selfclosingtags then
-- complete the parse straightaway.
( do tok TokEndClose -- self-closing <tag />
debug (e++"[+]")
return ([], Elem e avs [])) `onFail`
-- ( do tok TokAnyClose -- sequence <tag></tag> (**not HTML?**)
-- debug (e++"[+")
-- n <- bracket (tok TokEndOpen) (tok TokAnyClose) name
-- debug "]"
-- if e == (map toLower n :: Name)
-- then return ([], Elem e avs [])
-- else return (error "no nesting in empty tag")) `onFail`
( do tok TokAnyClose -- <tag> with no close (e.g. <IMG>)
debug (e++"[+]")
return ([], Elem e avs []))
else
(( do tok TokEndClose
debug (e++"[]")
return ([], Elem e avs [])) `onFail`
( do tok TokAnyClose `onFail` failP "missing > or /> in element tag"
debug (e++"[")
-- zz <- many (content e)
-- n <- bracket (tok TokEndOpen) (tok TokAnyClose) name
zz <- manyFinally (content e)
(tok TokEndOpen)
n <- name
commit (tok TokAnyClose)
debug "]"
let (ss,cs) = unzip zz
let s = if null ss then [] else last ss
( if e == (map toLower n :: Name) then
do unparse (reformatTags (closeInner e s))
debug "^"
return ([], Elem e avs cs)
else
do unparse [TokEndOpen, TokName n, TokAnyClose]
debug "-"
return (((e,avs):s), Elem e avs cs))
) `onFail` failP ("failed to repair non-matching tags in context: "++ctx)))
closeInner :: Name -> [(Name,[Attribute])] -> [(Name,[Attribute])]
closeInner c ts =
case lookup c closeInnerTags of
(Just these) -> filter ((`notElem` these).fst) ts
Nothing -> ts
unparse ts = do p <- posn
reparse (zip (repeat p) ts)
reformatAttrs avs = concatMap f0 avs
where f0 (a, AttValue [Left s]) = [TokName a, TokEqual, TokQuote,
TokFreeText s, TokQuote]
reformatTags ts = concatMap f0 ts
where f0 (t,avs) = [TokAnyOpen, TokName t]++reformatAttrs avs++[TokAnyClose]
content :: Name -> HParser (Stack,Content Posn)
content ctx = do { p <- posn ; content' p ctx }
where content' p ctx = oneOf'
[ ( "element", element ctx >>= \(s,e)-> return (s, CElem e p))
, ( "chardata", chardata >>= \s-> return ([], CString False s p))
, ( "reference", reference >>= \r-> return ([], CRef r p))
, ( "cdsect", cdsect >>= \c-> return ([], CString True c p))
, ( "misc", misc >>= \m-> return ([], CMisc m p))
] `adjustErrP` ("when looking for a content item,\n"++)
----
elemtag :: HParser ElemTag
elemtag = do
n <- name `adjustErrBad` ("malformed element tag\n"++)
as <- many attribute
return (ElemTag (map toLower n) as)
attribute :: HParser Attribute
attribute = do
n <- name
v <- (do tok TokEqual
attvalue) `onFail`
(return (AttValue [Left "TRUE"]))
return (map toLower n,v)
--elementdecl :: HParser ElementDecl
--elementdecl = do
-- tok TokSpecialOpen
-- tok (TokSpecial ELEMENTx)
-- n <- name `onFail` failP "missing identifier in ELEMENT decl"
-- c <- contentspec `onFail` failP "missing content spec in ELEMENT decl"
-- tok TokAnyClose `onFail` failP "expected > terminating ELEMENT decl"
-- return (ElementDecl n c)
--
--contentspec :: HParser ContentSpec
--contentspec =
-- ( word "EMPTY" >> return EMPTY) `onFail`
-- ( word "ANY" >> return ANY) `onFail`
-- ( mixed >>= return . Mixed) `onFail`
-- ( cp >>= return . ContentSpec) `onFail`
-- PEREF(ContentPE,contentspec)
--
--choice :: HParser [CP]
--choice = do
-- bracket (tok TokBraOpen) (tok TokBraClose)
-- (cp `sepby1` (tok TokPipe))
--
--sequence :: HParser [CP]
--sequence = do
-- bracket (tok TokBraOpen) (tok TokBraClose)
-- (cp `sepby1` (tok TokComma))
--
--cp :: HParser CP
--cp =
-- ( do n <- name
-- m <- modifier
-- return (TagName n m)) `onFail`
-- ( do ss <- sequence
-- m <- modifier
-- return (Seq ss m)) `onFail`
-- ( do cs <- choice
-- m <- modifier
-- return (Choice cs m)) `onFail`
-- PEREF(CPPE,cp)
--
--modifier :: HParser Modifier
--modifier =
-- ( tok TokStar >> return Star) `onFail`
-- ( tok TokQuery >> return Query) `onFail`
-- ( tok TokPlus >> return Plus) `onFail`
-- ( return None)
--
--mixed :: HParser Mixed
--mixed = do
-- tok TokBraOpen
-- tok TokHash
-- word "PCDATA"
-- cont
-- where
-- cont = ( tok TokBraClose >> return PCDATA) `onFail`
-- ( do cs <- many ( do tok TokPipe
-- n <- name
-- return n)
-- tok TokBraClose
-- tok TokStar
-- return (PCDATAplus cs))
--
--attlistdecl :: HParser AttListDecl
--attlistdecl = do
-- tok TokSpecialOpen
-- tok (TokSpecial ATTLISTx)
-- n <- name `onFail` failP "missing identifier in ATTLIST"
-- ds <- many attdef
-- tok TokAnyClose `onFail` failP "missing > terminating ATTLIST"
-- return (AttListDecl n ds)
--
--attdef :: HParser AttDef
--attdef = do
-- n <- name
-- t <- atttype `onFail` failP "missing attribute type in attlist defn"
-- d <- defaultdecl
-- return (AttDef n t d)
--
--atttype :: HParser AttType
--atttype =
-- ( word "CDATA" >> return StringType) `onFail`
-- ( tokenizedtype >>= return . TokenizedType) `onFail`
-- ( enumeratedtype >>= return . EnumeratedType)
--
--tokenizedtype :: HParser TokenizedType
--tokenizedtype =
-- ( word "ID" >> return ID) `onFail`
-- ( word "IDREF" >> return IDREF) `onFail`
-- ( word "IDREFS" >> return IDREFS) `onFail`
-- ( word "ENTITY" >> return ENTITY) `onFail`
-- ( word "ENTITIES" >> return ENTITIES) `onFail`
-- ( word "NMTOKEN" >> return NMTOKEN) `onFail`
-- ( word "NMTOKENS" >> return NMTOKENS)
--
--enumeratedtype :: HParser EnumeratedType
--enumeratedtype =
-- ( notationtype >>= return . NotationType) `onFail`
-- ( enumeration >>= return . Enumeration)
--
--notationtype :: HParser NotationType
--notationtype = do
-- word "NOTATION"
-- bracket (tok TokBraOpen) (tok TokBraClose)
-- (name `sepby1` (tok TokPipe))
--
--enumeration :: HParser Enumeration
--enumeration =
-- bracket (tok TokBraOpen) (tok TokBraClose)
-- (nmtoken `sepby1` (tok TokPipe))
--
--defaultdecl :: HParser DefaultDecl
--defaultdecl =
-- ( tok TokHash >> word "REQUIRED" >> return REQUIRED) `onFail`
-- ( tok TokHash >> word "IMPLIED" >> return IMPLIED) `onFail`
-- ( do f <- maybe (tok TokHash >> word "FIXED" >> return FIXED)
-- a <- attvalue
-- return (DefaultTo a f))
--
--conditionalsect :: HParser ConditionalSect
--conditionalsect =
-- ( do tok TokSectionOpen
-- tok (TokSection INCLUDEx)
-- tok TokSqOpen `onFail` failP "missing [ after INCLUDE"
-- i <- extsubsetdecl `onFail` failP "missing ExtSubsetDecl in INCLUDE"
-- tok TokSectionClose `onFail` failP "missing ] after INCLUDE"
-- return (IncludeSect i)) `onFail`
-- ( do tok TokSectionOpen
-- tok (TokSection IGNOREx)
-- tok TokSqOpen `onFail` failP "missing [ after IGNORE"
-- i <- many ignoresectcontents
-- tok TokSectionClose `onFail` failP "missing ] after IGNORE"
-- return (IgnoreSect i))
--
--ignoresectcontents :: HParser IgnoreSectContents
--ignoresectcontents = do
-- i <- ignore
-- is <- many (do tok TokSectionOpen
-- ic <- ignoresectcontents
-- tok TokSectionClose
-- ig <- ignore
-- return (ic,ig))
-- return (IgnoreSectContents i is)
--
--ignore :: HParser Ignore
--ignore = freetext >>= return . Ignore
reference :: HParser Reference
reference = do
bracket (tok TokAmp) (tok TokSemi) (freetext >>= val)
where
val ('#':'x':i) | all isHexDigit i
= return . RefChar . fst . head . readHex $ i
val ('#':i) | all isDigit i
= return . RefChar . fst . head . readDec $ i
val name = return . RefEntity $ name
{-
reference :: HParser Reference
reference =
( charref >>= return . RefChar) `onFail`
( entityref >>= return . RefEntity)
entityref :: HParser EntityRef
entityref = do
n <- bracket (tok TokAmp) (tok TokSemi) name
return n
charref :: HParser CharRef
charref = do
bracket (tok TokAmp) (tok TokSemi) (freetext >>= readCharVal)
where
readCharVal ('#':'x':i) = return . fst . head . readHex $ i
readCharVal ('#':i) = return . fst . head . readDec $ i
readCharVal _ = mzero
-}
--pereference :: HParser PEReference
--pereference = do
-- bracket (tok TokPercent) (tok TokSemi) nmtoken
--
--entitydecl :: HParser EntityDecl
--entitydecl =
-- ( gedecl >>= return . EntityGEDecl) `onFail`
-- ( pedecl >>= return . EntityPEDecl)
--
--gedecl :: HParser GEDecl
--gedecl = do
-- tok TokSpecialOpen
-- tok (TokSpecial ENTITYx)
-- n <- name
-- e <- entitydef `onFail` failP "missing entity defn in G ENTITY decl"
-- tok TokAnyClose `onFail` failP "expected > terminating G ENTITY decl"
-- return (GEDecl n e)
--
--pedecl :: HParser PEDecl
--pedecl = do
-- tok TokSpecialOpen
-- tok (TokSpecial ENTITYx)
-- tok TokPercent
-- n <- name
-- e <- pedef `onFail` failP "missing entity defn in P ENTITY decl"
-- tok TokAnyClose `onFail` failP "expected > terminating P ENTITY decl"
-- return (PEDecl n e)
--
--entitydef :: HParser EntityDef
--entitydef =
-- ( entityvalue >>= return . DefEntityValue) `onFail`
-- ( do eid <- externalid
-- ndd <- maybe ndatadecl
-- return (DefExternalID eid ndd))
--
--pedef :: HParser PEDef
--pedef =
-- ( entityvalue >>= return . PEDefEntityValue) `onFail`
-- ( externalid >>= return . PEDefExternalID)
externalid :: HParser ExternalID
externalid =
( do word "SYSTEM"
s <- systemliteral
return (SYSTEM s)) `onFail`
( do word "PUBLIC"
p <- pubidliteral
s <- (systemliteral `onFail` return (SystemLiteral ""))
return (PUBLIC p s))
--ndatadecl :: HParser NDataDecl
--ndatadecl = do
-- word "NDATA"
-- n <- name
-- return (NDATA n)
textdecl :: HParser TextDecl
textdecl = do
tok TokPIOpen
(word "xml" `onFail` word "XML")
v <- maybe versioninfo
e <- encodingdecl
tok TokPIClose `onFail` failP "expected ?> terminating text decl"
return (TextDecl v e)
--extparsedent :: HParser ExtParsedEnt
--extparsedent = do
-- t <- maybe textdecl
-- (_,c) <- (content "")
-- return (ExtParsedEnt t c)
--
--extpe :: HParser ExtPE
--extpe = do
-- t <- maybe textdecl
-- e <- extsubsetdecl
-- return (ExtPE t e)
encodingdecl :: HParser EncodingDecl
encodingdecl = do
(word "encoding" `onFail` word "ENCODING")
tok TokEqual `onFail` failBadP "expected = in 'encoding' decl"
f <- bracket (tok TokQuote) (tok TokQuote) freetext
return (EncodingDecl f)
--notationdecl :: HParser NotationDecl
--notationdecl = do
-- tok TokSpecialOpen
-- word "NOTATION"
-- n <- name
-- e <- either externalid publicid
-- tok TokAnyClose `onFail` failP "expected > terminating NOTATION decl"
-- return (NOTATION n e)
publicid :: HParser PublicID
publicid = do
word "PUBLICID"
p <- pubidliteral
return (PUBLICID p)
entityvalue :: HParser EntityValue
entityvalue = do
evs <- bracket (tok TokQuote) (tok TokQuote) (many ev)
return (EntityValue evs)
ev :: HParser EV
ev =
( freetext >>= return . EVString) `onFail`
-- PEREF(EVPERef,ev) `onFail`
( reference >>= return . EVRef)
attvalue :: HParser AttValue
attvalue =
( do avs <- bracket (tok TokQuote) (tok TokQuote)
(many (either freetext reference))
return (AttValue avs) ) `onFail`
( do v <- nmtoken
s <- (tok TokPercent >> return "%") `onFail` return ""
return (AttValue [Left (v++s)]) ) `onFail`
( do s <- oneOf [ tok TokPlus >> return "+"
, tok TokHash >> return "#"
]
v <- nmtoken
return (AttValue [Left (s++v)]) ) `onFail`
failP "Badly formatted attribute value"
systemliteral :: HParser SystemLiteral
systemliteral = do
s <- bracket (tok TokQuote) (tok TokQuote) freetext
return (SystemLiteral s) -- note: need to fold &...; escapes
pubidliteral :: HParser PubidLiteral
pubidliteral = do
s <- bracket (tok TokQuote) (tok TokQuote) freetext
return (PubidLiteral s) -- note: need to fold &...; escapes
chardata :: HParser CharData
chardata = freetext -- >>= return . CharData
| FranklinChen/hugs98-plus-Sep2006 | packages/HaXml/src/Text/XML/HaXml/Html/Parse.hs | bsd-3-clause | 23,765 | 0 | 27 | 6,694 | 5,501 | 2,975 | 2,526 | 334 | 5 |
-- Needed to ensure correctness, and because we can't guarantee rules fire
-- The MagicHash is for unboxed primitives (-fglasgow-exts also works)
-- We only need MagicHash if on GHC, but we can't hide it in an #ifdef
{-# LANGUAGE CPP
, MultiParamTypeClasses
, FlexibleInstances
#-}
#if __GLASGOW_HASKELL__ < 710
{-# LANGUAGE OverlappingInstances #-}
#endif
-- We don't put these in LANGUAGE, because it's CPP guarded for GHC only
{-# OPTIONS_GHC -XMagicHash #-}
{-# OPTIONS_GHC -Wall -fwarn-tabs #-}
----------------------------------------------------------------
-- ~ 2021.10.17
-- |
-- Module : Data.Number.RealToFrac
-- Copyright : Copyright (c) 2007--2021 wren gayle romano
-- License : BSD3
-- Maintainer : wren@cpan.org
-- Stability : stable
-- Portability : semi-portable (CPP, MPTC, OverlappingInstances)
--
-- This module presents a type class for generic conversion between
-- numeric types, generalizing @realToFrac@ in order to overcome
-- problems with pivoting through 'Rational'
----------------------------------------------------------------
module Data.Number.RealToFrac (RealToFrac(..)) where
import Prelude hiding (realToFrac, isInfinite, isNaN)
import qualified Prelude (realToFrac)
import Data.Number.Transfinite
#ifdef __GLASGOW_HASKELL__
import GHC.Exts
( Int(..), Float(..), Double(..)
, int2Double#
, int2Float#
, double2Float#
, float2Double#
)
#endif
----------------------------------------------------------------
-- | The 'Prelude.realToFrac' function is defined to pivot through
-- a 'Rational' according to the haskell98 spec. This is non-portable
-- and problematic as discussed in "Data.Number.Transfinite". Since
-- there is resistance to breaking from the spec, this class defines
-- a reasonable variant which deals with transfinite values
-- appropriately.
--
-- There is a generic instance from any Transfinite Real to any
-- Transfinite Fractional, using checks to ensure correctness. GHC
-- has specialized versions for some types which use primitive
-- converters instead, for large performance gains. (These definitions
-- are hidden from other compilers via CPP.) Due to a bug in Haddock
-- the specialized instances are shown twice and the generic instance
-- isn't shown at all. Since the instances are overlapped, you'll
-- need to give type signatures if the arguments to 'realToFrac'
-- are polymorphic. There's also a generic instance for any Real
-- Fractional type to itself, thus if you write any generic instances
-- beware of incoherence.
--
-- If any of these restrictions (CPP, GHC-only optimizations,
-- OverlappingInstances) are onerous to you, contact the maintainer
-- (we like patches). Note that this /does/ work for Hugs with
-- suitable options (e.g. @hugs -98 +o -F'cpp -P'@). However, Hugs
-- doesn't allow @IncoherentInstances@ nor does it allow diamonds
-- with @OverlappingInstances@, which restricts the ability to add
-- additional generic instances.
class (Real a, Fractional b) => RealToFrac a b where
realToFrac :: a -> b
instance (Real a, Fractional a) => RealToFrac a a where
realToFrac = id
instance
#if __GLASGOW_HASKELL__ >= 710
{-# OVERLAPPABLE #-}
#endif
(Real a, Transfinite a, Fractional b, Transfinite b)
=> RealToFrac a b
where
realToFrac x
| isNaN x = notANumber
| isInfinite x = if x > 0 then infinity
else negativeInfinity
| otherwise = Prelude.realToFrac x
#ifdef __GLASGOW_HASKELL__
instance
#if __GLASGOW_HASKELL__ >= 710
{-# OVERLAPPING #-}
#endif
RealToFrac Int Float where
{-# INLINE realToFrac #-}
realToFrac (I# i) = F# (int2Float# i)
instance
#if __GLASGOW_HASKELL__ >= 710
{-# OVERLAPPING #-}
#endif
RealToFrac Int Double where
{-# INLINE realToFrac #-}
realToFrac (I# i) = D# (int2Double# i)
instance
#if __GLASGOW_HASKELL__ >= 710
{-# OVERLAPPING #-}
#endif
RealToFrac Integer Float where
-- TODO: is there a more primitive way?
{-# INLINE realToFrac #-}
realToFrac j = Prelude.realToFrac j
instance
#if __GLASGOW_HASKELL__ >= 710
{-# OVERLAPPING #-}
#endif
RealToFrac Integer Double where
-- TODO: is there a more primitive way?
{-# INLINE realToFrac #-}
realToFrac j = Prelude.realToFrac j
instance
#if __GLASGOW_HASKELL__ >= 710
{-# OVERLAPPING #-}
#endif
RealToFrac Float Double where
{-# INLINE realToFrac #-}
realToFrac (F# f) = D# (float2Double# f)
instance
#if __GLASGOW_HASKELL__ >= 710
{-# OVERLAPPING #-}
#endif
RealToFrac Double Float where
{-# INLINE realToFrac #-}
realToFrac (D# d) = F# (double2Float# d)
#endif
----------------------------------------------------------------
----------------------------------------------------------- fin.
| wrengr/logfloat | src/Data/Number/RealToFrac.hs | bsd-3-clause | 4,913 | 0 | 9 | 999 | 507 | 308 | 199 | 22 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.