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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
module Main where
import Test.HUnit
import System.Exit
import Control.Monad
import ___class_dojogen___
main = do counts <- runTestTT tests
when ((errors counts, failures counts) /= (0, 0)) $
exitWith (ExitFailure 1)
tests = TestList [___camel_dojogen___Test]
___camel_dojogen___Test = TestList [
"___camel_dojogen___ 1 retorna -1" ~:
___camel_dojogen___ 1 ~=? -1,
"___camel_dojogen___ 2 retorna -1" ~:
___camel_dojogen___ 2 ~=? -1
]
| dojorio/dojogen | dojogen/generators/haskell/Test___class_dojogen___.hs | mit | 512 | 1 | 12 | 136 | 134 | 69 | 65 | -1 | -1 |
g :: Double
g = 9.8
alpha :: Double
alpha = pi / 8.0
gamma :: Double
gamma = 0.08
rollSpeed :: Double
rollSpeed = 4.0
postImpactRollSpeed :: Double -> Double
postImpactRollSpeed l = let y = 2 * g * x / l
x = 1 - ( cos $ alpha - gamma )
in sqrt $ (rollSpeed ^ 2) - y
lengthGivenPostImpactRollSpeed :: Double -> Double
lengthGivenPostImpactRollSpeed speed
returnMap :: Double -> Double
returnMap l = lengthGivenPostImpactRollSpeed $ postImpactRollSpeed l
main = putStrLn $ show $ ( returnMap 1.0, returnMap 2.0, returnMap 3.0 )
| Zomega/thesis | Wurm/RimlessWheel/calc.hs | mit | 572 | 0 | 12 | 142 | 190 | 100 | 90 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module Gen2.Utils where
import Control.Monad.State.Strict
import Data.Array
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import qualified Data.ByteString.Search as S
import Data.Char (isSpace)
import Data.List (isPrefixOf)
import Data.Text (Text)
-- import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import Compiler.JMacro
import Prelude
import DynFlags
import SrcLoc
import Outputable (defaultUserStyle, text)
import ErrUtils (Severity(..))
import FastString
import qualified Debug.Trace
import qualified GHC.Stack
import Util
trace' :: HasDebugCallStack => String -> a -> a
trace' xs a
| otherwise = a
| otherwise = Debug.Trace.trace (xs ++ "\n" ++ GHC.Stack.prettyCallStack GHC.Stack.callStack) a
trace'' :: HasDebugCallStack => String -> a -> a
trace'' xs a
| otherwise = a
| otherwise = Debug.Trace.trace (xs ++ "\n" ++ GHC.Stack.prettyCallStack GHC.Stack.callStack) a
insertAt :: Int -> a -> [a] -> [a]
insertAt 0 y xs = y:xs
insertAt n y (x:xs) | n > 0 = x : insertAt (n-1) y xs
insertAt _ _ _ = error "insertAt"
showIndent :: Show s => s -> String
showIndent x = unlines . runIndent 0 . map trim . lines . replaceParens . show $ x
where
replaceParens ('(':xs) = "\n( " ++ replaceParens xs
replaceParens (')':xs) = "\n)\n" ++ replaceParens xs
replaceParens (x:xs) = x : replaceParens xs
replaceParens [] = []
-- don't indent more than this to avoid space explosion
maxIndent = 40
indent n xs = replicate (min maxIndent n) ' ' ++ xs
runIndent n (x:xs) | "(" `isPrefixOf` x = indent n x : runIndent (n+2) xs
| ")" `isPrefixOf` x = indent (n-2) x : runIndent (n-2) xs
| all isSpace x = runIndent n xs
| otherwise = indent n x : runIndent n xs
runIndent _ [] = []
trim :: String -> String
trim = let f = dropWhile isSpace . reverse in f . f
ve :: Text -> JExpr
ve = ValExpr . JVar . TxtI
concatMapM :: (Monad m, Monoid b) => (a -> m b) -> [a] -> m b
concatMapM f xs = mapM f xs >>= return . mconcat
-- Encode integers (for example used as Unique keys) to a relatively short String
-- that's valid as part of a JS indentifier (but it might start with a number)
encodeUnique :: Int -> String
encodeUnique = reverse . go -- reversed is more compressible
where
chars = listArray (0,61) (['a'..'z'] ++ ['A'..'Z'] ++ ['0'..'9'])
go n | n < 0 = '_' : encodeUnique (negate n)
| n > 61 = let (q,r) = n `quotRem` 62
in chars ! r : encodeUnique q
| otherwise = [chars ! n]
-- GHC produces modified UTF8 that the Text package doesn't particularly like
-- unmodify it before decoding
decodeModifiedUTF8 :: B.ByteString -> Maybe Text
decodeModifiedUTF8 bs
| B.any (==0) bs = Nothing
| otherwise =
either (const Nothing) Just . TE.decodeUtf8' . unmodify $ bs
where
unmodify = BL.toStrict . S.replace (B.pack [192,128]) (B.singleton 0)
buildingDebug :: DynFlags -> Bool
buildingDebug dflags = WayDebug `elem` ways dflags
buildingProf :: DynFlags -> Bool
buildingProf dflags = WayProf `elem` ways dflags
-- use instead of ErrUtils variant to prevent being suppressed
compilationProgressMsg :: DynFlags -> String -> IO ()
compilationProgressMsg dflags msg
= ifVerbose dflags 1 (log_action dflags dflags NoReason SevOutput ghcjsSrcSpan (defaultUserStyle dflags) (text msg))
ifVerbose :: DynFlags -> Int -> IO () -> IO ()
ifVerbose dflags val act
| verbosity dflags >= val = act
| otherwise = return ()
ghcjsSrcSpan :: SrcSpan
ghcjsSrcSpan = UnhelpfulSpan (mkFastString "<GHCJS>")
| ghcjs/ghcjs | src/Gen2/Utils.hs | mit | 3,910 | 0 | 12 | 1,036 | 1,304 | 679 | 625 | -1 | -1 |
module HAD.Y2014.M02.D25.Exercise where
import Data.List
import Control.Arrow
-- Implement a variation of the RLE algorithm
-- | Compress a list with RLE
--
-- Examples:
--
-- >>> compress "Hello"
-- [('H',1),('e',1),('l',2),('o',1)]
--
-- >>> compress [1,1,1,1,1]
-- [(1,5)]
compress :: Eq a => [a] -> [(a, Int)]
compress = (map $ (&&&) head length) . group
-- | Expand a list with RLE
--
-- Examples:
--
-- >>> expand [('H',1),('e',1),('l',2),('o',1)]
-- "Hello"
--
-- >>> expand [(1,5)]
-- [1,1,1,1,1]
expand :: [(a, Int)] -> [a]
expand = ((uncurry.flip $ replicate) =<<)
-- | It should verify
-- prop> (expand . compress) xs == (xs :: String)
| smwhr/1HAD | exercises/HAD/Y2014/M02/D25/Exercise.hs | mit | 652 | 0 | 8 | 113 | 130 | 87 | 43 | 7 | 1 |
module Out.Syllable
( syllabifyWord
) where
import ClassyPrelude hiding (Word, maximumBy)
import Data.List (findIndices, findIndex)
import HelperFunctions
import Data.Phoneme
import Data.Word
import Data.Inflection
import Data.Language
-- Word's can be made up of both MorphemeS and MorphemeP's
-- The syllabifyWord function needs to deal with the MorphemeP's
-- They need to be added to previous/next syllable if possible
-- Otherwise a central/mid vowel needs to be inserted to save it
-- Syllabification
-- Given a word and sonority hierarchy, syllabify the word
syllabifyWord :: Language -> Word -> Maybe [Syllable]
syllabifyWord lang (Word m (MorphemeC _ Root rads) (MorphemeV _ Transfix patts)) = syllabifyConsRoot lang rads patts
syllabifyWord lang (Word m (MorphemeV _ Root patts) (MorphemeC _ CTransfix rads)) = syllabifyConsRoot lang rads patts
syllabifyWord _ (Word _ MorphemeC{} _) = Nothing
syllabifyWord _ (Word _ _ MorphemeC{}) = Nothing
syllabifyWord _ (Word _ MorphemeV{} _) = Nothing
syllabifyWord _ (Word _ _ MorphemeV{}) = Nothing
syllabifyWord lang (Word _ leftM rightM) = syllabifyWord lang leftM ++ syllabifyWord lang rightM
syllabifyWord _ (MorphemeS _ _ sylls) = Just sylls
syllabifyWord lang (MorphemeP _ _ ps) = sylls where
groups = breakPhonemes lang ps []
sylls = map (makeSyllable lang) <$> groups
syllabifyWord _ MorphemeC{} = Nothing
syllabifyWord _ MorphemeV{} = Nothing
-- Given a group of phonemes (and a tone?), make a proper syllable structure
makeSyllable :: Language -> [Phoneme] -> Syllable
makeSyllable lang ps = out where
nuclei = getNuclei lang
out = maybe (Syllable ps Blank [Blank] NONET NONES) foo (findIndex (`elem` nuclei) ps)
foo i = Syllable onset nucleus coda NONET NONES where
(onset, nucleus:coda) = splitAt i ps
-- Interweave Consonantal (Semitic) roots and vowel Patterns
-- Doesn't check if it results in proper syllables
syllabifyConsRoot :: Language -> [ConsCluster] -> [Syllable] -> Maybe [Syllable]
syllabifyConsRoot _ [] patts = Just (filter (Syllable [] Blank [] NONET NONES /=) patts)
syllabifyConsRoot lang rads [] = Nothing
syllabifyConsRoot lang (r1:r2:rads) (p1:p2:patts)
| p2 == Syllable [] Blank [] NONET NONES = (:) p1 <$> syllabifyConsRoot lang ((r1 ++ r2):rads) patts
| isNothing (syllabifyConsRoot lang (r2:rads) patts) = (:) p1 <$> Just [p2{getOnset = r1, getCoda = concat (r2:rads)}]
| otherwise = (:) p1 <$> syllabifyConsRoot lang (r2:rads) (p2{getOnset = r1}:patts)
syllabifyConsRoot lang [r] (p1:p2:patts)
| p2 == Syllable [] Blank [] NONET NONES = (:) p1 <$> syllabifyConsRoot lang [r] patts
| otherwise = (:) p1 <$> syllabifyConsRoot lang [] (p2{getOnset = r}:patts)
syllabifyConsRoot lang (r:rads) [p]
| p == Syllable [] Blank [] NONET NONES = Nothing
| otherwise = Just [p{getCoda = concat (r:rads)}]
{- This one is based on Sonority Hierarchy, and not valid CC/Nuclei...
breakPhonemes :: [Phoneme] -> [Phoneme] -> [[Phoneme]] -> [[Phoneme]]
breakPhonemes [] syll sonhier = [syll]
breakPhonemes phonemes [] sonhier = breakPhonemes (initMay phonemes) [lastMay phonemes] sonhier
breakPhonemes phonemes syll sonhier
-- start a new syllable for a vowel immediately after another vowel
| retrieveSon sonhier (lastMay phonemes) == length sonhier + 1
&& retrieveSon sonhier (headMay syll) == length sonhier + 1 = breakPhonemes phonemes [] sonhier ++ [syll]
-- start new syllable when at local minimum (edge case)
| length syll < 2 &&
retrieveSon sonhier (lastMay phonemes) > retrieveSon sonhier (headMay syll) = breakPhonemes (initMay phonemes) (lastMay phonemes : syll) sonhier
-- start new syllable when at local minimum
| length syll >= 2 &&
retrieveSon sonhier (lastMay phonemes) > retrieveSon sonhier (headMay syll)
&& retrieveSon sonhier (syll !! 1) >= retrieveSon sonhier (headMay syll) = breakPhonemes phonemes [] sonhier ++ [syll]
-- otherwise add next phoneme to syllable
| otherwise = breakPhonemes (initMay phonemes) (lastMay phonemes : syll) sonhier
-}
-- Input the raw string of phonemes, output groups of phonemes that correspond to syllables
breakPhonemes :: Language -> [Phoneme] -> [Phoneme] -> Maybe [[Phoneme]]
breakPhonemes _ [] _ = Just []
breakPhonemes lang ps [] = do
let nuclei = getNuclei lang
let codas = getCodaCCs lang
i <- lastMay (findIndices (`elem` nuclei) ps)
let (r, n:c) = splitAt i ps
if c `elem` codas then breakPhonemes lang r (n:c) else Nothing
breakPhonemes lang ps (n:c) = do
let onsets = getOnsetCCs lang
--let nuclei = getNuclei lang
--let codas = getCodaCCs lang
(r, o) <- dropUntil 0 (`elem` onsets) ps
f <- breakPhonemes lang r []
return (f ++ [o ++ n:c])
-- dropUntil and takeRUntilNot do different but similar things
-- Imagine a language where /br/ was valid but /r/ was not
-- dropUntil would allow /br/ in intermediate onsets, takeRUntilNot wouldn't
dropUntil :: Int -> ([a] -> Bool) -> [a] -> Maybe ([a], [a])
dropUntil i b xs
| i == length xs = Nothing
| (b . snd) (splitAt i xs) = Just (splitAt i xs)
| otherwise = dropUntil (i+1) b xs
{-
takeRUntilNot :: Int -> [a] -> ([a] -> Bool) -> Maybe [a]
takeRUntilNot 0 _ _ = Nothing
takeRUntilNot _ [] _ = Nothing
takeRUntilNot n xs b
| n < length xs = Nothing
| not.b $ takeR n xs = Just $ takeR (n-1) xs
| otherwise = takeRUntilNot (n+1) xs b
takeR :: Int -> [a] -> [a]
takeR n l = go (drop n l) l
where
go [] r = r
go (_:xs) (_:ys) = go xs ys
-}
| Brightgalrs/con-lang-gen | src/Out/Syllable.hs | mit | 5,539 | 0 | 13 | 1,092 | 1,425 | 739 | 686 | 60 | 2 |
module Hasql.Postgres.TemplateConverter where
import Hasql.Postgres.Prelude
import qualified Data.ByteString.Lazy as BL
import qualified Data.ByteString.Lazy.Builder as BB
import qualified Data.ByteString.Lazy.Builder.ASCII as BB
import qualified Hasql.Postgres.TemplateConverter.Parser as Parser
convert :: ByteString -> Either Text ByteString
convert t =
do
parts <- Parser.run t Parser.parts
return $
BL.toStrict $ BB.toLazyByteString $ mconcat $ ($ 1) $ evalState $ do
forM parts $ \case
Parser.Chunk c -> do
return c
Parser.Placeholder -> do
i <- get
put $ succ i
return $ BB.char8 '$' <> BB.wordDec i
| begriffs/hasql-postgres | library/Hasql/Postgres/TemplateConverter.hs | mit | 703 | 0 | 19 | 178 | 201 | 109 | 92 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module RunSpec (spec) where
import Control.Lens
import qualified Data.List as List
import Data.List.Lens
import System.Directory.Layout
import Test.Hspec.Lens
import Run (find)
import SpecHelper (withBiegunkaTempDirectory)
spec :: Spec
spec =
describe "find" $
around withBiegunkaTempDirectory $ do
it "deeply traverses the directory looking for files name ‘Biegunka.hs’" $ \tmpDir -> do
make tmpDir $ do
dir "foo" $
file "Biegunka.hs"
& contents ?~ ""
dir "bar" $ do
dir "baz" $
file "Biegunka.hs"
& contents ?~ ""
dir "qux" $
emptydir "quux"
file "Biegunka.hs"
& contents ?~ ""
res <- find tmpDir
res `shouldList` ["Biegunka.hs", "bar/baz/Biegunka.hs", "foo/Biegunka.hs"]
`through` sorted.traverse.prefixed tmpDir.prefixed "/"
it "ignores the directories whose name starts with a dot" $ \tmpDir -> do
make tmpDir $ do
dir "foo" $
file "Biegunka.hs"
& contents ?~ ""
dir "bar" $ do
dir ".baz" $
file "Biegunka.hs"
& contents ?~ ""
dir "qux" $
emptydir "quux"
file "Biegunka.hs"
& contents ?~ ""
res <- find tmpDir
res `shouldList` ["Biegunka.hs", "foo/Biegunka.hs"]
`through` sorted.traverse.prefixed tmpDir.prefixed "/"
where
sorted = to List.sort
| biegunka/biegunka | test/spec/RunSpec.hs | mit | 1,619 | 0 | 21 | 601 | 388 | 190 | 198 | -1 | -1 |
l = [1,2,4,5,6,7]
addone :: Integer -> Integer
addone = (\x -> x+1)
g( x, y) = x^2 + 5*y +3
{-
- 7.8 exercises
-
-
-}
mf0 :: (a -> b) -> (a -> Bool) -> [a] -> [b]
mf0 f p xs = op
where op = [f x | x<-xs , p x]
mf1 :: (a -> b) -> (a -> Bool) -> [a] -> [b]
mf1 f p xs = map f (filter p xs)
all0 :: (a -> Bool) -> [a] -> Bool
all0 p (x:xs) | null xs = p x
| otherwise = p x && all0 p xs
any0 :: (a->Bool) -> [a] -> Bool
any0 p (x:xs) | null xs = p x
| otherwise = p x || any0 p xs
all1 p xs = bc p xs (&&)
any1 p xs = bc p xs (||)
bc :: (a->Bool) -> [a] -> (Bool -> Bool ->Bool) -> Bool
bc p (x:xs) c | null xs = p x
| otherwise = c (p x) (bc p xs c)
takeWhile0 :: (a -> Bool) -> [a] -> [a]
takeWhile0 p (x:xs) | p x = x : takeWhile0 p xs
| otherwise = []
dropWhile0 :: (a->Bool) -> [a] -> [a]
dropWhile0 p (x:xs) | p x = dropWhile0 p xs
| otherwise = x : xs
map0 :: (a -> b) -> [a] -> [b]
map0 f xs = foldr (\y ys -> f y : ys ) [] xs
filter0 :: (a -> Bool) -> [a] -> [a]
-- | making a list and concatenating isn't very slick
--
filter0 p xs = foldr (\y ys -> [a | a <- [y], p y ] ++ ys) [] xs
dec2Int :: [Int] -> Int
dec2Int xs = foldl (\c x -> c*10 +x) 0 xs
curry0 :: ((a,b) -> c) -> a -> b -> c
curry0 f = (\x y -> f(x,y))
uncurry0 :: (a -> b -> c) -> (a,b) -> c
uncurry0 f = (\(x,y) -> f x y)
| codingSteve/fp101x | 20151026/lambdas.hs | cc0-1.0 | 1,478 | 0 | 12 | 529 | 948 | 497 | 451 | 36 | 1 |
import GoldenRatio
import Clay
import Control.Monad.State
import Data.Default
main = do
putCss $
do
html ?
do fs
h1 ? hs
h2 ? shs
where
ts = grTitleSize 20
hs = grHeadLineSize 20
shs = grSubHeadLineSize 20
fs = grFontSize 20
st = grSecondaryText 20
lh = grBaseLineHeight 20
| pgarg22/Pottery | test2.hs | gpl-2.0 | 398 | 0 | 14 | 173 | 104 | 52 | 52 | 17 | 1 |
module Text.Pandoc2.Parsing.Generic
where
import Text.Parsec
import Control.Applicative ((<$>), (*>))
import Control.Monad (join, guard)
-- | 'sepBy' redefined to include a 'try', so the separator
-- can fail.
sepBy :: Stream s m t
=> ParsecT s u m a -> ParsecT s u m b -> ParsecT s u m [a]
sepBy p sep = do
x <- p
xs <- many $ try (sep *> p)
return (x:xs)
upto :: Stream s m t => Int -> ParsecT s u m t -> ParsecT s u m [t]
upto n _ | n <= 0 = return []
upto n p = do
(p >>= (\x -> (x:) <$> upto (n-1) p)) <|> return []
-- | A more general form of @notFollowedBy@. This one allows any
-- type of parser to be specified, and succeeds only if that parser
-- fails. It does not consume any input.
notFollowedBy' :: (Stream s m t, Show b)
=> ParsecT s u m b -> ParsecT s u m ()
notFollowedBy' p = try $ join $ do a <- try p
return (unexpected (show a))
<|>
return (return ())
-- (This version due to Andrew Pimlott on the Haskell mailing list.)
-- | Like 'manyTill', but parses at least one element.
many1Till :: Stream s m t
=> ParsecT s u m a -> ParsecT s u m end -> ParsecT s u m [a]
many1Till p q = do
x <- p
xs <- manyTill p q
return (x:xs)
-- | Fail unless in column 1.
pInColumn1 :: Stream s m t
=> ParsecT s u m ()
pInColumn1 = do
pos <- getPosition
guard $ sourceColumn pos == 1
| jgm/pandoc2 | Text/Pandoc2/Parsing/Generic.hs | gpl-2.0 | 1,461 | 0 | 15 | 457 | 539 | 271 | 268 | 31 | 1 |
module Language.Untyped.Church where
import Language.Untyped.Syntax
id :: NamelessTerm
id = NmAbs "x" (NmVar 0)
-- Church Booleans
fls :: NamelessTerm
fls = NmAbs "t" (NmAbs "f" (NmVar 0))
tru :: NamelessTerm
tru = NmAbs "t" (NmAbs "f" (NmVar 1))
-- Church Boolean Operations
test :: NamelessTerm
test = NmAbs "l" (NmAbs "m" (NmAbs "n" (NmApp (NmApp (NmVar 2) (NmVar 1)) (NmVar 0))))
and :: NamelessTerm
and = NmAbs "b" (NmAbs "c" (NmApp (NmApp (NmVar 1) (NmVar 0)) (NmAbs "t" (NmAbs "f" (NmVar 0)))))
or :: NamelessTerm
or = NmAbs "b" (NmAbs "c" (NmApp (NmApp (NmVar 0) tru) (NmVar 0)))
not :: NamelessTerm
not = NmAbs "b" (NmApp (NmApp (NmVar 0) (NmAbs "t" (NmAbs "f" (NmVar 0)))) (NmAbs "t" (NmAbs "f" (NmVar 1))))
-- Church Pairs
pair :: NamelessTerm
pair = NmAbs "f" (NmAbs "s" (NmAbs "b" (NmApp (NmApp (NmVar 0) (NmVar 2)) (NmVar 1))))
fst :: NamelessTerm
fst = NmAbs "p" (NmApp (NmVar 0) tru)
snd :: NamelessTerm
snd = NmAbs "p" (NmApp (NmVar 0) fls)
-- Church Numerals
c0, c1, c2, c3 :: NamelessTerm
c0 = NmAbs "s" (NmAbs "z" (NmVar 0))
c1 = NmAbs "s" (NmAbs "z" (NmApp (NmVar 1) (NmVar 0)))
c2 = NmAbs "s" (NmAbs "z" (NmApp (NmVar 1) (NmApp (NmVar 1) (NmVar 0))))
c3 = NmAbs "s" (NmAbs "z" (NmApp (NmVar 1) (NmApp (NmVar 1) (NmApp (NmVar 1) (NmVar 0)))))
-- Operations on Church Numerals
scc :: NamelessTerm
scc = NmAbs "n" (NmAbs "s" (NmAbs "z" (NmApp (NmVar 1) (NmApp (NmApp (NmVar 2) (NmVar 1)) (NmVar 0)))))
plus :: NamelessTerm
plus = NmAbs "m" (NmAbs "n" (NmAbs "s" (NmAbs "z" (NmApp (NmApp (NmVar 3) (NmVar 1)) (NmApp (NmApp (NmVar 2) (NmVar 1)) (NmVar 0))))))
times :: NamelessTerm
times = NmAbs "m" (NmAbs "n" (NmAbs "s" (NmAbs "z" (NmApp (NmApp (NmVar 3) (NmApp (NmVar 2) (NmVar 1))) (NmVar 0)))))
exp :: NamelessTerm
exp = NmAbs "m" (NmAbs "n" (NmApp (NmVar 1) (NmVar 0)))
iszro :: NamelessTerm
iszro = NmAbs "m" (NmApp (NmApp (NmVar 0) (NmAbs "x" fls)) tru)
pred :: NamelessTerm
pred = undefined
subs :: NamelessTerm
subs = undefined
-- Church Lists
| juanbono/tapl-haskell | untyped/src/Language/Untyped/Church.hs | gpl-3.0 | 2,001 | 0 | 19 | 377 | 1,057 | 547 | 510 | 41 | 1 |
{-# LANGUAGE RankNTypes #-}
module Language.SPO.Parser.PrimaryParser
( runPrimaryParser
) where
-- TODO Get rid of `IO`, carry warnings and other messages around
-- before displaying them.
-- NB Warnings are shown for code that should be modified but will compile.
-- Errors, for code that will not compile.
-- Fatal errors, for internal cases that can not or have not be made
-- impossible by the type system. For any given input they should never
-- appear to the user. A Fatal indicates that something inside the
-- compiler is not behaving correctly.
import Control.Applicative ((<$>), (<*>))
import Control.Monad
import Control.Monad.IO.Class (liftIO)
import Data.Bits ((.&.), (.|.), xor, complement, shiftL, shiftR)
import Data.List (findIndices)
import qualified Data.Map.Strict as M
import qualified Data.Text as T
import Text.Parsec
import Text.Parsec.Text ()
import Text.Parsec.Expr
import qualified Text.Parsec.Token as Token
import Language.SPO.Parser.Types
scopeKeyGlobal :: T.Text
scopeKeyGlobal = "_global"
runPrimaryParser :: SourceName -> T.Text -> IO (Either ParseError Statement)
runPrimaryParser = runParserT programParser st
where st = PParserState
{ psScopes = M.singleton scopeKeyGlobal M.empty
, psCurrent = scopeKeyGlobal
}
data PScopeEntry = PScopeEntry
{ sePos :: SourcePos
, seType :: Type
, _seAss :: Maybe ExprAssignment -- underscore to get rid of unused warning
} deriving (Show)
type PScope = M.Map T.Text PScopeEntry
type PScopeMap = M.Map T.Text PScope
data PParserState = PParserState
{ psScopes :: PScopeMap
, psCurrent :: T.Text
} deriving (Show)
type PParser = ParsecT T.Text PParserState IO
type POperatorTable a = OperatorTable T.Text PParserState IO a
type PTokenParser = Token.GenTokenParser T.Text PParserState IO
type PLanguageDef = Token.GenLanguageDef T.Text PParserState IO
type ArrayDeclarationInternal = (Maybe (Maybe ExprArithmetic))
fromTagAr :: SourcePos -> Maybe (T.Text) -> Maybe (Maybe Int) -> PParser VarType
fromTagAr pos (Just "String") (Just s) = do
putWarnLn pos $
"W: For backwards " ++
"compatibility reasons, String" ++
" arrays are interpreted as " ++
"Char arrays."
return $ VTArray VTChar s
fromTagAr pos (Just "String") (Nothing) = do
putWarnLn pos $
"W: For backwards " ++
"compatibility reasons, String" ++
" arrays are interpreted as " ++
"Char arrays."
return $ VTArray VTChar Nothing
fromTagAr pos t (Just s) = do
tag <- fromTag pos t
return $ VTArray tag s
fromTagAr _ (Just "_") _ = return $ VT_
fromTagAr _ (Just "Int") _ = return $ VTInt
fromTagAr _ (Just "Float") _ = return $ VTFloat
fromTagAr _ (Just "Bool") _ = return $ VTBool
fromTagAr _ (Just "Char") _ = return $ VTChar
fromTagAr _ (Just u) _ = return $ VTUser u
fromTagAr pos _ _ = do
putWarnLn pos $ "W: No tags were" ++
" found, defaulting to Int."
return $ VTInt
fromTag :: SourcePos -> Maybe (T.Text) -> PParser VarType
fromTag pos t = fromTagAr pos t Nothing
--getAllScopes :: PParser PScopeMap
--getAllScopes = getState >>= return . fst
getScope :: T.Text -> PParser PScope
getScope sk = do
st <- getState
let sm = psScopes st
case M.lookup sk sm of
Just se -> return se
_ -> fail $ "Fatal: unknown `" ++ T.unpack sk ++ "` scope."
getCurrentScopeKey :: PParser T.Text
getCurrentScopeKey = getState >>= return . psCurrent
getCurrentScope :: PParser PScope
getCurrentScope = getCurrentScopeKey >>= getScope
getGlobalScope :: PParser PScope
getGlobalScope = getScope scopeKeyGlobal
isGlobalScope :: PParser Bool
isGlobalScope = getCurrentScopeKey >>= return . (==) scopeKeyGlobal
modifyCurrentScope :: (PScope -> PScope) -> PParser ()
modifyCurrentScope f = modifyState (\(PParserState sm cs) ->
PParserState (M.adjust f cs sm) cs)
createNewScope :: T.Text -> PParser ()
createNewScope sk = modifyState (\(PParserState sm cs) ->
PParserState (M.insert sk M.empty sm) cs)
switchScope :: T.Text -> PParser a -> PParser a
switchScope sk p = do
PParserState psm psk <- getState
case M.lookup sk psm of
Just _ -> do
modifyState (\(PParserState sm _) -> PParserState sm sk)
r <- p
modifyState (\(PParserState sm _) -> PParserState sm psk)
return r
_ -> fail "Fatal: switching to unknown scope"
lookupCurrentAndGlobal :: T.Text -> PParser (Maybe (T.Text, PScopeEntry))
lookupCurrentAndGlobal var = do
cs <- getCurrentScope
csk <- getCurrentScopeKey
case M.lookup var cs of
Just se -> return $ Just (csk, se)
_ -> do
gs <- getGlobalScope
case M.lookup var gs of
Just gse -> return $ Just (scopeKeyGlobal, gse)
_ -> return $ Nothing
-- Many thanks to Daniel Fischer for this workaround.
-- http://haskell.1045720.n5.nabble.com/Parsec-Custom-Fail-tp3131949p3131952.html
setPosAndFail :: SourcePos -> String -> PParser ()
setPosAndFail pos msg = do
setPosition pos
inp <- getInput
setInput (T.cons 'a' inp)
_ <- tokenPrim (const "") (\p _ _ -> p) Just
fail msg
putWarnLn :: SourcePos -> String -> PParser ()
putWarnLn pos msg = liftIO $ putStrLn $ show pos ++ ":\n" ++ msg
forceGlobalScope :: SourcePos -> String -> PParser ()
forceGlobalScope pos msg = do
igs <- isGlobalScope
when (not igs) $ do
setPosAndFail pos msg
forceValidateOrSetIdentifier
:: T.Text -> SourcePos -> Type -> Maybe ExprAssignment -> PParser ()
forceValidateOrSetIdentifier var pos t ass = do
csk <- getCurrentScopeKey
mvi <- lookupCurrentAndGlobal var
case mvi of
Just (sk, se) | sk == csk -> setPosAndFail pos $
"E: redefining variable found at " ++ show (sePos se)
| otherwise -> putWarnLn pos $
"W: `"++ T.unpack var ++"` is shadowing another identifier from " ++
show (sePos se)
_ -> modifyCurrentScope (M.insert var (PScopeEntry pos t ass))
forceDefined :: SourcePos -> T.Text -> (Type -> Bool) -> String -> PParser ()
forceDefined pos var f msg = do
mvi <- lookupCurrentAndGlobal var
case mvi of
Just (_, se) -> when (not $ f (seType se)) $ do
setPosAndFail pos msg
_ -> setPosAndFail pos msg
forceSetConstantArrayDeclaration
:: VarModifiers
-> T.Text
-> SourcePos
-> Maybe T.Text
-> Maybe ExprArithmetic
-> Maybe ExprAssignment
-> PParser ()
forceSetConstantArrayDeclaration ms var pos mtag marr mass = case marr of
Just mexpr -> case evalIntConstExprArithmetic mexpr of
Just size -> do
when (size < 1) $
setPosAndFail pos "E: array declared size is less than 1"
varType <- fromTagAr pos mtag (Just $ Just size)
let typ = TVar varType ms
case mass of
Just ass -> do
exprSize <- case ass of
ExprAssArrayInit exprs -> return $ length exprs
ExprAssAr (ExprString str) -> return $ T.length str
_ -> setPosAndFail pos "E: expected array initializer"
>> return 0
when (exprSize > size) $
setPosAndFail pos ("E: array initializer size is " ++
"bigger than declared size")
when (exprSize < size) $
putWarnLn pos ("W: array initializer size is " ++
"smaller than declared size")
forceValidateOrSetIdentifier var pos typ mass
_ -> forceValidateOrSetIdentifier var pos typ Nothing
_ -> setPosAndFail pos ("E: expected constant expression in " ++
"array declaration")
_ -> case mass of
Just ass -> do
exprSize <- case ass of
ExprAssArrayInit exprs -> return $ length exprs
ExprAssAr (ExprString str) -> return $ T.length str
_ -> setPosAndFail pos "E: expected array initializer"
>> return 0
varType <- fromTagAr pos mtag (Just $ Just $ exprSize)
forceValidateOrSetIdentifier var pos (TVar varType ms) mass
_ -> setPosAndFail pos "E: expected array size declaration"
evalIntConstExprArithmetic :: ExprArithmetic -> Maybe Int
evalIntConstExprArithmetic (ExprInt i) = Just (fromIntegral i)
evalIntConstExprArithmetic (ExprUnaAr op expr1) =
(intFromOpUnaArithmetic op)
<$> evalIntConstExprArithmetic expr1
evalIntConstExprArithmetic (ExprBinAr op expr1 expr2) =
(intFromOpBinArithmetic op)
<$> evalIntConstExprArithmetic expr1
<*> evalIntConstExprArithmetic expr2
evalIntConstExprArithmetic _ = Nothing
intFromOpUnaArithmetic :: OpUnaArithmetic -> (Int -> Int)
intFromOpUnaArithmetic OpNegate = (-)0
intFromOpUnaArithmetic OpPreInc = (+)1
intFromOpUnaArithmetic OpPostInc = (+)1
intFromOpUnaArithmetic OpPreDec = (-)1
intFromOpUnaArithmetic OpPostDec = (-)1
intFromOpUnaArithmetic OpBNot = complement
intFromOpBinArithmetic :: OpBinArithmetic -> (Int -> Int -> Int)
intFromOpBinArithmetic OpAdd = (+)
intFromOpBinArithmetic OpSub = (-)
intFromOpBinArithmetic OpMul = (*)
intFromOpBinArithmetic OpDiv = div
intFromOpBinArithmetic OpMod = mod
intFromOpBinArithmetic OpBAnd = (.&.)
intFromOpBinArithmetic OpBOr = (.|.)
intFromOpBinArithmetic OpBXor = xor
intFromOpBinArithmetic OpBLS = shiftL
intFromOpBinArithmetic OpBRS = shiftR
forceSetVariable
:: VarModifiers
-> T.Text
-> SourcePos
-> Maybe T.Text
-> Maybe (Maybe ExprArithmetic)
-> Maybe ExprAssignment
-> PParser VarType
forceSetVariable ms var pos mtag marr mexpr = case marr of
Just arr -> do
forceSetConstantArrayDeclaration ms var pos mtag arr mexpr
(Just (_, se)) <- lookupCurrentAndGlobal var
let (TVar varType _) = seType se
return varType
_ -> do
varType <- fromTagAr pos mtag Nothing
forceValidateOrSetIdentifier var pos (TVar varType ms) mexpr
return varType
forceReturn :: SourcePos -> Statement -> PParser ()
forceReturn pos (StmtSeq ss) = case findIndices isReturnStmt ss of
[] -> putWarnLn pos "W: no return statement in function"
[i] | i /= (length ss-1) -> setPosAndFail pos ("E: unreachable code " ++
"following return statement")
| otherwise -> return ()
_ -> setPosAndFail pos "E: multiple return statements in function"
forceReturn _ (StmtReturn _) = return ()
forceReturn pos _ = putWarnLn pos "W: no return statement in function"
langDef :: PLanguageDef
langDef = Token.LanguageDef
{ Token.commentStart = "/*"
, Token.commentEnd = "*/"
, Token.commentLine = "//"
, Token.nestedComments = True
, Token.identStart = letter
, Token.identLetter = alphaNum <|> oneOf "_'"
, Token.opStart = Token.opLetter langDef
, Token.opLetter = oneOf ":!#$%&*+./<=>?@\\^|-~"
, Token.reservedNames = [ "if", "else"
, "while", "do", "for"
, "true", "false"
, "native", "public", "normal", "static", "stock"
, "forward"
, "private", "protected"
, "new", "decl"
, "return"
, "class", "interface"
]
, Token.reservedOpNames = [ "+", "-", "*", "/", "++", "--"
, "|", "&", "^", "~", "<<", ">>"
, "<", ">", "<=", ">=", "==", "!="
, "="
, "!", "&&", "||"
]
, Token.caseSensitive = True
}
lexer :: PTokenParser
lexer = Token.makeTokenParser langDef
identifier :: PParser T.Text
identifier = Token.identifier lexer >>= return . T.pack
reserved :: String -> PParser ()
reserved = Token.reserved lexer
reservedOp :: String -> PParser ()
reservedOp = Token.reservedOp lexer
charLiteral :: PParser Char
charLiteral = Token.charLiteral lexer
stringLiteral :: PParser T.Text
stringLiteral = Token.stringLiteral lexer >>= return . T.pack
symbol :: String -> PParser String
symbol = Token.symbol lexer
integer :: PParser Integer
integer = Token.integer lexer
semicolon :: PParser ()
semicolon = Token.semi lexer >> return ()
whiteSpace :: PParser ()
whiteSpace = Token.whiteSpace lexer
commaSep :: PParser a -> PParser [a]
commaSep = Token.commaSep lexer
parens, braces ,{- angles, -} brackets :: forall a. PParser a -> PParser a
parens = Token.parens lexer -- ()
braces = Token.braces lexer -- {}
--angles = Token.angles lexer -- <>
brackets = Token.brackets lexer -- []
programParser :: PParser Statement
programParser = do
whiteSpace
stmt <- stmts globalStatement
eof
#ifdef DebugEnabled
st <- getState
pos <- getPosition
putWarnLn pos $ "Debug: -> State is below\n---\n" ++ show st ++ "\n---\n"
#endif
return stmt
stmts :: PParser Statement -> PParser Statement
stmts pstmt = do
list <- sepBy1 pstmt whiteSpace
return $ if length list == 1 then head list else StmtSeq list
globalStatement :: PParser Statement
globalStatement = funcStmt
-- <|> funcCallStmt
<|> newStmt
<|> declStmt
<|> assignStmt
funcStatement :: PParser Statement
funcStatement = funcCallStmt
<|> returnStmt
<|> ifElseStmt
<|> ifStmt
<|> whileStmt
<|> doWhileStmt
<|> forStmt
<|> assignStmt
<|> newStmt
<|> declStmt
bracedStatement :: PParser Statement
bracedStatement = (try funcStatement)
<|> braces (stmts funcStatement)
ifStmt :: PParser Statement
ifStmt = do
(cond, stmt1) <- try $ do
reserved "if"
cond <- parens exprBoolean
stmt1 <- bracedStatement
return $ (cond, stmt1)
return $ StmtIf cond stmt1
ifElseStmt :: PParser Statement
ifElseStmt = do
(cond, stmt1) <- try $ do
reserved "if"
cond <- parens exprBoolean
stmt1 <- bracedStatement
reserved "else"
return $ (cond, stmt1)
stmt2 <- bracedStatement
return $ StmtIfElse cond stmt1 stmt2
whileStmt :: PParser Statement
whileStmt = do
reserved "while"
cond <- parens exprBoolean
stmt <- bracedStatement
return $ StmtWhile cond stmt
doWhileStmt :: PParser Statement
doWhileStmt = do
reserved "do"
stmt <- bracedStatement
reserved "while"
cond <- parens exprBoolean
semicolon
return $ StmtDoWhile cond stmt
forStmt :: PParser Statement
forStmt = do
reserved "for"
(ini, cond, it) <- parens $ do
ini <- newStmt
cond <- exprBoolean
semicolon
it <- exprArithmetic
return $ (ini, cond, it)
stmt <- bracedStatement
return $ StmtFor ini cond it stmt
assignStmt :: PParser Statement
assignStmt = do
(pos, var, marr, expr) <- try $ do
pos <- getPosition
var <- identifier
marr <- arrayDeclaration
reservedOp "="
expr <- exprAssignment
_ <- semicolon
return $ (pos, var, marr, expr)
forceDefined pos var isVariable $ "E: unknown var `" ++ T.unpack var ++ "`"
case marr of
Just arr -> case arr of
Just exprIdx -> return $ StmtIndex var exprIdx expr
_ -> fail "expected index in array assignment"
_ -> return $ StmtAss var expr
returnStmt :: PParser Statement
returnStmt = do
reserved "return"
expr <- exprAssignment
semicolon
return $ StmtReturn expr
declStmt :: PParser Statement
declStmt = do
reserved "decl"
ms <- varModifiers
mtag <- tagDeclaration
pos <- getPosition
var <- identifier
marr <- arrayDeclaration
semicolon
varType <- forceSetVariable ms var pos mtag marr Nothing
return $ StmtDecl ms varType var
newStmt :: PParser Statement
newStmt = do
reserved "new"
ms <- varModifiers
mtag <- tagDeclaration
pos <- getPosition
var <- identifier
marr <- arrayDeclaration
mexpr <- optionMaybe (try (reservedOp "=" >> exprAssignment))
semicolon
varType <- forceSetVariable ms var pos mtag marr mexpr
return $ StmtNew ms varType var mexpr
funcStmt :: PParser Statement
funcStmt = do
(ms, var, args, stmt, pos, varType) <- try $ do
ms <- funcModifiers
mtag <- tagDeclaration
pos <- getPosition
var <- identifier
args <- parens $ commaSep $ do
ams <- funcArgModifiers
matag <- tagDeclaration
argpos <- getPosition
arg <- identifier
marr <- optionMaybe $ symbol "[]" >> return Nothing
expr <- optionMaybe $ do
reservedOp "="
exprAssignment
varargs <- fromTagAr argpos matag marr
return $ (ams, varargs, arg, expr)
varType <- fromTag pos mtag
forceValidateOrSetIdentifier var pos (TFunc varType ms) Nothing
createNewScope var
stmt <- switchScope var $ do
braces (stmts funcStatement)
return $ (ms, var, args, stmt, pos, varType)
forceReturn pos stmt
forceGlobalScope pos "Fatal: defining function outside of global scope"
return $ StmtFunc ms varType var args stmt
funcCallStmt :: PParser Statement
funcCallStmt = do
(var,expr) <- funcCallInternal
semicolon
return $ StmtFuncCall var expr
funcCallInternal :: PParser (T.Text, [ExprArithmetic])
funcCallInternal = do
pos <- getPosition
(var, expr) <- try $ do
var <- identifier
expr <- parens $ commaSep exprArithmetic
return $ (var, expr)
forceDefined pos var isFunc $ "E: unknown function `" ++ T.unpack var ++ "`"
return $ (var, expr)
funcModifiers :: PParser FuncModifiers
funcModifiers = do
ms <- many $ (reserved "native" >> return MFNative)
<|> (reserved "public" >> return MFPublic)
<|> (reserved "static" >> return MFStatic)
<|> (reserved "stock" >> return MFStock)
<|> (reserved "forward" >> return MFForward)
if null ms
then return [MFNormal]
else return ms
funcArgModifiers :: PParser FuncArgModifiers
funcArgModifiers = many $ (reserved "const" >> return MFAConst)
-- <|> (reserved "in" >> return OpFAIn)
-- <|> (reserved "out" >> return OpFAOut)
tagDeclaration :: PParser (Maybe T.Text)
tagDeclaration = optionMaybe $ try $ do
tag <- identifier <|> liftM T.pack (count 1 (char '_'))
reservedOp ":"
return tag
arrayDeclaration :: PParser ArrayDeclarationInternal
arrayDeclaration = optionMaybe $ try $ do
reservedOp "["
expr <- optionMaybe (try exprArithmetic)
reservedOp "]"
return expr
exprAssignment :: PParser ExprAssignment
exprAssignment = try (liftM ExprAssBool exprBoolean)
<|> liftM ExprAssAr exprArithmetic
<|> liftM ExprAssArrayInit (braces (commaSep exprArithmetic))
varModifiers :: PParser VarModifiers
varModifiers = many $ (reserved "const" >> return MVConst)
<|> (reserved "static" >> return MVStatic)
exprBoolean :: PParser ExprBoolean
exprBoolean = buildExpressionParser opBoolean termBoolean
exprArithmetic :: PParser ExprArithmetic
exprArithmetic = buildExpressionParser opArithmetic termArithmetic
opBoolean :: POperatorTable ExprBoolean
opBoolean = [ [Prefix (reservedOp "!" >> return (ExprNot )) ]
, [Infix (reservedOp "&&" >> return (ExprBinBool OpAnd)) AssocLeft]
, [Infix (reservedOp "||" >> return (ExprBinBool OpOr )) AssocLeft]
]
opArithmetic :: POperatorTable ExprArithmetic
opArithmetic =
[ [Prefix (reservedOp "-" >> return (ExprUnaAr OpNegate)) ]
, [Prefix (reservedOp "~" >> return (ExprUnaAr OpBNot)) ]
, [Prefix (reservedOp "++" >> return (ExprUnaAr OpPreInc)) ]
, [Postfix (reservedOp "++" >> return (ExprUnaAr OpPostInc)) ]
, [Prefix (reservedOp "--" >> return (ExprUnaAr OpPreDec)) ]
, [Postfix (reservedOp "--" >> return (ExprUnaAr OpPostDec)) ]
, [Infix (reservedOp "%" >> return (ExprBinAr OpMod)) AssocLeft]
, [Infix (reservedOp "*" >> return (ExprBinAr OpMul)) AssocLeft]
, [Infix (reservedOp "/" >> return (ExprBinAr OpDiv)) AssocLeft]
, [Infix (reservedOp "+" >> return (ExprBinAr OpAdd)) AssocLeft]
, [Infix (reservedOp "-" >> return (ExprBinAr OpSub)) AssocLeft]
, [Infix (reservedOp "&" >> return (ExprBinAr OpBAnd)) AssocLeft]
, [Infix (reservedOp "|" >> return (ExprBinAr OpBOr)) AssocLeft]
, [Infix (reservedOp "^" >> return (ExprBinAr OpBXor)) AssocLeft]
, [Infix (reservedOp "<<" >> return (ExprBinAr OpBLS)) AssocLeft]
, [Infix (reservedOp ">>" >> return (ExprBinAr OpBRS)) AssocLeft]
]
termArithmetic :: PParser ExprArithmetic
termArithmetic = parens exprArithmetic
<|> do pos <- getPosition
-- `try` is here to display `forceDefined` errors
(var, expr) <- try $ do
var <- identifier
expr <- brackets exprArithmetic
return $ (var, expr)
forceDefined pos var isVariable "E: not using a variable"
return $ ExprIndex var expr
<|> do (var, expr) <- funcCallInternal
return $ ExprFuncCall var expr
<|> liftM ExprVar (try identifier)
<|> liftM ExprInt (try integer)
<|> liftM ExprChar (try charLiteral)
<|> liftM ExprString (try stringLiteral)
termBoolean :: PParser ExprBoolean
termBoolean = parens exprBoolean
<|> (reserved "true" >> return (ExprBool True ))
<|> (reserved "false" >> return (ExprBool False))
<|> exprRelational
exprRelational :: PParser ExprBoolean
exprRelational = do
a1 <- exprArithmetic
op <- relation
a2 <- exprArithmetic
return $ ExprBinRel op a1 a2
relation :: PParser OpBinRelational
relation = (reservedOp ">" >> return OpGT)
<|> (reservedOp ">=" >> return OpGE)
<|> (reservedOp "<" >> return OpLT)
<|> (reservedOp "<=" >> return OpLE)
<|> (reservedOp "==" >> return OpEq)
<|> (reservedOp "!=" >> return OpNE)
| gxtaillon/spot | src/lib/Language/SPO/Parser/PrimaryParser.hs | gpl-3.0 | 23,914 | 0 | 24 | 7,600 | 6,561 | 3,238 | 3,323 | 538 | 9 |
{-|
Module : Photobooth
Description : Photobooth Core
Copyright : (c) Chris Tetreault, 2014
License : GPL-3
Stability : experimental
-}
module DMP.Photobooth where
import DMP.Photobooth.Core
import DMP.Photobooth.Core.Types
import DMP.Photobooth.Module.Types
import Control.Monad.Trans (liftIO)
import DMP.Photobooth.Module
import DMP.Photobooth.Monads
import Control.Concurrent.STM
import Control.Monad.Error
import Control.Concurrent
import Control.Monad.Trans.Maybe
import DMP.Photobooth.Loop
photoboothMain ::
CoreMonad cas ins pes phs prs trs ()
photoboothMain =
do
initModules
loopShouldDie <-
liftIO $
atomically $
newTVar False
-- launch interface
finalizeModules
{-|
Initializes all the modules
-}
initModules ::
CoreMonad cas ins pes phs prs trs ()
initModules =
do
unwrap initPersistence getPersistenceStorage
readAllConfigs
unwrap initCamera getCameraStorage
unwrap initInterface getInterfaceStorage
unwrap initPhotostrip getPhotostripStorage
unwrap initPrinter getPrinterStorage
unwrap initTrigger getTriggerStorage
return ()
{-|
Finalizes all the modules
-}
finalizeModules ::
CoreMonad cas ins pes phs prs trs ()
finalizeModules =
do
unwrap finalizeCamera getCameraStorage
unwrap finalizePrinter getPrinterStorage
unwrap finalizeTrigger getTriggerStorage
unwrap finalizePhotostrip getPhotostripStorage
unwrap finalizeInterface getInterfaceStorage
unwrap finalizePersistence getPersistenceStorage
return ()
| christetreault/dmp-photo-booth-prime | DMP/Photobooth.hs | gpl-3.0 | 1,604 | 0 | 9 | 335 | 303 | 152 | 151 | 45 | 1 |
module Epics where
import Data.List
import GHC.Exts
import Text.Printf
--import Aggregate
import Comm
import Etran
import Portfolio
import Types
import Utils
data Epic = Epic { sym::Sym, eqty::Double , ucost::Double, uvalue::Double
, cost::Pennies, value::Pennies, ret::Double} deriving (Show)
showEpic :: (Int, Epic) -> String
showEpic (n, epic) =
printf fmt n s q uc uv c v r
where
fmt = "%03d %-5s %8.2f %8.2f %8.2f %12.2f %12.2f %8.2f"
s = sym epic
q = eqty epic
uc = ucost epic
uv = uvalue epic
c = (unPennies $ cost epic) -- / 100.0
v = unPennies $ value epic
r = ret epic
epicHdr = "IDX SYM QTY UCOST UVALUE COST VALUE RET%"
every e = True
epicSum :: Pennies -> Pennies -> String
epicSum inCost inValue =
printf "0%35s %s %s" " " (show inCost) (show inValue)
deltaEtrans (inQty, inCost) e =
(inQty+eQty, inCost |+| incCost)
where
eQty = etQty e
incCost = if etIsBuy e -- incremental cost
then (etAmount e)
else (scalep inCost (eQty/ inQty))
processSymGrp comms etrans =
Epic { sym = theSym, eqty = theQty, ucost = theUcost, uvalue = theUvalue
, cost = theCost, value = theValue, ret = theRet}
where
theSym = etSym $ head etrans
sortedEtrans = sortWith etDstamp etrans
--(theQty, theCost) = foldEtrans 0.0 (Pennies 0) sortedEtrans
(theQty, theCost) = foldl deltaEtrans (0.0, Pennies 0) sortedEtrans
theUcost = 100.0 * (unPennies theCost) / theQty
theUvalue = commEndPriceOrDie comms theSym
theValue = enPennies (0.01 * theQty * theUvalue)
theRet = gainpc (unPennies theValue) (unPennies theCost)
reduceEtrans comms etrans =
(nonzeros, zeros)
where
--symGrp = groupByKey etSym etrans
symGrp = groupWith etSym etrans
epics = map (processSymGrp comms) symGrp
(nonzeros, zeros) = partition (\e -> (eqty e) > 0.0) epics
reportOn title comms etrans =
(fullTableLines, zeroLines)
where
(nonzeros, zeros) = reduceEtrans comms etrans
tableLines = map showEpic $ zip [1..] nonzeros
tCost = countPennies $ map cost nonzeros
tValue = countPennies $ map value nonzeros
sumLine = epicSum tCost tValue
fullTitle = "EPICS: " ++ title
fullTableLines = [fullTitle, epicHdr] ++ tableLines ++ [sumLine]
zeroLines = map sym zeros
subEpicsReportWithTitle title comms etrans cmp aFolio =
fst $ reportOn title comms $ feopn aFolio cmp etrans
subEpicsReport comms etrans cmp aFolio =
subEpicsReportWithTitle aFolio comms etrans cmp aFolio
reportEpics :: Ledger -> [String]
reportEpics ledger =
nonUts ++ nzTab ++ zTab1 ++ subReports
where
theEtrans = etrans ledger
etransBySym = sortWith etSym theEtrans --FIXME work around apparent groupBy bug
theComms = comms ledger
-- FIXME looks like a lot of generalisation required here
(nzTab, zTab) = reportOn "ALL" theComms etransBySym
zTab1 = ["EPICS: ZEROS"] ++ zTab ++ [";"]
-- folios = ["hal", "hl", "tdi", "tdn", "ut"]
folios = map ncAcc $ filter ncEquity $ naccs ledger
(nonUts, _) = reportOn "NON-UT" theComms $ myFolio theEtrans
subReports = concatMap (subEpicsReport theComms etransBySym (==)) folios
| blippy/sifi | src/Epics.hs | gpl-3.0 | 3,295 | 0 | 12 | 832 | 974 | 528 | 446 | 73 | 2 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ViewPatterns #-}
module Main where
import Fizz
import Fizz.Core as Fizz
import Fizz.Infuser as Infuser
import qualified Fizz.Store as Fizz
import Fizz.Utils (showDollars, between, getTime)
import Control.Monad
import Control.Concurrent
import Data.Char (toLower)
import Data.Function
import Data.List
import Data.Maybe
import qualified Data.Map as M
import qualified Data.Text as T
import Data.Time
import System.Environment (getArgs)
import Text.Cassius
import Text.Julius
import Yesod
data Fizz = Fizz T.Text
main :: IO ()
main = do
args <- getArgs
if "--debug" `elem` args
then debug
else prod args
prod :: [String] -> IO ()
prod (host:port:_) =
case reads port of
((p,_):_) -> startUp p host
_ -> error $ "Invalid port " ++ port
prod (host:_) = startUp 80 host
prod _ = error "Must specify host a la FizzWeb example.com 8080"
debug :: IO ()
debug = startUp 3000 "localhost"
startUp :: Int -> String -> IO ()
startUp port host = do
void $ forkIO Infuser.start
warp port (Fizz . T.pack $ host)
mkYesod "Fizz" [parseRoutes|
/budgets BudgetsR GET
/budgets/#CategoryPiece BudgetR GET PUT DELETE
/savings/#CategoryPiece SavingsR DELETE
/expenses ExpensesR GET
/expenses/#CategoryPiece ExpenseCategoryR GET POST
/dash DashR GET POST
/dash/fizz FizzR POST
|]
newtype CategoryPiece = CategoryPiece Category deriving (Show, Eq, Read)
wrap :: Category -> CategoryPiece
wrap = CategoryPiece
unwrap :: CategoryPiece -> Category
unwrap (CategoryPiece c) = c
categoryPath :: Category -> T.Text
categoryPath = T.pack . fmap toLower . printCategory
instance PathPiece CategoryPiece where
toPathPiece = categoryPath . unwrap
fromPathPiece = Just . wrap . mkCategory . T.unpack
instance Yesod Fizz where
approot = ApprootMaster (\(Fizz f) -> f)
postFizzR :: Handler RepXml
postFizzR = do
mBody <- lookupPostParam "Body"
let body = fromMaybe "" mBody
$(logDebug) $ "Request: " `T.append` body
let action = parseFizz . T.unpack $ body
content <- liftIO . doFizz $ action
let responseBody = wrapBody . T.pack $ content
$(logDebug) $ "Response: " `T.append` responseBody
return . RepXml . toContent $ responseBody
where
wrapBody :: T.Text -> T.Text
wrapBody c = "<Response><Sms>"
`T.append` c `T.append` "</Sms></Response>"
getBudgetsR :: Handler Html
getBudgetsR = defaultLayout $ do
setTitle "Fizzckle"
journal <- liftIO Fizz.loadJournal
let allBudgets = filter ((>0) . getBudgetValue) . fmap snd . mostRecentBudgets $ journal
let activeCategories = fmap getBudgetCategory allBudgets :: [Category]
let spentEach = fmap (\c
-> totalSpent
. filter (spendCategory c . snd)
. takeWhile (not . budgetCategory c . snd)
. reverse
$ journal) $ activeCategories
let totals = zip activeCategories spentEach
let
(budgets, savings)
= partition ((==Expense) . getBudgetType)
$ allBudgets
let totalBudget = sum . fmap getMonthlyValue $ (budgets ++ savings)
now <- liftIO getTime
let monthStart = (toMonthStart . localDay) now
let lastMonthStart = (toMonthStart . addGregorianMonthsClip (negate 1)) monthStart
let earned = totalEarned . filter ((between lastMonthStart monthStart) . fst) $ journal
let realized = totalRealized . filter ((>monthStart) . fst) $ journal
let disposable = earned + realized
let savedTotals = fmap (\(c, j) -> (c, totalSaved j - totalRealized j)) . Fizz.categories $ journal
$(whamletFile "budgets.hamlet")
toWidget $(cassiusFile "budgets.cassius")
addScriptRemote "http://code.jquery.com/jquery-1.10.2.min.js"
addScriptRemote "https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"
toWidget $(juliusFile "budgets.julius")
getBudgetR :: CategoryPiece -> Handler Html
getBudgetR _ = defaultLayout [whamlet|Content!|]
putBudgetR :: CategoryPiece -> Handler ()
putBudgetR c = do
mv <- lookupPostParam "value"
mf <- lookupPostParam "freq"
mt <- lookupPostParam "type"
let
mbe = newBudgetEntry (unwrap c)
<$> (mv >>= maybeReadT)
<*> (mf >>= maybeReadT)
<*> (mt >>= maybeReadT)
case mbe of
Just be -> liftIO $ Fizz.budget (noTimestamp be)
Nothing -> return ()
deleteBudgetR :: CategoryPiece -> Handler ()
deleteBudgetR cp = liftIO $ do
journal <- Fizz.loadJournal
let budget = mostRecentBudgets journal
case lookup (unwrap cp) budget of
(Just be) -> Fizz.budget (noTimestamp be)
Nothing -> return ()
deleteSavingsR :: CategoryPiece -> Handler ()
deleteSavingsR cp = liftIO $ do
journal <- Fizz.loadJournal
let savingsToRealize = getSavings journal
(Fizz.realize . noTimestamp) (newExpenseEntry c savingsToRealize ("Realized " ++ printCategory c))
where
c = unwrap cp
getSavings = totalSaved
. filter ((==c) . getCategory . snd)
. takeWhile
( not
. (\e -> isRealize e && getCategory e == c)
. snd)
. reverse
getExpensesR :: Handler Html
getExpensesR = defaultLayout $ do
journal <- liftIO Fizz.loadJournal
let rows = toRows . groupExpenses $ journal
toWidget $(cassiusFile "budgets.cassius")
$(whamletFile "expenses.hamlet")
where
groupExpenses
= M.toAscList
. M.fromListWith (++)
. fmap (\e -> (getExpenseCategory e, [e]))
. catMaybes
. fmap extractEntry
. fmap snd
toRow :: (Category, [ExpenseEntry]) -> (Category, Double, Int, Double)
toRow (c, es) =
( c
, sum . fmap getExpenseValue $ es
, length es
, meanSpent es
)
toRows :: [(Category, [ExpenseEntry])]
-> [(Category, Double, Int, Double)]
toRows = sortBy (\(_, t1, _, _) (_, t2, _, _) -> compare t2 t1)
. filter (\(_, _, n, _) -> n > 0)
. fmap toRow
meanSpent :: [ExpenseEntry] -> Double
meanSpent [] = 0
meanSpent es = (/ (fromIntegral . length $ es))
. sum
. fmap getExpenseValue
$ es
extractEntry :: Entry -> Maybe ExpenseEntry
extractEntry (Spend e) = Just e
extractEntry (Save e) = Just e
extractEntry _ = Nothing
getExpenseCategoryR :: CategoryPiece -> Handler Html
getExpenseCategoryR cat = defaultLayout $ do
journal <- liftIO Fizz.loadJournal
let expenses = catMaybes . maybe [] (fmap (\(t, e) -> maybe Nothing (Just . (,) t) (extractEntry e))) . lookup (unwrap cat) . categories $ journal
let rows = toRows expenses
toWidget $(cassiusFile "budgets.cassius")
$(whamletFile "expense.hamlet")
where
toRow :: (Timestamped ExpenseEntry) -> (Double, String, String)
toRow e = (getExpenseValue . snd $ e
, getExpenseDescription . snd $ e
, show . getTimestamp $ e)
toRows :: [Timestamped ExpenseEntry] -> [(Double, String, String)]
toRows = fmap toRow
. reverse
. sortBy (compare `on` getTimestamp)
postExpenseCategoryR :: CategoryPiece -> Handler ()
postExpenseCategoryR _ = undefined
postDashR :: Handler String
postDashR = do
maybeFizz <- lookupPostParam "doFizz"
maybe (return "bad param") (liftIO . doFizz . parseFizz . T.unpack) maybeFizz
getDashR :: Handler Html
getDashR = defaultLayout $ do
now <- liftIO getTime
journal <- liftIO Fizz.loadJournal
let rows = getDashRows (localDay now) journal
toWidget $(cassiusFile "budgets.cassius")
$(whamletFile "dash.hamlet")
addScriptRemote "http://code.jquery.com/jquery-1.10.2.min.js"
toWidget $(juliusFile "dash.julius")
getDashRows :: Day -> Journal -> [(String, String, String, Double, Double, Double, Double)]
getDashRows today journal = snd (mapAccumL toRow M.empty expenses)
where
(monthStart, monthEnd) = (toMonthStart today, toMonthEnd today)
thisMonth = filter (between monthStart monthEnd . getTimestamp) journal
lastMonth = filter ((<monthStart) . getTimestamp) journal
lastMonthBalances = M.map (\j -> totalBudgeted j - totalSpent j) . M.fromList . categories $ lastMonth
budgets = M.fromList . mostRecentBudgets $ journal
expenses = (orderByDate . filter (isSpend . snd)) thisMonth
addHistory e = M.insertWith (+) (getExpenseCategory e) (getExpenseValue e)
getRemaining cat val budgetMap spendingMap = (maybe 0 getBudgetValue (M.lookup cat budgetMap)) - (maybe 0 id (M.lookup cat spendingMap)) - val
toRow spendingHistory (day, Spend e) = (addHistory e spendingHistory, (show day,
printCategory . getExpenseCategory $ e,
getExpenseDescription e,
getExpenseValue e,
maybe 0 getBudgetValue . M.lookup (getExpenseCategory e) $ budgets,
getRemaining (getExpenseCategory e) (getExpenseValue e) budgets spendingHistory,
maybe 0 id . M.lookup (getExpenseCategory e) $ lastMonthBalances))
toRow _ _ = error "Non-Spend Entry in toRow"
toMonthStart :: Day -> Day
toMonthStart = (\(y, m, _) -> fromGregorian y m 1)
. toGregorian
toMonthEnd :: Day -> Day
toMonthEnd = (\(y, m, _) -> if m < 12 then fromGregorian y (m + 1) 1 else fromGregorian (y + 1) 1 1)
. toGregorian
maybeReadT :: Read a => T.Text -> Maybe a
maybeReadT s =
case reads . T.unpack $ s of
((v,_):_) -> Just v
_ -> Nothing
maybeRead :: Read a => String -> Maybe a
maybeRead s =
case reads s of
((v,_):_) -> Just v
_ -> Nothing
| josuf107/Fizzckle | src/FizzWeb.hs | gpl-3.0 | 9,827 | 0 | 24 | 2,462 | 3,238 | 1,657 | 1,581 | 233 | 2 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Sheets.Types.Sum
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
module Network.Google.Sheets.Types.Sum where
import Network.Google.Prelude hiding (Bytes)
-- | The major dimension that results should use. For example, if the
-- spreadsheet data is: \`A1=1,B1=2,A2=3,B2=4\`, then requesting
-- \`range=A1:B2,majorDimension=ROWS\` returns \`[[1,2],[3,4]]\`, whereas
-- requesting \`range=A1:B2,majorDimension=COLUMNS\` returns
-- \`[[1,3],[2,4]]\`.
data SpreadsheetsValuesBatchGetMajorDimension
= DimensionUnspecified
-- ^ @DIMENSION_UNSPECIFIED@
-- The default value, do not use.
| Rows
-- ^ @ROWS@
-- Operates on the rows of a sheet.
| Columns
-- ^ @COLUMNS@
-- Operates on the columns of a sheet.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable SpreadsheetsValuesBatchGetMajorDimension
instance FromHttpApiData SpreadsheetsValuesBatchGetMajorDimension where
parseQueryParam = \case
"DIMENSION_UNSPECIFIED" -> Right DimensionUnspecified
"ROWS" -> Right Rows
"COLUMNS" -> Right Columns
x -> Left ("Unable to parse SpreadsheetsValuesBatchGetMajorDimension from: " <> x)
instance ToHttpApiData SpreadsheetsValuesBatchGetMajorDimension where
toQueryParam = \case
DimensionUnspecified -> "DIMENSION_UNSPECIFIED"
Rows -> "ROWS"
Columns -> "COLUMNS"
instance FromJSON SpreadsheetsValuesBatchGetMajorDimension where
parseJSON = parseJSONText "SpreadsheetsValuesBatchGetMajorDimension"
instance ToJSON SpreadsheetsValuesBatchGetMajorDimension where
toJSON = toJSONText
-- | The stacked type for charts that support vertical stacking. Applies to
-- Area, Bar, Column, Combo, and Stepped Area charts.
data BasicChartSpecStackedType
= BasicChartStackedTypeUnspecified
-- ^ @BASIC_CHART_STACKED_TYPE_UNSPECIFIED@
-- Default value, do not use.
| NotStacked
-- ^ @NOT_STACKED@
-- Series are not stacked.
| Stacked
-- ^ @STACKED@
-- Series values are stacked, each value is rendered vertically beginning
-- from the top of the value below it.
| PercentStacked
-- ^ @PERCENT_STACKED@
-- Vertical stacks are stretched to reach the top of the chart, with values
-- laid out as percentages of each other.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable BasicChartSpecStackedType
instance FromHttpApiData BasicChartSpecStackedType where
parseQueryParam = \case
"BASIC_CHART_STACKED_TYPE_UNSPECIFIED" -> Right BasicChartStackedTypeUnspecified
"NOT_STACKED" -> Right NotStacked
"STACKED" -> Right Stacked
"PERCENT_STACKED" -> Right PercentStacked
x -> Left ("Unable to parse BasicChartSpecStackedType from: " <> x)
instance ToHttpApiData BasicChartSpecStackedType where
toQueryParam = \case
BasicChartStackedTypeUnspecified -> "BASIC_CHART_STACKED_TYPE_UNSPECIFIED"
NotStacked -> "NOT_STACKED"
Stacked -> "STACKED"
PercentStacked -> "PERCENT_STACKED"
instance FromJSON BasicChartSpecStackedType where
parseJSON = parseJSONText "BasicChartSpecStackedType"
instance ToJSON BasicChartSpecStackedType where
toJSON = toJSONText
-- | What kind of data to paste.
data CopyPasteRequestPasteType
= PasteNormal
-- ^ @PASTE_NORMAL@
-- Paste values, formulas, formats, and merges.
| PasteValues
-- ^ @PASTE_VALUES@
-- Paste the values ONLY without formats, formulas, or merges.
| PasteFormat
-- ^ @PASTE_FORMAT@
-- Paste the format and data validation only.
| PasteNoBOrders
-- ^ @PASTE_NO_BORDERS@
-- Like \`PASTE_NORMAL\` but without borders.
| PasteFormula
-- ^ @PASTE_FORMULA@
-- Paste the formulas only.
| PasteDataValidation
-- ^ @PASTE_DATA_VALIDATION@
-- Paste the data validation only.
| PasteConditionalFormatting
-- ^ @PASTE_CONDITIONAL_FORMATTING@
-- Paste the conditional formatting rules only.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable CopyPasteRequestPasteType
instance FromHttpApiData CopyPasteRequestPasteType where
parseQueryParam = \case
"PASTE_NORMAL" -> Right PasteNormal
"PASTE_VALUES" -> Right PasteValues
"PASTE_FORMAT" -> Right PasteFormat
"PASTE_NO_BORDERS" -> Right PasteNoBOrders
"PASTE_FORMULA" -> Right PasteFormula
"PASTE_DATA_VALIDATION" -> Right PasteDataValidation
"PASTE_CONDITIONAL_FORMATTING" -> Right PasteConditionalFormatting
x -> Left ("Unable to parse CopyPasteRequestPasteType from: " <> x)
instance ToHttpApiData CopyPasteRequestPasteType where
toQueryParam = \case
PasteNormal -> "PASTE_NORMAL"
PasteValues -> "PASTE_VALUES"
PasteFormat -> "PASTE_FORMAT"
PasteNoBOrders -> "PASTE_NO_BORDERS"
PasteFormula -> "PASTE_FORMULA"
PasteDataValidation -> "PASTE_DATA_VALIDATION"
PasteConditionalFormatting -> "PASTE_CONDITIONAL_FORMATTING"
instance FromJSON CopyPasteRequestPasteType where
parseJSON = parseJSONText "CopyPasteRequestPasteType"
instance ToJSON CopyPasteRequestPasteType where
toJSON = toJSONText
-- | Determines how this lookup matches the location. If this field is
-- specified as EXACT, only developer metadata associated on the exact
-- location specified is matched. If this field is specified to
-- INTERSECTING, developer metadata associated on intersecting locations is
-- also matched. If left unspecified, this field assumes a default value of
-- INTERSECTING. If this field is specified, a metadataLocation must also
-- be specified.
data DeveloperMetadataLookupLocationMatchingStrategy
= DeveloperMetadataLocationMatchingStrategyUnspecified
-- ^ @DEVELOPER_METADATA_LOCATION_MATCHING_STRATEGY_UNSPECIFIED@
-- Default value. This value must not be used.
| ExactLocation
-- ^ @EXACT_LOCATION@
-- Indicates that a specified location should be matched exactly. For
-- example, if row three were specified as a location this matching
-- strategy would only match developer metadata also associated on row
-- three. Metadata associated on other locations would not be considered.
| IntersectingLocation
-- ^ @INTERSECTING_LOCATION@
-- Indicates that a specified location should match that exact location as
-- well as any intersecting locations. For example, if row three were
-- specified as a location this matching strategy would match developer
-- metadata associated on row three as well as metadata associated on
-- locations that intersect row three. If, for instance, there was
-- developer metadata associated on column B, this matching strategy would
-- also match that location because column B intersects row three.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable DeveloperMetadataLookupLocationMatchingStrategy
instance FromHttpApiData DeveloperMetadataLookupLocationMatchingStrategy where
parseQueryParam = \case
"DEVELOPER_METADATA_LOCATION_MATCHING_STRATEGY_UNSPECIFIED" -> Right DeveloperMetadataLocationMatchingStrategyUnspecified
"EXACT_LOCATION" -> Right ExactLocation
"INTERSECTING_LOCATION" -> Right IntersectingLocation
x -> Left ("Unable to parse DeveloperMetadataLookupLocationMatchingStrategy from: " <> x)
instance ToHttpApiData DeveloperMetadataLookupLocationMatchingStrategy where
toQueryParam = \case
DeveloperMetadataLocationMatchingStrategyUnspecified -> "DEVELOPER_METADATA_LOCATION_MATCHING_STRATEGY_UNSPECIFIED"
ExactLocation -> "EXACT_LOCATION"
IntersectingLocation -> "INTERSECTING_LOCATION"
instance FromJSON DeveloperMetadataLookupLocationMatchingStrategy where
parseJSON = parseJSONText "DeveloperMetadataLookupLocationMatchingStrategy"
instance ToJSON DeveloperMetadataLookupLocationMatchingStrategy where
toJSON = toJSONText
-- | Determines how dates, times, and durations in the response should be
-- rendered. This is ignored if response_value_render_option is
-- FORMATTED_VALUE. The default dateTime render option is SERIAL_NUMBER.
data BatchUpdateValuesByDataFilterRequestResponseDateTimeRenderOption
= SerialNumber
-- ^ @SERIAL_NUMBER@
-- Instructs date, time, datetime, and duration fields to be output as
-- doubles in \"serial number\" format, as popularized by Lotus 1-2-3. The
-- whole number portion of the value (left of the decimal) counts the days
-- since December 30th 1899. The fractional portion (right of the decimal)
-- counts the time as a fraction of the day. For example, January 1st 1900
-- at noon would be 2.5, 2 because it\'s 2 days after December 30st 1899,
-- and .5 because noon is half a day. February 1st 1900 at 3pm would be
-- 33.625. This correctly treats the year 1900 as not a leap year.
| FormattedString
-- ^ @FORMATTED_STRING@
-- Instructs date, time, datetime, and duration fields to be output as
-- strings in their given number format (which is dependent on the
-- spreadsheet locale).
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable BatchUpdateValuesByDataFilterRequestResponseDateTimeRenderOption
instance FromHttpApiData BatchUpdateValuesByDataFilterRequestResponseDateTimeRenderOption where
parseQueryParam = \case
"SERIAL_NUMBER" -> Right SerialNumber
"FORMATTED_STRING" -> Right FormattedString
x -> Left ("Unable to parse BatchUpdateValuesByDataFilterRequestResponseDateTimeRenderOption from: " <> x)
instance ToHttpApiData BatchUpdateValuesByDataFilterRequestResponseDateTimeRenderOption where
toQueryParam = \case
SerialNumber -> "SERIAL_NUMBER"
FormattedString -> "FORMATTED_STRING"
instance FromJSON BatchUpdateValuesByDataFilterRequestResponseDateTimeRenderOption where
parseJSON = parseJSONText "BatchUpdateValuesByDataFilterRequestResponseDateTimeRenderOption"
instance ToJSON BatchUpdateValuesByDataFilterRequestResponseDateTimeRenderOption where
toJSON = toJSONText
-- | The position of this axis.
data BasicChartAxisPosition
= BasicChartAxisPositionUnspecified
-- ^ @BASIC_CHART_AXIS_POSITION_UNSPECIFIED@
-- Default value, do not use.
| BottomAxis
-- ^ @BOTTOM_AXIS@
-- The axis rendered at the bottom of a chart. For most charts, this is the
-- standard major axis. For bar charts, this is a minor axis.
| LeftAxis
-- ^ @LEFT_AXIS@
-- The axis rendered at the left of a chart. For most charts, this is a
-- minor axis. For bar charts, this is the standard major axis.
| RightAxis
-- ^ @RIGHT_AXIS@
-- The axis rendered at the right of a chart. For most charts, this is a
-- minor axis. For bar charts, this is an unusual major axis.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable BasicChartAxisPosition
instance FromHttpApiData BasicChartAxisPosition where
parseQueryParam = \case
"BASIC_CHART_AXIS_POSITION_UNSPECIFIED" -> Right BasicChartAxisPositionUnspecified
"BOTTOM_AXIS" -> Right BottomAxis
"LEFT_AXIS" -> Right LeftAxis
"RIGHT_AXIS" -> Right RightAxis
x -> Left ("Unable to parse BasicChartAxisPosition from: " <> x)
instance ToHttpApiData BasicChartAxisPosition where
toQueryParam = \case
BasicChartAxisPositionUnspecified -> "BASIC_CHART_AXIS_POSITION_UNSPECIFIED"
BottomAxis -> "BOTTOM_AXIS"
LeftAxis -> "LEFT_AXIS"
RightAxis -> "RIGHT_AXIS"
instance FromJSON BasicChartAxisPosition where
parseJSON = parseJSONText "BasicChartAxisPosition"
instance ToJSON BasicChartAxisPosition where
toJSON = toJSONText
-- | The view window\'s mode.
data ChartAxisViewWindowOptionsViewWindowMode
= DefaultViewWindowMode
-- ^ @DEFAULT_VIEW_WINDOW_MODE@
-- The default view window mode used in the Sheets editor for this chart
-- type. In most cases, if set, the default mode is equivalent to
-- \`PRETTY\`.
| ViewWindowModeUnsupported
-- ^ @VIEW_WINDOW_MODE_UNSUPPORTED@
-- Do not use. Represents that the currently set mode is not supported by
-- the API.
| Explicit
-- ^ @EXPLICIT@
-- Follows the min and max exactly if specified. If a value is unspecified,
-- it will fall back to the \`PRETTY\` value.
| Pretty
-- ^ @PRETTY@
-- Chooses a min and max that make the chart look good. Both min and max
-- are ignored in this mode.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable ChartAxisViewWindowOptionsViewWindowMode
instance FromHttpApiData ChartAxisViewWindowOptionsViewWindowMode where
parseQueryParam = \case
"DEFAULT_VIEW_WINDOW_MODE" -> Right DefaultViewWindowMode
"VIEW_WINDOW_MODE_UNSUPPORTED" -> Right ViewWindowModeUnsupported
"EXPLICIT" -> Right Explicit
"PRETTY" -> Right Pretty
x -> Left ("Unable to parse ChartAxisViewWindowOptionsViewWindowMode from: " <> x)
instance ToHttpApiData ChartAxisViewWindowOptionsViewWindowMode where
toQueryParam = \case
DefaultViewWindowMode -> "DEFAULT_VIEW_WINDOW_MODE"
ViewWindowModeUnsupported -> "VIEW_WINDOW_MODE_UNSUPPORTED"
Explicit -> "EXPLICIT"
Pretty -> "PRETTY"
instance FromJSON ChartAxisViewWindowOptionsViewWindowMode where
parseJSON = parseJSONText "ChartAxisViewWindowOptionsViewWindowMode"
instance ToJSON ChartAxisViewWindowOptionsViewWindowMode where
toJSON = toJSONText
-- | The dimension from which deleted cells will be replaced with. If ROWS,
-- existing cells will be shifted upward to replace the deleted cells. If
-- COLUMNS, existing cells will be shifted left to replace the deleted
-- cells.
data DeleteRangeRequestShiftDimension
= DRRSDDimensionUnspecified
-- ^ @DIMENSION_UNSPECIFIED@
-- The default value, do not use.
| DRRSDRows
-- ^ @ROWS@
-- Operates on the rows of a sheet.
| DRRSDColumns
-- ^ @COLUMNS@
-- Operates on the columns of a sheet.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable DeleteRangeRequestShiftDimension
instance FromHttpApiData DeleteRangeRequestShiftDimension where
parseQueryParam = \case
"DIMENSION_UNSPECIFIED" -> Right DRRSDDimensionUnspecified
"ROWS" -> Right DRRSDRows
"COLUMNS" -> Right DRRSDColumns
x -> Left ("Unable to parse DeleteRangeRequestShiftDimension from: " <> x)
instance ToHttpApiData DeleteRangeRequestShiftDimension where
toQueryParam = \case
DRRSDDimensionUnspecified -> "DIMENSION_UNSPECIFIED"
DRRSDRows -> "ROWS"
DRRSDColumns -> "COLUMNS"
instance FromJSON DeleteRangeRequestShiftDimension where
parseJSON = parseJSONText "DeleteRangeRequestShiftDimension"
instance ToJSON DeleteRangeRequestShiftDimension where
toJSON = toJSONText
-- | How dates, times, and durations should be represented in the output.
-- This is ignored if value_render_option is FORMATTED_VALUE. The default
-- dateTime render option is SERIAL_NUMBER.
data SpreadsheetsValuesBatchGetDateTimeRenderOption
= SVBGDTROSerialNumber
-- ^ @SERIAL_NUMBER@
-- Instructs date, time, datetime, and duration fields to be output as
-- doubles in \"serial number\" format, as popularized by Lotus 1-2-3. The
-- whole number portion of the value (left of the decimal) counts the days
-- since December 30th 1899. The fractional portion (right of the decimal)
-- counts the time as a fraction of the day. For example, January 1st 1900
-- at noon would be 2.5, 2 because it\'s 2 days after December 30st 1899,
-- and .5 because noon is half a day. February 1st 1900 at 3pm would be
-- 33.625. This correctly treats the year 1900 as not a leap year.
| SVBGDTROFormattedString
-- ^ @FORMATTED_STRING@
-- Instructs date, time, datetime, and duration fields to be output as
-- strings in their given number format (which is dependent on the
-- spreadsheet locale).
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable SpreadsheetsValuesBatchGetDateTimeRenderOption
instance FromHttpApiData SpreadsheetsValuesBatchGetDateTimeRenderOption where
parseQueryParam = \case
"SERIAL_NUMBER" -> Right SVBGDTROSerialNumber
"FORMATTED_STRING" -> Right SVBGDTROFormattedString
x -> Left ("Unable to parse SpreadsheetsValuesBatchGetDateTimeRenderOption from: " <> x)
instance ToHttpApiData SpreadsheetsValuesBatchGetDateTimeRenderOption where
toQueryParam = \case
SVBGDTROSerialNumber -> "SERIAL_NUMBER"
SVBGDTROFormattedString -> "FORMATTED_STRING"
instance FromJSON SpreadsheetsValuesBatchGetDateTimeRenderOption where
parseJSON = parseJSONText "SpreadsheetsValuesBatchGetDateTimeRenderOption"
instance ToJSON SpreadsheetsValuesBatchGetDateTimeRenderOption where
toJSON = toJSONText
-- | The minor axis that will specify the range of values for this series.
-- For example, if charting stocks over time, the \"Volume\" series may
-- want to be pinned to the right with the prices pinned to the left,
-- because the scale of trading volume is different than the scale of
-- prices. It is an error to specify an axis that isn\'t a valid minor axis
-- for the chart\'s type.
data BasicChartSeriesTargetAxis
= BCSTABasicChartAxisPositionUnspecified
-- ^ @BASIC_CHART_AXIS_POSITION_UNSPECIFIED@
-- Default value, do not use.
| BCSTABottomAxis
-- ^ @BOTTOM_AXIS@
-- The axis rendered at the bottom of a chart. For most charts, this is the
-- standard major axis. For bar charts, this is a minor axis.
| BCSTALeftAxis
-- ^ @LEFT_AXIS@
-- The axis rendered at the left of a chart. For most charts, this is a
-- minor axis. For bar charts, this is the standard major axis.
| BCSTARightAxis
-- ^ @RIGHT_AXIS@
-- The axis rendered at the right of a chart. For most charts, this is a
-- minor axis. For bar charts, this is an unusual major axis.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable BasicChartSeriesTargetAxis
instance FromHttpApiData BasicChartSeriesTargetAxis where
parseQueryParam = \case
"BASIC_CHART_AXIS_POSITION_UNSPECIFIED" -> Right BCSTABasicChartAxisPositionUnspecified
"BOTTOM_AXIS" -> Right BCSTABottomAxis
"LEFT_AXIS" -> Right BCSTALeftAxis
"RIGHT_AXIS" -> Right BCSTARightAxis
x -> Left ("Unable to parse BasicChartSeriesTargetAxis from: " <> x)
instance ToHttpApiData BasicChartSeriesTargetAxis where
toQueryParam = \case
BCSTABasicChartAxisPositionUnspecified -> "BASIC_CHART_AXIS_POSITION_UNSPECIFIED"
BCSTABottomAxis -> "BOTTOM_AXIS"
BCSTALeftAxis -> "LEFT_AXIS"
BCSTARightAxis -> "RIGHT_AXIS"
instance FromJSON BasicChartSeriesTargetAxis where
parseJSON = parseJSONText "BasicChartSeriesTargetAxis"
instance ToJSON BasicChartSeriesTargetAxis where
toJSON = toJSONText
-- | The major dimension of the values.
data DataFilterValueRangeMajorDimension
= DFVRMDDimensionUnspecified
-- ^ @DIMENSION_UNSPECIFIED@
-- The default value, do not use.
| DFVRMDRows
-- ^ @ROWS@
-- Operates on the rows of a sheet.
| DFVRMDColumns
-- ^ @COLUMNS@
-- Operates on the columns of a sheet.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable DataFilterValueRangeMajorDimension
instance FromHttpApiData DataFilterValueRangeMajorDimension where
parseQueryParam = \case
"DIMENSION_UNSPECIFIED" -> Right DFVRMDDimensionUnspecified
"ROWS" -> Right DFVRMDRows
"COLUMNS" -> Right DFVRMDColumns
x -> Left ("Unable to parse DataFilterValueRangeMajorDimension from: " <> x)
instance ToHttpApiData DataFilterValueRangeMajorDimension where
toQueryParam = \case
DFVRMDDimensionUnspecified -> "DIMENSION_UNSPECIFIED"
DFVRMDRows -> "ROWS"
DFVRMDColumns -> "COLUMNS"
instance FromJSON DataFilterValueRangeMajorDimension where
parseJSON = parseJSONText "DataFilterValueRangeMajorDimension"
instance ToJSON DataFilterValueRangeMajorDimension where
toJSON = toJSONText
-- | Where the legend of the chart should be drawn.
data BubbleChartSpecLegendPosition
= BubbleChartLegendPositionUnspecified
-- ^ @BUBBLE_CHART_LEGEND_POSITION_UNSPECIFIED@
-- Default value, do not use.
| BottomLegend
-- ^ @BOTTOM_LEGEND@
-- The legend is rendered on the bottom of the chart.
| LeftLegend
-- ^ @LEFT_LEGEND@
-- The legend is rendered on the left of the chart.
| RightLegend
-- ^ @RIGHT_LEGEND@
-- The legend is rendered on the right of the chart.
| TopLegend
-- ^ @TOP_LEGEND@
-- The legend is rendered on the top of the chart.
| NoLegend
-- ^ @NO_LEGEND@
-- No legend is rendered.
| InsideLegend
-- ^ @INSIDE_LEGEND@
-- The legend is rendered inside the chart area.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable BubbleChartSpecLegendPosition
instance FromHttpApiData BubbleChartSpecLegendPosition where
parseQueryParam = \case
"BUBBLE_CHART_LEGEND_POSITION_UNSPECIFIED" -> Right BubbleChartLegendPositionUnspecified
"BOTTOM_LEGEND" -> Right BottomLegend
"LEFT_LEGEND" -> Right LeftLegend
"RIGHT_LEGEND" -> Right RightLegend
"TOP_LEGEND" -> Right TopLegend
"NO_LEGEND" -> Right NoLegend
"INSIDE_LEGEND" -> Right InsideLegend
x -> Left ("Unable to parse BubbleChartSpecLegendPosition from: " <> x)
instance ToHttpApiData BubbleChartSpecLegendPosition where
toQueryParam = \case
BubbleChartLegendPositionUnspecified -> "BUBBLE_CHART_LEGEND_POSITION_UNSPECIFIED"
BottomLegend -> "BOTTOM_LEGEND"
LeftLegend -> "LEFT_LEGEND"
RightLegend -> "RIGHT_LEGEND"
TopLegend -> "TOP_LEGEND"
NoLegend -> "NO_LEGEND"
InsideLegend -> "INSIDE_LEGEND"
instance FromJSON BubbleChartSpecLegendPosition where
parseJSON = parseJSONText "BubbleChartSpecLegendPosition"
instance ToJSON BubbleChartSpecLegendPosition where
toJSON = toJSONText
-- | Determines how dates, times, and durations in the response should be
-- rendered. This is ignored if response_value_render_option is
-- FORMATTED_VALUE. The default dateTime render option is SERIAL_NUMBER.
data BatchUpdateValuesRequestResponseDateTimeRenderOption
= BUVRRDTROSerialNumber
-- ^ @SERIAL_NUMBER@
-- Instructs date, time, datetime, and duration fields to be output as
-- doubles in \"serial number\" format, as popularized by Lotus 1-2-3. The
-- whole number portion of the value (left of the decimal) counts the days
-- since December 30th 1899. The fractional portion (right of the decimal)
-- counts the time as a fraction of the day. For example, January 1st 1900
-- at noon would be 2.5, 2 because it\'s 2 days after December 30st 1899,
-- and .5 because noon is half a day. February 1st 1900 at 3pm would be
-- 33.625. This correctly treats the year 1900 as not a leap year.
| BUVRRDTROFormattedString
-- ^ @FORMATTED_STRING@
-- Instructs date, time, datetime, and duration fields to be output as
-- strings in their given number format (which is dependent on the
-- spreadsheet locale).
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable BatchUpdateValuesRequestResponseDateTimeRenderOption
instance FromHttpApiData BatchUpdateValuesRequestResponseDateTimeRenderOption where
parseQueryParam = \case
"SERIAL_NUMBER" -> Right BUVRRDTROSerialNumber
"FORMATTED_STRING" -> Right BUVRRDTROFormattedString
x -> Left ("Unable to parse BatchUpdateValuesRequestResponseDateTimeRenderOption from: " <> x)
instance ToHttpApiData BatchUpdateValuesRequestResponseDateTimeRenderOption where
toQueryParam = \case
BUVRRDTROSerialNumber -> "SERIAL_NUMBER"
BUVRRDTROFormattedString -> "FORMATTED_STRING"
instance FromJSON BatchUpdateValuesRequestResponseDateTimeRenderOption where
parseJSON = parseJSONText "BatchUpdateValuesRequestResponseDateTimeRenderOption"
instance ToJSON BatchUpdateValuesRequestResponseDateTimeRenderOption where
toJSON = toJSONText
-- | Whether rows or columns should be appended.
data AppendDimensionRequestDimension
= ADRDDimensionUnspecified
-- ^ @DIMENSION_UNSPECIFIED@
-- The default value, do not use.
| ADRDRows
-- ^ @ROWS@
-- Operates on the rows of a sheet.
| ADRDColumns
-- ^ @COLUMNS@
-- Operates on the columns of a sheet.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable AppendDimensionRequestDimension
instance FromHttpApiData AppendDimensionRequestDimension where
parseQueryParam = \case
"DIMENSION_UNSPECIFIED" -> Right ADRDDimensionUnspecified
"ROWS" -> Right ADRDRows
"COLUMNS" -> Right ADRDColumns
x -> Left ("Unable to parse AppendDimensionRequestDimension from: " <> x)
instance ToHttpApiData AppendDimensionRequestDimension where
toQueryParam = \case
ADRDDimensionUnspecified -> "DIMENSION_UNSPECIFIED"
ADRDRows -> "ROWS"
ADRDColumns -> "COLUMNS"
instance FromJSON AppendDimensionRequestDimension where
parseJSON = parseJSONText "AppendDimensionRequestDimension"
instance ToJSON AppendDimensionRequestDimension where
toJSON = toJSONText
-- | Determines how dates, times, and durations in the response should be
-- rendered. This is ignored if response_value_render_option is
-- FORMATTED_VALUE. The default dateTime render option is SERIAL_NUMBER.
data SpreadsheetsValuesUpdateResponseDateTimeRenderOption
= SVURDTROSerialNumber
-- ^ @SERIAL_NUMBER@
-- Instructs date, time, datetime, and duration fields to be output as
-- doubles in \"serial number\" format, as popularized by Lotus 1-2-3. The
-- whole number portion of the value (left of the decimal) counts the days
-- since December 30th 1899. The fractional portion (right of the decimal)
-- counts the time as a fraction of the day. For example, January 1st 1900
-- at noon would be 2.5, 2 because it\'s 2 days after December 30st 1899,
-- and .5 because noon is half a day. February 1st 1900 at 3pm would be
-- 33.625. This correctly treats the year 1900 as not a leap year.
| SVURDTROFormattedString
-- ^ @FORMATTED_STRING@
-- Instructs date, time, datetime, and duration fields to be output as
-- strings in their given number format (which is dependent on the
-- spreadsheet locale).
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable SpreadsheetsValuesUpdateResponseDateTimeRenderOption
instance FromHttpApiData SpreadsheetsValuesUpdateResponseDateTimeRenderOption where
parseQueryParam = \case
"SERIAL_NUMBER" -> Right SVURDTROSerialNumber
"FORMATTED_STRING" -> Right SVURDTROFormattedString
x -> Left ("Unable to parse SpreadsheetsValuesUpdateResponseDateTimeRenderOption from: " <> x)
instance ToHttpApiData SpreadsheetsValuesUpdateResponseDateTimeRenderOption where
toQueryParam = \case
SVURDTROSerialNumber -> "SERIAL_NUMBER"
SVURDTROFormattedString -> "FORMATTED_STRING"
instance FromJSON SpreadsheetsValuesUpdateResponseDateTimeRenderOption where
parseJSON = parseJSONText "SpreadsheetsValuesUpdateResponseDateTimeRenderOption"
instance ToJSON SpreadsheetsValuesUpdateResponseDateTimeRenderOption where
toJSON = toJSONText
-- | The dimension of the span.
data DimensionRangeDimension
= DRDDimensionUnspecified
-- ^ @DIMENSION_UNSPECIFIED@
-- The default value, do not use.
| DRDRows
-- ^ @ROWS@
-- Operates on the rows of a sheet.
| DRDColumns
-- ^ @COLUMNS@
-- Operates on the columns of a sheet.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable DimensionRangeDimension
instance FromHttpApiData DimensionRangeDimension where
parseQueryParam = \case
"DIMENSION_UNSPECIFIED" -> Right DRDDimensionUnspecified
"ROWS" -> Right DRDRows
"COLUMNS" -> Right DRDColumns
x -> Left ("Unable to parse DimensionRangeDimension from: " <> x)
instance ToHttpApiData DimensionRangeDimension where
toQueryParam = \case
DRDDimensionUnspecified -> "DIMENSION_UNSPECIFIED"
DRDRows -> "ROWS"
DRDColumns -> "COLUMNS"
instance FromJSON DimensionRangeDimension where
parseJSON = parseJSONText "DimensionRangeDimension"
instance ToJSON DimensionRangeDimension where
toJSON = toJSONText
-- | How values should be represented in the output. The default render
-- option is FORMATTED_VALUE.
data BatchGetValuesByDataFilterRequestValueRenderOption
= FormattedValue
-- ^ @FORMATTED_VALUE@
-- Values will be calculated & formatted in the reply according to the
-- cell\'s formatting. Formatting is based on the spreadsheet\'s locale,
-- not the requesting user\'s locale. For example, if \`A1\` is \`1.23\`
-- and \`A2\` is \`=A1\` and formatted as currency, then \`A2\` would
-- return \`\"$1.23\"\`.
| UnformattedValue
-- ^ @UNFORMATTED_VALUE@
-- Values will be calculated, but not formatted in the reply. For example,
-- if \`A1\` is \`1.23\` and \`A2\` is \`=A1\` and formatted as currency,
-- then \`A2\` would return the number \`1.23\`.
| Formula
-- ^ @FORMULA@
-- Values will not be calculated. The reply will include the formulas. For
-- example, if \`A1\` is \`1.23\` and \`A2\` is \`=A1\` and formatted as
-- currency, then A2 would return \`\"=A1\"\`.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable BatchGetValuesByDataFilterRequestValueRenderOption
instance FromHttpApiData BatchGetValuesByDataFilterRequestValueRenderOption where
parseQueryParam = \case
"FORMATTED_VALUE" -> Right FormattedValue
"UNFORMATTED_VALUE" -> Right UnformattedValue
"FORMULA" -> Right Formula
x -> Left ("Unable to parse BatchGetValuesByDataFilterRequestValueRenderOption from: " <> x)
instance ToHttpApiData BatchGetValuesByDataFilterRequestValueRenderOption where
toQueryParam = \case
FormattedValue -> "FORMATTED_VALUE"
UnformattedValue -> "UNFORMATTED_VALUE"
Formula -> "FORMULA"
instance FromJSON BatchGetValuesByDataFilterRequestValueRenderOption where
parseJSON = parseJSONText "BatchGetValuesByDataFilterRequestValueRenderOption"
instance ToJSON BatchGetValuesByDataFilterRequestValueRenderOption where
toJSON = toJSONText
-- | The dimension that data should be filled into.
data SourceAndDestinationDimension
= SADDDimensionUnspecified
-- ^ @DIMENSION_UNSPECIFIED@
-- The default value, do not use.
| SADDRows
-- ^ @ROWS@
-- Operates on the rows of a sheet.
| SADDColumns
-- ^ @COLUMNS@
-- Operates on the columns of a sheet.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable SourceAndDestinationDimension
instance FromHttpApiData SourceAndDestinationDimension where
parseQueryParam = \case
"DIMENSION_UNSPECIFIED" -> Right SADDDimensionUnspecified
"ROWS" -> Right SADDRows
"COLUMNS" -> Right SADDColumns
x -> Left ("Unable to parse SourceAndDestinationDimension from: " <> x)
instance ToHttpApiData SourceAndDestinationDimension where
toQueryParam = \case
SADDDimensionUnspecified -> "DIMENSION_UNSPECIFIED"
SADDRows -> "ROWS"
SADDColumns -> "COLUMNS"
instance FromJSON SourceAndDestinationDimension where
parseJSON = parseJSONText "SourceAndDestinationDimension"
instance ToJSON SourceAndDestinationDimension where
toJSON = toJSONText
-- | How the input data should be interpreted.
data SpreadsheetsValuesUpdateValueInputOption
= InputValueOptionUnspecified
-- ^ @INPUT_VALUE_OPTION_UNSPECIFIED@
-- Default input value. This value must not be used.
| Raw
-- ^ @RAW@
-- The values the user has entered will not be parsed and will be stored
-- as-is.
| UserEntered
-- ^ @USER_ENTERED@
-- The values will be parsed as if the user typed them into the UI. Numbers
-- will stay as numbers, but strings may be converted to numbers, dates,
-- etc. following the same rules that are applied when entering text into a
-- cell via the Google Sheets UI.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable SpreadsheetsValuesUpdateValueInputOption
instance FromHttpApiData SpreadsheetsValuesUpdateValueInputOption where
parseQueryParam = \case
"INPUT_VALUE_OPTION_UNSPECIFIED" -> Right InputValueOptionUnspecified
"RAW" -> Right Raw
"USER_ENTERED" -> Right UserEntered
x -> Left ("Unable to parse SpreadsheetsValuesUpdateValueInputOption from: " <> x)
instance ToHttpApiData SpreadsheetsValuesUpdateValueInputOption where
toQueryParam = \case
InputValueOptionUnspecified -> "INPUT_VALUE_OPTION_UNSPECIFIED"
Raw -> "RAW"
UserEntered -> "USER_ENTERED"
instance FromJSON SpreadsheetsValuesUpdateValueInputOption where
parseJSON = parseJSONText "SpreadsheetsValuesUpdateValueInputOption"
instance ToJSON SpreadsheetsValuesUpdateValueInputOption where
toJSON = toJSONText
-- | The wrap strategy for the value in the cell.
data CellFormatWrapStrategy
= WrapStrategyUnspecified
-- ^ @WRAP_STRATEGY_UNSPECIFIED@
-- The default value, do not use.
| OverflowCell
-- ^ @OVERFLOW_CELL@
-- Lines that are longer than the cell width will be written in the next
-- cell over, so long as that cell is empty. If the next cell over is
-- non-empty, this behaves the same as \`CLIP\`. The text will never wrap
-- to the next line unless the user manually inserts a new line. Example: |
-- First sentence. | | Manual newline that is very long. \<- Text continues
-- into next cell | Next newline. |
| LegacyWrap
-- ^ @LEGACY_WRAP@
-- This wrap strategy represents the old Google Sheets wrap strategy where
-- words that are longer than a line are clipped rather than broken. This
-- strategy is not supported on all platforms and is being phased out.
-- Example: | Cell has a | | loooooooooo| \<- Word is clipped. | word. |
| Clip
-- ^ @CLIP@
-- Lines that are longer than the cell width will be clipped. The text will
-- never wrap to the next line unless the user manually inserts a new line.
-- Example: | First sentence. | | Manual newline t| \<- Text is clipped |
-- Next newline. |
| Wrap
-- ^ @WRAP@
-- Words that are longer than a line are wrapped at the character level
-- rather than clipped. Example: | Cell has a | | loooooooooo| \<- Word is
-- broken. | ong word. |
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable CellFormatWrapStrategy
instance FromHttpApiData CellFormatWrapStrategy where
parseQueryParam = \case
"WRAP_STRATEGY_UNSPECIFIED" -> Right WrapStrategyUnspecified
"OVERFLOW_CELL" -> Right OverflowCell
"LEGACY_WRAP" -> Right LegacyWrap
"CLIP" -> Right Clip
"WRAP" -> Right Wrap
x -> Left ("Unable to parse CellFormatWrapStrategy from: " <> x)
instance ToHttpApiData CellFormatWrapStrategy where
toQueryParam = \case
WrapStrategyUnspecified -> "WRAP_STRATEGY_UNSPECIFIED"
OverflowCell -> "OVERFLOW_CELL"
LegacyWrap -> "LEGACY_WRAP"
Clip -> "CLIP"
Wrap -> "WRAP"
instance FromJSON CellFormatWrapStrategy where
parseJSON = parseJSONText "CellFormatWrapStrategy"
instance ToJSON CellFormatWrapStrategy where
toJSON = toJSONText
-- | The scope of the refresh. Must be ALL_DATA_SOURCES.
data DataSourceRefreshScheduleRefreshScope
= DataSourceRefreshScopeUnspecified
-- ^ @DATA_SOURCE_REFRESH_SCOPE_UNSPECIFIED@
-- Default value, do not use.
| AllDataSources
-- ^ @ALL_DATA_SOURCES@
-- Refreshes all data sources and their associated data source objects in
-- the spreadsheet.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable DataSourceRefreshScheduleRefreshScope
instance FromHttpApiData DataSourceRefreshScheduleRefreshScope where
parseQueryParam = \case
"DATA_SOURCE_REFRESH_SCOPE_UNSPECIFIED" -> Right DataSourceRefreshScopeUnspecified
"ALL_DATA_SOURCES" -> Right AllDataSources
x -> Left ("Unable to parse DataSourceRefreshScheduleRefreshScope from: " <> x)
instance ToHttpApiData DataSourceRefreshScheduleRefreshScope where
toQueryParam = \case
DataSourceRefreshScopeUnspecified -> "DATA_SOURCE_REFRESH_SCOPE_UNSPECIFIED"
AllDataSources -> "ALL_DATA_SOURCES"
instance FromJSON DataSourceRefreshScheduleRefreshScope where
parseJSON = parseJSONText "DataSourceRefreshScheduleRefreshScope"
instance ToJSON DataSourceRefreshScheduleRefreshScope where
toJSON = toJSONText
-- | Determines how values in the response should be rendered. The default
-- render option is FORMATTED_VALUE.
data SpreadsheetsValuesAppendResponseValueRenderOption
= SVARVROFormattedValue
-- ^ @FORMATTED_VALUE@
-- Values will be calculated & formatted in the reply according to the
-- cell\'s formatting. Formatting is based on the spreadsheet\'s locale,
-- not the requesting user\'s locale. For example, if \`A1\` is \`1.23\`
-- and \`A2\` is \`=A1\` and formatted as currency, then \`A2\` would
-- return \`\"$1.23\"\`.
| SVARVROUnformattedValue
-- ^ @UNFORMATTED_VALUE@
-- Values will be calculated, but not formatted in the reply. For example,
-- if \`A1\` is \`1.23\` and \`A2\` is \`=A1\` and formatted as currency,
-- then \`A2\` would return the number \`1.23\`.
| SVARVROFormula
-- ^ @FORMULA@
-- Values will not be calculated. The reply will include the formulas. For
-- example, if \`A1\` is \`1.23\` and \`A2\` is \`=A1\` and formatted as
-- currency, then A2 would return \`\"=A1\"\`.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable SpreadsheetsValuesAppendResponseValueRenderOption
instance FromHttpApiData SpreadsheetsValuesAppendResponseValueRenderOption where
parseQueryParam = \case
"FORMATTED_VALUE" -> Right SVARVROFormattedValue
"UNFORMATTED_VALUE" -> Right SVARVROUnformattedValue
"FORMULA" -> Right SVARVROFormula
x -> Left ("Unable to parse SpreadsheetsValuesAppendResponseValueRenderOption from: " <> x)
instance ToHttpApiData SpreadsheetsValuesAppendResponseValueRenderOption where
toQueryParam = \case
SVARVROFormattedValue -> "FORMATTED_VALUE"
SVARVROUnformattedValue -> "UNFORMATTED_VALUE"
SVARVROFormula -> "FORMULA"
instance FromJSON SpreadsheetsValuesAppendResponseValueRenderOption where
parseJSON = parseJSONText "SpreadsheetsValuesAppendResponseValueRenderOption"
instance ToJSON SpreadsheetsValuesAppendResponseValueRenderOption where
toJSON = toJSONText
-- | How the input data should be interpreted.
data BatchUpdateValuesRequestValueInputOption
= BUVRVIOInputValueOptionUnspecified
-- ^ @INPUT_VALUE_OPTION_UNSPECIFIED@
-- Default input value. This value must not be used.
| BUVRVIORaw
-- ^ @RAW@
-- The values the user has entered will not be parsed and will be stored
-- as-is.
| BUVRVIOUserEntered
-- ^ @USER_ENTERED@
-- The values will be parsed as if the user typed them into the UI. Numbers
-- will stay as numbers, but strings may be converted to numbers, dates,
-- etc. following the same rules that are applied when entering text into a
-- cell via the Google Sheets UI.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable BatchUpdateValuesRequestValueInputOption
instance FromHttpApiData BatchUpdateValuesRequestValueInputOption where
parseQueryParam = \case
"INPUT_VALUE_OPTION_UNSPECIFIED" -> Right BUVRVIOInputValueOptionUnspecified
"RAW" -> Right BUVRVIORaw
"USER_ENTERED" -> Right BUVRVIOUserEntered
x -> Left ("Unable to parse BatchUpdateValuesRequestValueInputOption from: " <> x)
instance ToHttpApiData BatchUpdateValuesRequestValueInputOption where
toQueryParam = \case
BUVRVIOInputValueOptionUnspecified -> "INPUT_VALUE_OPTION_UNSPECIFIED"
BUVRVIORaw -> "RAW"
BUVRVIOUserEntered -> "USER_ENTERED"
instance FromJSON BatchUpdateValuesRequestValueInputOption where
parseJSON = parseJSONText "BatchUpdateValuesRequestValueInputOption"
instance ToJSON BatchUpdateValuesRequestValueInputOption where
toJSON = toJSONText
-- | Determines how values in the response should be rendered. The default
-- render option is FORMATTED_VALUE.
data SpreadsheetsValuesUpdateResponseValueRenderOption
= SVURVROFormattedValue
-- ^ @FORMATTED_VALUE@
-- Values will be calculated & formatted in the reply according to the
-- cell\'s formatting. Formatting is based on the spreadsheet\'s locale,
-- not the requesting user\'s locale. For example, if \`A1\` is \`1.23\`
-- and \`A2\` is \`=A1\` and formatted as currency, then \`A2\` would
-- return \`\"$1.23\"\`.
| SVURVROUnformattedValue
-- ^ @UNFORMATTED_VALUE@
-- Values will be calculated, but not formatted in the reply. For example,
-- if \`A1\` is \`1.23\` and \`A2\` is \`=A1\` and formatted as currency,
-- then \`A2\` would return the number \`1.23\`.
| SVURVROFormula
-- ^ @FORMULA@
-- Values will not be calculated. The reply will include the formulas. For
-- example, if \`A1\` is \`1.23\` and \`A2\` is \`=A1\` and formatted as
-- currency, then A2 would return \`\"=A1\"\`.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable SpreadsheetsValuesUpdateResponseValueRenderOption
instance FromHttpApiData SpreadsheetsValuesUpdateResponseValueRenderOption where
parseQueryParam = \case
"FORMATTED_VALUE" -> Right SVURVROFormattedValue
"UNFORMATTED_VALUE" -> Right SVURVROUnformattedValue
"FORMULA" -> Right SVURVROFormula
x -> Left ("Unable to parse SpreadsheetsValuesUpdateResponseValueRenderOption from: " <> x)
instance ToHttpApiData SpreadsheetsValuesUpdateResponseValueRenderOption where
toQueryParam = \case
SVURVROFormattedValue -> "FORMATTED_VALUE"
SVURVROUnformattedValue -> "UNFORMATTED_VALUE"
SVURVROFormula -> "FORMULA"
instance FromJSON SpreadsheetsValuesUpdateResponseValueRenderOption where
parseJSON = parseJSONText "SpreadsheetsValuesUpdateResponseValueRenderOption"
instance ToJSON SpreadsheetsValuesUpdateResponseValueRenderOption where
toJSON = toJSONText
-- | Horizontal alignment setting for the piece of text.
data TextPositionHorizontalAlignment
= HorizontalAlignUnspecified
-- ^ @HORIZONTAL_ALIGN_UNSPECIFIED@
-- The horizontal alignment is not specified. Do not use this.
| Left'
-- ^ @LEFT@
-- The text is explicitly aligned to the left of the cell.
| Center
-- ^ @CENTER@
-- The text is explicitly aligned to the center of the cell.
| Right'
-- ^ @RIGHT@
-- The text is explicitly aligned to the right of the cell.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable TextPositionHorizontalAlignment
instance FromHttpApiData TextPositionHorizontalAlignment where
parseQueryParam = \case
"HORIZONTAL_ALIGN_UNSPECIFIED" -> Right HorizontalAlignUnspecified
"LEFT" -> Right Left'
"CENTER" -> Right Center
"RIGHT" -> Right Right'
x -> Left ("Unable to parse TextPositionHorizontalAlignment from: " <> x)
instance ToHttpApiData TextPositionHorizontalAlignment where
toQueryParam = \case
HorizontalAlignUnspecified -> "HORIZONTAL_ALIGN_UNSPECIFIED"
Left' -> "LEFT"
Center -> "CENTER"
Right' -> "RIGHT"
instance FromJSON TextPositionHorizontalAlignment where
parseJSON = parseJSONText "TextPositionHorizontalAlignment"
instance ToJSON TextPositionHorizontalAlignment where
toJSON = toJSONText
-- | The metadata visibility. Developer metadata must always have a
-- visibility specified.
data DeveloperMetadataVisibility
= DeveloperMetadataVisibilityUnspecified
-- ^ @DEVELOPER_METADATA_VISIBILITY_UNSPECIFIED@
-- Default value.
| Document
-- ^ @DOCUMENT@
-- Document-visible metadata is accessible from any developer project with
-- access to the document.
| Project
-- ^ @PROJECT@
-- Project-visible metadata is only visible to and accessible by the
-- developer project that created the metadata.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable DeveloperMetadataVisibility
instance FromHttpApiData DeveloperMetadataVisibility where
parseQueryParam = \case
"DEVELOPER_METADATA_VISIBILITY_UNSPECIFIED" -> Right DeveloperMetadataVisibilityUnspecified
"DOCUMENT" -> Right Document
"PROJECT" -> Right Project
x -> Left ("Unable to parse DeveloperMetadataVisibility from: " <> x)
instance ToHttpApiData DeveloperMetadataVisibility where
toQueryParam = \case
DeveloperMetadataVisibilityUnspecified -> "DEVELOPER_METADATA_VISIBILITY_UNSPECIFIED"
Document -> "DOCUMENT"
Project -> "PROJECT"
instance FromJSON DeveloperMetadataVisibility where
parseJSON = parseJSONText "DeveloperMetadataVisibility"
instance ToJSON DeveloperMetadataVisibility where
toJSON = toJSONText
-- | Determines how values in the response should be rendered. The default
-- render option is FORMATTED_VALUE.
data BatchUpdateValuesRequestResponseValueRenderOption
= BUVRRVROFormattedValue
-- ^ @FORMATTED_VALUE@
-- Values will be calculated & formatted in the reply according to the
-- cell\'s formatting. Formatting is based on the spreadsheet\'s locale,
-- not the requesting user\'s locale. For example, if \`A1\` is \`1.23\`
-- and \`A2\` is \`=A1\` and formatted as currency, then \`A2\` would
-- return \`\"$1.23\"\`.
| BUVRRVROUnformattedValue
-- ^ @UNFORMATTED_VALUE@
-- Values will be calculated, but not formatted in the reply. For example,
-- if \`A1\` is \`1.23\` and \`A2\` is \`=A1\` and formatted as currency,
-- then \`A2\` would return the number \`1.23\`.
| BUVRRVROFormula
-- ^ @FORMULA@
-- Values will not be calculated. The reply will include the formulas. For
-- example, if \`A1\` is \`1.23\` and \`A2\` is \`=A1\` and formatted as
-- currency, then A2 would return \`\"=A1\"\`.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable BatchUpdateValuesRequestResponseValueRenderOption
instance FromHttpApiData BatchUpdateValuesRequestResponseValueRenderOption where
parseQueryParam = \case
"FORMATTED_VALUE" -> Right BUVRRVROFormattedValue
"UNFORMATTED_VALUE" -> Right BUVRRVROUnformattedValue
"FORMULA" -> Right BUVRRVROFormula
x -> Left ("Unable to parse BatchUpdateValuesRequestResponseValueRenderOption from: " <> x)
instance ToHttpApiData BatchUpdateValuesRequestResponseValueRenderOption where
toQueryParam = \case
BUVRRVROFormattedValue -> "FORMATTED_VALUE"
BUVRRVROUnformattedValue -> "UNFORMATTED_VALUE"
BUVRRVROFormula -> "FORMULA"
instance FromJSON BatchUpdateValuesRequestResponseValueRenderOption where
parseJSON = parseJSONText "BatchUpdateValuesRequestResponseValueRenderOption"
instance ToJSON BatchUpdateValuesRequestResponseValueRenderOption where
toJSON = toJSONText
-- | How values should be represented in the output. The default render
-- option is ValueRenderOption.FORMATTED_VALUE.
data SpreadsheetsValuesBatchGetValueRenderOption
= SVBGVROFormattedValue
-- ^ @FORMATTED_VALUE@
-- Values will be calculated & formatted in the reply according to the
-- cell\'s formatting. Formatting is based on the spreadsheet\'s locale,
-- not the requesting user\'s locale. For example, if \`A1\` is \`1.23\`
-- and \`A2\` is \`=A1\` and formatted as currency, then \`A2\` would
-- return \`\"$1.23\"\`.
| SVBGVROUnformattedValue
-- ^ @UNFORMATTED_VALUE@
-- Values will be calculated, but not formatted in the reply. For example,
-- if \`A1\` is \`1.23\` and \`A2\` is \`=A1\` and formatted as currency,
-- then \`A2\` would return the number \`1.23\`.
| SVBGVROFormula
-- ^ @FORMULA@
-- Values will not be calculated. The reply will include the formulas. For
-- example, if \`A1\` is \`1.23\` and \`A2\` is \`=A1\` and formatted as
-- currency, then A2 would return \`\"=A1\"\`.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable SpreadsheetsValuesBatchGetValueRenderOption
instance FromHttpApiData SpreadsheetsValuesBatchGetValueRenderOption where
parseQueryParam = \case
"FORMATTED_VALUE" -> Right SVBGVROFormattedValue
"UNFORMATTED_VALUE" -> Right SVBGVROUnformattedValue
"FORMULA" -> Right SVBGVROFormula
x -> Left ("Unable to parse SpreadsheetsValuesBatchGetValueRenderOption from: " <> x)
instance ToHttpApiData SpreadsheetsValuesBatchGetValueRenderOption where
toQueryParam = \case
SVBGVROFormattedValue -> "FORMATTED_VALUE"
SVBGVROUnformattedValue -> "UNFORMATTED_VALUE"
SVBGVROFormula -> "FORMULA"
instance FromJSON SpreadsheetsValuesBatchGetValueRenderOption where
parseJSON = parseJSONText "SpreadsheetsValuesBatchGetValueRenderOption"
instance ToJSON SpreadsheetsValuesBatchGetValueRenderOption where
toJSON = toJSONText
-- | Where the legend of the pie chart should be drawn.
data PieChartSpecLegendPosition
= PCSLPPieChartLegendPositionUnspecified
-- ^ @PIE_CHART_LEGEND_POSITION_UNSPECIFIED@
-- Default value, do not use.
| PCSLPBottomLegend
-- ^ @BOTTOM_LEGEND@
-- The legend is rendered on the bottom of the chart.
| PCSLPLeftLegend
-- ^ @LEFT_LEGEND@
-- The legend is rendered on the left of the chart.
| PCSLPRightLegend
-- ^ @RIGHT_LEGEND@
-- The legend is rendered on the right of the chart.
| PCSLPTopLegend
-- ^ @TOP_LEGEND@
-- The legend is rendered on the top of the chart.
| PCSLPNoLegend
-- ^ @NO_LEGEND@
-- No legend is rendered.
| PCSLPLabeledLegend
-- ^ @LABELED_LEGEND@
-- Each pie slice has a label attached to it.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable PieChartSpecLegendPosition
instance FromHttpApiData PieChartSpecLegendPosition where
parseQueryParam = \case
"PIE_CHART_LEGEND_POSITION_UNSPECIFIED" -> Right PCSLPPieChartLegendPositionUnspecified
"BOTTOM_LEGEND" -> Right PCSLPBottomLegend
"LEFT_LEGEND" -> Right PCSLPLeftLegend
"RIGHT_LEGEND" -> Right PCSLPRightLegend
"TOP_LEGEND" -> Right PCSLPTopLegend
"NO_LEGEND" -> Right PCSLPNoLegend
"LABELED_LEGEND" -> Right PCSLPLabeledLegend
x -> Left ("Unable to parse PieChartSpecLegendPosition from: " <> x)
instance ToHttpApiData PieChartSpecLegendPosition where
toQueryParam = \case
PCSLPPieChartLegendPositionUnspecified -> "PIE_CHART_LEGEND_POSITION_UNSPECIFIED"
PCSLPBottomLegend -> "BOTTOM_LEGEND"
PCSLPLeftLegend -> "LEFT_LEGEND"
PCSLPRightLegend -> "RIGHT_LEGEND"
PCSLPTopLegend -> "TOP_LEGEND"
PCSLPNoLegend -> "NO_LEGEND"
PCSLPLabeledLegend -> "LABELED_LEGEND"
instance FromJSON PieChartSpecLegendPosition where
parseJSON = parseJSONText "PieChartSpecLegendPosition"
instance ToJSON PieChartSpecLegendPosition where
toJSON = toJSONText
-- | The vertical alignment of the value in the cell.
data CellFormatVerticalAlignment
= VerticalAlignUnspecified
-- ^ @VERTICAL_ALIGN_UNSPECIFIED@
-- The vertical alignment is not specified. Do not use this.
| Top
-- ^ @TOP@
-- The text is explicitly aligned to the top of the cell.
| Middle
-- ^ @MIDDLE@
-- The text is explicitly aligned to the middle of the cell.
| Bottom
-- ^ @BOTTOM@
-- The text is explicitly aligned to the bottom of the cell.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable CellFormatVerticalAlignment
instance FromHttpApiData CellFormatVerticalAlignment where
parseQueryParam = \case
"VERTICAL_ALIGN_UNSPECIFIED" -> Right VerticalAlignUnspecified
"TOP" -> Right Top
"MIDDLE" -> Right Middle
"BOTTOM" -> Right Bottom
x -> Left ("Unable to parse CellFormatVerticalAlignment from: " <> x)
instance ToHttpApiData CellFormatVerticalAlignment where
toQueryParam = \case
VerticalAlignUnspecified -> "VERTICAL_ALIGN_UNSPECIFIED"
Top -> "TOP"
Middle -> "MIDDLE"
Bottom -> "BOTTOM"
instance FromJSON CellFormatVerticalAlignment where
parseJSON = parseJSONText "CellFormatVerticalAlignment"
instance ToJSON CellFormatVerticalAlignment where
toJSON = toJSONText
-- | The type of the number format. When writing, this field must be set.
data NumberFormatType
= NumberFormatTypeUnspecified
-- ^ @NUMBER_FORMAT_TYPE_UNSPECIFIED@
-- The number format is not specified and is based on the contents of the
-- cell. Do not explicitly use this.
| Text
-- ^ @TEXT@
-- Text formatting, e.g \`1000.12\`
| Number
-- ^ @NUMBER@
-- Number formatting, e.g, \`1,000.12\`
| Percent
-- ^ @PERCENT@
-- Percent formatting, e.g \`10.12%\`
| Currency
-- ^ @CURRENCY@
-- Currency formatting, e.g \`$1,000.12\`
| Date
-- ^ @DATE@
-- Date formatting, e.g \`9\/26\/2008\`
| Time
-- ^ @TIME@
-- Time formatting, e.g \`3:59:00 PM\`
| DateTime''
-- ^ @DATE_TIME@
-- Date+Time formatting, e.g \`9\/26\/08 15:59:00\`
| Scientific
-- ^ @SCIENTIFIC@
-- Scientific number formatting, e.g \`1.01E+03\`
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable NumberFormatType
instance FromHttpApiData NumberFormatType where
parseQueryParam = \case
"NUMBER_FORMAT_TYPE_UNSPECIFIED" -> Right NumberFormatTypeUnspecified
"TEXT" -> Right Text
"NUMBER" -> Right Number
"PERCENT" -> Right Percent
"CURRENCY" -> Right Currency
"DATE" -> Right Date
"TIME" -> Right Time
"DATE_TIME" -> Right DateTime''
"SCIENTIFIC" -> Right Scientific
x -> Left ("Unable to parse NumberFormatType from: " <> x)
instance ToHttpApiData NumberFormatType where
toQueryParam = \case
NumberFormatTypeUnspecified -> "NUMBER_FORMAT_TYPE_UNSPECIFIED"
Text -> "TEXT"
Number -> "NUMBER"
Percent -> "PERCENT"
Currency -> "CURRENCY"
Date -> "DATE"
Time -> "TIME"
DateTime'' -> "DATE_TIME"
Scientific -> "SCIENTIFIC"
instance FromJSON NumberFormatType where
parseJSON = parseJSONText "NumberFormatType"
instance ToJSON NumberFormatType where
toJSON = toJSONText
-- | A relative date (based on the current date). Valid only if the type is
-- DATE_BEFORE, DATE_AFTER, DATE_ON_OR_BEFORE or DATE_ON_OR_AFTER. Relative
-- dates are not supported in data validation. They are supported only in
-- conditional formatting and conditional filters.
data ConditionValueRelativeDate
= RelativeDateUnspecified
-- ^ @RELATIVE_DATE_UNSPECIFIED@
-- Default value, do not use.
| PastYear
-- ^ @PAST_YEAR@
-- The value is one year before today.
| PastMonth
-- ^ @PAST_MONTH@
-- The value is one month before today.
| PastWeek
-- ^ @PAST_WEEK@
-- The value is one week before today.
| Yesterday
-- ^ @YESTERDAY@
-- The value is yesterday.
| Today
-- ^ @TODAY@
-- The value is today.
| Tomorrow
-- ^ @TOMORROW@
-- The value is tomorrow.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable ConditionValueRelativeDate
instance FromHttpApiData ConditionValueRelativeDate where
parseQueryParam = \case
"RELATIVE_DATE_UNSPECIFIED" -> Right RelativeDateUnspecified
"PAST_YEAR" -> Right PastYear
"PAST_MONTH" -> Right PastMonth
"PAST_WEEK" -> Right PastWeek
"YESTERDAY" -> Right Yesterday
"TODAY" -> Right Today
"TOMORROW" -> Right Tomorrow
x -> Left ("Unable to parse ConditionValueRelativeDate from: " <> x)
instance ToHttpApiData ConditionValueRelativeDate where
toQueryParam = \case
RelativeDateUnspecified -> "RELATIVE_DATE_UNSPECIFIED"
PastYear -> "PAST_YEAR"
PastMonth -> "PAST_MONTH"
PastWeek -> "PAST_WEEK"
Yesterday -> "YESTERDAY"
Today -> "TODAY"
Tomorrow -> "TOMORROW"
instance FromJSON ConditionValueRelativeDate where
parseJSON = parseJSONText "ConditionValueRelativeDate"
instance ToJSON ConditionValueRelativeDate where
toJSON = toJSONText
-- | The type of the spreadsheet theme color.
data ThemeColorPairColorType
= TCPCTThemeColorTypeUnspecified
-- ^ @THEME_COLOR_TYPE_UNSPECIFIED@
-- Unspecified theme color
| TCPCTText
-- ^ @TEXT@
-- Represents the primary text color
| TCPCTBackgRound
-- ^ @BACKGROUND@
-- Represents the primary background color
| TCPCTACCENT1
-- ^ @ACCENT1@
-- Represents the first accent color
| TCPCTACCENT2
-- ^ @ACCENT2@
-- Represents the second accent color
| TCPCTACCENT3
-- ^ @ACCENT3@
-- Represents the third accent color
| TCPCTACCENT4
-- ^ @ACCENT4@
-- Represents the fourth accent color
| TCPCTACCENT5
-- ^ @ACCENT5@
-- Represents the fifth accent color
| TCPCTACCENT6
-- ^ @ACCENT6@
-- Represents the sixth accent color
| TCPCTLink
-- ^ @LINK@
-- Represents the color to use for hyperlinks
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable ThemeColorPairColorType
instance FromHttpApiData ThemeColorPairColorType where
parseQueryParam = \case
"THEME_COLOR_TYPE_UNSPECIFIED" -> Right TCPCTThemeColorTypeUnspecified
"TEXT" -> Right TCPCTText
"BACKGROUND" -> Right TCPCTBackgRound
"ACCENT1" -> Right TCPCTACCENT1
"ACCENT2" -> Right TCPCTACCENT2
"ACCENT3" -> Right TCPCTACCENT3
"ACCENT4" -> Right TCPCTACCENT4
"ACCENT5" -> Right TCPCTACCENT5
"ACCENT6" -> Right TCPCTACCENT6
"LINK" -> Right TCPCTLink
x -> Left ("Unable to parse ThemeColorPairColorType from: " <> x)
instance ToHttpApiData ThemeColorPairColorType where
toQueryParam = \case
TCPCTThemeColorTypeUnspecified -> "THEME_COLOR_TYPE_UNSPECIFIED"
TCPCTText -> "TEXT"
TCPCTBackgRound -> "BACKGROUND"
TCPCTACCENT1 -> "ACCENT1"
TCPCTACCENT2 -> "ACCENT2"
TCPCTACCENT3 -> "ACCENT3"
TCPCTACCENT4 -> "ACCENT4"
TCPCTACCENT5 -> "ACCENT5"
TCPCTACCENT6 -> "ACCENT6"
TCPCTLink -> "LINK"
instance FromJSON ThemeColorPairColorType where
parseJSON = parseJSONText "ThemeColorPairColorType"
instance ToJSON ThemeColorPairColorType where
toJSON = toJSONText
-- | The type of location this object represents. This field is read-only.
data DeveloperMetadataLocationLocationType
= DMLLTDeveloperMetadataLocationTypeUnspecified
-- ^ @DEVELOPER_METADATA_LOCATION_TYPE_UNSPECIFIED@
-- Default value.
| DMLLTRow
-- ^ @ROW@
-- Developer metadata associated on an entire row dimension.
| DMLLTColumn
-- ^ @COLUMN@
-- Developer metadata associated on an entire column dimension.
| DMLLTSheet
-- ^ @SHEET@
-- Developer metadata associated on an entire sheet.
| DMLLTSpreadsheet
-- ^ @SPREADSHEET@
-- Developer metadata associated on the entire spreadsheet.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable DeveloperMetadataLocationLocationType
instance FromHttpApiData DeveloperMetadataLocationLocationType where
parseQueryParam = \case
"DEVELOPER_METADATA_LOCATION_TYPE_UNSPECIFIED" -> Right DMLLTDeveloperMetadataLocationTypeUnspecified
"ROW" -> Right DMLLTRow
"COLUMN" -> Right DMLLTColumn
"SHEET" -> Right DMLLTSheet
"SPREADSHEET" -> Right DMLLTSpreadsheet
x -> Left ("Unable to parse DeveloperMetadataLocationLocationType from: " <> x)
instance ToHttpApiData DeveloperMetadataLocationLocationType where
toQueryParam = \case
DMLLTDeveloperMetadataLocationTypeUnspecified -> "DEVELOPER_METADATA_LOCATION_TYPE_UNSPECIFIED"
DMLLTRow -> "ROW"
DMLLTColumn -> "COLUMN"
DMLLTSheet -> "SHEET"
DMLLTSpreadsheet -> "SPREADSHEET"
instance FromJSON DeveloperMetadataLocationLocationType where
parseJSON = parseJSONText "DeveloperMetadataLocationLocationType"
instance ToJSON DeveloperMetadataLocationLocationType where
toJSON = toJSONText
-- | The error code.
data DataExecutionStatusErrorCode
= DataExecutionErrorCodeUnspecified
-- ^ @DATA_EXECUTION_ERROR_CODE_UNSPECIFIED@
-- Default value, do not use.
| TimedOut
-- ^ @TIMED_OUT@
-- The data execution timed out.
| TooManyRows
-- ^ @TOO_MANY_ROWS@
-- The data execution returns more rows than the limit.
| TooManyCells
-- ^ @TOO_MANY_CELLS@
-- The data execution returns more cells than the limit.
| Engine
-- ^ @ENGINE@
-- Error is received from the backend data execution engine (e.g.
-- BigQuery). Check error_message for details.
| ParameterInvalid
-- ^ @PARAMETER_INVALID@
-- One or some of the provided data source parameters are invalid.
| UnsupportedDataType
-- ^ @UNSUPPORTED_DATA_TYPE@
-- The data execution returns an unsupported data type.
| DuplicateColumnNames
-- ^ @DUPLICATE_COLUMN_NAMES@
-- The data execution returns duplicate column names or aliases.
| Interrupted
-- ^ @INTERRUPTED@
-- The data execution is interrupted. Please refresh later.
| ConcurrentQuery
-- ^ @CONCURRENT_QUERY@
-- The data execution is currently in progress, can not be refreshed until
-- it completes.
| Other
-- ^ @OTHER@
-- Other errors.
| TooManyCharsPerCell
-- ^ @TOO_MANY_CHARS_PER_CELL@
-- The data execution returns values that exceed the maximum characters
-- allowed in a single cell.
| DataNotFound
-- ^ @DATA_NOT_FOUND@
-- The database referenced by the data source is not found. *\/
| PermissionDenied
-- ^ @PERMISSION_DENIED@
-- The user does not have access to the database referenced by the data
-- source.
| MissingColumnAlias
-- ^ @MISSING_COLUMN_ALIAS@
-- The data execution returns columns with missing aliases.
| ObjectNotFound
-- ^ @OBJECT_NOT_FOUND@
-- The data source object does not exist.
| ObjectInErrorState
-- ^ @OBJECT_IN_ERROR_STATE@
-- The data source object is currently in error state. To force refresh,
-- set force in RefreshDataSourceRequest.
| ObjectSpecInvalid
-- ^ @OBJECT_SPEC_INVALID@
-- The data source object specification is invalid.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable DataExecutionStatusErrorCode
instance FromHttpApiData DataExecutionStatusErrorCode where
parseQueryParam = \case
"DATA_EXECUTION_ERROR_CODE_UNSPECIFIED" -> Right DataExecutionErrorCodeUnspecified
"TIMED_OUT" -> Right TimedOut
"TOO_MANY_ROWS" -> Right TooManyRows
"TOO_MANY_CELLS" -> Right TooManyCells
"ENGINE" -> Right Engine
"PARAMETER_INVALID" -> Right ParameterInvalid
"UNSUPPORTED_DATA_TYPE" -> Right UnsupportedDataType
"DUPLICATE_COLUMN_NAMES" -> Right DuplicateColumnNames
"INTERRUPTED" -> Right Interrupted
"CONCURRENT_QUERY" -> Right ConcurrentQuery
"OTHER" -> Right Other
"TOO_MANY_CHARS_PER_CELL" -> Right TooManyCharsPerCell
"DATA_NOT_FOUND" -> Right DataNotFound
"PERMISSION_DENIED" -> Right PermissionDenied
"MISSING_COLUMN_ALIAS" -> Right MissingColumnAlias
"OBJECT_NOT_FOUND" -> Right ObjectNotFound
"OBJECT_IN_ERROR_STATE" -> Right ObjectInErrorState
"OBJECT_SPEC_INVALID" -> Right ObjectSpecInvalid
x -> Left ("Unable to parse DataExecutionStatusErrorCode from: " <> x)
instance ToHttpApiData DataExecutionStatusErrorCode where
toQueryParam = \case
DataExecutionErrorCodeUnspecified -> "DATA_EXECUTION_ERROR_CODE_UNSPECIFIED"
TimedOut -> "TIMED_OUT"
TooManyRows -> "TOO_MANY_ROWS"
TooManyCells -> "TOO_MANY_CELLS"
Engine -> "ENGINE"
ParameterInvalid -> "PARAMETER_INVALID"
UnsupportedDataType -> "UNSUPPORTED_DATA_TYPE"
DuplicateColumnNames -> "DUPLICATE_COLUMN_NAMES"
Interrupted -> "INTERRUPTED"
ConcurrentQuery -> "CONCURRENT_QUERY"
Other -> "OTHER"
TooManyCharsPerCell -> "TOO_MANY_CHARS_PER_CELL"
DataNotFound -> "DATA_NOT_FOUND"
PermissionDenied -> "PERMISSION_DENIED"
MissingColumnAlias -> "MISSING_COLUMN_ALIAS"
ObjectNotFound -> "OBJECT_NOT_FOUND"
ObjectInErrorState -> "OBJECT_IN_ERROR_STATE"
ObjectSpecInvalid -> "OBJECT_SPEC_INVALID"
instance FromJSON DataExecutionStatusErrorCode where
parseJSON = parseJSONText "DataExecutionStatusErrorCode"
instance ToJSON DataExecutionStatusErrorCode where
toJSON = toJSONText
data DataSourceRefreshWeeklyScheduleDaysOfWeekItem
= DayOfWeekUnspecified
-- ^ @DAY_OF_WEEK_UNSPECIFIED@
-- The day of the week is unspecified.
| Monday
-- ^ @MONDAY@
-- Monday
| Tuesday
-- ^ @TUESDAY@
-- Tuesday
| Wednesday
-- ^ @WEDNESDAY@
-- Wednesday
| Thursday
-- ^ @THURSDAY@
-- Thursday
| Friday
-- ^ @FRIDAY@
-- Friday
| Saturday
-- ^ @SATURDAY@
-- Saturday
| Sunday
-- ^ @SUNDAY@
-- Sunday
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable DataSourceRefreshWeeklyScheduleDaysOfWeekItem
instance FromHttpApiData DataSourceRefreshWeeklyScheduleDaysOfWeekItem where
parseQueryParam = \case
"DAY_OF_WEEK_UNSPECIFIED" -> Right DayOfWeekUnspecified
"MONDAY" -> Right Monday
"TUESDAY" -> Right Tuesday
"WEDNESDAY" -> Right Wednesday
"THURSDAY" -> Right Thursday
"FRIDAY" -> Right Friday
"SATURDAY" -> Right Saturday
"SUNDAY" -> Right Sunday
x -> Left ("Unable to parse DataSourceRefreshWeeklyScheduleDaysOfWeekItem from: " <> x)
instance ToHttpApiData DataSourceRefreshWeeklyScheduleDaysOfWeekItem where
toQueryParam = \case
DayOfWeekUnspecified -> "DAY_OF_WEEK_UNSPECIFIED"
Monday -> "MONDAY"
Tuesday -> "TUESDAY"
Wednesday -> "WEDNESDAY"
Thursday -> "THURSDAY"
Friday -> "FRIDAY"
Saturday -> "SATURDAY"
Sunday -> "SUNDAY"
instance FromJSON DataSourceRefreshWeeklyScheduleDaysOfWeekItem where
parseJSON = parseJSONText "DataSourceRefreshWeeklyScheduleDaysOfWeekItem"
instance ToJSON DataSourceRefreshWeeklyScheduleDaysOfWeekItem where
toJSON = toJSONText
-- | The order data should be sorted.
data SortSpecSortOrder
= SortOrderUnspecified
-- ^ @SORT_ORDER_UNSPECIFIED@
-- Default value, do not use this.
| Ascending
-- ^ @ASCENDING@
-- Sort ascending.
| Descending
-- ^ @DESCENDING@
-- Sort descending.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable SortSpecSortOrder
instance FromHttpApiData SortSpecSortOrder where
parseQueryParam = \case
"SORT_ORDER_UNSPECIFIED" -> Right SortOrderUnspecified
"ASCENDING" -> Right Ascending
"DESCENDING" -> Right Descending
x -> Left ("Unable to parse SortSpecSortOrder from: " <> x)
instance ToHttpApiData SortSpecSortOrder where
toQueryParam = \case
SortOrderUnspecified -> "SORT_ORDER_UNSPECIFIED"
Ascending -> "ASCENDING"
Descending -> "DESCENDING"
instance FromJSON SortSpecSortOrder where
parseJSON = parseJSONText "SortSpecSortOrder"
instance ToJSON SortSpecSortOrder where
toJSON = toJSONText
-- | The horizontal alignment of title in the slicer. If unspecified,
-- defaults to \`LEFT\`
data SlicerSpecHorizontalAlignment
= SSHAHorizontalAlignUnspecified
-- ^ @HORIZONTAL_ALIGN_UNSPECIFIED@
-- The horizontal alignment is not specified. Do not use this.
| SSHALeft'
-- ^ @LEFT@
-- The text is explicitly aligned to the left of the cell.
| SSHACenter
-- ^ @CENTER@
-- The text is explicitly aligned to the center of the cell.
| SSHARight'
-- ^ @RIGHT@
-- The text is explicitly aligned to the right of the cell.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable SlicerSpecHorizontalAlignment
instance FromHttpApiData SlicerSpecHorizontalAlignment where
parseQueryParam = \case
"HORIZONTAL_ALIGN_UNSPECIFIED" -> Right SSHAHorizontalAlignUnspecified
"LEFT" -> Right SSHALeft'
"CENTER" -> Right SSHACenter
"RIGHT" -> Right SSHARight'
x -> Left ("Unable to parse SlicerSpecHorizontalAlignment from: " <> x)
instance ToHttpApiData SlicerSpecHorizontalAlignment where
toQueryParam = \case
SSHAHorizontalAlignUnspecified -> "HORIZONTAL_ALIGN_UNSPECIFIED"
SSHALeft' -> "LEFT"
SSHACenter -> "CENTER"
SSHARight' -> "RIGHT"
instance FromJSON SlicerSpecHorizontalAlignment where
parseJSON = parseJSONText "SlicerSpecHorizontalAlignment"
instance ToJSON SlicerSpecHorizontalAlignment where
toJSON = toJSONText
-- | Theme color.
data ColorStyleThemeColor
= CSTCThemeColorTypeUnspecified
-- ^ @THEME_COLOR_TYPE_UNSPECIFIED@
-- Unspecified theme color
| CSTCText
-- ^ @TEXT@
-- Represents the primary text color
| CSTCBackgRound
-- ^ @BACKGROUND@
-- Represents the primary background color
| CSTCACCENT1
-- ^ @ACCENT1@
-- Represents the first accent color
| CSTCACCENT2
-- ^ @ACCENT2@
-- Represents the second accent color
| CSTCACCENT3
-- ^ @ACCENT3@
-- Represents the third accent color
| CSTCACCENT4
-- ^ @ACCENT4@
-- Represents the fourth accent color
| CSTCACCENT5
-- ^ @ACCENT5@
-- Represents the fifth accent color
| CSTCACCENT6
-- ^ @ACCENT6@
-- Represents the sixth accent color
| CSTCLink
-- ^ @LINK@
-- Represents the color to use for hyperlinks
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable ColorStyleThemeColor
instance FromHttpApiData ColorStyleThemeColor where
parseQueryParam = \case
"THEME_COLOR_TYPE_UNSPECIFIED" -> Right CSTCThemeColorTypeUnspecified
"TEXT" -> Right CSTCText
"BACKGROUND" -> Right CSTCBackgRound
"ACCENT1" -> Right CSTCACCENT1
"ACCENT2" -> Right CSTCACCENT2
"ACCENT3" -> Right CSTCACCENT3
"ACCENT4" -> Right CSTCACCENT4
"ACCENT5" -> Right CSTCACCENT5
"ACCENT6" -> Right CSTCACCENT6
"LINK" -> Right CSTCLink
x -> Left ("Unable to parse ColorStyleThemeColor from: " <> x)
instance ToHttpApiData ColorStyleThemeColor where
toQueryParam = \case
CSTCThemeColorTypeUnspecified -> "THEME_COLOR_TYPE_UNSPECIFIED"
CSTCText -> "TEXT"
CSTCBackgRound -> "BACKGROUND"
CSTCACCENT1 -> "ACCENT1"
CSTCACCENT2 -> "ACCENT2"
CSTCACCENT3 -> "ACCENT3"
CSTCACCENT4 -> "ACCENT4"
CSTCACCENT5 -> "ACCENT5"
CSTCACCENT6 -> "ACCENT6"
CSTCLink -> "LINK"
instance FromJSON ColorStyleThemeColor where
parseJSON = parseJSONText "ColorStyleThemeColor"
instance ToJSON ColorStyleThemeColor where
toJSON = toJSONText
-- | A function to summarize the value. If formula is set, the only supported
-- values are SUM and CUSTOM. If sourceColumnOffset is set, then \`CUSTOM\`
-- is not supported.
data PivotValueSummarizeFunction
= PivotStandardValueFunctionUnspecified
-- ^ @PIVOT_STANDARD_VALUE_FUNCTION_UNSPECIFIED@
-- The default, do not use.
| Sum
-- ^ @SUM@
-- Corresponds to the \`SUM\` function.
| Counta
-- ^ @COUNTA@
-- Corresponds to the \`COUNTA\` function.
| Count
-- ^ @COUNT@
-- Corresponds to the \`COUNT\` function.
| Countunique
-- ^ @COUNTUNIQUE@
-- Corresponds to the \`COUNTUNIQUE\` function.
| Average
-- ^ @AVERAGE@
-- Corresponds to the \`AVERAGE\` function.
| Max
-- ^ @MAX@
-- Corresponds to the \`MAX\` function.
| Min
-- ^ @MIN@
-- Corresponds to the \`MIN\` function.
| Median
-- ^ @MEDIAN@
-- Corresponds to the \`MEDIAN\` function.
| Product
-- ^ @PRODUCT@
-- Corresponds to the \`PRODUCT\` function.
| Stdev
-- ^ @STDEV@
-- Corresponds to the \`STDEV\` function.
| Stdevp
-- ^ @STDEVP@
-- Corresponds to the \`STDEVP\` function.
| Var
-- ^ @VAR@
-- Corresponds to the \`VAR\` function.
| Varp
-- ^ @VARP@
-- Corresponds to the \`VARP\` function.
| Custom
-- ^ @CUSTOM@
-- Indicates the formula should be used as-is. Only valid if
-- PivotValue.formula was set.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable PivotValueSummarizeFunction
instance FromHttpApiData PivotValueSummarizeFunction where
parseQueryParam = \case
"PIVOT_STANDARD_VALUE_FUNCTION_UNSPECIFIED" -> Right PivotStandardValueFunctionUnspecified
"SUM" -> Right Sum
"COUNTA" -> Right Counta
"COUNT" -> Right Count
"COUNTUNIQUE" -> Right Countunique
"AVERAGE" -> Right Average
"MAX" -> Right Max
"MIN" -> Right Min
"MEDIAN" -> Right Median
"PRODUCT" -> Right Product
"STDEV" -> Right Stdev
"STDEVP" -> Right Stdevp
"VAR" -> Right Var
"VARP" -> Right Varp
"CUSTOM" -> Right Custom
x -> Left ("Unable to parse PivotValueSummarizeFunction from: " <> x)
instance ToHttpApiData PivotValueSummarizeFunction where
toQueryParam = \case
PivotStandardValueFunctionUnspecified -> "PIVOT_STANDARD_VALUE_FUNCTION_UNSPECIFIED"
Sum -> "SUM"
Counta -> "COUNTA"
Count -> "COUNT"
Countunique -> "COUNTUNIQUE"
Average -> "AVERAGE"
Max -> "MAX"
Min -> "MIN"
Median -> "MEDIAN"
Product -> "PRODUCT"
Stdev -> "STDEV"
Stdevp -> "STDEVP"
Var -> "VAR"
Varp -> "VARP"
Custom -> "CUSTOM"
instance FromJSON PivotValueSummarizeFunction where
parseJSON = parseJSONText "PivotValueSummarizeFunction"
instance ToJSON PivotValueSummarizeFunction where
toJSON = toJSONText
-- | The size of the org chart nodes.
data OrgChartSpecNodeSize
= OrgChartLabelSizeUnspecified
-- ^ @ORG_CHART_LABEL_SIZE_UNSPECIFIED@
-- Default value, do not use.
| Small
-- ^ @SMALL@
-- The small org chart node size.
| Medium
-- ^ @MEDIUM@
-- The medium org chart node size.
| Large
-- ^ @LARGE@
-- The large org chart node size.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable OrgChartSpecNodeSize
instance FromHttpApiData OrgChartSpecNodeSize where
parseQueryParam = \case
"ORG_CHART_LABEL_SIZE_UNSPECIFIED" -> Right OrgChartLabelSizeUnspecified
"SMALL" -> Right Small
"MEDIUM" -> Right Medium
"LARGE" -> Right Large
x -> Left ("Unable to parse OrgChartSpecNodeSize from: " <> x)
instance ToHttpApiData OrgChartSpecNodeSize where
toQueryParam = \case
OrgChartLabelSizeUnspecified -> "ORG_CHART_LABEL_SIZE_UNSPECIFIED"
Small -> "SMALL"
Medium -> "MEDIUM"
Large -> "LARGE"
instance FromJSON OrgChartSpecNodeSize where
parseJSON = parseJSONText "OrgChartSpecNodeSize"
instance ToJSON OrgChartSpecNodeSize where
toJSON = toJSONText
-- | Determines how values in the response should be rendered. The default
-- render option is FORMATTED_VALUE.
data BatchUpdateValuesByDataFilterRequestResponseValueRenderOption
= BUVBDFRRVROFormattedValue
-- ^ @FORMATTED_VALUE@
-- Values will be calculated & formatted in the reply according to the
-- cell\'s formatting. Formatting is based on the spreadsheet\'s locale,
-- not the requesting user\'s locale. For example, if \`A1\` is \`1.23\`
-- and \`A2\` is \`=A1\` and formatted as currency, then \`A2\` would
-- return \`\"$1.23\"\`.
| BUVBDFRRVROUnformattedValue
-- ^ @UNFORMATTED_VALUE@
-- Values will be calculated, but not formatted in the reply. For example,
-- if \`A1\` is \`1.23\` and \`A2\` is \`=A1\` and formatted as currency,
-- then \`A2\` would return the number \`1.23\`.
| BUVBDFRRVROFormula
-- ^ @FORMULA@
-- Values will not be calculated. The reply will include the formulas. For
-- example, if \`A1\` is \`1.23\` and \`A2\` is \`=A1\` and formatted as
-- currency, then A2 would return \`\"=A1\"\`.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable BatchUpdateValuesByDataFilterRequestResponseValueRenderOption
instance FromHttpApiData BatchUpdateValuesByDataFilterRequestResponseValueRenderOption where
parseQueryParam = \case
"FORMATTED_VALUE" -> Right BUVBDFRRVROFormattedValue
"UNFORMATTED_VALUE" -> Right BUVBDFRRVROUnformattedValue
"FORMULA" -> Right BUVBDFRRVROFormula
x -> Left ("Unable to parse BatchUpdateValuesByDataFilterRequestResponseValueRenderOption from: " <> x)
instance ToHttpApiData BatchUpdateValuesByDataFilterRequestResponseValueRenderOption where
toQueryParam = \case
BUVBDFRRVROFormattedValue -> "FORMATTED_VALUE"
BUVBDFRRVROUnformattedValue -> "UNFORMATTED_VALUE"
BUVBDFRRVROFormula -> "FORMULA"
instance FromJSON BatchUpdateValuesByDataFilterRequestResponseValueRenderOption where
parseJSON = parseJSONText "BatchUpdateValuesByDataFilterRequestResponseValueRenderOption"
instance ToJSON BatchUpdateValuesByDataFilterRequestResponseValueRenderOption where
toJSON = toJSONText
-- | The type of the data label.
data DataLabelType
= DLTDataLabelTypeUnspecified
-- ^ @DATA_LABEL_TYPE_UNSPECIFIED@
-- The data label type is not specified and will be interpreted depending
-- on the context of the data label within the chart.
| DLTNone
-- ^ @NONE@
-- The data label is not displayed.
| DLTData'
-- ^ @DATA@
-- The data label is displayed using values from the series data.
| DLTCustom
-- ^ @CUSTOM@
-- The data label is displayed using values from a custom data source
-- indicated by customLabelData.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable DataLabelType
instance FromHttpApiData DataLabelType where
parseQueryParam = \case
"DATA_LABEL_TYPE_UNSPECIFIED" -> Right DLTDataLabelTypeUnspecified
"NONE" -> Right DLTNone
"DATA" -> Right DLTData'
"CUSTOM" -> Right DLTCustom
x -> Left ("Unable to parse DataLabelType from: " <> x)
instance ToHttpApiData DataLabelType where
toQueryParam = \case
DLTDataLabelTypeUnspecified -> "DATA_LABEL_TYPE_UNSPECIFIED"
DLTNone -> "NONE"
DLTData' -> "DATA"
DLTCustom -> "CUSTOM"
instance FromJSON DataLabelType where
parseJSON = parseJSONText "DataLabelType"
instance ToJSON DataLabelType where
toJSON = toJSONText
-- | The dash type of the line.
data LineStyleType
= LSTLineDashTypeUnspecified
-- ^ @LINE_DASH_TYPE_UNSPECIFIED@
-- Default value, do not use.
| LSTInvisible
-- ^ @INVISIBLE@
-- No dash type, which is equivalent to a non-visible line.
| LSTCustom
-- ^ @CUSTOM@
-- A custom dash for a line. Modifying the exact custom dash style is
-- currently unsupported.
| LSTSolid
-- ^ @SOLID@
-- A solid line.
| LSTDotted
-- ^ @DOTTED@
-- A dotted line.
| LSTMediumDashed
-- ^ @MEDIUM_DASHED@
-- A dashed line where the dashes have \"medium\" length.
| LSTMediumDashedDotted
-- ^ @MEDIUM_DASHED_DOTTED@
-- A line that alternates between a \"medium\" dash and a dot.
| LSTLongDashed
-- ^ @LONG_DASHED@
-- A dashed line where the dashes have \"long\" length.
| LSTLongDashedDotted
-- ^ @LONG_DASHED_DOTTED@
-- A line that alternates between a \"long\" dash and a dot.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable LineStyleType
instance FromHttpApiData LineStyleType where
parseQueryParam = \case
"LINE_DASH_TYPE_UNSPECIFIED" -> Right LSTLineDashTypeUnspecified
"INVISIBLE" -> Right LSTInvisible
"CUSTOM" -> Right LSTCustom
"SOLID" -> Right LSTSolid
"DOTTED" -> Right LSTDotted
"MEDIUM_DASHED" -> Right LSTMediumDashed
"MEDIUM_DASHED_DOTTED" -> Right LSTMediumDashedDotted
"LONG_DASHED" -> Right LSTLongDashed
"LONG_DASHED_DOTTED" -> Right LSTLongDashedDotted
x -> Left ("Unable to parse LineStyleType from: " <> x)
instance ToHttpApiData LineStyleType where
toQueryParam = \case
LSTLineDashTypeUnspecified -> "LINE_DASH_TYPE_UNSPECIFIED"
LSTInvisible -> "INVISIBLE"
LSTCustom -> "CUSTOM"
LSTSolid -> "SOLID"
LSTDotted -> "DOTTED"
LSTMediumDashed -> "MEDIUM_DASHED"
LSTMediumDashedDotted -> "MEDIUM_DASHED_DOTTED"
LSTLongDashed -> "LONG_DASHED"
LSTLongDashedDotted -> "LONG_DASHED_DOTTED"
instance FromJSON LineStyleType where
parseJSON = parseJSONText "LineStyleType"
instance ToJSON LineStyleType where
toJSON = toJSONText
-- | How a hyperlink, if it exists, should be displayed in the cell.
data CellFormatHyperlinkDisplayType
= HyperlinkDisplayTypeUnspecified
-- ^ @HYPERLINK_DISPLAY_TYPE_UNSPECIFIED@
-- The default value: the hyperlink is rendered. Do not use this.
| Linked
-- ^ @LINKED@
-- A hyperlink should be explicitly rendered.
| PlainText
-- ^ @PLAIN_TEXT@
-- A hyperlink should not be rendered.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable CellFormatHyperlinkDisplayType
instance FromHttpApiData CellFormatHyperlinkDisplayType where
parseQueryParam = \case
"HYPERLINK_DISPLAY_TYPE_UNSPECIFIED" -> Right HyperlinkDisplayTypeUnspecified
"LINKED" -> Right Linked
"PLAIN_TEXT" -> Right PlainText
x -> Left ("Unable to parse CellFormatHyperlinkDisplayType from: " <> x)
instance ToHttpApiData CellFormatHyperlinkDisplayType where
toQueryParam = \case
HyperlinkDisplayTypeUnspecified -> "HYPERLINK_DISPLAY_TYPE_UNSPECIFIED"
Linked -> "LINKED"
PlainText -> "PLAIN_TEXT"
instance FromJSON CellFormatHyperlinkDisplayType where
parseJSON = parseJSONText "CellFormatHyperlinkDisplayType"
instance ToJSON CellFormatHyperlinkDisplayType where
toJSON = toJSONText
-- | How the input data should be interpreted.
data BatchUpdateValuesByDataFilterRequestValueInputOption
= BUVBDFRVIOInputValueOptionUnspecified
-- ^ @INPUT_VALUE_OPTION_UNSPECIFIED@
-- Default input value. This value must not be used.
| BUVBDFRVIORaw
-- ^ @RAW@
-- The values the user has entered will not be parsed and will be stored
-- as-is.
| BUVBDFRVIOUserEntered
-- ^ @USER_ENTERED@
-- The values will be parsed as if the user typed them into the UI. Numbers
-- will stay as numbers, but strings may be converted to numbers, dates,
-- etc. following the same rules that are applied when entering text into a
-- cell via the Google Sheets UI.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable BatchUpdateValuesByDataFilterRequestValueInputOption
instance FromHttpApiData BatchUpdateValuesByDataFilterRequestValueInputOption where
parseQueryParam = \case
"INPUT_VALUE_OPTION_UNSPECIFIED" -> Right BUVBDFRVIOInputValueOptionUnspecified
"RAW" -> Right BUVBDFRVIORaw
"USER_ENTERED" -> Right BUVBDFRVIOUserEntered
x -> Left ("Unable to parse BatchUpdateValuesByDataFilterRequestValueInputOption from: " <> x)
instance ToHttpApiData BatchUpdateValuesByDataFilterRequestValueInputOption where
toQueryParam = \case
BUVBDFRVIOInputValueOptionUnspecified -> "INPUT_VALUE_OPTION_UNSPECIFIED"
BUVBDFRVIORaw -> "RAW"
BUVBDFRVIOUserEntered -> "USER_ENTERED"
instance FromJSON BatchUpdateValuesByDataFilterRequestValueInputOption where
parseJSON = parseJSONText "BatchUpdateValuesByDataFilterRequestValueInputOption"
instance ToJSON BatchUpdateValuesByDataFilterRequestValueInputOption where
toJSON = toJSONText
-- | The position of the chart legend.
data HistogramChartSpecLegendPosition
= HCSLPHistogramChartLegendPositionUnspecified
-- ^ @HISTOGRAM_CHART_LEGEND_POSITION_UNSPECIFIED@
-- Default value, do not use.
| HCSLPBottomLegend
-- ^ @BOTTOM_LEGEND@
-- The legend is rendered on the bottom of the chart.
| HCSLPLeftLegend
-- ^ @LEFT_LEGEND@
-- The legend is rendered on the left of the chart.
| HCSLPRightLegend
-- ^ @RIGHT_LEGEND@
-- The legend is rendered on the right of the chart.
| HCSLPTopLegend
-- ^ @TOP_LEGEND@
-- The legend is rendered on the top of the chart.
| HCSLPNoLegend
-- ^ @NO_LEGEND@
-- No legend is rendered.
| HCSLPInsideLegend
-- ^ @INSIDE_LEGEND@
-- The legend is rendered inside the chart area.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable HistogramChartSpecLegendPosition
instance FromHttpApiData HistogramChartSpecLegendPosition where
parseQueryParam = \case
"HISTOGRAM_CHART_LEGEND_POSITION_UNSPECIFIED" -> Right HCSLPHistogramChartLegendPositionUnspecified
"BOTTOM_LEGEND" -> Right HCSLPBottomLegend
"LEFT_LEGEND" -> Right HCSLPLeftLegend
"RIGHT_LEGEND" -> Right HCSLPRightLegend
"TOP_LEGEND" -> Right HCSLPTopLegend
"NO_LEGEND" -> Right HCSLPNoLegend
"INSIDE_LEGEND" -> Right HCSLPInsideLegend
x -> Left ("Unable to parse HistogramChartSpecLegendPosition from: " <> x)
instance ToHttpApiData HistogramChartSpecLegendPosition where
toQueryParam = \case
HCSLPHistogramChartLegendPositionUnspecified -> "HISTOGRAM_CHART_LEGEND_POSITION_UNSPECIFIED"
HCSLPBottomLegend -> "BOTTOM_LEGEND"
HCSLPLeftLegend -> "LEFT_LEGEND"
HCSLPRightLegend -> "RIGHT_LEGEND"
HCSLPTopLegend -> "TOP_LEGEND"
HCSLPNoLegend -> "NO_LEGEND"
HCSLPInsideLegend -> "INSIDE_LEGEND"
instance FromJSON HistogramChartSpecLegendPosition where
parseJSON = parseJSONText "HistogramChartSpecLegendPosition"
instance ToJSON HistogramChartSpecLegendPosition where
toJSON = toJSONText
-- | The type of sheet. Defaults to GRID. This field cannot be changed once
-- set.
data SheetPropertiesSheetType
= SPSTSheetTypeUnspecified
-- ^ @SHEET_TYPE_UNSPECIFIED@
-- Default value, do not use.
| SPSTGrid
-- ^ @GRID@
-- The sheet is a grid.
| SPSTObject
-- ^ @OBJECT@
-- The sheet has no grid and instead has an object like a chart or image.
| SPSTDataSource
-- ^ @DATA_SOURCE@
-- The sheet connects with an external DataSource and shows the preview of
-- data.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable SheetPropertiesSheetType
instance FromHttpApiData SheetPropertiesSheetType where
parseQueryParam = \case
"SHEET_TYPE_UNSPECIFIED" -> Right SPSTSheetTypeUnspecified
"GRID" -> Right SPSTGrid
"OBJECT" -> Right SPSTObject
"DATA_SOURCE" -> Right SPSTDataSource
x -> Left ("Unable to parse SheetPropertiesSheetType from: " <> x)
instance ToHttpApiData SheetPropertiesSheetType where
toQueryParam = \case
SPSTSheetTypeUnspecified -> "SHEET_TYPE_UNSPECIFIED"
SPSTGrid -> "GRID"
SPSTObject -> "OBJECT"
SPSTDataSource -> "DATA_SOURCE"
instance FromJSON SheetPropertiesSheetType where
parseJSON = parseJSONText "SheetPropertiesSheetType"
instance ToJSON SheetPropertiesSheetType where
toJSON = toJSONText
-- | Limits the selected developer metadata to those entries which are
-- associated with locations of the specified type. For example, when this
-- field is specified as ROW this lookup only considers developer metadata
-- associated on rows. If the field is left unspecified, all location types
-- are considered. This field cannot be specified as SPREADSHEET when the
-- locationMatchingStrategy is specified as INTERSECTING or when the
-- metadataLocation is specified as a non-spreadsheet location: spreadsheet
-- metadata cannot intersect any other developer metadata location. This
-- field also must be left unspecified when the locationMatchingStrategy is
-- specified as EXACT.
data DeveloperMetadataLookupLocationType
= DDeveloperMetadataLocationTypeUnspecified
-- ^ @DEVELOPER_METADATA_LOCATION_TYPE_UNSPECIFIED@
-- Default value.
| DRow
-- ^ @ROW@
-- Developer metadata associated on an entire row dimension.
| DColumn
-- ^ @COLUMN@
-- Developer metadata associated on an entire column dimension.
| DSheet
-- ^ @SHEET@
-- Developer metadata associated on an entire sheet.
| DSpreadsheet
-- ^ @SPREADSHEET@
-- Developer metadata associated on the entire spreadsheet.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable DeveloperMetadataLookupLocationType
instance FromHttpApiData DeveloperMetadataLookupLocationType where
parseQueryParam = \case
"DEVELOPER_METADATA_LOCATION_TYPE_UNSPECIFIED" -> Right DDeveloperMetadataLocationTypeUnspecified
"ROW" -> Right DRow
"COLUMN" -> Right DColumn
"SHEET" -> Right DSheet
"SPREADSHEET" -> Right DSpreadsheet
x -> Left ("Unable to parse DeveloperMetadataLookupLocationType from: " <> x)
instance ToHttpApiData DeveloperMetadataLookupLocationType where
toQueryParam = \case
DDeveloperMetadataLocationTypeUnspecified -> "DEVELOPER_METADATA_LOCATION_TYPE_UNSPECIFIED"
DRow -> "ROW"
DColumn -> "COLUMN"
DSheet -> "SHEET"
DSpreadsheet -> "SPREADSHEET"
instance FromJSON DeveloperMetadataLookupLocationType where
parseJSON = parseJSONText "DeveloperMetadataLookupLocationType"
instance ToJSON DeveloperMetadataLookupLocationType where
toJSON = toJSONText
-- | The point shape. If empty or unspecified, a default shape is used.
data PointStyleShape
= PointShapeUnspecified
-- ^ @POINT_SHAPE_UNSPECIFIED@
-- Default value.
| Circle
-- ^ @CIRCLE@
-- A circle shape.
| Diamond
-- ^ @DIAMOND@
-- A diamond shape.
| Hexagon
-- ^ @HEXAGON@
-- A hexagon shape.
| Pentagon
-- ^ @PENTAGON@
-- A pentagon shape.
| Square
-- ^ @SQUARE@
-- A square shape.
| Star
-- ^ @STAR@
-- A star shape.
| Triangle
-- ^ @TRIANGLE@
-- A triangle shape.
| XMark
-- ^ @X_MARK@
-- An x-mark shape.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable PointStyleShape
instance FromHttpApiData PointStyleShape where
parseQueryParam = \case
"POINT_SHAPE_UNSPECIFIED" -> Right PointShapeUnspecified
"CIRCLE" -> Right Circle
"DIAMOND" -> Right Diamond
"HEXAGON" -> Right Hexagon
"PENTAGON" -> Right Pentagon
"SQUARE" -> Right Square
"STAR" -> Right Star
"TRIANGLE" -> Right Triangle
"X_MARK" -> Right XMark
x -> Left ("Unable to parse PointStyleShape from: " <> x)
instance ToHttpApiData PointStyleShape where
toQueryParam = \case
PointShapeUnspecified -> "POINT_SHAPE_UNSPECIFIED"
Circle -> "CIRCLE"
Diamond -> "DIAMOND"
Hexagon -> "HEXAGON"
Pentagon -> "PENTAGON"
Square -> "SQUARE"
Star -> "STAR"
Triangle -> "TRIANGLE"
XMark -> "X_MARK"
instance FromJSON PointStyleShape where
parseJSON = parseJSONText "PointStyleShape"
instance ToJSON PointStyleShape where
toJSON = toJSONText
-- | The aggregation type for key and baseline chart data in scorecard chart.
-- This field is not supported for data source charts. Use the
-- ChartData.aggregateType field of the key_value_data or
-- baseline_value_data instead for data source charts. This field is
-- optional.
data ScorecardChartSpecAggregateType
= SCSATChartAggregateTypeUnspecified
-- ^ @CHART_AGGREGATE_TYPE_UNSPECIFIED@
-- Default value, do not use.
| SCSATAverage
-- ^ @AVERAGE@
-- Average aggregate function.
| SCSATCount
-- ^ @COUNT@
-- Count aggregate function.
| SCSATMax
-- ^ @MAX@
-- Maximum aggregate function.
| SCSATMedian
-- ^ @MEDIAN@
-- Median aggregate function.
| SCSATMin
-- ^ @MIN@
-- Minimum aggregate function.
| SCSATSum
-- ^ @SUM@
-- Sum aggregate function.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable ScorecardChartSpecAggregateType
instance FromHttpApiData ScorecardChartSpecAggregateType where
parseQueryParam = \case
"CHART_AGGREGATE_TYPE_UNSPECIFIED" -> Right SCSATChartAggregateTypeUnspecified
"AVERAGE" -> Right SCSATAverage
"COUNT" -> Right SCSATCount
"MAX" -> Right SCSATMax
"MEDIAN" -> Right SCSATMedian
"MIN" -> Right SCSATMin
"SUM" -> Right SCSATSum
x -> Left ("Unable to parse ScorecardChartSpecAggregateType from: " <> x)
instance ToHttpApiData ScorecardChartSpecAggregateType where
toQueryParam = \case
SCSATChartAggregateTypeUnspecified -> "CHART_AGGREGATE_TYPE_UNSPECIFIED"
SCSATAverage -> "AVERAGE"
SCSATCount -> "COUNT"
SCSATMax -> "MAX"
SCSATMedian -> "MEDIAN"
SCSATMin -> "MIN"
SCSATSum -> "SUM"
instance FromJSON ScorecardChartSpecAggregateType where
parseJSON = parseJSONText "ScorecardChartSpecAggregateType"
instance ToJSON ScorecardChartSpecAggregateType where
toJSON = toJSONText
-- | How the cells should be merged.
data MergeCellsRequestMergeType
= MergeAll
-- ^ @MERGE_ALL@
-- Create a single merge from the range
| MergeColumns
-- ^ @MERGE_COLUMNS@
-- Create a merge for each column in the range
| MergeRows
-- ^ @MERGE_ROWS@
-- Create a merge for each row in the range
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable MergeCellsRequestMergeType
instance FromHttpApiData MergeCellsRequestMergeType where
parseQueryParam = \case
"MERGE_ALL" -> Right MergeAll
"MERGE_COLUMNS" -> Right MergeColumns
"MERGE_ROWS" -> Right MergeRows
x -> Left ("Unable to parse MergeCellsRequestMergeType from: " <> x)
instance ToHttpApiData MergeCellsRequestMergeType where
toQueryParam = \case
MergeAll -> "MERGE_ALL"
MergeColumns -> "MERGE_COLUMNS"
MergeRows -> "MERGE_ROWS"
instance FromJSON MergeCellsRequestMergeType where
parseJSON = parseJSONText "MergeCellsRequestMergeType"
instance ToJSON MergeCellsRequestMergeType where
toJSON = toJSONText
-- | The horizontal alignment of the value in the cell.
data CellFormatHorizontalAlignment
= CFHAHorizontalAlignUnspecified
-- ^ @HORIZONTAL_ALIGN_UNSPECIFIED@
-- The horizontal alignment is not specified. Do not use this.
| CFHALeft'
-- ^ @LEFT@
-- The text is explicitly aligned to the left of the cell.
| CFHACenter
-- ^ @CENTER@
-- The text is explicitly aligned to the center of the cell.
| CFHARight'
-- ^ @RIGHT@
-- The text is explicitly aligned to the right of the cell.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable CellFormatHorizontalAlignment
instance FromHttpApiData CellFormatHorizontalAlignment where
parseQueryParam = \case
"HORIZONTAL_ALIGN_UNSPECIFIED" -> Right CFHAHorizontalAlignUnspecified
"LEFT" -> Right CFHALeft'
"CENTER" -> Right CFHACenter
"RIGHT" -> Right CFHARight'
x -> Left ("Unable to parse CellFormatHorizontalAlignment from: " <> x)
instance ToHttpApiData CellFormatHorizontalAlignment where
toQueryParam = \case
CFHAHorizontalAlignUnspecified -> "HORIZONTAL_ALIGN_UNSPECIFIED"
CFHALeft' -> "LEFT"
CFHACenter -> "CENTER"
CFHARight' -> "RIGHT"
instance FromJSON CellFormatHorizontalAlignment where
parseJSON = parseJSONText "CellFormatHorizontalAlignment"
instance ToJSON CellFormatHorizontalAlignment where
toJSON = toJSONText
-- | The stacked type.
data WaterfallChartSpecStackedType
= WCSSTWaterfallStackedTypeUnspecified
-- ^ @WATERFALL_STACKED_TYPE_UNSPECIFIED@
-- Default value, do not use.
| WCSSTStacked
-- ^ @STACKED@
-- Values corresponding to the same domain (horizontal axis) value will be
-- stacked vertically.
| WCSSTSequential
-- ^ @SEQUENTIAL@
-- Series will spread out along the horizontal axis.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable WaterfallChartSpecStackedType
instance FromHttpApiData WaterfallChartSpecStackedType where
parseQueryParam = \case
"WATERFALL_STACKED_TYPE_UNSPECIFIED" -> Right WCSSTWaterfallStackedTypeUnspecified
"STACKED" -> Right WCSSTStacked
"SEQUENTIAL" -> Right WCSSTSequential
x -> Left ("Unable to parse WaterfallChartSpecStackedType from: " <> x)
instance ToHttpApiData WaterfallChartSpecStackedType where
toQueryParam = \case
WCSSTWaterfallStackedTypeUnspecified -> "WATERFALL_STACKED_TYPE_UNSPECIFIED"
WCSSTStacked -> "STACKED"
WCSSTSequential -> "SEQUENTIAL"
instance FromJSON WaterfallChartSpecStackedType where
parseJSON = parseJSONText "WaterfallChartSpecStackedType"
instance ToJSON WaterfallChartSpecStackedType where
toJSON = toJSONText
-- | The type of date-time grouping to apply.
data DateTimeRuleType
= DateTimeRuleTypeUnspecified
-- ^ @DATE_TIME_RULE_TYPE_UNSPECIFIED@
-- The default type, do not use.
| Second
-- ^ @SECOND@
-- Group dates by second, from 0 to 59.
| Minute
-- ^ @MINUTE@
-- Group dates by minute, from 0 to 59.
| Hour
-- ^ @HOUR@
-- Group dates by hour using a 24-hour system, from 0 to 23.
| HourMinute
-- ^ @HOUR_MINUTE@
-- Group dates by hour and minute using a 24-hour system, for example
-- 19:45.
| HourMinuteAmpm
-- ^ @HOUR_MINUTE_AMPM@
-- Group dates by hour and minute using a 12-hour system, for example 7:45
-- PM. The AM\/PM designation is translated based on the spreadsheet
-- locale.
| DayOfWeek
-- ^ @DAY_OF_WEEK@
-- Group dates by day of week, for example Sunday. The days of the week
-- will be translated based on the spreadsheet locale.
| DayOfYear
-- ^ @DAY_OF_YEAR@
-- Group dates by day of year, from 1 to 366. Note that dates after Feb. 29
-- fall in different buckets in leap years than in non-leap years.
| DayOfMonth
-- ^ @DAY_OF_MONTH@
-- Group dates by day of month, from 1 to 31.
| DayMonth
-- ^ @DAY_MONTH@
-- Group dates by day and month, for example 22-Nov. The month is
-- translated based on the spreadsheet locale.
| Month
-- ^ @MONTH@
-- Group dates by month, for example Nov. The month is translated based on
-- the spreadsheet locale.
| Quarter
-- ^ @QUARTER@
-- Group dates by quarter, for example Q1 (which represents Jan-Mar).
| Year
-- ^ @YEAR@
-- Group dates by year, for example 2008.
| YearMonth
-- ^ @YEAR_MONTH@
-- Group dates by year and month, for example 2008-Nov. The month is
-- translated based on the spreadsheet locale.
| YearQuarter
-- ^ @YEAR_QUARTER@
-- Group dates by year and quarter, for example 2008 Q4.
| YearMonthDay
-- ^ @YEAR_MONTH_DAY@
-- Group dates by year, month, and day, for example 2008-11-22.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable DateTimeRuleType
instance FromHttpApiData DateTimeRuleType where
parseQueryParam = \case
"DATE_TIME_RULE_TYPE_UNSPECIFIED" -> Right DateTimeRuleTypeUnspecified
"SECOND" -> Right Second
"MINUTE" -> Right Minute
"HOUR" -> Right Hour
"HOUR_MINUTE" -> Right HourMinute
"HOUR_MINUTE_AMPM" -> Right HourMinuteAmpm
"DAY_OF_WEEK" -> Right DayOfWeek
"DAY_OF_YEAR" -> Right DayOfYear
"DAY_OF_MONTH" -> Right DayOfMonth
"DAY_MONTH" -> Right DayMonth
"MONTH" -> Right Month
"QUARTER" -> Right Quarter
"YEAR" -> Right Year
"YEAR_MONTH" -> Right YearMonth
"YEAR_QUARTER" -> Right YearQuarter
"YEAR_MONTH_DAY" -> Right YearMonthDay
x -> Left ("Unable to parse DateTimeRuleType from: " <> x)
instance ToHttpApiData DateTimeRuleType where
toQueryParam = \case
DateTimeRuleTypeUnspecified -> "DATE_TIME_RULE_TYPE_UNSPECIFIED"
Second -> "SECOND"
Minute -> "MINUTE"
Hour -> "HOUR"
HourMinute -> "HOUR_MINUTE"
HourMinuteAmpm -> "HOUR_MINUTE_AMPM"
DayOfWeek -> "DAY_OF_WEEK"
DayOfYear -> "DAY_OF_YEAR"
DayOfMonth -> "DAY_OF_MONTH"
DayMonth -> "DAY_MONTH"
Month -> "MONTH"
Quarter -> "QUARTER"
Year -> "YEAR"
YearMonth -> "YEAR_MONTH"
YearQuarter -> "YEAR_QUARTER"
YearMonthDay -> "YEAR_MONTH_DAY"
instance FromJSON DateTimeRuleType where
parseJSON = parseJSONText "DateTimeRuleType"
instance ToJSON DateTimeRuleType where
toJSON = toJSONText
-- | Limits the selected developer metadata to that which has a matching
-- DeveloperMetadata.visibility. If left unspecified, all developer
-- metadata visibile to the requesting project is considered.
data DeveloperMetadataLookupVisibility
= DMLVDeveloperMetadataVisibilityUnspecified
-- ^ @DEVELOPER_METADATA_VISIBILITY_UNSPECIFIED@
-- Default value.
| DMLVDocument
-- ^ @DOCUMENT@
-- Document-visible metadata is accessible from any developer project with
-- access to the document.
| DMLVProject
-- ^ @PROJECT@
-- Project-visible metadata is only visible to and accessible by the
-- developer project that created the metadata.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable DeveloperMetadataLookupVisibility
instance FromHttpApiData DeveloperMetadataLookupVisibility where
parseQueryParam = \case
"DEVELOPER_METADATA_VISIBILITY_UNSPECIFIED" -> Right DMLVDeveloperMetadataVisibilityUnspecified
"DOCUMENT" -> Right DMLVDocument
"PROJECT" -> Right DMLVProject
x -> Left ("Unable to parse DeveloperMetadataLookupVisibility from: " <> x)
instance ToHttpApiData DeveloperMetadataLookupVisibility where
toQueryParam = \case
DMLVDeveloperMetadataVisibilityUnspecified -> "DEVELOPER_METADATA_VISIBILITY_UNSPECIFIED"
DMLVDocument -> "DOCUMENT"
DMLVProject -> "PROJECT"
instance FromJSON DeveloperMetadataLookupVisibility where
parseJSON = parseJSONText "DeveloperMetadataLookupVisibility"
instance ToJSON DeveloperMetadataLookupVisibility where
toJSON = toJSONText
-- | The placement of the data label relative to the labeled data.
data DataLabelPlacement
= DLPDataLabelPlacementUnspecified
-- ^ @DATA_LABEL_PLACEMENT_UNSPECIFIED@
-- The positioning is determined automatically by the renderer.
| DLPCenter
-- ^ @CENTER@
-- Center within a bar or column, both horizontally and vertically.
| DLPLeft'
-- ^ @LEFT@
-- To the left of a data point.
| DLPRight'
-- ^ @RIGHT@
-- To the right of a data point.
| DLPAbove
-- ^ @ABOVE@
-- Above a data point.
| DLPBelow
-- ^ @BELOW@
-- Below a data point.
| DLPInsideEnd
-- ^ @INSIDE_END@
-- Inside a bar or column at the end (top if positive, bottom if negative).
| DLPInsideBase
-- ^ @INSIDE_BASE@
-- Inside a bar or column at the base.
| DLPOutsideEnd
-- ^ @OUTSIDE_END@
-- Outside a bar or column at the end.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable DataLabelPlacement
instance FromHttpApiData DataLabelPlacement where
parseQueryParam = \case
"DATA_LABEL_PLACEMENT_UNSPECIFIED" -> Right DLPDataLabelPlacementUnspecified
"CENTER" -> Right DLPCenter
"LEFT" -> Right DLPLeft'
"RIGHT" -> Right DLPRight'
"ABOVE" -> Right DLPAbove
"BELOW" -> Right DLPBelow
"INSIDE_END" -> Right DLPInsideEnd
"INSIDE_BASE" -> Right DLPInsideBase
"OUTSIDE_END" -> Right DLPOutsideEnd
x -> Left ("Unable to parse DataLabelPlacement from: " <> x)
instance ToHttpApiData DataLabelPlacement where
toQueryParam = \case
DLPDataLabelPlacementUnspecified -> "DATA_LABEL_PLACEMENT_UNSPECIFIED"
DLPCenter -> "CENTER"
DLPLeft' -> "LEFT"
DLPRight' -> "RIGHT"
DLPAbove -> "ABOVE"
DLPBelow -> "BELOW"
DLPInsideEnd -> "INSIDE_END"
DLPInsideBase -> "INSIDE_BASE"
DLPOutsideEnd -> "OUTSIDE_END"
instance FromJSON DataLabelPlacement where
parseJSON = parseJSONText "DataLabelPlacement"
instance ToJSON DataLabelPlacement where
toJSON = toJSONText
-- | The behavior of tooltips and data highlighting when hovering on data and
-- chart area.
data BasicChartSpecCompareMode
= BasicChartCompareModeUnspecified
-- ^ @BASIC_CHART_COMPARE_MODE_UNSPECIFIED@
-- Default value, do not use.
| Datum
-- ^ @DATUM@
-- Only the focused data element is highlighted and shown in the tooltip.
| Category
-- ^ @CATEGORY@
-- All data elements with the same category (e.g., domain value) are
-- highlighted and shown in the tooltip.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable BasicChartSpecCompareMode
instance FromHttpApiData BasicChartSpecCompareMode where
parseQueryParam = \case
"BASIC_CHART_COMPARE_MODE_UNSPECIFIED" -> Right BasicChartCompareModeUnspecified
"DATUM" -> Right Datum
"CATEGORY" -> Right Category
x -> Left ("Unable to parse BasicChartSpecCompareMode from: " <> x)
instance ToHttpApiData BasicChartSpecCompareMode where
toQueryParam = \case
BasicChartCompareModeUnspecified -> "BASIC_CHART_COMPARE_MODE_UNSPECIFIED"
Datum -> "DATUM"
Category -> "CATEGORY"
instance FromJSON BasicChartSpecCompareMode where
parseJSON = parseJSONText "BasicChartSpecCompareMode"
instance ToJSON BasicChartSpecCompareMode where
toJSON = toJSONText
-- | The type of condition.
data BooleanConditionType
= ConditionTypeUnspecified
-- ^ @CONDITION_TYPE_UNSPECIFIED@
-- The default value, do not use.
| NumberGreater
-- ^ @NUMBER_GREATER@
-- The cell\'s value must be greater than the condition\'s value. Supported
-- by data validation, conditional formatting and filters. Requires a
-- single ConditionValue.
| NumberGreaterThanEQ
-- ^ @NUMBER_GREATER_THAN_EQ@
-- The cell\'s value must be greater than or equal to the condition\'s
-- value. Supported by data validation, conditional formatting and filters.
-- Requires a single ConditionValue.
| NumberLess
-- ^ @NUMBER_LESS@
-- The cell\'s value must be less than the condition\'s value. Supported by
-- data validation, conditional formatting and filters. Requires a single
-- ConditionValue.
| NumberLessThanEQ
-- ^ @NUMBER_LESS_THAN_EQ@
-- The cell\'s value must be less than or equal to the condition\'s value.
-- Supported by data validation, conditional formatting and filters.
-- Requires a single ConditionValue.
| NumberEQ
-- ^ @NUMBER_EQ@
-- The cell\'s value must be equal to the condition\'s value. Supported by
-- data validation, conditional formatting and filters. Requires a single
-- ConditionValue for data validation, conditional formatting, and filters
-- on non-data source objects and at least one ConditionValue for filters
-- on data source objects.
| NumberNotEQ
-- ^ @NUMBER_NOT_EQ@
-- The cell\'s value must be not equal to the condition\'s value. Supported
-- by data validation, conditional formatting and filters. Requires a
-- single ConditionValue for data validation, conditional formatting, and
-- filters on non-data source objects and at least one ConditionValue for
-- filters on data source objects.
| NumberBetween
-- ^ @NUMBER_BETWEEN@
-- The cell\'s value must be between the two condition values. Supported by
-- data validation, conditional formatting and filters. Requires exactly
-- two ConditionValues.
| NumberNotBetween
-- ^ @NUMBER_NOT_BETWEEN@
-- The cell\'s value must not be between the two condition values.
-- Supported by data validation, conditional formatting and filters.
-- Requires exactly two ConditionValues.
| TextContains
-- ^ @TEXT_CONTAINS@
-- The cell\'s value must contain the condition\'s value. Supported by data
-- validation, conditional formatting and filters. Requires a single
-- ConditionValue.
| TextNotContains
-- ^ @TEXT_NOT_CONTAINS@
-- The cell\'s value must not contain the condition\'s value. Supported by
-- data validation, conditional formatting and filters. Requires a single
-- ConditionValue.
| TextStartsWith
-- ^ @TEXT_STARTS_WITH@
-- The cell\'s value must start with the condition\'s value. Supported by
-- conditional formatting and filters. Requires a single ConditionValue.
| TextEndsWith
-- ^ @TEXT_ENDS_WITH@
-- The cell\'s value must end with the condition\'s value. Supported by
-- conditional formatting and filters. Requires a single ConditionValue.
| TextEQ
-- ^ @TEXT_EQ@
-- The cell\'s value must be exactly the condition\'s value. Supported by
-- data validation, conditional formatting and filters. Requires a single
-- ConditionValue for data validation, conditional formatting, and filters
-- on non-data source objects and at least one ConditionValue for filters
-- on data source objects.
| TextIsEmail
-- ^ @TEXT_IS_EMAIL@
-- The cell\'s value must be a valid email address. Supported by data
-- validation. Requires no ConditionValues.
| TextIsURL
-- ^ @TEXT_IS_URL@
-- The cell\'s value must be a valid URL. Supported by data validation.
-- Requires no ConditionValues.
| DateEQ
-- ^ @DATE_EQ@
-- The cell\'s value must be the same date as the condition\'s value.
-- Supported by data validation, conditional formatting and filters.
-- Requires a single ConditionValue for data validation, conditional
-- formatting, and filters on non-data source objects and at least one
-- ConditionValue for filters on data source objects.
| DateBefore
-- ^ @DATE_BEFORE@
-- The cell\'s value must be before the date of the condition\'s value.
-- Supported by data validation, conditional formatting and filters.
-- Requires a single ConditionValue that may be a relative date.
| DateAfter
-- ^ @DATE_AFTER@
-- The cell\'s value must be after the date of the condition\'s value.
-- Supported by data validation, conditional formatting and filters.
-- Requires a single ConditionValue that may be a relative date.
| DateOnOrBefore
-- ^ @DATE_ON_OR_BEFORE@
-- The cell\'s value must be on or before the date of the condition\'s
-- value. Supported by data validation. Requires a single ConditionValue
-- that may be a relative date.
| DateOnOrAfter
-- ^ @DATE_ON_OR_AFTER@
-- The cell\'s value must be on or after the date of the condition\'s
-- value. Supported by data validation. Requires a single ConditionValue
-- that may be a relative date.
| DateBetween
-- ^ @DATE_BETWEEN@
-- The cell\'s value must be between the dates of the two condition values.
-- Supported by data validation. Requires exactly two ConditionValues.
| DateNotBetween
-- ^ @DATE_NOT_BETWEEN@
-- The cell\'s value must be outside the dates of the two condition values.
-- Supported by data validation. Requires exactly two ConditionValues.
| DateIsValid
-- ^ @DATE_IS_VALID@
-- The cell\'s value must be a date. Supported by data validation. Requires
-- no ConditionValues.
| OneOfRange
-- ^ @ONE_OF_RANGE@
-- The cell\'s value must be listed in the grid in condition value\'s
-- range. Supported by data validation. Requires a single ConditionValue,
-- and the value must be a valid range in A1 notation.
| OneOfList
-- ^ @ONE_OF_LIST@
-- The cell\'s value must be in the list of condition values. Supported by
-- data validation. Supports any number of condition values, one per item
-- in the list. Formulas are not supported in the values.
| Blank
-- ^ @BLANK@
-- The cell\'s value must be empty. Supported by conditional formatting and
-- filters. Requires no ConditionValues.
| NotBlank
-- ^ @NOT_BLANK@
-- The cell\'s value must not be empty. Supported by conditional formatting
-- and filters. Requires no ConditionValues.
| CustomFormula
-- ^ @CUSTOM_FORMULA@
-- The condition\'s formula must evaluate to true. Supported by data
-- validation, conditional formatting and filters. Not supported by data
-- source sheet filters. Requires a single ConditionValue.
| Boolean
-- ^ @BOOLEAN@
-- The cell\'s value must be TRUE\/FALSE or in the list of condition
-- values. Supported by data validation. Renders as a cell checkbox.
-- Supports zero, one or two ConditionValues. No values indicates the cell
-- must be TRUE or FALSE, where TRUE renders as checked and FALSE renders
-- as unchecked. One value indicates the cell will render as checked when
-- it contains that value and unchecked when it is blank. Two values
-- indicate that the cell will render as checked when it contains the first
-- value and unchecked when it contains the second value. For example,
-- [\"Yes\",\"No\"] indicates that the cell will render a checked box when
-- it has the value \"Yes\" and an unchecked box when it has the value
-- \"No\".
| TextNotEQ
-- ^ @TEXT_NOT_EQ@
-- The cell\'s value must be exactly not the condition\'s value. Supported
-- by filters on data source objects. Requires at least one ConditionValue.
| DateNotEQ
-- ^ @DATE_NOT_EQ@
-- The cell\'s value must be exactly not the condition\'s value. Supported
-- by filters on data source objects. Requires at least one ConditionValue.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable BooleanConditionType
instance FromHttpApiData BooleanConditionType where
parseQueryParam = \case
"CONDITION_TYPE_UNSPECIFIED" -> Right ConditionTypeUnspecified
"NUMBER_GREATER" -> Right NumberGreater
"NUMBER_GREATER_THAN_EQ" -> Right NumberGreaterThanEQ
"NUMBER_LESS" -> Right NumberLess
"NUMBER_LESS_THAN_EQ" -> Right NumberLessThanEQ
"NUMBER_EQ" -> Right NumberEQ
"NUMBER_NOT_EQ" -> Right NumberNotEQ
"NUMBER_BETWEEN" -> Right NumberBetween
"NUMBER_NOT_BETWEEN" -> Right NumberNotBetween
"TEXT_CONTAINS" -> Right TextContains
"TEXT_NOT_CONTAINS" -> Right TextNotContains
"TEXT_STARTS_WITH" -> Right TextStartsWith
"TEXT_ENDS_WITH" -> Right TextEndsWith
"TEXT_EQ" -> Right TextEQ
"TEXT_IS_EMAIL" -> Right TextIsEmail
"TEXT_IS_URL" -> Right TextIsURL
"DATE_EQ" -> Right DateEQ
"DATE_BEFORE" -> Right DateBefore
"DATE_AFTER" -> Right DateAfter
"DATE_ON_OR_BEFORE" -> Right DateOnOrBefore
"DATE_ON_OR_AFTER" -> Right DateOnOrAfter
"DATE_BETWEEN" -> Right DateBetween
"DATE_NOT_BETWEEN" -> Right DateNotBetween
"DATE_IS_VALID" -> Right DateIsValid
"ONE_OF_RANGE" -> Right OneOfRange
"ONE_OF_LIST" -> Right OneOfList
"BLANK" -> Right Blank
"NOT_BLANK" -> Right NotBlank
"CUSTOM_FORMULA" -> Right CustomFormula
"BOOLEAN" -> Right Boolean
"TEXT_NOT_EQ" -> Right TextNotEQ
"DATE_NOT_EQ" -> Right DateNotEQ
x -> Left ("Unable to parse BooleanConditionType from: " <> x)
instance ToHttpApiData BooleanConditionType where
toQueryParam = \case
ConditionTypeUnspecified -> "CONDITION_TYPE_UNSPECIFIED"
NumberGreater -> "NUMBER_GREATER"
NumberGreaterThanEQ -> "NUMBER_GREATER_THAN_EQ"
NumberLess -> "NUMBER_LESS"
NumberLessThanEQ -> "NUMBER_LESS_THAN_EQ"
NumberEQ -> "NUMBER_EQ"
NumberNotEQ -> "NUMBER_NOT_EQ"
NumberBetween -> "NUMBER_BETWEEN"
NumberNotBetween -> "NUMBER_NOT_BETWEEN"
TextContains -> "TEXT_CONTAINS"
TextNotContains -> "TEXT_NOT_CONTAINS"
TextStartsWith -> "TEXT_STARTS_WITH"
TextEndsWith -> "TEXT_ENDS_WITH"
TextEQ -> "TEXT_EQ"
TextIsEmail -> "TEXT_IS_EMAIL"
TextIsURL -> "TEXT_IS_URL"
DateEQ -> "DATE_EQ"
DateBefore -> "DATE_BEFORE"
DateAfter -> "DATE_AFTER"
DateOnOrBefore -> "DATE_ON_OR_BEFORE"
DateOnOrAfter -> "DATE_ON_OR_AFTER"
DateBetween -> "DATE_BETWEEN"
DateNotBetween -> "DATE_NOT_BETWEEN"
DateIsValid -> "DATE_IS_VALID"
OneOfRange -> "ONE_OF_RANGE"
OneOfList -> "ONE_OF_LIST"
Blank -> "BLANK"
NotBlank -> "NOT_BLANK"
CustomFormula -> "CUSTOM_FORMULA"
Boolean -> "BOOLEAN"
TextNotEQ -> "TEXT_NOT_EQ"
DateNotEQ -> "DATE_NOT_EQ"
instance FromJSON BooleanConditionType where
parseJSON = parseJSONText "BooleanConditionType"
instance ToJSON BooleanConditionType where
toJSON = toJSONText
-- | The major dimension of the values. For output, if the spreadsheet data
-- is: \`A1=1,B1=2,A2=3,B2=4\`, then requesting
-- \`range=A1:B2,majorDimension=ROWS\` will return \`[[1,2],[3,4]]\`,
-- whereas requesting \`range=A1:B2,majorDimension=COLUMNS\` will return
-- \`[[1,3],[2,4]]\`. For input, with \`range=A1:B2,majorDimension=ROWS\`
-- then \`[[1,2],[3,4]]\` will set \`A1=1,B1=2,A2=3,B2=4\`. With
-- \`range=A1:B2,majorDimension=COLUMNS\` then \`[[1,2],[3,4]]\` will set
-- \`A1=1,B1=3,A2=2,B2=4\`. When writing, if this field is not set, it
-- defaults to ROWS.
data ValueRangeMajorDimension
= VRMDDimensionUnspecified
-- ^ @DIMENSION_UNSPECIFIED@
-- The default value, do not use.
| VRMDRows
-- ^ @ROWS@
-- Operates on the rows of a sheet.
| VRMDColumns
-- ^ @COLUMNS@
-- Operates on the columns of a sheet.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable ValueRangeMajorDimension
instance FromHttpApiData ValueRangeMajorDimension where
parseQueryParam = \case
"DIMENSION_UNSPECIFIED" -> Right VRMDDimensionUnspecified
"ROWS" -> Right VRMDRows
"COLUMNS" -> Right VRMDColumns
x -> Left ("Unable to parse ValueRangeMajorDimension from: " <> x)
instance ToHttpApiData ValueRangeMajorDimension where
toQueryParam = \case
VRMDDimensionUnspecified -> "DIMENSION_UNSPECIFIED"
VRMDRows -> "ROWS"
VRMDColumns -> "COLUMNS"
instance FromJSON ValueRangeMajorDimension where
parseJSON = parseJSONText "ValueRangeMajorDimension"
instance ToJSON ValueRangeMajorDimension where
toJSON = toJSONText
-- | The order the values in this group should be sorted.
data PivotGroupSortOrder
= PGSOSortOrderUnspecified
-- ^ @SORT_ORDER_UNSPECIFIED@
-- Default value, do not use this.
| PGSOAscending
-- ^ @ASCENDING@
-- Sort ascending.
| PGSODescending
-- ^ @DESCENDING@
-- Sort descending.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable PivotGroupSortOrder
instance FromHttpApiData PivotGroupSortOrder where
parseQueryParam = \case
"SORT_ORDER_UNSPECIFIED" -> Right PGSOSortOrderUnspecified
"ASCENDING" -> Right PGSOAscending
"DESCENDING" -> Right PGSODescending
x -> Left ("Unable to parse PivotGroupSortOrder from: " <> x)
instance ToHttpApiData PivotGroupSortOrder where
toQueryParam = \case
PGSOSortOrderUnspecified -> "SORT_ORDER_UNSPECIFIED"
PGSOAscending -> "ASCENDING"
PGSODescending -> "DESCENDING"
instance FromJSON PivotGroupSortOrder where
parseJSON = parseJSONText "PivotGroupSortOrder"
instance ToJSON PivotGroupSortOrder where
toJSON = toJSONText
-- | How the input data should be inserted.
data SpreadsheetsValuesAppendInsertDataOption
= Overwrite
-- ^ @OVERWRITE@
-- The new data overwrites existing data in the areas it is written. (Note:
-- adding data to the end of the sheet will still insert new rows or
-- columns so the data can be written.)
| InsertRows
-- ^ @INSERT_ROWS@
-- Rows are inserted for the new data.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable SpreadsheetsValuesAppendInsertDataOption
instance FromHttpApiData SpreadsheetsValuesAppendInsertDataOption where
parseQueryParam = \case
"OVERWRITE" -> Right Overwrite
"INSERT_ROWS" -> Right InsertRows
x -> Left ("Unable to parse SpreadsheetsValuesAppendInsertDataOption from: " <> x)
instance ToHttpApiData SpreadsheetsValuesAppendInsertDataOption where
toQueryParam = \case
Overwrite -> "OVERWRITE"
InsertRows -> "INSERT_ROWS"
instance FromJSON SpreadsheetsValuesAppendInsertDataOption where
parseJSON = parseJSONText "SpreadsheetsValuesAppendInsertDataOption"
instance ToJSON SpreadsheetsValuesAppendInsertDataOption where
toJSON = toJSONText
-- | The type of the chart.
data BasicChartSpecChartType
= BasicChartTypeUnspecified
-- ^ @BASIC_CHART_TYPE_UNSPECIFIED@
-- Default value, do not use.
| Bar
-- ^ @BAR@
-- A bar chart.
| Line
-- ^ @LINE@
-- A line chart.
| Area
-- ^ @AREA@
-- An area chart.
| Column
-- ^ @COLUMN@
-- A column chart.
| Scatter
-- ^ @SCATTER@
-- A scatter chart.
| Combo
-- ^ @COMBO@
-- A combo chart.
| SteppedArea
-- ^ @STEPPED_AREA@
-- A stepped area chart.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable BasicChartSpecChartType
instance FromHttpApiData BasicChartSpecChartType where
parseQueryParam = \case
"BASIC_CHART_TYPE_UNSPECIFIED" -> Right BasicChartTypeUnspecified
"BAR" -> Right Bar
"LINE" -> Right Line
"AREA" -> Right Area
"COLUMN" -> Right Column
"SCATTER" -> Right Scatter
"COMBO" -> Right Combo
"STEPPED_AREA" -> Right SteppedArea
x -> Left ("Unable to parse BasicChartSpecChartType from: " <> x)
instance ToHttpApiData BasicChartSpecChartType where
toQueryParam = \case
BasicChartTypeUnspecified -> "BASIC_CHART_TYPE_UNSPECIFIED"
Bar -> "BAR"
Line -> "LINE"
Area -> "AREA"
Column -> "COLUMN"
Scatter -> "SCATTER"
Combo -> "COMBO"
SteppedArea -> "STEPPED_AREA"
instance FromJSON BasicChartSpecChartType where
parseJSON = parseJSONText "BasicChartSpecChartType"
instance ToJSON BasicChartSpecChartType where
toJSON = toJSONText
-- | The comparison type of key value with baseline value.
data BaselineValueFormatComparisonType
= ComparisonTypeUndefined
-- ^ @COMPARISON_TYPE_UNDEFINED@
-- Default value, do not use.
| AbsoluteDifference
-- ^ @ABSOLUTE_DIFFERENCE@
-- Use absolute difference between key and baseline value.
| PercentageDifference
-- ^ @PERCENTAGE_DIFFERENCE@
-- Use percentage difference between key and baseline value.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable BaselineValueFormatComparisonType
instance FromHttpApiData BaselineValueFormatComparisonType where
parseQueryParam = \case
"COMPARISON_TYPE_UNDEFINED" -> Right ComparisonTypeUndefined
"ABSOLUTE_DIFFERENCE" -> Right AbsoluteDifference
"PERCENTAGE_DIFFERENCE" -> Right PercentageDifference
x -> Left ("Unable to parse BaselineValueFormatComparisonType from: " <> x)
instance ToHttpApiData BaselineValueFormatComparisonType where
toQueryParam = \case
ComparisonTypeUndefined -> "COMPARISON_TYPE_UNDEFINED"
AbsoluteDifference -> "ABSOLUTE_DIFFERENCE"
PercentageDifference -> "PERCENTAGE_DIFFERENCE"
instance FromJSON BaselineValueFormatComparisonType where
parseJSON = parseJSONText "BaselineValueFormatComparisonType"
instance ToJSON BaselineValueFormatComparisonType where
toJSON = toJSONText
-- | V1 error format.
data Xgafv
= X1
-- ^ @1@
-- v1 error format
| X2
-- ^ @2@
-- v2 error format
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable Xgafv
instance FromHttpApiData Xgafv where
parseQueryParam = \case
"1" -> Right X1
"2" -> Right X2
x -> Left ("Unable to parse Xgafv from: " <> x)
instance ToHttpApiData Xgafv where
toQueryParam = \case
X1 -> "1"
X2 -> "2"
instance FromJSON Xgafv where
parseJSON = parseJSONText "Xgafv"
instance ToJSON Xgafv where
toJSON = toJSONText
-- | The amount of time to wait before volatile functions are recalculated.
data SpreadsheetPropertiesAutoRecalc
= SPARRecalculationIntervalUnspecified
-- ^ @RECALCULATION_INTERVAL_UNSPECIFIED@
-- Default value. This value must not be used.
| SPAROnChange
-- ^ @ON_CHANGE@
-- Volatile functions are updated on every change.
| SPARMinute
-- ^ @MINUTE@
-- Volatile functions are updated on every change and every minute.
| SPARHour
-- ^ @HOUR@
-- Volatile functions are updated on every change and hourly.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable SpreadsheetPropertiesAutoRecalc
instance FromHttpApiData SpreadsheetPropertiesAutoRecalc where
parseQueryParam = \case
"RECALCULATION_INTERVAL_UNSPECIFIED" -> Right SPARRecalculationIntervalUnspecified
"ON_CHANGE" -> Right SPAROnChange
"MINUTE" -> Right SPARMinute
"HOUR" -> Right SPARHour
x -> Left ("Unable to parse SpreadsheetPropertiesAutoRecalc from: " <> x)
instance ToHttpApiData SpreadsheetPropertiesAutoRecalc where
toQueryParam = \case
SPARRecalculationIntervalUnspecified -> "RECALCULATION_INTERVAL_UNSPECIFIED"
SPAROnChange -> "ON_CHANGE"
SPARMinute -> "MINUTE"
SPARHour -> "HOUR"
instance FromJSON SpreadsheetPropertiesAutoRecalc where
parseJSON = parseJSONText "SpreadsheetPropertiesAutoRecalc"
instance ToJSON SpreadsheetPropertiesAutoRecalc where
toJSON = toJSONText
-- | How that data should be oriented when pasting.
data CopyPasteRequestPasteOrientation
= Normal
-- ^ @NORMAL@
-- Paste normally.
| Transpose
-- ^ @TRANSPOSE@
-- Paste transposed, where all rows become columns and vice versa.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable CopyPasteRequestPasteOrientation
instance FromHttpApiData CopyPasteRequestPasteOrientation where
parseQueryParam = \case
"NORMAL" -> Right Normal
"TRANSPOSE" -> Right Transpose
x -> Left ("Unable to parse CopyPasteRequestPasteOrientation from: " <> x)
instance ToHttpApiData CopyPasteRequestPasteOrientation where
toQueryParam = \case
Normal -> "NORMAL"
Transpose -> "TRANSPOSE"
instance FromJSON CopyPasteRequestPasteOrientation where
parseJSON = parseJSONText "CopyPasteRequestPasteOrientation"
instance ToJSON CopyPasteRequestPasteOrientation where
toJSON = toJSONText
-- | How the data should be pasted.
data PasteDataRequestType
= PDRTPasteNormal
-- ^ @PASTE_NORMAL@
-- Paste values, formulas, formats, and merges.
| PDRTPasteValues
-- ^ @PASTE_VALUES@
-- Paste the values ONLY without formats, formulas, or merges.
| PDRTPasteFormat
-- ^ @PASTE_FORMAT@
-- Paste the format and data validation only.
| PDRTPasteNoBOrders
-- ^ @PASTE_NO_BORDERS@
-- Like \`PASTE_NORMAL\` but without borders.
| PDRTPasteFormula
-- ^ @PASTE_FORMULA@
-- Paste the formulas only.
| PDRTPasteDataValidation
-- ^ @PASTE_DATA_VALIDATION@
-- Paste the data validation only.
| PDRTPasteConditionalFormatting
-- ^ @PASTE_CONDITIONAL_FORMATTING@
-- Paste the conditional formatting rules only.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable PasteDataRequestType
instance FromHttpApiData PasteDataRequestType where
parseQueryParam = \case
"PASTE_NORMAL" -> Right PDRTPasteNormal
"PASTE_VALUES" -> Right PDRTPasteValues
"PASTE_FORMAT" -> Right PDRTPasteFormat
"PASTE_NO_BORDERS" -> Right PDRTPasteNoBOrders
"PASTE_FORMULA" -> Right PDRTPasteFormula
"PASTE_DATA_VALIDATION" -> Right PDRTPasteDataValidation
"PASTE_CONDITIONAL_FORMATTING" -> Right PDRTPasteConditionalFormatting
x -> Left ("Unable to parse PasteDataRequestType from: " <> x)
instance ToHttpApiData PasteDataRequestType where
toQueryParam = \case
PDRTPasteNormal -> "PASTE_NORMAL"
PDRTPasteValues -> "PASTE_VALUES"
PDRTPasteFormat -> "PASTE_FORMAT"
PDRTPasteNoBOrders -> "PASTE_NO_BORDERS"
PDRTPasteFormula -> "PASTE_FORMULA"
PDRTPasteDataValidation -> "PASTE_DATA_VALIDATION"
PDRTPasteConditionalFormatting -> "PASTE_CONDITIONAL_FORMATTING"
instance FromJSON PasteDataRequestType where
parseJSON = parseJSONText "PasteDataRequestType"
instance ToJSON PasteDataRequestType where
toJSON = toJSONText
-- | How the input data should be interpreted.
data SpreadsheetsValuesAppendValueInputOption
= SVAVIOInputValueOptionUnspecified
-- ^ @INPUT_VALUE_OPTION_UNSPECIFIED@
-- Default input value. This value must not be used.
| SVAVIORaw
-- ^ @RAW@
-- The values the user has entered will not be parsed and will be stored
-- as-is.
| SVAVIOUserEntered
-- ^ @USER_ENTERED@
-- The values will be parsed as if the user typed them into the UI. Numbers
-- will stay as numbers, but strings may be converted to numbers, dates,
-- etc. following the same rules that are applied when entering text into a
-- cell via the Google Sheets UI.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable SpreadsheetsValuesAppendValueInputOption
instance FromHttpApiData SpreadsheetsValuesAppendValueInputOption where
parseQueryParam = \case
"INPUT_VALUE_OPTION_UNSPECIFIED" -> Right SVAVIOInputValueOptionUnspecified
"RAW" -> Right SVAVIORaw
"USER_ENTERED" -> Right SVAVIOUserEntered
x -> Left ("Unable to parse SpreadsheetsValuesAppendValueInputOption from: " <> x)
instance ToHttpApiData SpreadsheetsValuesAppendValueInputOption where
toQueryParam = \case
SVAVIOInputValueOptionUnspecified -> "INPUT_VALUE_OPTION_UNSPECIFIED"
SVAVIORaw -> "RAW"
SVAVIOUserEntered -> "USER_ENTERED"
instance FromJSON SpreadsheetsValuesAppendValueInputOption where
parseJSON = parseJSONText "SpreadsheetsValuesAppendValueInputOption"
instance ToJSON SpreadsheetsValuesAppendValueInputOption where
toJSON = toJSONText
-- | The direction of the text in the cell.
data CellFormatTextDirection
= TextDirectionUnspecified
-- ^ @TEXT_DIRECTION_UNSPECIFIED@
-- The text direction is not specified. Do not use this.
| LeftToRight
-- ^ @LEFT_TO_RIGHT@
-- The text direction of left-to-right was set by the user.
| RightToLeft
-- ^ @RIGHT_TO_LEFT@
-- The text direction of right-to-left was set by the user.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable CellFormatTextDirection
instance FromHttpApiData CellFormatTextDirection where
parseQueryParam = \case
"TEXT_DIRECTION_UNSPECIFIED" -> Right TextDirectionUnspecified
"LEFT_TO_RIGHT" -> Right LeftToRight
"RIGHT_TO_LEFT" -> Right RightToLeft
x -> Left ("Unable to parse CellFormatTextDirection from: " <> x)
instance ToHttpApiData CellFormatTextDirection where
toQueryParam = \case
TextDirectionUnspecified -> "TEXT_DIRECTION_UNSPECIFIED"
LeftToRight -> "LEFT_TO_RIGHT"
RightToLeft -> "RIGHT_TO_LEFT"
instance FromJSON CellFormatTextDirection where
parseJSON = parseJSONText "CellFormatTextDirection"
instance ToJSON CellFormatTextDirection where
toJSON = toJSONText
-- | The type to select columns for the data source table. Defaults to
-- SELECTED.
data DataSourceTableColumnSelectionType
= DataSourceTableColumnSelectionTypeUnspecified
-- ^ @DATA_SOURCE_TABLE_COLUMN_SELECTION_TYPE_UNSPECIFIED@
-- The default column selection type, do not use.
| Selected
-- ^ @SELECTED@
-- Select columns specified by columns field.
| SyncAll
-- ^ @SYNC_ALL@
-- Sync all current and future columns in the data source. If set, the data
-- source table fetches all the columns in the data source at the time of
-- refresh.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable DataSourceTableColumnSelectionType
instance FromHttpApiData DataSourceTableColumnSelectionType where
parseQueryParam = \case
"DATA_SOURCE_TABLE_COLUMN_SELECTION_TYPE_UNSPECIFIED" -> Right DataSourceTableColumnSelectionTypeUnspecified
"SELECTED" -> Right Selected
"SYNC_ALL" -> Right SyncAll
x -> Left ("Unable to parse DataSourceTableColumnSelectionType from: " <> x)
instance ToHttpApiData DataSourceTableColumnSelectionType where
toQueryParam = \case
DataSourceTableColumnSelectionTypeUnspecified -> "DATA_SOURCE_TABLE_COLUMN_SELECTION_TYPE_UNSPECIFIED"
Selected -> "SELECTED"
SyncAll -> "SYNC_ALL"
instance FromJSON DataSourceTableColumnSelectionType where
parseJSON = parseJSONText "DataSourceTableColumnSelectionType"
instance ToJSON DataSourceTableColumnSelectionType where
toJSON = toJSONText
-- | The type of this series. Valid only if the chartType is COMBO. Different
-- types will change the way the series is visualized. Only LINE, AREA, and
-- COLUMN are supported.
data BasicChartSeriesType
= BCSTBasicChartTypeUnspecified
-- ^ @BASIC_CHART_TYPE_UNSPECIFIED@
-- Default value, do not use.
| BCSTBar
-- ^ @BAR@
-- A bar chart.
| BCSTLine
-- ^ @LINE@
-- A line chart.
| BCSTArea
-- ^ @AREA@
-- An area chart.
| BCSTColumn
-- ^ @COLUMN@
-- A column chart.
| BCSTScatter
-- ^ @SCATTER@
-- A scatter chart.
| BCSTCombo
-- ^ @COMBO@
-- A combo chart.
| BCSTSteppedArea
-- ^ @STEPPED_AREA@
-- A stepped area chart.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable BasicChartSeriesType
instance FromHttpApiData BasicChartSeriesType where
parseQueryParam = \case
"BASIC_CHART_TYPE_UNSPECIFIED" -> Right BCSTBasicChartTypeUnspecified
"BAR" -> Right BCSTBar
"LINE" -> Right BCSTLine
"AREA" -> Right BCSTArea
"COLUMN" -> Right BCSTColumn
"SCATTER" -> Right BCSTScatter
"COMBO" -> Right BCSTCombo
"STEPPED_AREA" -> Right BCSTSteppedArea
x -> Left ("Unable to parse BasicChartSeriesType from: " <> x)
instance ToHttpApiData BasicChartSeriesType where
toQueryParam = \case
BCSTBasicChartTypeUnspecified -> "BASIC_CHART_TYPE_UNSPECIFIED"
BCSTBar -> "BAR"
BCSTLine -> "LINE"
BCSTArea -> "AREA"
BCSTColumn -> "COLUMN"
BCSTScatter -> "SCATTER"
BCSTCombo -> "COMBO"
BCSTSteppedArea -> "STEPPED_AREA"
instance FromJSON BasicChartSeriesType where
parseJSON = parseJSONText "BasicChartSeriesType"
instance ToJSON BasicChartSeriesType where
toJSON = toJSONText
-- | If specified, indicates that pivot values should be displayed as the
-- result of a calculation with another pivot value. For example, if
-- calculated_display_type is specified as PERCENT_OF_GRAND_TOTAL, all the
-- pivot values are displayed as the percentage of the grand total. In the
-- Sheets editor, this is referred to as \"Show As\" in the value section
-- of a pivot table.
data PivotValueCalculatedDisplayType
= PivotValueCalculatedDisplayTypeUnspecified
-- ^ @PIVOT_VALUE_CALCULATED_DISPLAY_TYPE_UNSPECIFIED@
-- Default value, do not use.
| PercentOfRowTotal
-- ^ @PERCENT_OF_ROW_TOTAL@
-- Shows the pivot values as percentage of the row total values.
| PercentOfColumnTotal
-- ^ @PERCENT_OF_COLUMN_TOTAL@
-- Shows the pivot values as percentage of the column total values.
| PercentOfGrandTotal
-- ^ @PERCENT_OF_GRAND_TOTAL@
-- Shows the pivot values as percentage of the grand total values.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable PivotValueCalculatedDisplayType
instance FromHttpApiData PivotValueCalculatedDisplayType where
parseQueryParam = \case
"PIVOT_VALUE_CALCULATED_DISPLAY_TYPE_UNSPECIFIED" -> Right PivotValueCalculatedDisplayTypeUnspecified
"PERCENT_OF_ROW_TOTAL" -> Right PercentOfRowTotal
"PERCENT_OF_COLUMN_TOTAL" -> Right PercentOfColumnTotal
"PERCENT_OF_GRAND_TOTAL" -> Right PercentOfGrandTotal
x -> Left ("Unable to parse PivotValueCalculatedDisplayType from: " <> x)
instance ToHttpApiData PivotValueCalculatedDisplayType where
toQueryParam = \case
PivotValueCalculatedDisplayTypeUnspecified -> "PIVOT_VALUE_CALCULATED_DISPLAY_TYPE_UNSPECIFIED"
PercentOfRowTotal -> "PERCENT_OF_ROW_TOTAL"
PercentOfColumnTotal -> "PERCENT_OF_COLUMN_TOTAL"
PercentOfGrandTotal -> "PERCENT_OF_GRAND_TOTAL"
instance FromJSON PivotValueCalculatedDisplayType where
parseJSON = parseJSONText "PivotValueCalculatedDisplayType"
instance ToJSON PivotValueCalculatedDisplayType where
toJSON = toJSONText
-- | The aggregation type for the series of a data source chart. Only
-- supported for data source charts.
data ChartDataAggregateType
= CDATChartAggregateTypeUnspecified
-- ^ @CHART_AGGREGATE_TYPE_UNSPECIFIED@
-- Default value, do not use.
| CDATAverage
-- ^ @AVERAGE@
-- Average aggregate function.
| CDATCount
-- ^ @COUNT@
-- Count aggregate function.
| CDATMax
-- ^ @MAX@
-- Maximum aggregate function.
| CDATMedian
-- ^ @MEDIAN@
-- Median aggregate function.
| CDATMin
-- ^ @MIN@
-- Minimum aggregate function.
| CDATSum
-- ^ @SUM@
-- Sum aggregate function.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable ChartDataAggregateType
instance FromHttpApiData ChartDataAggregateType where
parseQueryParam = \case
"CHART_AGGREGATE_TYPE_UNSPECIFIED" -> Right CDATChartAggregateTypeUnspecified
"AVERAGE" -> Right CDATAverage
"COUNT" -> Right CDATCount
"MAX" -> Right CDATMax
"MEDIAN" -> Right CDATMedian
"MIN" -> Right CDATMin
"SUM" -> Right CDATSum
x -> Left ("Unable to parse ChartDataAggregateType from: " <> x)
instance ToHttpApiData ChartDataAggregateType where
toQueryParam = \case
CDATChartAggregateTypeUnspecified -> "CHART_AGGREGATE_TYPE_UNSPECIFIED"
CDATAverage -> "AVERAGE"
CDATCount -> "COUNT"
CDATMax -> "MAX"
CDATMedian -> "MEDIAN"
CDATMin -> "MIN"
CDATSum -> "SUM"
instance FromJSON ChartDataAggregateType where
parseJSON = parseJSONText "ChartDataAggregateType"
instance ToJSON ChartDataAggregateType where
toJSON = toJSONText
-- | The major dimension that results should use. For example, if the
-- spreadsheet data is: \`A1=1,B1=2,A2=3,B2=4\`, then requesting
-- \`range=A1:B2,majorDimension=ROWS\` returns \`[[1,2],[3,4]]\`, whereas
-- requesting \`range=A1:B2,majorDimension=COLUMNS\` returns
-- \`[[1,3],[2,4]]\`.
data SpreadsheetsValuesGetMajorDimension
= SVGMDDimensionUnspecified
-- ^ @DIMENSION_UNSPECIFIED@
-- The default value, do not use.
| SVGMDRows
-- ^ @ROWS@
-- Operates on the rows of a sheet.
| SVGMDColumns
-- ^ @COLUMNS@
-- Operates on the columns of a sheet.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable SpreadsheetsValuesGetMajorDimension
instance FromHttpApiData SpreadsheetsValuesGetMajorDimension where
parseQueryParam = \case
"DIMENSION_UNSPECIFIED" -> Right SVGMDDimensionUnspecified
"ROWS" -> Right SVGMDRows
"COLUMNS" -> Right SVGMDColumns
x -> Left ("Unable to parse SpreadsheetsValuesGetMajorDimension from: " <> x)
instance ToHttpApiData SpreadsheetsValuesGetMajorDimension where
toQueryParam = \case
SVGMDDimensionUnspecified -> "DIMENSION_UNSPECIFIED"
SVGMDRows -> "ROWS"
SVGMDColumns -> "COLUMNS"
instance FromJSON SpreadsheetsValuesGetMajorDimension where
parseJSON = parseJSONText "SpreadsheetsValuesGetMajorDimension"
instance ToJSON SpreadsheetsValuesGetMajorDimension where
toJSON = toJSONText
-- | The number format source used in the scorecard chart. This field is
-- optional.
data ScorecardChartSpecNumberFormatSource
= SCSNFSChartNumberFormatSourceUndefined
-- ^ @CHART_NUMBER_FORMAT_SOURCE_UNDEFINED@
-- Default value, do not use.
| SCSNFSFromData
-- ^ @FROM_DATA@
-- Inherit number formatting from data.
| SCSNFSCustom
-- ^ @CUSTOM@
-- Apply custom formatting as specified by ChartCustomNumberFormatOptions.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable ScorecardChartSpecNumberFormatSource
instance FromHttpApiData ScorecardChartSpecNumberFormatSource where
parseQueryParam = \case
"CHART_NUMBER_FORMAT_SOURCE_UNDEFINED" -> Right SCSNFSChartNumberFormatSourceUndefined
"FROM_DATA" -> Right SCSNFSFromData
"CUSTOM" -> Right SCSNFSCustom
x -> Left ("Unable to parse ScorecardChartSpecNumberFormatSource from: " <> x)
instance ToHttpApiData ScorecardChartSpecNumberFormatSource where
toQueryParam = \case
SCSNFSChartNumberFormatSourceUndefined -> "CHART_NUMBER_FORMAT_SOURCE_UNDEFINED"
SCSNFSFromData -> "FROM_DATA"
SCSNFSCustom -> "CUSTOM"
instance FromJSON ScorecardChartSpecNumberFormatSource where
parseJSON = parseJSONText "ScorecardChartSpecNumberFormatSource"
instance ToJSON ScorecardChartSpecNumberFormatSource where
toJSON = toJSONText
-- | Determines how dates, times, and durations in the response should be
-- rendered. This is ignored if response_value_render_option is
-- FORMATTED_VALUE. The default dateTime render option is SERIAL_NUMBER.
data SpreadsheetsValuesAppendResponseDateTimeRenderOption
= SVARDTROSerialNumber
-- ^ @SERIAL_NUMBER@
-- Instructs date, time, datetime, and duration fields to be output as
-- doubles in \"serial number\" format, as popularized by Lotus 1-2-3. The
-- whole number portion of the value (left of the decimal) counts the days
-- since December 30th 1899. The fractional portion (right of the decimal)
-- counts the time as a fraction of the day. For example, January 1st 1900
-- at noon would be 2.5, 2 because it\'s 2 days after December 30st 1899,
-- and .5 because noon is half a day. February 1st 1900 at 3pm would be
-- 33.625. This correctly treats the year 1900 as not a leap year.
| SVARDTROFormattedString
-- ^ @FORMATTED_STRING@
-- Instructs date, time, datetime, and duration fields to be output as
-- strings in their given number format (which is dependent on the
-- spreadsheet locale).
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable SpreadsheetsValuesAppendResponseDateTimeRenderOption
instance FromHttpApiData SpreadsheetsValuesAppendResponseDateTimeRenderOption where
parseQueryParam = \case
"SERIAL_NUMBER" -> Right SVARDTROSerialNumber
"FORMATTED_STRING" -> Right SVARDTROFormattedString
x -> Left ("Unable to parse SpreadsheetsValuesAppendResponseDateTimeRenderOption from: " <> x)
instance ToHttpApiData SpreadsheetsValuesAppendResponseDateTimeRenderOption where
toQueryParam = \case
SVARDTROSerialNumber -> "SERIAL_NUMBER"
SVARDTROFormattedString -> "FORMATTED_STRING"
instance FromJSON SpreadsheetsValuesAppendResponseDateTimeRenderOption where
parseJSON = parseJSONText "SpreadsheetsValuesAppendResponseDateTimeRenderOption"
instance ToJSON SpreadsheetsValuesAppendResponseDateTimeRenderOption where
toJSON = toJSONText
-- | How dates, times, and durations should be represented in the output.
-- This is ignored if value_render_option is FORMATTED_VALUE. The default
-- dateTime render option is SERIAL_NUMBER.
data BatchGetValuesByDataFilterRequestDateTimeRenderOption
= BGVBDFRDTROSerialNumber
-- ^ @SERIAL_NUMBER@
-- Instructs date, time, datetime, and duration fields to be output as
-- doubles in \"serial number\" format, as popularized by Lotus 1-2-3. The
-- whole number portion of the value (left of the decimal) counts the days
-- since December 30th 1899. The fractional portion (right of the decimal)
-- counts the time as a fraction of the day. For example, January 1st 1900
-- at noon would be 2.5, 2 because it\'s 2 days after December 30st 1899,
-- and .5 because noon is half a day. February 1st 1900 at 3pm would be
-- 33.625. This correctly treats the year 1900 as not a leap year.
| BGVBDFRDTROFormattedString
-- ^ @FORMATTED_STRING@
-- Instructs date, time, datetime, and duration fields to be output as
-- strings in their given number format (which is dependent on the
-- spreadsheet locale).
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable BatchGetValuesByDataFilterRequestDateTimeRenderOption
instance FromHttpApiData BatchGetValuesByDataFilterRequestDateTimeRenderOption where
parseQueryParam = \case
"SERIAL_NUMBER" -> Right BGVBDFRDTROSerialNumber
"FORMATTED_STRING" -> Right BGVBDFRDTROFormattedString
x -> Left ("Unable to parse BatchGetValuesByDataFilterRequestDateTimeRenderOption from: " <> x)
instance ToHttpApiData BatchGetValuesByDataFilterRequestDateTimeRenderOption where
toQueryParam = \case
BGVBDFRDTROSerialNumber -> "SERIAL_NUMBER"
BGVBDFRDTROFormattedString -> "FORMATTED_STRING"
instance FromJSON BatchGetValuesByDataFilterRequestDateTimeRenderOption where
parseJSON = parseJSONText "BatchGetValuesByDataFilterRequestDateTimeRenderOption"
instance ToJSON BatchGetValuesByDataFilterRequestDateTimeRenderOption where
toJSON = toJSONText
-- | Determines how the charts will use hidden rows or columns.
data ChartSpecHiddenDimensionStrategy
= ChartHiddenDimensionStrategyUnspecified
-- ^ @CHART_HIDDEN_DIMENSION_STRATEGY_UNSPECIFIED@
-- Default value, do not use.
| SkipHiddenRowsAndColumns
-- ^ @SKIP_HIDDEN_ROWS_AND_COLUMNS@
-- Charts will skip hidden rows and columns.
| SkipHiddenRows
-- ^ @SKIP_HIDDEN_ROWS@
-- Charts will skip hidden rows only.
| SkipHiddenColumns
-- ^ @SKIP_HIDDEN_COLUMNS@
-- Charts will skip hidden columns only.
| ShowAll
-- ^ @SHOW_ALL@
-- Charts will not skip any hidden rows or columns.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable ChartSpecHiddenDimensionStrategy
instance FromHttpApiData ChartSpecHiddenDimensionStrategy where
parseQueryParam = \case
"CHART_HIDDEN_DIMENSION_STRATEGY_UNSPECIFIED" -> Right ChartHiddenDimensionStrategyUnspecified
"SKIP_HIDDEN_ROWS_AND_COLUMNS" -> Right SkipHiddenRowsAndColumns
"SKIP_HIDDEN_ROWS" -> Right SkipHiddenRows
"SKIP_HIDDEN_COLUMNS" -> Right SkipHiddenColumns
"SHOW_ALL" -> Right ShowAll
x -> Left ("Unable to parse ChartSpecHiddenDimensionStrategy from: " <> x)
instance ToHttpApiData ChartSpecHiddenDimensionStrategy where
toQueryParam = \case
ChartHiddenDimensionStrategyUnspecified -> "CHART_HIDDEN_DIMENSION_STRATEGY_UNSPECIFIED"
SkipHiddenRowsAndColumns -> "SKIP_HIDDEN_ROWS_AND_COLUMNS"
SkipHiddenRows -> "SKIP_HIDDEN_ROWS"
SkipHiddenColumns -> "SKIP_HIDDEN_COLUMNS"
ShowAll -> "SHOW_ALL"
instance FromJSON ChartSpecHiddenDimensionStrategy where
parseJSON = parseJSONText "ChartSpecHiddenDimensionStrategy"
instance ToJSON ChartSpecHiddenDimensionStrategy where
toJSON = toJSONText
-- | The style of the border.
data BOrderStyle
= StyleUnspecified
-- ^ @STYLE_UNSPECIFIED@
-- The style is not specified. Do not use this.
| Dotted
-- ^ @DOTTED@
-- The border is dotted.
| Dashed
-- ^ @DASHED@
-- The border is dashed.
| Solid
-- ^ @SOLID@
-- The border is a thin solid line.
| SolidMedium
-- ^ @SOLID_MEDIUM@
-- The border is a medium solid line.
| SolidThick
-- ^ @SOLID_THICK@
-- The border is a thick solid line.
| None
-- ^ @NONE@
-- No border. Used only when updating a border in order to erase it.
| Double
-- ^ @DOUBLE@
-- The border is two solid lines.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable BOrderStyle
instance FromHttpApiData BOrderStyle where
parseQueryParam = \case
"STYLE_UNSPECIFIED" -> Right StyleUnspecified
"DOTTED" -> Right Dotted
"DASHED" -> Right Dashed
"SOLID" -> Right Solid
"SOLID_MEDIUM" -> Right SolidMedium
"SOLID_THICK" -> Right SolidThick
"NONE" -> Right None
"DOUBLE" -> Right Double
x -> Left ("Unable to parse BOrderStyle from: " <> x)
instance ToHttpApiData BOrderStyle where
toQueryParam = \case
StyleUnspecified -> "STYLE_UNSPECIFIED"
Dotted -> "DOTTED"
Dashed -> "DASHED"
Solid -> "SOLID"
SolidMedium -> "SOLID_MEDIUM"
SolidThick -> "SOLID_THICK"
None -> "NONE"
Double -> "DOUBLE"
instance FromJSON BOrderStyle where
parseJSON = parseJSONText "BOrderStyle"
instance ToJSON BOrderStyle where
toJSON = toJSONText
-- | What kind of data to paste. All the source data will be cut, regardless
-- of what is pasted.
data CutPasteRequestPasteType
= CPRPTPasteNormal
-- ^ @PASTE_NORMAL@
-- Paste values, formulas, formats, and merges.
| CPRPTPasteValues
-- ^ @PASTE_VALUES@
-- Paste the values ONLY without formats, formulas, or merges.
| CPRPTPasteFormat
-- ^ @PASTE_FORMAT@
-- Paste the format and data validation only.
| CPRPTPasteNoBOrders
-- ^ @PASTE_NO_BORDERS@
-- Like \`PASTE_NORMAL\` but without borders.
| CPRPTPasteFormula
-- ^ @PASTE_FORMULA@
-- Paste the formulas only.
| CPRPTPasteDataValidation
-- ^ @PASTE_DATA_VALIDATION@
-- Paste the data validation only.
| CPRPTPasteConditionalFormatting
-- ^ @PASTE_CONDITIONAL_FORMATTING@
-- Paste the conditional formatting rules only.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable CutPasteRequestPasteType
instance FromHttpApiData CutPasteRequestPasteType where
parseQueryParam = \case
"PASTE_NORMAL" -> Right CPRPTPasteNormal
"PASTE_VALUES" -> Right CPRPTPasteValues
"PASTE_FORMAT" -> Right CPRPTPasteFormat
"PASTE_NO_BORDERS" -> Right CPRPTPasteNoBOrders
"PASTE_FORMULA" -> Right CPRPTPasteFormula
"PASTE_DATA_VALIDATION" -> Right CPRPTPasteDataValidation
"PASTE_CONDITIONAL_FORMATTING" -> Right CPRPTPasteConditionalFormatting
x -> Left ("Unable to parse CutPasteRequestPasteType from: " <> x)
instance ToHttpApiData CutPasteRequestPasteType where
toQueryParam = \case
CPRPTPasteNormal -> "PASTE_NORMAL"
CPRPTPasteValues -> "PASTE_VALUES"
CPRPTPasteFormat -> "PASTE_FORMAT"
CPRPTPasteNoBOrders -> "PASTE_NO_BORDERS"
CPRPTPasteFormula -> "PASTE_FORMULA"
CPRPTPasteDataValidation -> "PASTE_DATA_VALIDATION"
CPRPTPasteConditionalFormatting -> "PASTE_CONDITIONAL_FORMATTING"
instance FromJSON CutPasteRequestPasteType where
parseJSON = parseJSONText "CutPasteRequestPasteType"
instance ToJSON CutPasteRequestPasteType where
toJSON = toJSONText
-- | The position of the chart legend.
data BasicChartSpecLegendPosition
= BCSLPBasicChartLegendPositionUnspecified
-- ^ @BASIC_CHART_LEGEND_POSITION_UNSPECIFIED@
-- Default value, do not use.
| BCSLPBottomLegend
-- ^ @BOTTOM_LEGEND@
-- The legend is rendered on the bottom of the chart.
| BCSLPLeftLegend
-- ^ @LEFT_LEGEND@
-- The legend is rendered on the left of the chart.
| BCSLPRightLegend
-- ^ @RIGHT_LEGEND@
-- The legend is rendered on the right of the chart.
| BCSLPTopLegend
-- ^ @TOP_LEGEND@
-- The legend is rendered on the top of the chart.
| BCSLPNoLegend
-- ^ @NO_LEGEND@
-- No legend is rendered.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable BasicChartSpecLegendPosition
instance FromHttpApiData BasicChartSpecLegendPosition where
parseQueryParam = \case
"BASIC_CHART_LEGEND_POSITION_UNSPECIFIED" -> Right BCSLPBasicChartLegendPositionUnspecified
"BOTTOM_LEGEND" -> Right BCSLPBottomLegend
"LEFT_LEGEND" -> Right BCSLPLeftLegend
"RIGHT_LEGEND" -> Right BCSLPRightLegend
"TOP_LEGEND" -> Right BCSLPTopLegend
"NO_LEGEND" -> Right BCSLPNoLegend
x -> Left ("Unable to parse BasicChartSpecLegendPosition from: " <> x)
instance ToHttpApiData BasicChartSpecLegendPosition where
toQueryParam = \case
BCSLPBasicChartLegendPositionUnspecified -> "BASIC_CHART_LEGEND_POSITION_UNSPECIFIED"
BCSLPBottomLegend -> "BOTTOM_LEGEND"
BCSLPLeftLegend -> "LEFT_LEGEND"
BCSLPRightLegend -> "RIGHT_LEGEND"
BCSLPTopLegend -> "TOP_LEGEND"
BCSLPNoLegend -> "NO_LEGEND"
instance FromJSON BasicChartSpecLegendPosition where
parseJSON = parseJSONText "BasicChartSpecLegendPosition"
instance ToJSON BasicChartSpecLegendPosition where
toJSON = toJSONText
-- | The type of error.
data ErrorValueType
= ErrorTypeUnspecified
-- ^ @ERROR_TYPE_UNSPECIFIED@
-- The default error type, do not use this.
| Error'
-- ^ @ERROR@
-- Corresponds to the \`#ERROR!\` error.
| NullValue
-- ^ @NULL_VALUE@
-- Corresponds to the \`#NULL!\` error.
| DivideByZero
-- ^ @DIVIDE_BY_ZERO@
-- Corresponds to the \`#DIV\/0\` error.
| Value
-- ^ @VALUE@
-- Corresponds to the \`#VALUE!\` error.
| Ref
-- ^ @REF@
-- Corresponds to the \`#REF!\` error.
| Name
-- ^ @NAME@
-- Corresponds to the \`#NAME?\` error.
| Num
-- ^ @NUM@
-- Corresponds to the \`#NUM!\` error.
| NA
-- ^ @N_A@
-- Corresponds to the \`#N\/A\` error.
| Loading
-- ^ @LOADING@
-- Corresponds to the \`Loading...\` state.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable ErrorValueType
instance FromHttpApiData ErrorValueType where
parseQueryParam = \case
"ERROR_TYPE_UNSPECIFIED" -> Right ErrorTypeUnspecified
"ERROR" -> Right Error'
"NULL_VALUE" -> Right NullValue
"DIVIDE_BY_ZERO" -> Right DivideByZero
"VALUE" -> Right Value
"REF" -> Right Ref
"NAME" -> Right Name
"NUM" -> Right Num
"N_A" -> Right NA
"LOADING" -> Right Loading
x -> Left ("Unable to parse ErrorValueType from: " <> x)
instance ToHttpApiData ErrorValueType where
toQueryParam = \case
ErrorTypeUnspecified -> "ERROR_TYPE_UNSPECIFIED"
Error' -> "ERROR"
NullValue -> "NULL_VALUE"
DivideByZero -> "DIVIDE_BY_ZERO"
Value -> "VALUE"
Ref -> "REF"
Name -> "NAME"
Num -> "NUM"
NA -> "N_A"
Loading -> "LOADING"
instance FromJSON ErrorValueType where
parseJSON = parseJSONText "ErrorValueType"
instance ToJSON ErrorValueType where
toJSON = toJSONText
-- | The major dimension that results should use. For example, if the
-- spreadsheet data is: \`A1=1,B1=2,A2=3,B2=4\`, then a request that
-- selects that range and sets \`majorDimension=ROWS\` returns
-- \`[[1,2],[3,4]]\`, whereas a request that sets
-- \`majorDimension=COLUMNS\` returns \`[[1,3],[2,4]]\`.
data BatchGetValuesByDataFilterRequestMajorDimension
= BGVBDFRMDDimensionUnspecified
-- ^ @DIMENSION_UNSPECIFIED@
-- The default value, do not use.
| BGVBDFRMDRows
-- ^ @ROWS@
-- Operates on the rows of a sheet.
| BGVBDFRMDColumns
-- ^ @COLUMNS@
-- Operates on the columns of a sheet.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable BatchGetValuesByDataFilterRequestMajorDimension
instance FromHttpApiData BatchGetValuesByDataFilterRequestMajorDimension where
parseQueryParam = \case
"DIMENSION_UNSPECIFIED" -> Right BGVBDFRMDDimensionUnspecified
"ROWS" -> Right BGVBDFRMDRows
"COLUMNS" -> Right BGVBDFRMDColumns
x -> Left ("Unable to parse BatchGetValuesByDataFilterRequestMajorDimension from: " <> x)
instance ToHttpApiData BatchGetValuesByDataFilterRequestMajorDimension where
toQueryParam = \case
BGVBDFRMDDimensionUnspecified -> "DIMENSION_UNSPECIFIED"
BGVBDFRMDRows -> "ROWS"
BGVBDFRMDColumns -> "COLUMNS"
instance FromJSON BatchGetValuesByDataFilterRequestMajorDimension where
parseJSON = parseJSONText "BatchGetValuesByDataFilterRequestMajorDimension"
instance ToJSON BatchGetValuesByDataFilterRequestMajorDimension where
toJSON = toJSONText
-- | The type of date-time grouping to apply.
data ChartDateTimeRuleType
= CDTRTChartDateTimeRuleTypeUnspecified
-- ^ @CHART_DATE_TIME_RULE_TYPE_UNSPECIFIED@
-- The default type, do not use.
| CDTRTSecond
-- ^ @SECOND@
-- Group dates by second, from 0 to 59.
| CDTRTMinute
-- ^ @MINUTE@
-- Group dates by minute, from 0 to 59.
| CDTRTHour
-- ^ @HOUR@
-- Group dates by hour using a 24-hour system, from 0 to 23.
| CDTRTHourMinute
-- ^ @HOUR_MINUTE@
-- Group dates by hour and minute using a 24-hour system, for example
-- 19:45.
| CDTRTHourMinuteAmpm
-- ^ @HOUR_MINUTE_AMPM@
-- Group dates by hour and minute using a 12-hour system, for example 7:45
-- PM. The AM\/PM designation is translated based on the spreadsheet
-- locale.
| CDTRTDayOfWeek
-- ^ @DAY_OF_WEEK@
-- Group dates by day of week, for example Sunday. The days of the week
-- will be translated based on the spreadsheet locale.
| CDTRTDayOfYear
-- ^ @DAY_OF_YEAR@
-- Group dates by day of year, from 1 to 366. Note that dates after Feb. 29
-- fall in different buckets in leap years than in non-leap years.
| CDTRTDayOfMonth
-- ^ @DAY_OF_MONTH@
-- Group dates by day of month, from 1 to 31.
| CDTRTDayMonth
-- ^ @DAY_MONTH@
-- Group dates by day and month, for example 22-Nov. The month is
-- translated based on the spreadsheet locale.
| CDTRTMonth
-- ^ @MONTH@
-- Group dates by month, for example Nov. The month is translated based on
-- the spreadsheet locale.
| CDTRTQuarter
-- ^ @QUARTER@
-- Group dates by quarter, for example Q1 (which represents Jan-Mar).
| CDTRTYear
-- ^ @YEAR@
-- Group dates by year, for example 2008.
| CDTRTYearMonth
-- ^ @YEAR_MONTH@
-- Group dates by year and month, for example 2008-Nov. The month is
-- translated based on the spreadsheet locale.
| CDTRTYearQuarter
-- ^ @YEAR_QUARTER@
-- Group dates by year and quarter, for example 2008 Q4.
| CDTRTYearMonthDay
-- ^ @YEAR_MONTH_DAY@
-- Group dates by year, month, and day, for example 2008-11-22.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable ChartDateTimeRuleType
instance FromHttpApiData ChartDateTimeRuleType where
parseQueryParam = \case
"CHART_DATE_TIME_RULE_TYPE_UNSPECIFIED" -> Right CDTRTChartDateTimeRuleTypeUnspecified
"SECOND" -> Right CDTRTSecond
"MINUTE" -> Right CDTRTMinute
"HOUR" -> Right CDTRTHour
"HOUR_MINUTE" -> Right CDTRTHourMinute
"HOUR_MINUTE_AMPM" -> Right CDTRTHourMinuteAmpm
"DAY_OF_WEEK" -> Right CDTRTDayOfWeek
"DAY_OF_YEAR" -> Right CDTRTDayOfYear
"DAY_OF_MONTH" -> Right CDTRTDayOfMonth
"DAY_MONTH" -> Right CDTRTDayMonth
"MONTH" -> Right CDTRTMonth
"QUARTER" -> Right CDTRTQuarter
"YEAR" -> Right CDTRTYear
"YEAR_MONTH" -> Right CDTRTYearMonth
"YEAR_QUARTER" -> Right CDTRTYearQuarter
"YEAR_MONTH_DAY" -> Right CDTRTYearMonthDay
x -> Left ("Unable to parse ChartDateTimeRuleType from: " <> x)
instance ToHttpApiData ChartDateTimeRuleType where
toQueryParam = \case
CDTRTChartDateTimeRuleTypeUnspecified -> "CHART_DATE_TIME_RULE_TYPE_UNSPECIFIED"
CDTRTSecond -> "SECOND"
CDTRTMinute -> "MINUTE"
CDTRTHour -> "HOUR"
CDTRTHourMinute -> "HOUR_MINUTE"
CDTRTHourMinuteAmpm -> "HOUR_MINUTE_AMPM"
CDTRTDayOfWeek -> "DAY_OF_WEEK"
CDTRTDayOfYear -> "DAY_OF_YEAR"
CDTRTDayOfMonth -> "DAY_OF_MONTH"
CDTRTDayMonth -> "DAY_MONTH"
CDTRTMonth -> "MONTH"
CDTRTQuarter -> "QUARTER"
CDTRTYear -> "YEAR"
CDTRTYearMonth -> "YEAR_MONTH"
CDTRTYearQuarter -> "YEAR_QUARTER"
CDTRTYearMonthDay -> "YEAR_MONTH_DAY"
instance FromJSON ChartDateTimeRuleType where
parseJSON = parseJSONText "ChartDateTimeRuleType"
instance ToJSON ChartDateTimeRuleType where
toJSON = toJSONText
-- | Whether values should be listed horizontally (as columns) or vertically
-- (as rows).
data PivotTableValueLayout
= Horizontal
-- ^ @HORIZONTAL@
-- Values are laid out horizontally (as columns).
| Vertical
-- ^ @VERTICAL@
-- Values are laid out vertically (as rows).
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable PivotTableValueLayout
instance FromHttpApiData PivotTableValueLayout where
parseQueryParam = \case
"HORIZONTAL" -> Right Horizontal
"VERTICAL" -> Right Vertical
x -> Left ("Unable to parse PivotTableValueLayout from: " <> x)
instance ToHttpApiData PivotTableValueLayout where
toQueryParam = \case
Horizontal -> "HORIZONTAL"
Vertical -> "VERTICAL"
instance FromJSON PivotTableValueLayout where
parseJSON = parseJSONText "PivotTableValueLayout"
instance ToJSON PivotTableValueLayout where
toJSON = toJSONText
-- | How dates, times, and durations should be represented in the output.
-- This is ignored if value_render_option is FORMATTED_VALUE. The default
-- dateTime render option is SERIAL_NUMBER.
data SpreadsheetsValuesGetDateTimeRenderOption
= SVGDTROSerialNumber
-- ^ @SERIAL_NUMBER@
-- Instructs date, time, datetime, and duration fields to be output as
-- doubles in \"serial number\" format, as popularized by Lotus 1-2-3. The
-- whole number portion of the value (left of the decimal) counts the days
-- since December 30th 1899. The fractional portion (right of the decimal)
-- counts the time as a fraction of the day. For example, January 1st 1900
-- at noon would be 2.5, 2 because it\'s 2 days after December 30st 1899,
-- and .5 because noon is half a day. February 1st 1900 at 3pm would be
-- 33.625. This correctly treats the year 1900 as not a leap year.
| SVGDTROFormattedString
-- ^ @FORMATTED_STRING@
-- Instructs date, time, datetime, and duration fields to be output as
-- strings in their given number format (which is dependent on the
-- spreadsheet locale).
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable SpreadsheetsValuesGetDateTimeRenderOption
instance FromHttpApiData SpreadsheetsValuesGetDateTimeRenderOption where
parseQueryParam = \case
"SERIAL_NUMBER" -> Right SVGDTROSerialNumber
"FORMATTED_STRING" -> Right SVGDTROFormattedString
x -> Left ("Unable to parse SpreadsheetsValuesGetDateTimeRenderOption from: " <> x)
instance ToHttpApiData SpreadsheetsValuesGetDateTimeRenderOption where
toQueryParam = \case
SVGDTROSerialNumber -> "SERIAL_NUMBER"
SVGDTROFormattedString -> "FORMATTED_STRING"
instance FromJSON SpreadsheetsValuesGetDateTimeRenderOption where
parseJSON = parseJSONText "SpreadsheetsValuesGetDateTimeRenderOption"
instance ToJSON SpreadsheetsValuesGetDateTimeRenderOption where
toJSON = toJSONText
-- | How the value should be interpreted.
data InterpolationPointType
= IPTInterpolationPointTypeUnspecified
-- ^ @INTERPOLATION_POINT_TYPE_UNSPECIFIED@
-- The default value, do not use.
| IPTMin
-- ^ @MIN@
-- The interpolation point uses the minimum value in the cells over the
-- range of the conditional format.
| IPTMax
-- ^ @MAX@
-- The interpolation point uses the maximum value in the cells over the
-- range of the conditional format.
| IPTNumber
-- ^ @NUMBER@
-- The interpolation point uses exactly the value in
-- InterpolationPoint.value.
| IPTPercent
-- ^ @PERCENT@
-- The interpolation point is the given percentage over all the cells in
-- the range of the conditional format. This is equivalent to \`NUMBER\` if
-- the value was: \`=(MAX(FLATTEN(range)) * (value \/ 100)) +
-- (MIN(FLATTEN(range)) * (1 - (value \/ 100)))\` (where errors in the
-- range are ignored when flattening).
| IPTPercentile
-- ^ @PERCENTILE@
-- The interpolation point is the given percentile over all the cells in
-- the range of the conditional format. This is equivalent to \`NUMBER\` if
-- the value was: \`=PERCENTILE(FLATTEN(range), value \/ 100)\` (where
-- errors in the range are ignored when flattening).
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable InterpolationPointType
instance FromHttpApiData InterpolationPointType where
parseQueryParam = \case
"INTERPOLATION_POINT_TYPE_UNSPECIFIED" -> Right IPTInterpolationPointTypeUnspecified
"MIN" -> Right IPTMin
"MAX" -> Right IPTMax
"NUMBER" -> Right IPTNumber
"PERCENT" -> Right IPTPercent
"PERCENTILE" -> Right IPTPercentile
x -> Left ("Unable to parse InterpolationPointType from: " <> x)
instance ToHttpApiData InterpolationPointType where
toQueryParam = \case
IPTInterpolationPointTypeUnspecified -> "INTERPOLATION_POINT_TYPE_UNSPECIFIED"
IPTMin -> "MIN"
IPTMax -> "MAX"
IPTNumber -> "NUMBER"
IPTPercent -> "PERCENT"
IPTPercentile -> "PERCENTILE"
instance FromJSON InterpolationPointType where
parseJSON = parseJSONText "InterpolationPointType"
instance ToJSON InterpolationPointType where
toJSON = toJSONText
-- | The delimiter type to use.
data TextToColumnsRequestDelimiterType
= TTCRDTDelimiterTypeUnspecified
-- ^ @DELIMITER_TYPE_UNSPECIFIED@
-- Default value. This value must not be used.
| TTCRDTComma
-- ^ @COMMA@
-- \",\"
| TTCRDTSemicolon
-- ^ @SEMICOLON@
-- \";\"
| TTCRDTPeriod
-- ^ @PERIOD@
-- \".\"
| TTCRDTSpace
-- ^ @SPACE@
-- \" \"
| TTCRDTCustom
-- ^ @CUSTOM@
-- A custom value as defined in delimiter.
| TTCRDTAutodetect
-- ^ @AUTODETECT@
-- Automatically detect columns.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable TextToColumnsRequestDelimiterType
instance FromHttpApiData TextToColumnsRequestDelimiterType where
parseQueryParam = \case
"DELIMITER_TYPE_UNSPECIFIED" -> Right TTCRDTDelimiterTypeUnspecified
"COMMA" -> Right TTCRDTComma
"SEMICOLON" -> Right TTCRDTSemicolon
"PERIOD" -> Right TTCRDTPeriod
"SPACE" -> Right TTCRDTSpace
"CUSTOM" -> Right TTCRDTCustom
"AUTODETECT" -> Right TTCRDTAutodetect
x -> Left ("Unable to parse TextToColumnsRequestDelimiterType from: " <> x)
instance ToHttpApiData TextToColumnsRequestDelimiterType where
toQueryParam = \case
TTCRDTDelimiterTypeUnspecified -> "DELIMITER_TYPE_UNSPECIFIED"
TTCRDTComma -> "COMMA"
TTCRDTSemicolon -> "SEMICOLON"
TTCRDTPeriod -> "PERIOD"
TTCRDTSpace -> "SPACE"
TTCRDTCustom -> "CUSTOM"
TTCRDTAutodetect -> "AUTODETECT"
instance FromJSON TextToColumnsRequestDelimiterType where
parseJSON = parseJSONText "TextToColumnsRequestDelimiterType"
instance ToJSON TextToColumnsRequestDelimiterType where
toJSON = toJSONText
-- | The dimension which will be shifted when inserting cells. If ROWS,
-- existing cells will be shifted down. If COLUMNS, existing cells will be
-- shifted right.
data InsertRangeRequestShiftDimension
= IRRSDDimensionUnspecified
-- ^ @DIMENSION_UNSPECIFIED@
-- The default value, do not use.
| IRRSDRows
-- ^ @ROWS@
-- Operates on the rows of a sheet.
| IRRSDColumns
-- ^ @COLUMNS@
-- Operates on the columns of a sheet.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable InsertRangeRequestShiftDimension
instance FromHttpApiData InsertRangeRequestShiftDimension where
parseQueryParam = \case
"DIMENSION_UNSPECIFIED" -> Right IRRSDDimensionUnspecified
"ROWS" -> Right IRRSDRows
"COLUMNS" -> Right IRRSDColumns
x -> Left ("Unable to parse InsertRangeRequestShiftDimension from: " <> x)
instance ToHttpApiData InsertRangeRequestShiftDimension where
toQueryParam = \case
IRRSDDimensionUnspecified -> "DIMENSION_UNSPECIFIED"
IRRSDRows -> "ROWS"
IRRSDColumns -> "COLUMNS"
instance FromJSON InsertRangeRequestShiftDimension where
parseJSON = parseJSONText "InsertRangeRequestShiftDimension"
instance ToJSON InsertRangeRequestShiftDimension where
toJSON = toJSONText
-- | The state of the data execution.
data DataExecutionStatusState
= DataExecutionStateUnspecified
-- ^ @DATA_EXECUTION_STATE_UNSPECIFIED@
-- Default value, do not use.
| NotStarted
-- ^ @NOT_STARTED@
-- The data execution has not started.
| Running
-- ^ @RUNNING@
-- The data execution has started and is running.
| Succeeded
-- ^ @SUCCEEDED@
-- The data execution has completed successfully.
| Failed
-- ^ @FAILED@
-- The data execution has completed with errors.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable DataExecutionStatusState
instance FromHttpApiData DataExecutionStatusState where
parseQueryParam = \case
"DATA_EXECUTION_STATE_UNSPECIFIED" -> Right DataExecutionStateUnspecified
"NOT_STARTED" -> Right NotStarted
"RUNNING" -> Right Running
"SUCCEEDED" -> Right Succeeded
"FAILED" -> Right Failed
x -> Left ("Unable to parse DataExecutionStatusState from: " <> x)
instance ToHttpApiData DataExecutionStatusState where
toQueryParam = \case
DataExecutionStateUnspecified -> "DATA_EXECUTION_STATE_UNSPECIFIED"
NotStarted -> "NOT_STARTED"
Running -> "RUNNING"
Succeeded -> "SUCCEEDED"
Failed -> "FAILED"
instance FromJSON DataExecutionStatusState where
parseJSON = parseJSONText "DataExecutionStatusState"
instance ToJSON DataExecutionStatusState where
toJSON = toJSONText
-- | How values should be represented in the output. The default render
-- option is FORMATTED_VALUE.
data SpreadsheetsValuesGetValueRenderOption
= SVGVROFormattedValue
-- ^ @FORMATTED_VALUE@
-- Values will be calculated & formatted in the reply according to the
-- cell\'s formatting. Formatting is based on the spreadsheet\'s locale,
-- not the requesting user\'s locale. For example, if \`A1\` is \`1.23\`
-- and \`A2\` is \`=A1\` and formatted as currency, then \`A2\` would
-- return \`\"$1.23\"\`.
| SVGVROUnformattedValue
-- ^ @UNFORMATTED_VALUE@
-- Values will be calculated, but not formatted in the reply. For example,
-- if \`A1\` is \`1.23\` and \`A2\` is \`=A1\` and formatted as currency,
-- then \`A2\` would return the number \`1.23\`.
| SVGVROFormula
-- ^ @FORMULA@
-- Values will not be calculated. The reply will include the formulas. For
-- example, if \`A1\` is \`1.23\` and \`A2\` is \`=A1\` and formatted as
-- currency, then A2 would return \`\"=A1\"\`.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable SpreadsheetsValuesGetValueRenderOption
instance FromHttpApiData SpreadsheetsValuesGetValueRenderOption where
parseQueryParam = \case
"FORMATTED_VALUE" -> Right SVGVROFormattedValue
"UNFORMATTED_VALUE" -> Right SVGVROUnformattedValue
"FORMULA" -> Right SVGVROFormula
x -> Left ("Unable to parse SpreadsheetsValuesGetValueRenderOption from: " <> x)
instance ToHttpApiData SpreadsheetsValuesGetValueRenderOption where
toQueryParam = \case
SVGVROFormattedValue -> "FORMATTED_VALUE"
SVGVROUnformattedValue -> "UNFORMATTED_VALUE"
SVGVROFormula -> "FORMULA"
instance FromJSON SpreadsheetsValuesGetValueRenderOption where
parseJSON = parseJSONText "SpreadsheetsValuesGetValueRenderOption"
instance ToJSON SpreadsheetsValuesGetValueRenderOption where
toJSON = toJSONText
| brendanhay/gogol | gogol-sheets/gen/Network/Google/Sheets/Types/Sum.hs | mpl-2.0 | 178,343 | 0 | 11 | 39,973 | 21,237 | 11,483 | 9,754 | 2,552 | 0 |
{-# LANGUAGE DataKinds
, GADTs
, KindSignatures
#-}
module Avro.Inspector
( Inspector
( ANull
, ABool
, AInt
, ALong
, AFloat
, ADouble
, ABytes
, AString
, ARecord
, AEnum
, AArray
, AMap
, AFixed
)
)
where
import Data.Int (Int32, Int64)
import Data.Map (Map)
import Data.ByteString (ByteString)
import Data.Text (Text)
import Data.Vinyl (Rec, HList)
import Avro.Records
( Field
, RecordDesc
)
import Avro.Schema
( Schema
( avroNull
, avroBool
, avroInt
, avroFloat
, avroDouble
, avroLong
, avroBytes
, avroString
, avroRecord
, avroEnum
, avroArray
, avroMap
, avroFixed
)
)
data Inspector a
where ANull :: Inspector ()
ABool :: Inspector Bool
AInt :: Inspector Int32
ALong :: Inspector Int64
AFloat :: Inspector Float
ADouble :: Inspector Double
ABytes :: Inspector ByteString
AString :: Inspector Text
ARecord :: RecordDesc -> Rec (Field Inspector) as -> Inspector (HList as)
AEnum :: Enum a => Inspector a
AArray :: Inspector a -> Inspector [a]
AMap :: Inspector a -> Inspector (Map Text a)
AFixed :: Int32 -> Inspector ByteString
instance Schema Inspector
where avroNull = ANull
avroBool = ABool
avroInt = AInt
avroLong = ALong
avroFloat = AFloat
avroDouble = ADouble
avroBytes = ABytes
avroString = AString
avroRecord = ARecord
avroEnum = AEnum
avroArray = AArray
avroMap = AMap
avroFixed = AFixed
| cumber/havro | src/Avro/Inspector.hs | lgpl-3.0 | 1,725 | 0 | 10 | 636 | 392 | 239 | 153 | 72 | 0 |
module Serialization where
import Protolude
import Data.Serialize as S
import Gen
import Key
import Hedgehog
import Hedgehog.Gen
encodeThenDecode :: Serialize a => a -> Either [Char] a
encodeThenDecode = S.decodeLazy . S.encodeLazy
prop_blockHeaderSerialization :: Property
prop_blockHeaderSerialization = property $ do
pk <- liftIO $ fst <$> Key.newKeyPair
bh <- forAll $ Gen.genBlockHeader pk
encodeThenDecode bh === Right bh
prop_transferSerialization :: Property
prop_transferSerialization = property $ do
pk <- liftIO $ fst <$> Key.newKeyPair
transfer <- forAll $ Gen.genTransfer pk
encodeThenDecode transfer === Right transfer
prop_rewardSerialization :: Property
prop_rewardSerialization = property $ do
pk <- liftIO $ fst <$> Key.newKeyPair
reward <- forAll $ Gen.genReward pk
encodeThenDecode reward === Right reward
tests :: IO Bool
tests = checkParallel $
Group "Nanocoin.SerializationTests"
[ ("prop_blockHeaderSerialization", prop_blockHeaderSerialization)
, ("prop_transferSerialization", prop_transferSerialization)
, ("prop_rewardSerialization", prop_rewardSerialization)
]
| tdietert/nanocoin | test/Serialization.hs | apache-2.0 | 1,136 | 0 | 11 | 176 | 294 | 151 | 143 | 30 | 1 |
module HeronianTriangles.A305704 (a305704, a305704_list) where
import HelperSequences.A051518 (a051518_list)
-- Even numbers not in A051518
a305704_list :: [Integer]
a305704_list = map (`div` 2) a051518_list
a305704 :: Int -> Integer
a305704 n = a305704_list !! (n-1)
| peterokagey/haskellOEIS | src/HeronianTriangles/A305704.hs | apache-2.0 | 270 | 0 | 7 | 36 | 77 | 46 | 31 | 6 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Main (main) where
import Control.Monad.Reader
import Network.HTTPMock
import Web.Shipping.Tracking.USPS
-- FOR TESTING
main :: IO ()
main = print =<< trackDat
trackDat = runReaderT (getTrackingData myTrackingNumber) ctx
myTrackingNumber = TrackingNumber "bogus"
ctx = RequestContext realHTTPBackend myAuth
myAuth = Auth "098ZE57JN801"
| MichaelXavier/Shipping | Main.hs | bsd-2-clause | 385 | 0 | 7 | 53 | 90 | 51 | 39 | 11 | 1 |
module Model.Household where
import Import
import Data.Maybe (listToMaybe)
findHousehold owner = listToMaybe <$> selectList [HouseholdOwner ==. owner] [LimitTo 1]
| MasseR/shoppinglist | Model/Household.hs | bsd-2-clause | 165 | 0 | 8 | 21 | 49 | 27 | 22 | 4 | 1 |
{-|
Copyright : (c) Dave Laing, 2017
License : BSD3
Maintainer : [email protected]
Stability : experimental
Portability : non-portable
-}
module Fragment.Annotation.Helpers (
tmAnnotation
) where
import Control.Lens (review)
import Ast.Type
import Ast.Term
import Fragment.Annotation.Ast.Term
tmAnnotation :: AsTmAnnotation ki ty pt tm
=> Type ki ty a
-> Term ki ty pt tm a
-> Term ki ty pt tm a
tmAnnotation =
curry $ review _TmAnnotation
| dalaing/type-systems | src/Fragment/Annotation/Helpers.hs | bsd-3-clause | 506 | 0 | 8 | 127 | 107 | 58 | 49 | 12 | 1 |
module Hash (
runInteractive,
runScript
) where
import Parsing.HashParser
import Language.Exec
import Control.Monad (when)
import Language.Commands (command_tb, CommandTable, ScriptState(..))
import Language.Expressions
import System.Directory
import System.IO
import qualified Data.Map as M
import Data.Maybe
import Data.List (isPrefixOf)
runInteractive :: IO ()
runInteractive = do
currDir <- getCurrentDirectory
let ss = ScriptState "" currDir $ M.fromList [("HOME", currDir)]
runInteractiveIter command_tb ss
return ()
runInteractiveIter :: CommandTable -> ScriptState -> IO ScriptState
runInteractiveIter ct ss = do
putStr "> "
hFlush stdout
string <- getLine
if not $ isPrefixOf "quit" string then do
let cmdLine = simpleParse readCommandLine string
cmd <- case cmdLine of
Left err -> do
putStrLn $ show err
return Nothing
Right ss -> return $ Just ss
nss <- if isJust cmd then
runTopLevel command_tb ss (TLCmd (fromJust cmd))
else
return ss
runInteractiveIter ct nss
else
return ss
runScript :: FilePath -> IO ()
runScript path = do
handle <- openFile path ReadMode
cont <- hGetContents handle
coms <- case simpleParse tlexpressions cont of
Left err -> do
putStrLn $ show err
return Nothing
Right ss -> return $ Just ss
when (isJust coms) $ do
nss <- runHashProgram command_tb (Left "script_state.conf") (fromJust coms)
putStrLn $ show nss
return () | edi-smoljan/FER-PUH-2014-Hash | Hash.hs | bsd-3-clause | 1,625 | 0 | 17 | 468 | 503 | 241 | 262 | 49 | 4 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TemplateHaskell #-}
module Main where
-------------------------------------------------------------------------------
import Control.Applicative
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy.Char8 as LB
import Data.DeriveTH
import qualified Data.Map as M
import qualified Data.Text as T
import qualified Database.Cassandra.Thrift.Cassandra_Client as C
import Database.Cassandra.Thrift.Cassandra_Types (ConsistencyLevel (..))
import Database.Cassandra.Thrift.Cassandra_Types as T
import System.IO.Unsafe
import Test.Framework (defaultMain,
testGroup)
import Test.Framework.Providers.HUnit
import Test.Framework.Providers.QuickCheck2 (testProperty)
import Test.HUnit
import Test.QuickCheck
import Test.QuickCheck.Property
-------------------------------------------------------------------------------
import Database.Cassandra.Basic
import Database.Cassandra.Pack
import Database.Cassandra.Pool
-------------------------------------------------------------------------------
main = do
pool <- mkTestConn
defaultMain $ tests pool
tests pool = [testGroup "packTests" (packTests pool)]
packTests pool =
[ testProperty "cas type marshalling long" prop_casTypeLong
, testProperty "cas type marshalling ascii" prop_casTypeAscii
, testProperty "cas type marshalling ascii" prop_casTypeInt32
, testProperty "cas type marshalling composite" prop_casTypeComp
, testCase "cas live test - composite get/set" test_composite_col
, testCase "cas live - set comp + single col slice" test_composite_slice
-- , testProperty "cas live test read/write QC" (prop_composite_col_readWrite pool)
]
deriving instance Arbitrary TAscii
deriving instance Arbitrary TBytes
deriving instance Arbitrary TCounter
deriving instance Arbitrary TInt32
deriving instance Arbitrary TInt64
deriving instance Arbitrary TUUID
deriving instance Arbitrary TLong
deriving instance Arbitrary TUtf8
deriving instance Arbitrary a => Arbitrary (Exclusive a)
instance Arbitrary T.Text where
arbitrary = T.pack <$> arbitrary
instance Arbitrary LB.ByteString where
arbitrary = LB.pack <$> arbitrary
prop_casTypeAscii :: TAscii -> Bool
prop_casTypeAscii a = (decodeCas . encodeCas) a == a
prop_casTypeLong :: TLong -> Property
prop_casTypeLong a@(TLong n) = n >= 0 ==> (decodeCas . encodeCas) a == a
prop_casTypeInt32 :: TInt32 -> Bool
prop_casTypeInt32 a = (decodeCas . encodeCas) a == a
prop_casTypeComp :: (TAscii, TBytes, TInt32, TUtf8) -> Property
prop_casTypeComp a = whenFail err $ a == a'
where
a' = (decodeCas . encodeCas) a
err = print $ "Decoded back into: " ++ show a'
prop_casTypeExcComp :: (TAscii, TBytes, TInt32, Exclusive TUtf8) -> Property
prop_casTypeExcComp a = whenFail err $ a == a'
where
a' = (decodeCas . encodeCas) a
err = print $ "Decoded back into: " ++ show a'
newKS = KsDef {
f_KsDef_name = Just "testing"
, f_KsDef_strategy_class = Just "org.apache.cassandra.locator.NetworkTopologyStrategy"
, f_KsDef_strategy_options = Just (M.fromList [("datacenter1","1")])
, f_KsDef_replication_factor = Nothing
, f_KsDef_cf_defs = Nothing
, f_KsDef_durable_writes = Just True
}
mkTestConn = createCassandraPool [("127.0.0.1", 9160)] 2 2 300 "testing"
-------------------------------------------------------------------------------
test_composite_col = do
pool <- mkTestConn
res <- runCas pool $ do
insert "testing" "row1" ONE [packCol content]
getCol "testing" "row1" (packKey key) ONE
assertEqual "composite get-set" (Just content) (fmap unpackCol res)
where
key = (TLong 125, TBytes "oklahoma")
content = (key, "asdf")
-------------------------------------------------------------------------------
test_composite_slice = do
pool <- mkTestConn
xs <- runCas pool $ do
insert "testing" "row2" ONE [packCol (key, content)]
get "testing" "row2" slice ONE
let (res :: [((TLong, TBytes), LB.ByteString)]) = map unpackCol xs
assertEqual "composite single col slice" content (snd . head $ res)
where
key = (TLong 125, TBytes "oklahoma")
content = "asdf"
slice = Range (Just (Exclusive (Single (TLong 125))))
(Just (Single (TLong 125)))
-- (Just (Single (TLong 127)))
Regular
100
-- slice = Range (Just (TLong 125, TBytes "")) (Just (TLong 125, TBytes "zzzzz")) Regular 100
-------------------------------------------------------------------------------
-- | test quick-check generated pairs for composite column
prop_composite_col_readWrite :: CPool -> ((TLong, TBytes), LB.ByteString) -> Property
prop_composite_col_readWrite pool content@(k@(TLong i, _),v) = i >= 0 ==>
unsafePerformIO $ do
res <- runCas pool $ do
insert "testing" "row" ONE [packCol content]
getCol "testing" "row" (packKey k) ONE
return $ (Just content) == fmap unpackCol res
| Soostone/cassy | test/Test.hs | bsd-3-clause | 5,619 | 0 | 15 | 1,359 | 1,215 | 659 | 556 | -1 | -1 |
module Hub.HelpText(helpText) where
helpText :: String
helpText = unlines
[ " Hub Help Page"
, " "
, " hub --usage is an aliase for the 'hub usage' command"
, " hub --help is an aliase for the 'hub help' command"
, " hub --version is an aliase for the 'hub version' command"
, ""
, "hub usage"
, ""
, " List the syntax of all the hub commands."
, ""
, "hub help [<hub-command>]"
, ""
, " List the help for a command or all commands if none specified."
, ""
, " See \"hub usage\" for a command-syntax summary."
, ""
, "hub version"
, ""
, " List the version information."
, ""
, "hub default [<g-hub>|-]"
, ""
, " (Needs to be run as root.)"
, " "
, " If no arguments are given then this command lists the the default global"
, " hub for the system (i.e., the default global hub used to set up each"
, " user's 'home' hub)."
, " "
, " If a global hub <g-hub> is specified then <g-hub> will become the"
, " default global hub."
, " "
, " If a '-' is specified then any older default settings are discarded and"
, " the system default re-established."
, ""
, "hub ls [-a] [-q]"
, ""
, " List the user hubs belonging to the logged in user and all of the"
, " global hubs. If -a is specified then all hubs are listed, otherwise"
, " the hidden hub (those starting with \"__\") are ommitted. Normally the"
, " locked status and any comments associated with the hub are displayed,"
, " but these will be ommitted if the -q flag is given."
, ""
, "hub set [<hub>|-]"
, ""
, " Set the 'current' hub for a directory and its sub-directories."
, " "
, " The HUB environment variable can be set to a hub name to override this"
, " setting."
, " "
, " '^' can genereally be specified in place of <hub>/<g-hub>/<u-hub>"
, " in a hub command to refer to the current hub. "
, ""
, "hub info [<hub>]"
, ""
, " Describe a hub. (See 'hub set' on how to set the current hub.)"
, " "
, " (See 'hub set' on how to set the current hub.)"
, ""
, "hub lock [<hub>]"
, ""
, " Lock a hub so that it can not be removed or renamed or have packages"
, " added or removed."
, ""
, " (See 'hub set' on how to set the current hub.)"
, ""
, "hub unlock [<hub>]"
, ""
, " Remove the lock from a hub."
, ""
, " (See 'hub lock' on locking a hub and 'hub set' on how to set the current hub.)"
, ""
, "hub name"
, ""
, " List the name of the current hub."
, " "
, " (See 'hub set' on how to set the current hub.)"
, ""
, "hub path [<hub>]"
, ""
, " List the path of the XML file defining the named or current hub."
, " "
, " (See 'hub set' on how to set the current hub.)"
, ""
, "hub xml [<hub>]"
, ""
, " List the contents of the XML file defining the named or current hub."
, " "
, " (See 'hub set' on how to set the current hub.)"
, ""
, "hub init [-n [<hub>]]"
, "hub init [-s] [<hub>] <u-hub'>"
, ""
, " The first form creates a new user hub with some unique name __h<num>"
, " and associates the current working directory with the new hub. If"
, " a hub is specified then that determines the global hub for the new"
, " hub otherwise the current defaulkt hub is used."
, " "
, " The second from creates the new named user hub <u-hub'>. If <hub>"
, " is specified then the global hub for the new hub is determined by"
, " this hub otherwise the default hub is used. Iff --set is specified"
, " the hub associated with the current directory is set to the new hub."
, " "
, " (See 'hub set' on how to set the current hub.)"
, ""
, "hub comment [<u-hub>] <comment-string>"
, ""
, " Set the comment string for a user hub."
, ""
, " (See 'hub set' on how to set the current hub.)"
, ""
, "hub cp [<u-hub>] <u-hub'>"
, ""
, " Duplicate <u-hub> (or the current hib) in <u-hub'>."
, " "
, " (See 'hub set' on how to set the current hub.)"
, ""
, "hub mv [<u-hub>] <u-hub'>"
, ""
, " Rename user hub <u-hub> (or the current hub) to <u-hub'>."
, " "
, " (See 'hub set' on how to set the current hub.)"
, ""
, "hub rm <u-hub>"
, ""
, " Delete user hub <u-hub>."
, ""
, "hub swap [<u-hub>] <u-hub'>"
, ""
, " Swap the contents of user hub <u-hub> (or the current hub) with"
, " user hub <u-hub'>."
, " "
, " (See 'hub set' on how to set the current hub.)"
, ""
, "hub list [<hub>]"
, ""
, " List the packages belonging to a hub (calls 'ghc-pkg list')."
, ""
, " (See 'hub set' on how to set the current hub.)"
, ""
, "hub check [<hub>]"
, ""
, " Check the packages belonging to a hub are coherent "
, " (calls 'ghc-pkg check')."
, ""
, " (See 'hub set' on how to set the current hub.)"
, ""
, "hub install <pkg-name> ..."
, ""
, " Equivalent to: hub install-into ^ <pkg-name> ... "
, ""
, "hub install-into <u-hub> <pkg-name> ..."
, ""
, " Uses 'cabal install' to install the named packages into a user"
, " hub."
, ""
, " (See 'hub set' on how to set the current hub.)"
, ""
, "hub erase <pkg-name> ..."
, ""
, " Equivalent to: hub esase-from ^ <pkg-name> ... "
, ""
, "hub erase-from [-f] <u-hub> <pkg-name> ..."
, ""
, " Run the garbage collector on the user hubs to reclaim library code"
, " that is no longer referenced by them. (The directories aren't removed"
, " from the file system, but moved from `~/.hubrc/heap` to"
, " `~/.hubrc/garbage` for manual removal.) "
, ""
, " (See 'hub set' on how to set the current hub.)"
, ""
, "hub gc"
, ""
, " Run the garbage collector to reclaim library code that is no longer"
, " referenced by the hubs."
, ""
, "hub save [<u-hub>]"
, " "
, " Save out the configuration of the hub onto standard output."
, ""
, " (See 'hub set' on how to set the current hub.)"
, ""
, "hub load [<u-hub>]"
, ""
, " Load the hub from standard input. If the named hub doesn't"
, " exist then the hub is created with the global hub specified by the"
, " archive. If <u-hub> does exist then it is checked that it is using the"
, " global hub specified and if necessary removed and recreated referencing"
, " the right global hub."
, " "
, " Any surplus packages not mentioned in the archive are then removed."
, " "
, " Finally any packages missing from the hub listed in the archive are"
, " installed with cabal-install."
, ""
, " (See 'hub set' on how to set the current hub.)"
, ""
, "hub verify [-s] [<u-hub>]"
, ""
, " Check that the named hub (or the default hub) uses the global hub"
, " specified in the archive and that it contains all of the packages"
, " at the versions specified by the archive. If -s is specified"
, " then check that the hub contains no packages other than those specified"
, " by the archive."
, ""
, " (See 'hub set' on how to set the current hub.)"
]
| Lainepress/hub-src | Hub/HelpText.hs | bsd-3-clause | 8,065 | 0 | 6 | 2,981 | 639 | 424 | 215 | 208 | 1 |
{-# OPTIONS_GHC -Wall -fno-warn-orphans #-}
module Language.Haskell.Exts.Desugar.Generic.Expression where
import Prelude hiding (error,foldl,any,foldr)
-- import Prelude (Integer,Enum(..))
--import Text.Show (Show(..))
import Language.Haskell.Exts hiding (binds,name)
import Language.Haskell.Exts.SrcLoc(noLoc)
import Language.Haskell.Exts.Unique
-- import Language.Haskell.Exts.Desugar
import Language.Haskell.Exts.Desugar.Basic
-- import Language.Haskell.Exts.Desugar.Type
import Language.Haskell.Exts.Desugar.Generic.Pattern
import Language.Haskell.Exts.Desugar.Generic.Case
import Language.Haskell.Exts.Desugar.Conversion
-- import {-# SOURCE #-} Language.Haskell.Exts.Desugar.Declaration ()
--import Control.Monad (mapM,sequence,Monad(..),(=<<))
import Control.Applicative ((<$>),(<*>))
import Data.Foldable (foldl,foldr,any) -- all,any)
-- desugarPTuple = undefined
desugarVar, desugarIPVar, desugarCon, desugarLit, desugarInfixApp, desugarApp, desugarNegApp, desugarLambda, desugarLet, desugarIf, desugarCase, desugarDo, desugarMDo, desugarTuple, desugarTupleSection, desugarList, desugarParen, desugarLeftSection, desugarRightSection, desugarRecConstr, desugarRecUpdate, desugarEnumFrom, desugarEnumFromTo, desugarEnumFromThen, desugarEnumFromThenTo, desugarListComp, desugarParComp, desugarExpTypeSig, desugarVarQuote, desugarTypQuote, desugarBracketExp, desugarSpliceExp, desugarQuasiQuote, desugarXTag, desugarXETag, desugarXPcdata, desugarXExpTag, desugarXChildTag, desugarCorePragma, desugarSCCPragma, desugarGenPragma, desugarProc, desugarLeftArrApp, desugarRightArrApp, desugarLeftArrHighApp, desugarRightArrHighApp :: Exp -> Unique Exp
-- Haskell 2010 Report Section 3.2
-- no desugaring
desugarVar = noDesugaring
-- not supported
desugarIPVar = notSupported
-- not Haskell 2010 Report Section 3.2
desugarCon (Con qn) = return $ Var qn
desugarCon e = noDesugaring e
-- not Haskell 2010 Report Section 3.2
-- no desugaring
-- could be considered as constant functions (Var)
desugarLit = noDesugaring
-- Haskell 2010 Report Section 3.4
desugarInfixApp (InfixApp exp1 (QVarOp qName) exp2) =
return $ App (App (Var qName) exp1) exp2
desugarInfixApp (InfixApp exp1 (QConOp qName) exp2) =
return $ App (App (Con qName) exp1) exp2
desugarInfixApp e = noDesugaring e
-- Haskell 2010 Report Section 3.2
-- no desugaring
desugarApp = noDesugaring
-- Haskell 2010 Report Section 3.4
desugarNegApp (NegApp e) =
return $ App (Var (UnQual (Ident "negate"))) e
desugarNegApp e = noDesugaring e
-- Haskell 2010 Report Section 3.3
-- HSE Specific Desugaring
desugarLambda (Lambda _ [] _) =
error "No header for the lambda expression!"
desugarLambda (Lambda src (p:[]) body)
| not $ isPVar p = do
name <- newVar
return $ Lambda src [PVar $ Ident name]
(Case (Var $ UnQual $ Ident name)
[Alt noLoc p (UnGuardedAlt body) emptyBind])
desugarLambda e@(Lambda _src (_p:[]) _body)
| otherwise =
noDesugaring e
desugarLambda (Lambda src ps@(_p:_pss) body)
| any (not . isPVar) ps = do
names <- sequence [newVar| _ <-ps]
desugarLambda $
Lambda src ((PVar . Ident) <$> names)
(Case (Tuple $ (Var . UnQual . Ident) <$> names)
[Alt noLoc (PTuple ps) (UnGuardedAlt body) emptyBind])
desugarLambda (Lambda src (p:ps) body)
| otherwise =
Lambda src [p] <$> desugarLambda (Lambda src ps body)
desugarLambda e = noDesugaring e
-- Haskell 2010 Report Section 3.12
-- let with empty binding is removed
desugarLet (Let (BDecls []) ex) = return ex
desugarLet e@(Let _ _) = noDesugaring e
desugarLet e = noDesugaring e
-- Haskell 2010 Report Section 3.6
desugarIf (If cond th el) = return $
Case cond
[Alt noLoc
(PApp (UnQual (Ident "True")) []) (UnGuardedAlt th) emptyBind
,Alt noLoc
(PApp (UnQual (Ident "False")) []) (UnGuardedAlt el) emptyBind]
desugarIf e = noDesugaring e
{-
Case con [] error
Case con (_ :[] ) stepA
Case con (A _ UG eb: emptAlt:[]) stepA
Case con (A con (G [] ) eb: emptAlt:[]) error
Case con (A con (G [GAlt _ [] _]) eb: emptAlt:[]) error
Case con (A con (G [GAlt _ [Q] _]) eb: emptAlt:[]) stepV
Case con (A con (G [GAlt _ [L] _]) eb: emptAlt:[]) stepU
Case con (A con (G [GAlt _ [G] _]) eb: emptAlt:[]) stepT
Case con (A con (G [GAlt _ (_:_) _]) eb: emptAlt:[]) stepS
Case con (A con (G (_:_) ) eb: emptAlt:[]) stepA
Case con (A ~con (G _ ) eb: emptAlt:[]) stepA
Case con (_ : _ :[]) stepA
Case con (_ : _ : _) stepA
Case var [] error
Case var (_ :[] ) stepJ'
Case var (A pvar ug eb: emptAlt:[]) stepIJ
Case var (A PIrrPat ug eb: emptAlt:[]) stepD
Case var (A PAsPat ug eb: emptAlt:[]) stepE
Case var (A PWildCard ug eb: emptAlt:[]) stepF
Case var (A PLit ug eb: emptAlt:[]) stepH
Case var (A PBangPat ug eb: emptAlt:[]) stepT'
Case var (A PViewPat ug eb: emptAlt:[]) stepV'
Case var (A PNPlusK ug eb: emptAlt:[]) stepS'
Case var (A PApp(isvar) ug eb: emptAlt:[]) stepFinal
Case var (A pApp(notvar) ug eb: emptAlt:[]) stepG
Case var (A _ ug eb: emptAlt:[]) error
Case var (A _ ug _: emptAlt:[]) stepBinding
Case var (A p g decls: emptAlt:[]) stepC
Case var (_ : _ :[]) stepB
Case var (_ : _ :_ ) stepB
-}
-- Haskell 2010 Report Sections 3.13 & 3.17.3
-- the optimization transformations (k .. r) are not implemented
desugarCase (Case e altsi) = do
-- reduce patterns to:
-- PApp, PVar, PLit, PAsPat, PWildCard, PIrrPat,
-- PNPlusk, PBangPat, PViewPat, PRecord
alts <- sequence $
[(Alt srcLoc) <$> desugarPat pat
<*> return guardedAlts
<*> return binds
|Alt srcLoc pat guardedAlts binds <- altsi]
let c = Case e alts
case e of
{Con (Special UnitCon) ->
case alts of
{[] -> error "Wrong HSE Tree!"
;_:[] -> stepA c
;Alt _ p galt _ : Alt _ PWildCard (UnGuardedAlt _)(BDecls []):[]->
case galt of
{UnGuardedAlt _ -> stepA c
;GuardedAlts gss ->
case p of
PApp (Special UnitCon) [] ->
case gss of
[] -> error "Wrong HSE Tree!"
GuardedAlt _ stmts _:[] ->
case stmts of
[] -> error "Wrong HSE Tree!"
[Qualifier _] -> desugarCase =<< _stepV c
[LetStmt _] -> stepU c
[Generator _ _ _] -> desugarCase =<< stepT c
_:_ -> desugarCase =<< stepS c
_:_ -> stepA c
_ -> stepA c
}
;_:_:[] -> stepA c
;_:_:_ -> stepA c}
;Var _ ->
case alts of
{[] -> error "Wrong HSE Tree!"
;_:[] -> desugarCase =<< stepJ' c
;Alt _ p galt decls:Alt _ PWildCard (UnGuardedAlt _)(BDecls []):[]->
case galt of
{UnGuardedAlt _ ->
case decls of
{BDecls [] ->
case p of
{PVar _ -> stepIJ c
;PIrrPat _ -> desugarCase =<< stepD c
;PAsPat _ _ -> desugarCase =<< stepE c
;PWildCard -> stepF c
;PLit _ -> desugarCase =<< _stepH c
;PBangPat _ -> desugarCase =<< stepT' c
;PViewPat _ _ -> desugarCase =<< stepV' c
;PNPlusK _ _ -> desugarCase =<< stepS' c
;PRec _ [] -> return c
;PRec _ [_] -> stepN c
;PRec _ (_:_) -> stepM c
;PApp _ ps
| all isPVar ps -> return c
| True -> desugarCase =<< stepG c
;_ -> error "Not Supported in case!"}
;_ -> desugarCase =<< stepBinding c}
;GuardedAlts _ -> desugarCase =<< stepC c}
;_:_:[] -> desugarCase =<< stepB c
;_:_:_ -> desugarCase =<< stepB c}
; _ -> stepA c}
desugarCase e = noDesugaring e
-- Haskell 2010 Report Section 3.14
desugarDo = _desugarDo False
desugarDo_MonoLocalBind :: Desugaring Exp
desugarDo_MonoLocalBind = _desugarDo True
_desugarDo :: Bool -> Desugaring Exp
_desugarDo _ (Do []) = error "Empty do block!"
_desugarDo _ (Do ((Qualifier e):[])) = return e
_desugarDo _ (Do ( _ :[])) =
error "The last statement in a 'do' block must be an expression!"
_desugarDo _ (Do ((Qualifier e):ss)) = do
return $ InfixApp e (QVarOp (UnQual (Symbol ">>"))) (Do ss)
_desugarDo False (Do ((Generator _ p e):stmts)) = do
ok <- newVar
return $ Let
(BDecls
[FunBind
[Match noLoc (Ident ok)
[p] Nothing
(UnGuardedRhs (Do stmts))
emptyBind
,Match noLoc (Ident ok)
[PWildCard] Nothing
(UnGuardedRhs (App (Var (UnQual (Ident "fail")))
(Lit (String "..."))))
emptyBind]])
(InfixApp e
(QVarOp (UnQual (Symbol ">>=")))
(Var (UnQual (Ident ok))))
_desugarDo True (Do ((Generator _ (PVar n) e):stmts)) = do
return $ InfixApp e
(QVarOp (UnQual (Symbol ">>=")))
(Lambda noLoc [PVar n] (Do stmts))
_desugarDo True (Do ((Generator _ p e):stmts)) = do
x <- newVar
return $ InfixApp e (QVarOp (UnQual (Symbol ">>=")))
(Lambda noLoc [PVar $ Ident x]
(Case (Var $ UnQual $ Ident x)
[Alt noLoc p (UnGuardedAlt (Do stmts))
emptyBind
,Alt noLoc PWildCard (UnGuardedAlt (App (Var (UnQual (Ident "fail")))
(Lit (String "..."))))
emptyBind]))
_desugarDo _ (Do ((LetStmt bs):ss)) =
return $ Let bs (Do ss)
_desugarDo _ (Do ((RecStmt _) : (_ : _))) =
error "not supported yet!" --ToDo
_desugarDo _ e = noDesugaring e
desugarMDo = notSupported
-- not Haskell 2010 Report Section 3.8
-- HSE
desugarTuple (Tuple []) = return $ Con (Special UnitCon)
desugarTuple (Tuple [e]) = return e
desugarTuple (Tuple exps@(_:_)) = return $
foldl App (Con $ Special $ TupleCon Boxed $ length exps) exps
desugarTuple e = noDesugaring e
-- HSE
desugarTupleSection (TupleSection mes) = do
eExps <- mapM (\m -> case m of {Nothing -> Left . Ident <$> newVar
;Just x -> return $ Right x }
) mes
return $ Lambda noLoc [PVar n | Left n <- eExps]
(Tuple [case x of
Left n -> Var $ UnQual n
Right e -> e
|x <- eExps])
desugarTupleSection e = noDesugaring e
-- Haskell 2010 Report Section 3.7
desugarList (List es) = return $
foldr (\e a -> App (App (Con $ Special Cons) e) a)
(Con (Special ListCon)) es
desugarList e = noDesugaring e
-- Haskell 2010 Report Section 3.9
desugarParen (Paren ex) = return ex
desugarParen e = noDesugaring e
-- Haskell 2010 Report Section 3.5
desugarLeftSection (LeftSection ex qOp) = do
n <- newVar
return $ Lambda noLoc [PVar $ Ident n]
(InfixApp ex qOp (Var $ UnQual $ Ident n))
desugarLeftSection e = noDesugaring e
-- Haskell 2010 Report Section 3.5
desugarRightSection (RightSection qOp ex) = do
n <- newVar
return $ Lambda noLoc [PVar $ Ident n]
(InfixApp (Var $ UnQual $ Ident n) qOp ex )
desugarRightSection e = noDesugaring e
-- not Haskell 2010 Report Section 3.15.2
desugarRecConstr = noDesugaring
{-
(RecConstr qName fieldUpdates) = do
qn <- addPrefixToQName newPrefix qName
fu <- desugarFieldUpdates fieldUpdates
desugarRecordUpdate $ RecUpdate (Var qn) fu
-}
-- not Haskell 2010 Report Section 3.15.3
desugarRecUpdate = noDesugaring
{-
(RecUpdate eexp fieldUpdates) = do
fu <- desugarFieldUpdates fieldUpdates
es <- sequence
[do
{qn <- addPrefixToQName setPrefix qName
;return $ App (Var qn) e}
| FieldUpdate qName e <- fu]
return $ foldl (flip App) eexp es
-}
-- Haskell 2010 Report Section 3.10
desugarEnumFrom (EnumFrom e) =
return $ App (Var (UnQual (Ident "enumFrom"))) e
desugarEnumFrom e = noDesugaring e
-- Haskell 2010 Report Section 3.10
desugarEnumFromTo (EnumFromTo ex1 ex2) = do
return $ App (App (Var (UnQual (Ident "enumFromTo"))) ex1) ex2
desugarEnumFromTo e = noDesugaring e
-- Haskell 2010 Report Section 3.10
desugarEnumFromThen (EnumFromThen ex1 ex2) =
return $ App (App (Var (UnQual (Ident "enumFromThen"))) ex1) ex2
desugarEnumFromThen e = noDesugaring e
-- Haskell 2010 Report Section 3.10
desugarEnumFromThenTo (EnumFromThenTo ex1 ex2 ex3) =
return $
App (App (App (Var (UnQual (Ident "enumFromThen"))) ex1) ex2) ex3
desugarEnumFromThenTo e = noDesugaring e
-- not Haskell 2010 Report Section 3.11
-- Generalized to monad comprehensions
-- based on: "Comprehending Moands" By Walder
desugarListComp (ListComp eexp qualStmts) =
return $
Do ( (cQualStmt <$> qualStmts) ++
[(Qualifier (App (Var ((UnQual (Ident "return")))) eexp))])
desugarListComp e = noDesugaring e
-- Not Supported
desugarParComp = notSupported
{-
desugar (ParComp eexp qualStmtss) = error "Not supported!"
let comps = [ ListComp
(Tuple [patToExp p| (Generator _ p _ ) <- qualStmts ])
qualStmts
| qualStmts <- qualStmtss
let x = Generator noLoc (PTuple [PTuple | <-])
(foldl App (Var (UnQual $ Ident ("zip" ++ (show (length comps))))) comps )
desugar (ListComp eexp x) -}
-- Haskell 2010 Report Section 3.16
desugarExpTypeSig (ExpTypeSig _ e t) = do
v <- newVar
return $ Let (BDecls [TypeSig noLoc [Ident v] t
,PatBind noLoc (PVar (Ident v)) Nothing
(UnGuardedRhs e) emptyBind])
(Var (UnQual (Ident v)))
desugarExpTypeSig e = noDesugaring e
-- Template Haskell
desugarVarQuote = notSupported
desugarTypQuote = notSupported
desugarBracketExp = notSupported
desugarSpliceExp = notSupported
desugarQuasiQuote = notSupported
-- Hsx
desugarXTag = notSupported
desugarXETag = notSupported
desugarXPcdata = notSupported
desugarXExpTag = notSupported
desugarXChildTag = notSupported
-- Pragmas
desugarCorePragma = notSupported
desugarSCCPragma = notSupported
desugarGenPragma = notSupported
-- Arrows
desugarProc = notSupported
desugarLeftArrApp = notSupported
desugarRightArrApp = notSupported
desugarLeftArrHighApp = notSupported
desugarRightArrHighApp = notSupported
stepFinal :: Exp -> Unique Exp
stepFinal c@(Case (Var _)
((Alt _ (PApp _ ps) (UnGuardedAlt _)
(BDecls []))
:(Alt _ PWildCard (UnGuardedAlt _)
(BDecls []))
:[]))
| all isPVar ps
= noDesugaring c
stepFinal _ = error "not in the final state!"
{-
desugarFieldUpdate :: FieldUpdate -> Unique FieldUpdate
desugarFieldUpdate (FieldUpdate qn e) =
return $ FieldUpdate qn e
desugarFieldUpdate (FieldPun n) =
desugarFieldUpdate $ FieldUpdate (UnQual n) (Var (UnQual n))
desugarFieldUpdate FieldWildcard =
error "FieldWildcard is not supported!"
-}
| shayan-najd/Haskell-Desugar-Generic | Language/Haskell/Exts/Desugar/Generic/Expression.hs | bsd-3-clause | 16,627 | 2 | 26 | 5,581 | 3,984 | 2,066 | 1,918 | 255 | 33 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-} -- keep TH usage here
-- | Constants used throughout the project.
module Stack.Constants
(buildPlanDir
,buildPlanCacheDir
,haskellFileExts
,haskellPreprocessorExts
,stackDotYaml
,stackWorkEnvVar
,stackRootEnvVar
,stackRootOptionName
,deprecatedStackRootOptionName
,inContainerEnvVar
,inNixShellEnvVar
,stackProgNameUpper
,wiredInPackages
,cabalPackageName
,implicitGlobalProjectDirDeprecated
,implicitGlobalProjectDir
,defaultUserConfigPathDeprecated
,defaultUserConfigPath
,defaultGlobalConfigPathDeprecated
,defaultGlobalConfigPath
,platformVariantEnvVar
,compilerOptionsCabalFlag
,ghcColorForceFlag
,minTerminalWidth
,maxTerminalWidth
,defaultTerminalWidth
,osIsWindows
,relFileSetupHs
,relFileSetupLhs
,relFileHpackPackageConfig
,relDirGlobalAutogen
,relDirAutogen
,relDirLogs
,relFileCabalMacrosH
,relDirBuild
,relDirBin
,relDirPantry
,relDirPrograms
,relDirUpperPrograms
,relDirStackProgName
,relDirStackWork
,relFileReadmeTxt
,relDirScript
,relFileConfigYaml
,relDirSnapshots
,relDirGlobalHints
,relFileGlobalHintsYaml
,relDirInstall
,relDirCompilerTools
,relDirHoogle
,relFileDatabaseHoo
,relDirPkgdb
,relFileStorage
,relDirLoadedSnapshotCache
,bindirSuffix
,docDirSuffix
,relDirHpc
,relDirLib
,relDirShare
,relDirLibexec
,relDirEtc
,setupGhciShimCode
,relDirSetupExeCache
,relDirSetupExeSrc
,relFileConfigure
,relDirDist
,relFileSetupMacrosH
,relDirSetup
,relFileSetupLower
,relDirMingw
,relDirMingw32
,relDirMingw64
,relDirLocal
,relDirUsr
,relDirInclude
,relFileIndexHtml
,relDirAll
,relFilePackageCache
,relFileDockerfile
,relDirHaskellStackGhci
,relFileGhciScript
,relDirCombined
,relFileHpcIndexHtml
,relDirCustom
,relDirPackageConfInplace
,relDirExtraTixFiles
,relDirInstalledPackages
,backupUrlRelPath
,relDirDotLocal
,relDirDotSsh
,relDirDotStackProgName
,relDirUnderHome
,relDirSrc
,relFileLibtinfoSo5
,relFileLibtinfoSo6
,relFileLibncurseswSo6
,relFileLibgmpSo10
,relFileLibgmpSo3
,relDirNewCabal
,relFileSetupExe
,relFileSetupUpper
,relFile7zexe
,relFile7zdll
,relFileMainHs
,relFileStack
,relFileStackDotExe
,relFileStackDotTmpDotExe
,relFileStackDotTmp
,ghcShowOptionsOutput
,hadrianCmdWindows
,hadrianCmdPosix
,usrLibDirs
,testGhcEnvRelFile
,relFileBuildLock
,stackDeveloperModeDefault
)
where
import Data.ByteString.Builder (byteString)
import Data.Char (toUpper)
import Data.FileEmbed (embedFile, makeRelativeToProject)
import qualified Data.Set as Set
import Distribution.Package (mkPackageName)
import qualified Hpack.Config as Hpack
import qualified Language.Haskell.TH.Syntax as TH (runIO, lift)
import Path as FL
import Stack.Prelude
import Stack.Types.Compiler
import System.Permissions (osIsWindows)
import System.Process (readProcess)
-- | Extensions used for Haskell modules. Excludes preprocessor ones.
haskellFileExts :: [Text]
haskellFileExts = ["hs", "hsc", "lhs"]
-- | Extensions for modules that are preprocessed by common preprocessors.
haskellPreprocessorExts :: [Text]
haskellPreprocessorExts = ["gc", "chs", "hsc", "x", "y", "ly", "cpphs"]
-- | Name of the 'stack' program, uppercased
stackProgNameUpper :: String
stackProgNameUpper = map toUpper stackProgName
-- | The filename used for the stack config file.
stackDotYaml :: Path Rel File
stackDotYaml = $(mkRelFile "stack.yaml")
-- | Environment variable used to override the '.stack-work' relative dir.
stackWorkEnvVar :: String
stackWorkEnvVar = "STACK_WORK"
-- | Environment variable used to override the '~/.stack' location.
stackRootEnvVar :: String
stackRootEnvVar = "STACK_ROOT"
-- | Option name for the global stack root.
stackRootOptionName :: String
stackRootOptionName = "stack-root"
-- | Deprecated option name for the global stack root.
--
-- Deprecated since stack-1.1.0.
--
-- TODO: Remove occurrences of this variable and use 'stackRootOptionName' only
-- after an appropriate deprecation period.
deprecatedStackRootOptionName :: String
deprecatedStackRootOptionName = "global-stack-root"
-- | Environment variable used to indicate stack is running in container.
inContainerEnvVar :: String
inContainerEnvVar = stackProgNameUpper ++ "_IN_CONTAINER"
-- | Environment variable used to indicate stack is running in container.
-- although we already have STACK_IN_NIX_EXTRA_ARGS that is set in the same conditions,
-- it can happen that STACK_IN_NIX_EXTRA_ARGS is set to empty.
inNixShellEnvVar :: String
inNixShellEnvVar = map toUpper stackProgName ++ "_IN_NIX_SHELL"
-- See https://downloads.haskell.org/~ghc/7.10.1/docs/html/libraries/ghc/src/Module.html#integerPackageKey
wiredInPackages :: Set PackageName
wiredInPackages =
maybe (error "Parse error in wiredInPackages") Set.fromList mparsed
where
mparsed = mapM parsePackageName
[ "ghc-prim"
, "integer-gmp"
, "integer-simple"
, "base"
, "rts"
, "template-haskell"
, "dph-seq"
, "dph-par"
, "ghc"
, "interactive"
]
-- | Just to avoid repetition and magic strings.
cabalPackageName :: PackageName
cabalPackageName =
mkPackageName "Cabal"
-- | Deprecated implicit global project directory used when outside of a project.
implicitGlobalProjectDirDeprecated :: Path Abs Dir -- ^ Stack root.
-> Path Abs Dir
implicitGlobalProjectDirDeprecated p =
p </>
$(mkRelDir "global")
-- | Implicit global project directory used when outside of a project.
-- Normally, @getImplicitGlobalProjectDir@ should be used instead.
implicitGlobalProjectDir :: Path Abs Dir -- ^ Stack root.
-> Path Abs Dir
implicitGlobalProjectDir p =
p </>
$(mkRelDir "global-project")
-- | Deprecated default global config path.
defaultUserConfigPathDeprecated :: Path Abs Dir -> Path Abs File
defaultUserConfigPathDeprecated = (</> $(mkRelFile "stack.yaml"))
-- | Default global config path.
-- Normally, @getDefaultUserConfigPath@ should be used instead.
defaultUserConfigPath :: Path Abs Dir -> Path Abs File
defaultUserConfigPath = (</> $(mkRelFile "config.yaml"))
-- | Deprecated default global config path.
-- Note that this will be @Nothing@ on Windows, which is by design.
defaultGlobalConfigPathDeprecated :: Maybe (Path Abs File)
defaultGlobalConfigPathDeprecated = parseAbsFile "/etc/stack/config"
-- | Default global config path.
-- Normally, @getDefaultGlobalConfigPath@ should be used instead.
-- Note that this will be @Nothing@ on Windows, which is by design.
defaultGlobalConfigPath :: Maybe (Path Abs File)
defaultGlobalConfigPath = parseAbsFile "/etc/stack/config.yaml"
-- | Path where build plans are stored.
buildPlanDir :: Path Abs Dir -- ^ Stack root
-> Path Abs Dir
buildPlanDir = (</> $(mkRelDir "build-plan"))
-- | Path where binary caches of the build plans are stored.
buildPlanCacheDir
:: Path Abs Dir -- ^ Stack root
-> Path Abs Dir
buildPlanCacheDir = (</> $(mkRelDir "build-plan-cache"))
-- | Environment variable that stores a variant to append to platform-specific directory
-- names. Used to ensure incompatible binaries aren't shared between Docker builds and host
platformVariantEnvVar :: String
platformVariantEnvVar = stackProgNameUpper ++ "_PLATFORM_VARIANT"
-- | Provides --ghc-options for 'Ghc'
compilerOptionsCabalFlag :: WhichCompiler -> String
compilerOptionsCabalFlag Ghc = "--ghc-options"
-- | The flag to pass to GHC when we want to force its output to be
-- colorized.
ghcColorForceFlag :: String
ghcColorForceFlag = "-fdiagnostics-color=always"
-- | The minimum allowed terminal width. Used for pretty-printing.
minTerminalWidth :: Int
minTerminalWidth = 40
-- | The maximum allowed terminal width. Used for pretty-printing.
maxTerminalWidth :: Int
maxTerminalWidth = 200
-- | The default terminal width. Used for pretty-printing when we can't
-- automatically detect it and when the user doesn't supply one.
defaultTerminalWidth :: Int
defaultTerminalWidth = 100
relFileSetupHs :: Path Rel File
relFileSetupHs = $(mkRelFile "Setup.hs")
relFileSetupLhs :: Path Rel File
relFileSetupLhs = $(mkRelFile "Setup.lhs")
relFileHpackPackageConfig :: Path Rel File
relFileHpackPackageConfig = $(mkRelFile Hpack.packageConfig)
relDirGlobalAutogen :: Path Rel Dir
relDirGlobalAutogen = $(mkRelDir "global-autogen")
relDirAutogen :: Path Rel Dir
relDirAutogen = $(mkRelDir "autogen")
relDirLogs :: Path Rel Dir
relDirLogs = $(mkRelDir "logs")
relFileCabalMacrosH :: Path Rel File
relFileCabalMacrosH = $(mkRelFile "cabal_macros.h")
relDirBuild :: Path Rel Dir
relDirBuild = $(mkRelDir "build")
relDirBin :: Path Rel Dir
relDirBin = $(mkRelDir "bin")
relDirPantry :: Path Rel Dir
relDirPantry = $(mkRelDir "pantry")
relDirPrograms :: Path Rel Dir
relDirPrograms = $(mkRelDir "programs")
relDirUpperPrograms :: Path Rel Dir
relDirUpperPrograms = $(mkRelDir "Programs")
relDirStackProgName :: Path Rel Dir
relDirStackProgName = $(mkRelDir stackProgName)
relDirStackWork :: Path Rel Dir
relDirStackWork = $(mkRelDir ".stack-work")
relFileReadmeTxt :: Path Rel File
relFileReadmeTxt = $(mkRelFile "README.txt")
relDirScript :: Path Rel Dir
relDirScript = $(mkRelDir "script")
relFileConfigYaml :: Path Rel File
relFileConfigYaml = $(mkRelFile "config.yaml")
relDirSnapshots :: Path Rel Dir
relDirSnapshots = $(mkRelDir "snapshots")
relDirGlobalHints :: Path Rel Dir
relDirGlobalHints = $(mkRelDir "global-hints")
relFileGlobalHintsYaml :: Path Rel File
relFileGlobalHintsYaml = $(mkRelFile "global-hints.yaml")
relDirInstall :: Path Rel Dir
relDirInstall = $(mkRelDir "install")
relDirCompilerTools :: Path Rel Dir
relDirCompilerTools = $(mkRelDir "compiler-tools")
relDirHoogle :: Path Rel Dir
relDirHoogle = $(mkRelDir "hoogle")
relFileDatabaseHoo :: Path Rel File
relFileDatabaseHoo = $(mkRelFile "database.hoo")
relDirPkgdb :: Path Rel Dir
relDirPkgdb = $(mkRelDir "pkgdb")
relFileStorage :: Path Rel File
relFileStorage = $(mkRelFile "stack.sqlite3")
relDirLoadedSnapshotCache :: Path Rel Dir
relDirLoadedSnapshotCache = $(mkRelDir "loaded-snapshot-cached")
-- | Suffix applied to an installation root to get the bin dir
bindirSuffix :: Path Rel Dir
bindirSuffix = relDirBin
-- | Suffix applied to an installation root to get the doc dir
docDirSuffix :: Path Rel Dir
docDirSuffix = $(mkRelDir "doc")
relDirHpc :: Path Rel Dir
relDirHpc = $(mkRelDir "hpc")
relDirLib :: Path Rel Dir
relDirLib = $(mkRelDir "lib")
relDirShare :: Path Rel Dir
relDirShare = $(mkRelDir "share")
relDirLibexec :: Path Rel Dir
relDirLibexec = $(mkRelDir "libexec")
relDirEtc :: Path Rel Dir
relDirEtc = $(mkRelDir "etc")
setupGhciShimCode :: Builder
setupGhciShimCode = byteString $(do
path <- makeRelativeToProject "src/setup-shim/StackSetupShim.hs"
embedFile path)
relDirSetupExeCache :: Path Rel Dir
relDirSetupExeCache = $(mkRelDir "setup-exe-cache")
relDirSetupExeSrc :: Path Rel Dir
relDirSetupExeSrc = $(mkRelDir "setup-exe-src")
relFileConfigure :: Path Rel File
relFileConfigure = $(mkRelFile "configure")
relDirDist :: Path Rel Dir
relDirDist = $(mkRelDir "dist")
relFileSetupMacrosH :: Path Rel File
relFileSetupMacrosH = $(mkRelFile "setup_macros.h")
relDirSetup :: Path Rel Dir
relDirSetup = $(mkRelDir "setup")
relFileSetupLower :: Path Rel File
relFileSetupLower = $(mkRelFile "setup")
relDirMingw :: Path Rel Dir
relDirMingw = $(mkRelDir "mingw")
relDirMingw32 :: Path Rel Dir
relDirMingw32 = $(mkRelDir "mingw32")
relDirMingw64 :: Path Rel Dir
relDirMingw64 = $(mkRelDir "mingw64")
relDirLocal :: Path Rel Dir
relDirLocal = $(mkRelDir "local")
relDirUsr :: Path Rel Dir
relDirUsr = $(mkRelDir "usr")
relDirInclude :: Path Rel Dir
relDirInclude = $(mkRelDir "include")
relFileIndexHtml :: Path Rel File
relFileIndexHtml = $(mkRelFile "index.html")
relDirAll :: Path Rel Dir
relDirAll = $(mkRelDir "all")
relFilePackageCache :: Path Rel File
relFilePackageCache = $(mkRelFile "package.cache")
relFileDockerfile :: Path Rel File
relFileDockerfile = $(mkRelFile "Dockerfile")
relDirHaskellStackGhci :: Path Rel Dir
relDirHaskellStackGhci = $(mkRelDir "haskell-stack-ghci")
relFileGhciScript :: Path Rel File
relFileGhciScript = $(mkRelFile "ghci-script")
relDirCombined :: Path Rel Dir
relDirCombined = $(mkRelDir "combined")
relFileHpcIndexHtml :: Path Rel File
relFileHpcIndexHtml = $(mkRelFile "hpc_index.html")
relDirCustom :: Path Rel Dir
relDirCustom = $(mkRelDir "custom")
relDirPackageConfInplace :: Path Rel Dir
relDirPackageConfInplace = $(mkRelDir "package.conf.inplace")
relDirExtraTixFiles :: Path Rel Dir
relDirExtraTixFiles = $(mkRelDir "extra-tix-files")
relDirInstalledPackages :: Path Rel Dir
relDirInstalledPackages = $(mkRelDir "installed-packages")
backupUrlRelPath :: Path Rel File
backupUrlRelPath = $(mkRelFile "downloaded.template.file.hsfiles")
relDirDotLocal :: Path Rel Dir
relDirDotLocal = $(mkRelDir ".local")
relDirDotSsh :: Path Rel Dir
relDirDotSsh = $(mkRelDir ".ssh")
relDirDotStackProgName :: Path Rel Dir
relDirDotStackProgName = $(mkRelDir ('.' : stackProgName))
relDirUnderHome :: Path Rel Dir
relDirUnderHome = $(mkRelDir "_home")
relDirSrc :: Path Rel Dir
relDirSrc = $(mkRelDir "src")
relFileLibtinfoSo5 :: Path Rel File
relFileLibtinfoSo5 = $(mkRelFile "libtinfo.so.5")
relFileLibtinfoSo6 :: Path Rel File
relFileLibtinfoSo6 = $(mkRelFile "libtinfo.so.6")
relFileLibncurseswSo6 :: Path Rel File
relFileLibncurseswSo6 = $(mkRelFile "libncursesw.so.6")
relFileLibgmpSo10 :: Path Rel File
relFileLibgmpSo10 = $(mkRelFile "libgmp.so.10")
relFileLibgmpSo3 :: Path Rel File
relFileLibgmpSo3 = $(mkRelFile "libgmp.so.3")
relDirNewCabal :: Path Rel Dir
relDirNewCabal = $(mkRelDir "new-cabal")
relFileSetupExe :: Path Rel File
relFileSetupExe = $(mkRelFile "Setup.exe")
relFileSetupUpper :: Path Rel File
relFileSetupUpper = $(mkRelFile "Setup")
relFile7zexe :: Path Rel File
relFile7zexe = $(mkRelFile "7z.exe")
relFile7zdll :: Path Rel File
relFile7zdll = $(mkRelFile "7z.dll")
relFileMainHs :: Path Rel File
relFileMainHs = $(mkRelFile "Main.hs")
relFileStackDotExe :: Path Rel File
relFileStackDotExe = $(mkRelFile "stack.exe")
relFileStackDotTmpDotExe :: Path Rel File
relFileStackDotTmpDotExe = $(mkRelFile "stack.tmp.exe")
relFileStackDotTmp :: Path Rel File
relFileStackDotTmp = $(mkRelFile "stack.tmp")
relFileStack :: Path Rel File
relFileStack = $(mkRelFile "stack")
-- Technically, we should be consulting the user's current ghc,
-- but that would require loading up a BuildConfig.
ghcShowOptionsOutput :: [String]
ghcShowOptionsOutput =
$(TH.runIO (readProcess "ghc" ["--show-options"] "") >>= TH.lift . lines)
-- | Relative path inside a GHC repo to the Hadrian build batch script
hadrianCmdWindows :: Path Rel File
hadrianCmdWindows = $(mkRelFile "hadrian/build.stack.bat")
-- | Relative path inside a GHC repo to the Hadrian build shell script
hadrianCmdPosix :: Path Rel File
hadrianCmdPosix = $(mkRelFile "hadrian/build.stack.sh")
-- | Used in Stack.Setup for detecting libtinfo, see comments at use site
usrLibDirs :: [Path Abs Dir]
#if WINDOWS
usrLibDirs = []
#else
usrLibDirs = [$(mkAbsDir "/usr/lib"),$(mkAbsDir "/usr/lib64")]
#endif
-- | Relative file path for a temporary GHC environment file for tests
testGhcEnvRelFile :: Path Rel File
testGhcEnvRelFile = $(mkRelFile "test-ghc-env")
-- | File inside a dist directory to use for locking
relFileBuildLock :: Path Rel File
relFileBuildLock = $(mkRelFile "build-lock")
-- | What should the default be for stack-developer-mode
stackDeveloperModeDefault :: Bool
stackDeveloperModeDefault = STACK_DEVELOPER_MODE_DEFAULT
| juhp/stack | src/Stack/Constants.hs | bsd-3-clause | 16,161 | 0 | 12 | 2,641 | 3,073 | 1,673 | 1,400 | 385 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Data.SBV.Examples.Puzzles.Counts
-- Copyright : (c) Levent Erkok
-- License : BSD3
-- Maintainer : [email protected]
-- Stability : experimental
--
-- Consider the sentence:
--
-- @
-- In this sentence, the number of occurrences of 0 is _, of 1 is _, of 2 is _,
-- of 3 is _, of 4 is _, of 5 is _, of 6 is _, of 7 is _, of 8 is _, and of 9 is _.
-- @
--
-- The puzzle is to fill the blanks with numbers, such that the sentence
-- will be correct. There are precisely two solutions to this puzzle, both of
-- which are found by SBV successfully.
--
-- References:
--
-- * Douglas Hofstadter, Metamagical Themes, pg. 27.
--
-- * <http://mathcentral.uregina.ca/mp/archives/previous2002/dec02sol.html>
--
-----------------------------------------------------------------------------
module Data.SBV.Examples.Puzzles.Counts where
import Data.SBV
-- | We will assume each number can be represented by an 8-bit word, i.e., can be at most 128.
type Count = SWord8
-- | Given a number, increment the count array depending on the digits of the number
count :: Count -> [Count] -> [Count]
count n cnts = ite (n .< 10)
(upd n cnts) -- only one digit
(ite (n .< 100)
(upd d1 (upd d2 cnts)) -- two digits
(upd d1 (upd d2 (upd d3 cnts)))) -- three digits
where (r1, d1) = n `sQuotRem` 10
(d3, d2) = r1 `sQuotRem` 10
upd d = zipWith inc [0..]
where inc i c = ite (i .== d) (c+1) c
-- | Encoding of the puzzle. The solution is a sequence of 10 numbers
-- for the occurrences of the digits such that if we count each digit,
-- we find these numbers.
puzzle :: [Count] -> SBool
puzzle cnt = cnt .== last css
where ones = replicate 10 1 -- all digits occur once to start with
css = ones : zipWith count cnt css
-- | Finds all two known solutions to this puzzle. We have:
--
-- >>> counts
-- Solution #1
-- In this sentence, the number of occurrences of 0 is 1, of 1 is 7, of 2 is 3, of 3 is 2, of 4 is 1, of 5 is 1, of 6 is 1, of 7 is 2, of 8 is 1, of 9 is 1.
-- Solution #2
-- In this sentence, the number of occurrences of 0 is 1, of 1 is 11, of 2 is 2, of 3 is 1, of 4 is 1, of 5 is 1, of 6 is 1, of 7 is 1, of 8 is 1, of 9 is 1.
-- Found: 2 solution(s).
counts :: IO ()
counts = do res <- allSat $ puzzle `fmap` mkExistVars 10
cnt <- displayModels disp res
putStrLn $ "Found: " ++ show cnt ++ " solution(s)."
where disp n (_, s) = do putStrLn $ "Solution #" ++ show n
dispSolution s
dispSolution :: [Word8] -> IO ()
dispSolution ns = putStrLn soln
where soln = "In this sentence, the number of occurrences"
++ " of 0 is " ++ show (ns !! 0)
++ ", of 1 is " ++ show (ns !! 1)
++ ", of 2 is " ++ show (ns !! 2)
++ ", of 3 is " ++ show (ns !! 3)
++ ", of 4 is " ++ show (ns !! 4)
++ ", of 5 is " ++ show (ns !! 5)
++ ", of 6 is " ++ show (ns !! 6)
++ ", of 7 is " ++ show (ns !! 7)
++ ", of 8 is " ++ show (ns !! 8)
++ ", of 9 is " ++ show (ns !! 9)
++ "."
{-# ANN counts ("HLint: ignore Use head" :: String) #-}
| josefs/sbv | Data/SBV/Examples/Puzzles/Counts.hs | bsd-3-clause | 3,507 | 0 | 31 | 1,156 | 636 | 349 | 287 | 38 | 1 |
import qualified System.IO.Streams.Lzma as LZMA
import qualified System.IO.Streams as Streams
import Test.Framework
import Test.Framework.Providers.HUnit
import Test.Framework.Providers.QuickCheck2
import Test.HUnit hiding (Test)
import qualified Data.ByteString as BS
import System.IO.Unsafe
main :: IO ()
main = defaultMain [ testGroup "System.IO.Streams.Lzma" tests ]
where
tests = [ test0, test1, test2, prop1, prop2 ]
test0 :: Test
test0 = testCase "empty" $ (decode . encode) BS.empty @?= BS.empty
test1 :: Test
test1 = testCase "hello" $ (decode . encode) bs @?= bs
where
bs = BS.pack [104,101,108,108,111]
test2 :: Test
test2 = testCase "10MiB" $ (decode . encode) bs @?= bs
where
bs = BS.replicate (10*1024*1024) 0xaa
prop1 :: Test
prop1 = testProperty "random" go
where
go s = (decode . encode) bs == bs
where
bs = BS.pack s
prop2 :: Test
prop2 = testProperty "random-concat" go
where
go s s2 = decode (encode bs `BS.append` encode bs2) == bs `BS.append` bs2
where
bs = BS.pack s
bs2 = BS.pack s2
encode :: BS.ByteString -> BS.ByteString
encode bs = unsafePerformIO $ do
lst <- Streams.outputToList $ \obs -> do
ibs <- Streams.fromByteString bs
obs' <- LZMA.compress obs
Streams.connect ibs obs'
return (BS.concat lst)
{-# NOINLINE encode #-}
decode :: BS.ByteString -> BS.ByteString
decode bs = unsafePerformIO $ do
lst <- Streams.outputToList $ \obs -> do
ibs <- Streams.fromByteString bs
ibs' <- LZMA.decompress ibs
Streams.connect ibs' obs
return (BS.concat lst)
{-# NOINLINE decode #-}
| hvr/lzma-streams | src-tests/lzma-streams-test.hs | bsd-3-clause | 1,712 | 0 | 15 | 440 | 577 | 305 | 272 | 44 | 1 |
{-# LANGUAGE OverloadedStrings #-}
-----------------------------------------------------------------------------
-- |
-- Copyright : (c) 2014 Ricky Elrod
-- License : BSD3
--
-- Maintainer : Ricky Elrod <[email protected]>
-- Stability : experimental
--
-- Provides functions and datatypes for searching Fedora Packages.
----------------------------------------------------------------------------
module Fedora.Packages.Search
( Package (..)
, Subpackage (..)
, SearchFilter (..)
, packageInfo
, search
) where
import Fedora.Packages.API
import Fedora.Packages.Config
import Control.Applicative
import Control.Monad (mzero)
import Data.Aeson
import qualified Data.ByteString.Lazy as LS
import Data.Maybe (listToMaybe)
import Data.Monoid
import qualified Data.Text as T
data SearchFilter = SearchFilter {
_sfSearch :: T.Text
} deriving (Eq, Show)
instance ToJSON SearchFilter where
toJSON (SearchFilter s) = object [ "search" .= s ]
data Package = Package {
_develOwner :: T.Text
, _icon :: T.Text
, _link :: T.Text
, _name :: T.Text
, _subPackages :: Maybe [Subpackage]
, _summary :: T.Text
, _upstreamUrl :: T.Text
, _description :: T.Text
} deriving (Eq, Show)
instance FromJSON Package where
parseJSON (Object v) = Package <$>
v .: "devel_owner"
<*> v .: "icon"
<*> v .: "link"
<*> v .: "name"
<*> v .: "sub_pkgs"
<*> v .: "summary"
<*> v .: "upstream_url"
<*> v .: "description"
parseJSON _ = mzero
data Subpackage = Subpackage {
_subIcon :: T.Text
, _subLink :: T.Text
, _subName :: T.Text
, _subSummary :: T.Text
, _subDescription :: T.Text
} deriving (Eq, Show)
instance FromJSON Subpackage where
parseJSON (Object v) = Subpackage <$>
v .: "icon"
<*> v .: "link"
<*> v .: "name"
<*> v .: "summary"
<*> v .: "description"
parseJSON _ = mzero
-- | Search Fedora Packages for a given pattern.
search :: PackagesConfig -- ^ The configuration to use.
-> Query SearchFilter -- ^ The search query to send.
-> IO (StandardResults Package)
search c s =
apiGet ("xapian/query/search_packages/" <> LS.toStrict (encode s)) c
-- | Search Fedora Packages and return the package if an exact one is found.
packageInfo :: PackagesConfig -> T.Text -> IO (Maybe Package)
packageInfo c q = do
s <- search c (Query (SearchFilter q) 1 0)
let rows = _srRows s
matches = filter (\x -> _name x == q) rows
in
return $ listToMaybe matches
| relrod/fedora-packages-hs | src/Fedora/Packages/Search.hs | bsd-3-clause | 2,830 | 0 | 21 | 870 | 656 | 366 | 290 | 68 | 1 |
module Rabbit
( bindHandlers
, echoToSlack
, doRpc
, logQ
, rpcQ
, runRabbit
, rpcDownload
) where
import Control.Monad.IO.Class (liftIO)
import Control.Monad.Reader (asks)
import qualified Data.ByteString.Lazy.Char8 as BC
import Data.Monoid ((<>))
import qualified Data.Text as T
import Data.Text.Lazy (fromStrict)
import Data.Text.Lazy.Encoding (encodeUtf8)
import Network.AMQP hiding (Channel, Message)
import qualified Network.AMQP as AMQP
import Network.URI (unEscapeString)
import Types
import qualified Slack
import Download (doDownload)
import Util (pprint)
rpcQ, logQ, downloadQ :: Queue
rpcQ = "rpc"
logQ = "log"
downloadQ = "download"
runRabbit :: RabbitConf -> IO AMQP.Channel
runRabbit RabbitConf{..} = do
conn <- openConnection rabbitHost rabbitVHost rabbitUser rabbitPass
chan <- openChannel conn
declareExchange chan newExchange
{ exchangeName = "notifications"
, exchangeType = "topic"
, exchangeDurable = True
}
_ <- declareQueue chan newQueue { queueName = logQ, queueDurable = False }
bindQueue chan logQ "notifications" "#"
_ <- declareQueue chan newQueue { queueName = downloadQ, queueDurable = True }
bindQueue chan downloadQ "notifications" "download"
_ <- declareQueue chan newQueue { queueName = "rpc", queueDurable = False }
bindQueue chan "rpc" "notifications" "rpc.#"
return chan
replyTo :: AMQP.Channel -> AMQP.Message -> BC.ByteString -> IO ()
replyTo chan msg body = case msgReplyTo msg of
Nothing -> return ()
Just rt -> publishMsg chan "" rt $
newMsg { msgBody = body, msgCorrelationID = msgCorrelationID msg }
bindHandlers :: (Z () -> IO ()) -> AMQP.Channel -> [ (Queue, RabbitHandler) ] -> IO ()
bindHandlers runIO chan hs = mapM_ bindOne hs
where
bindOne (q,h) = consumeMsgs chan q Ack $ \(msg, env) -> do
runIO $ h (envRoutingKey env) msg (msgBody msg)
ackEnv env
doRpc :: RabbitHandler
doRpc k m payload = do
ch <- asks rabbitChannel
let reply = liftIO . replyTo ch m
case k of
"rpc.ping" -> do
name <- asks botName
reply $ "pong (" <> (BC.pack $ T.unpack name) <> ")"
"rpc.download" -> do
doDownload payload
reply $ "Downloading " <> payload
other -> Slack.debug $ "Unknown RPC key - " <> other
echoToSlack :: RabbitHandler
echoToSlack k _ body = do
let body' = T.pack . BC.unpack . pprint $ body
msg = "*" <> k <> "*\n```" <> body' <> "```\n"
Slack.debug msg
rpcDownload :: T.Text -> Z ()
rpcDownload link = do
chan <- asks rabbitChannel
liftIO $ publishMsg chan "notifications" "rpc.download"
-- TODO: ugh
newMsg { msgBody = encodeUtf8 . fromStrict . T.pack . unEscapeString . T.unpack $ link
, msgDeliveryMode = Just Persistent
}
| jamesdabbs/zorya | src/Rabbit.hs | bsd-3-clause | 2,982 | 0 | 17 | 812 | 915 | 482 | 433 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS -fno-warn-unused-do-bind #-}
module Blaze.Html5
(-- * Re-exports
module Text.Blaze
, module Text.Blaze.Html5
, module Text.Blaze.Html5.Attributes
-- * Wrapper for class attribute
, ClassAttributeValue(..)
, toClassValue
-- * Attribute combinators
, (!.)
, (!#)
-- * Common operations
-- ** Linking
, css
, js
, linkTo
-- ** Forms
, postForm
-- ** Intercalation
, linesToHtml
, htmlIntercalate
, htmlCommasAnd
, htmlCommas
) where
import Data.String (IsString,fromString)
import Data.Monoid
import Text.Blaze
import Text.Blaze.Html5 hiding (map,style,title)
import qualified Text.Blaze.Html5.Attributes as A
import Text.Blaze.Html5.Attributes hiding (span,label,cite,form,summary,min)
import Text.Blaze.Internal (Attributable,stringValue)
-- | Class attribute.
(!.) :: (Attributable h) => h -> ClassAttributeValue -> h
e !. classes = e ! class_ (unClassAttributeValue classes)
-- | Id attribute.
(!#) :: (Attributable h) => h -> AttributeValue -> h
e !# idName = e ! A.id idName
-- | The html class attribute can have one or more space separated tokens.
-- @ClassAttributeValues@ are instances of @Monoid@ and therefore can be combined
-- with each other. Combined tokens are space separated. That allows more
-- flexible usage of predefined class tokens.
--
-- Example (uses blaze-bootstrap):
--
-- > div !. (md6 <> sm12) $ "Example"
--
-- Result:
--
-- > <div class="col-md-6 col-sm-12">Example</div>
newtype ClassAttributeValue =
ClassAttributeValue { unClassAttributeValue :: AttributeValue }
instance IsString ClassAttributeValue where
fromString = ClassAttributeValue . fromString
instance Monoid ClassAttributeValue where
mempty = ClassAttributeValue mempty
mappend (ClassAttributeValue c1) (ClassAttributeValue c2) =
ClassAttributeValue $ c1 <> stringValue " " <> c2
toClassValue :: ToValue a => a -> ClassAttributeValue
toClassValue = ClassAttributeValue . toValue
-- | Render the lines as HTML lines.
linesToHtml :: [Html] -> Html
linesToHtml = htmlIntercalate br
-- | Intercalate the given things.
htmlIntercalate :: Html -> [Html] -> Html
htmlIntercalate _ [x] = x
htmlIntercalate sep (x:xs) = do x; sep; htmlIntercalate sep xs
htmlIntercalate _ [] = mempty
-- | Show some HTML comma-separated with “and” inbetween to be grammatical.
htmlCommasAnd :: [Html] -> Html
htmlCommasAnd [x] = x
htmlCommasAnd [x,y] = do x; " and "; y
htmlCommasAnd (x:xs) = do x; ", "; htmlCommasAnd xs
htmlCommasAnd [] = mempty
-- | Comma-separate some HTML.
htmlCommas :: [Html] -> Html
htmlCommas = htmlIntercalate ", "
-- | Link to a CSS stylesheet.
css :: AttributeValue -> Html
css uri = link ! rel "stylesheet" ! type_ "text/css" ! href uri
-- | Link to a javascript file.
js :: AttributeValue -> Html
js uri = script ! type_ "text/javascript" ! src uri $ mempty
-- | Create a link.
linkTo :: AttributeValue -> Html -> Html
linkTo url = a ! href url
-- | Create a form with method = \"POST\" that posts to the given url.
postForm :: String -> Html -> Html
postForm uri = form ! action (toValue uri) ! method "post"
| zudov/blaze | src/Blaze/Html5.hs | bsd-3-clause | 3,215 | 4 | 9 | 624 | 744 | 425 | 319 | 61 | 1 |
{-# LANGUAGE TemplateHaskell #-}
-- | The @member@ element of a OSM file.
module Data.Geo.OSM.Member
(
Member
, member
) where
import Text.XML.HXT.Arrow.Pickle
import Data.Geo.OSM.MemberType
import Data.Geo.OSM.Lens.TypeL
import Data.Geo.OSM.Lens.RefL
import Data.Geo.OSM.Lens.RoleL
import Control.Lens.TH
-- | The @member@ element of a OSM file.
data Member = Member {
_memberType :: MemberType,
_memberRef :: String,
_memberRole :: String
} deriving Eq
makeLenses ''Member
instance XmlPickler Member where
xpickle =
xpElem "member" (xpWrap (\(mtype', mref', mrole') -> member mtype' mref' mrole', \(Member mtype' mref' mrole') -> (mtype', mref', mrole'))
(xpTriple xpickle (xpAttr "ref" xpText) (xpAttr "role" xpText0)))
instance Show Member where
show =
showPickled []
instance TypeL Member where
typeL = memberType
instance RefL Member where
refL = memberRef
instance RoleL Member where
roleL = memberRole
-- | Constructs a member with a type, ref and role.
member ::
MemberType -- ^ The member @type@ attribute.
-> String -- ^ The member @ref@ attribute.
-> String -- ^ The member @role@ attribute.
-> Member
member =
Member
| tonymorris/geo-osm | src/Data/Geo/OSM/Member.hs | bsd-3-clause | 1,196 | 0 | 12 | 230 | 288 | 171 | 117 | 37 | 1 |
module Text.Keepalived
( -- * Module imports
module Text.Keepalived.Parser
, module Text.Keepalived.Lexer
, module Text.Keepalived.Types
-- * Helper functions
, parseFromFile
, parseString
) where
import Text.Keepalived.Parser
import Text.Keepalived.Lexer
import Text.Keepalived.Types
import Data.Either
import Text.Parsec hiding (tokens)
import System.Directory
import System.FilePath
parseFromFile :: FilePath -> IO KeepalivedConf
parseFromFile f = do
cwd <- getCurrentDirectory
input <- readFile f
toks <- runLexer tokens (cwd </> f) input
case toks of
Right toks' -> do
case runParser pKeepalivedConf () "" toks' of
Right x -> return x
Left err -> error $ show err
Left err -> error $ show err
parseString :: String -> IO KeepalivedConf
parseString s = do
toks <- runLexer tokens "" s
case toks of
Right toks' -> do
case runParser pKeepalivedConf () "" toks' of
Right x -> return x
Left err -> error $ show err
Left err -> error $ show err
| maoe/text-keepalived | src/Text/Keepalived.hs | bsd-3-clause | 1,045 | 0 | 16 | 249 | 329 | 165 | 164 | 34 | 3 |
main = interact shortLinesOnly
-- 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 | randallalexander/LYAH | src/Ch9/shortlines.hs | bsd-3-clause | 319 | 0 | 13 | 77 | 76 | 39 | 37 | 7 | 1 |
{-# LANGUAGE ScopedTypeVariables, BangPatterns, GADTs, FlexibleContexts,
FlexibleInstances, TypeFamilies, NoMonomorphismRestriction #-}
module HEP.Parser.LHCOAnalysis.Analysis where
import HEP.Parser.LHCOAnalysis.PhysObj
import Debug.Trace
import qualified Data.ListLike as LL
import qualified Data.Iteratee as Iter
-- import HROOT
import Control.Monad
import Control.Monad.IO.Class
type EventCountIO a = Iter.Iteratee [PhyEventClassified] IO a
type EventAnalysisFunc = PhyEventClassified -> Maybe Double
iter_count_total_event :: EventCountIO Int
iter_count_total_event = Iter.length
iter_count_marker :: Int -> Int -> EventCountIO ()
iter_count_marker num start = do
h <- Iter.peek
case h of
Nothing -> return ()
Just _ -> if start `mod` num == 0
then do liftIO $ putStrLn (" data : " ++ show start)
Iter.head
iter_count_marker num (start+1)
else do Iter.head
iter_count_marker num (start+1)
iter_io :: (a -> IO ()) -> (PhyEventClassified -> Maybe a) -> EventCountIO ()
iter_io action func = do
h <- Iter.peek
case h of
Nothing -> return ()
Just x -> do
let fx = func x
case fx of
Nothing -> do Iter.head
iter_io action func
Just val -> do liftIO $ action val
Iter.head
iter_io action func
{-
iter_hist1 :: TH1F -> EventAnalysisFunc -> EventCountIO ()
iter_hist1 hist func = do
h <- Iter.peek
case h of
Nothing -> return ()
Just x -> do
let fx = func x
case fx of
Nothing -> do Iter.head
iter_hist1 hist func
Just val -> do liftIO $ do fill hist val
-- putStrLn "one event passed"
Iter.head
iter_hist1 hist func
iter_hist2 :: TH2F ->
(PhyEventClassified -> Maybe (Double,Double))
-> EventCountIO ()
iter_hist2 hist func = do
h <- Iter.peek
case h of
Nothing -> return ()
Just x -> do
let fx = func x
case fx of
Nothing -> do Iter.head
iter_hist2 hist func
Just val -> do liftIO $ do fill hist val
-- putStrLn "one event passed"
Iter.head
iter_hist2 hist func
-}
| wavewave/LHCOAnalysis | trash/Analysis.hs | bsd-3-clause | 2,571 | 0 | 18 | 1,004 | 396 | 201 | 195 | 37 | 3 |
module Logo.Evaluator where
import Logo.Types
import qualified Data.Map as M
import Control.Monad (replicateM)
import Control.Applicative ((<$>), (<|>))
import Control.Arrow ((&&&), (***))
import Control.Monad.Trans (lift)
import Text.Parsec.Prim (runParserT, tokenPrim, getState, putState, modifyState)
import Text.Parsec.Combinator (many1, choice, chainl1)
import Text.Parsec.Error (ParseError)
-- ----------------------------------------------------------------------
-- Expression Evaluation
-- ----------------------------------------------------------------------
-- Expression := RelationalExpression
-- RelationalExpression := AdditiveExpression [ ( '=' | '<' | '>' | '<=' | '>=' | '<>' ) AdditiveExpression ... ]
-- AdditiveExpression := MultiplicativeExpression [ ( '+' | '-' ) MultiplicativeExpression ... ]
-- MultiplicativeExpression := PowerExpression [ ( '*' | '/' | '%' ) PowerExpression ... ]
-- PowerExpression := UnaryExpression [ '^' UnaryExpression ]
-- UnaryExpression := ( '-' ) UnaryExpression
-- | FinalExpression
-- FinalExpression := string-literal
-- | number-literal
-- | list
-- | variable-reference
-- | procedure-call
-- | '(' Expression ')'
evaluateWithContext :: [LogoToken] -> LogoContext -> TurtleIO (Either ParseError ([LogoToken], LogoContext))
evaluateWithContext tokens ctx = runParserT expression ctx "(stream)" tokens
evaluateTokens :: [LogoToken] -> LogoEvaluator LogoToken
evaluateTokens [] = return $ StrLiteral ""
evaluateTokens tokens = do
ctx <- getState
(t,s) <- lift $ do
res <- evaluateWithContext tokens ctx
case res of
Left e -> error $ show e
Right r -> return r
putState s
return $ LogoList t
satisfy :: (LogoToken -> Bool) -> LogoEvaluator LogoToken
satisfy f =
tokenPrim (\c -> show [c])
(\pos _ _ -> pos)
(\c -> if f c then Just c else Nothing)
logoToken :: LogoToken -> LogoEvaluator LogoToken
logoToken x = satisfy (==x)
anyLogoToken :: LogoEvaluator LogoToken
anyLogoToken = satisfy (const True)
expression :: LogoEvaluator ([LogoToken], LogoContext)
expression = do
t <- many1 relationalExpression
s <- getState
return (t,s)
relationalExpression :: LogoEvaluator LogoToken
relationalExpression = parseWithOperators ["<", ">", "=", "<=", ">=", "<>"] additiveExpression
additiveExpression :: LogoEvaluator LogoToken
additiveExpression = parseWithOperators ["+", "-"] multiplicativeExpression
multiplicativeExpression :: LogoEvaluator LogoToken
multiplicativeExpression = parseWithOperators ["*", "/", "%"] powerExpression
powerExpression :: LogoEvaluator LogoToken
powerExpression = parseWithOperators ["^"] finalExpression
finalExpression :: LogoEvaluator LogoToken
finalExpression = anyLogoToken >>= evalFinal
evalFinal, evalList, eval :: LogoToken -> LogoEvaluator LogoToken
evalFinal (Identifier s) = dispatchFn s
evalFinal (VarLiteral v) = lookupVar v
evalFinal (LogoExpr e) = do
LogoList res <- evaluateTokens e
return $ head res
evalFinal token = return token
evalList (LogoList l) = evaluateTokens l
evalList _ = undefined
-- Forces evaluation of a token, even if it is a list
eval token = case token of
LogoList _ -> evalList token
_ -> evalFinal token
parseWithOperators :: [String] -> LogoEvaluator LogoToken -> LogoEvaluator LogoToken
parseWithOperators operators parser = parser `chainl1` func
where
func = do op <- choice $ map (logoToken . OperLiteral) operators
return $ evalBinOp op
evalBinOp :: LogoToken -> LogoToken -> LogoToken -> LogoToken
-- Arithmetic
evalBinOp (OperLiteral "+") (NumLiteral l) (NumLiteral r) = NumLiteral (l + r)
evalBinOp (OperLiteral "-") (NumLiteral l) (NumLiteral r) = NumLiteral (l - r)
evalBinOp (OperLiteral "*") (NumLiteral l) (NumLiteral r) = NumLiteral (l * r)
evalBinOp (OperLiteral "/") (NumLiteral l) (NumLiteral r) = NumLiteral (l / r)
evalBinOp (OperLiteral "%") (NumLiteral l) (NumLiteral r) = NumLiteral $ fromIntegral ((truncate l `rem` truncate r) :: Integer )
evalBinOp (OperLiteral "^") (NumLiteral l) (NumLiteral r) = NumLiteral (l ** r)
-- Logical
evalBinOp (OperLiteral "<") (NumLiteral l) (NumLiteral r) = StrLiteral (if l < r then "TRUE" else "FALSE")
evalBinOp (OperLiteral ">") (NumLiteral l) (NumLiteral r) = StrLiteral (if l > r then "TRUE" else "FALSE")
evalBinOp (OperLiteral "=") (NumLiteral l) (NumLiteral r) = StrLiteral (if l == r then "TRUE" else "FALSE")
evalBinOp (OperLiteral "<>") (NumLiteral l) (NumLiteral r) = StrLiteral (if l /= r then "TRUE" else "FALSE")
evalBinOp (OperLiteral "<=") (NumLiteral l) (NumLiteral r) = StrLiteral (if l <= r then "TRUE" else "FALSE")
evalBinOp (OperLiteral ">=") (NumLiteral l) (NumLiteral r) = StrLiteral (if l >= r then "TRUE" else "FALSE")
-- Undefined
evalBinOp op a b = error $ "Evaluation undefined for " ++ show [op, a, b]
setLocals :: LogoSymbolTable -> LogoEvaluator ()
setLocals l = modifyState $ \s -> s { locals = l }
getLocals :: LogoEvaluator LogoSymbolTable
getLocals = locals <$> getState
evaluateInLocalContext :: LogoSymbolTable -> LogoEvaluator a -> LogoEvaluator a
evaluateInLocalContext localVars computation = do
old <- getLocals
setLocals $ localVars `M.union` old
res <- computation
setLocals old
return res
lookupVar :: String -> LogoEvaluator LogoToken
lookupVar v = do
(l,g) <- (M.lookup v *** M.lookup v) . (locals &&& globals) <$> getState
case l <|> g of
Just x -> return x
_ -> error $ "variable " ++ v ++ " not in scope"
dispatchFn :: String -> LogoEvaluator LogoToken
dispatchFn fn = do
-- get function definition
ctx <- getState
let fns = functions ctx
f = case M.lookup fn fns of
Just x -> x
_ -> error ("Function undefined: " ++ fn)
-- find arity
let (LogoFunctionDef a func) = f
-- get number of tokens
-- FIXME evaludate the token before getting a list of expressions
arguments <- replicateM a relationalExpression
-- call function and update context
func arguments
| deepakjois/hs-logo | src/Logo/Evaluator.hs | bsd-3-clause | 6,225 | 0 | 15 | 1,275 | 1,816 | 945 | 871 | 104 | 7 |
-- 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.
module Duckling.Dimensions.Tests
( tests
) where
import Data.String
import Prelude
import Test.Tasty
import qualified Duckling.AmountOfMoney.Tests as AmountOfMoney
import qualified Duckling.CreditCardNumber.Tests as CreditCardNumber
import qualified Duckling.Distance.Tests as Distance
import qualified Duckling.Duration.Tests as Duration
import qualified Duckling.Email.Tests as Email
import qualified Duckling.Numeral.Tests as Numeral
import qualified Duckling.Ordinal.Tests as Ordinal
import qualified Duckling.PhoneNumber.Tests as PhoneNumber
import qualified Duckling.Quantity.Tests as Quantity
import qualified Duckling.Temperature.Tests as Temperature
import qualified Duckling.Time.Tests as Time
import qualified Duckling.Volume.Tests as Volume
import qualified Duckling.Url.Tests as Url
tests :: TestTree
tests = testGroup "Dimensions Tests"
[ AmountOfMoney.tests
, CreditCardNumber.tests
, Distance.tests
, Duration.tests
, Email.tests
, Numeral.tests
, Ordinal.tests
, PhoneNumber.tests
, Quantity.tests
, Temperature.tests
, Time.tests
, Volume.tests
, Url.tests
]
| facebookincubator/duckling | tests/Duckling/Dimensions/Tests.hs | bsd-3-clause | 1,319 | 0 | 7 | 184 | 227 | 159 | 68 | 33 | 1 |
{- | Module : ./GMP/GMP-CoLoSS/GMP/Logics/DisjUnion.hs
- Description : Implementation of logic instance of disjoint union of features
- Copyright : (c) Daniel Hausmann & Georgel Calin & Lutz Schroeder, DFKI Lab Bremen,
- Rob Myers & Dirk Pattinson, Department of Computing, ICL
- License : GPLv2 or higher, see LICENSE.txt
- Maintainer : [email protected]
- Stability : provisional
- Portability : portable
-
- Provides the implementation of the matching functions of disjoint union of features.
-}
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses, FlexibleContexts #-}
module GMP.Logics.DisjUnion where
import Data.List
import Data.Ratio
import Data.Maybe
import Debug.Trace
import Text.ParserCombinators.Parsec
import GMP.Logics.Generic
import GMP.Parser
{- ------------------------------------------------------------------------------
instance of feature for Disjoint union of features
------------------------------------------------------------------------------ -}
data DisjUnion a b c = DisjUnion (a c, b c) deriving (Eq, Ord, Show)
instance (Feature a (c (d e)), Feature b (c (d e)), Eq (a (c (d e))),
Eq (b (c (d e))), SigFeature c d e, Eq (d e)) =>
NonEmptyFeature (DisjUnion a b) c d e where
nefMatch flags seq =
let fstposlits = [ Mod p | Mod (DisjUnion (p, q)) <- seq ]
fstneglits = [ Neg (Mod p) | Neg (Mod (DisjUnion (p, q))) <- seq ]
sndposlits = [ Mod q | Mod (DisjUnion (p, q)) <- seq ]
sndneglits = [ Neg (Mod q) | Neg (Mod (DisjUnion (p, q))) <- seq ]
in if flags !! 1
then trace ("\n [+-matching this:] " ++ pretty_list seq) $
[[Sequent (fstposlits ++ fstneglits)]] :
[[[Sequent (sndposlits ++ sndneglits)]]]
else [[Sequent (fstposlits ++ fstneglits)]] :
[[[Sequent (sndposlits ++ sndneglits)]]]
nefPretty d = case d of
DisjUnion (p, q) -> "[DisjUnion](" ++ fPretty p ++ fPretty q ++ ")"
nefDisj2Conj (Mod (DisjUnion (p, q))) =
Mod (DisjUnion ((\ (Mod phi) -> phi) (fDisj2Conj (Mod p)),
(\ (Mod phi) -> phi) (fDisj2Conj (Mod q))))
nefNegNorm (Mod (DisjUnion (p, q))) =
Mod (DisjUnion ((\ (Mod phi) -> phi) (fNegNorm (Mod p)),
(\ (Mod phi) -> phi) (fNegNorm (Mod q))))
nefFeatureFromSignature (DisjUnion (p, q)) phi =
DisjUnion (fFeatureFromSignature p phi,
fFeatureFromSignature q phi)
nefStripFeature (DisjUnion (p, q)) = fStripFeature p
nefParser (DisjUnion (p, q)) = return (\ (phi : psi : _) ->
DisjUnion (fFeatureFromSignature p [phi],
fFeatureFromSignature q [psi]))
nefSeparator sig = "+"
nefFeatureFromFormula = error $ "nefFeatureFromFormula is not implemented " ++
"for instance NonEmptyFeature (DisjUnion a b) c d e"
{- ------------------------------------------------------------------------------
instance of sigFeature for disjoint union of features
------------------------------------------------------------------------------ -}
instance (Eq (b (c (d e))), Eq (a (c (d e))), Feature b (c (d e)), Feature a (c (d e)),
SigFeature c d e, Eq (d e)) => NonEmptySigFeature (DisjUnion a b) c d e where
neGoOn = genericPGoOn
| spechub/Hets | GMP/GMP-CoLoSS/GMP/Logics/DisjUnion.hs | gpl-2.0 | 3,249 | 0 | 18 | 730 | 1,040 | 549 | 491 | 45 | 0 |
{-# LANGUAGE CPP, GeneralizedNewtypeDeriving #-}
{-
Copyright (C) 2009 Ivan Lazar Miljenovic <[email protected]>
This file is part of SourceGraph.
SourceGraph is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-}
{- |
Module : Parsing.State
Description : State Monad for parsing.
Copyright : (c) Ivan Lazar Miljenovic 2009
License : GPL-3 or later.
Maintainer : [email protected]
Customised State Monad for parsing Haskell code.
-}
module Parsing.State
( PState
, runPState
, get
, put
, getModules
, getModuleNames
, getLookup
, getFutureParsedModule
, getModuleName
) where
import Parsing.Types
import Control.Monad.RWS
#if !(MIN_VERSION_base (4,8,0))
import Control.Applicative (Applicative)
#endif
-- -----------------------------------------------------------------------------
runPState :: ParsedModules -> ModuleNames
-> ParsedModule -> PState a -> ParsedModule
runPState hms mns pm st = pm'
where
-- Tying the knot
el = internalLookup pm'
mp = MD hms mns el pm'
(pm', _) = execRWS (runPS st) mp pm
data ModuleData = MD { moduleLookup :: ParsedModules
, modNmsLookup :: ModuleNames
, entityLookup :: EntityLookup
, futureParsedModule :: ParsedModule
}
type ModuleWrite = ()
newtype PState value
= PS { runPS :: RWS ModuleData ModuleWrite ParsedModule value }
-- Note: don't derive MonadReader, etc. as don't want anything
-- outside this module to get the actual types used.
deriving (Functor, Applicative, Monad, MonadState ParsedModule, MonadWriter ModuleWrite)
asks' :: (ModuleData -> a) -> PState a
asks' = PS . asks
getModules :: PState ParsedModules
getModules = asks' moduleLookup
getModuleNames :: PState ModuleNames
getModuleNames = asks' modNmsLookup
getLookup :: PState EntityLookup
getLookup = asks' entityLookup
getFutureParsedModule :: PState ParsedModule
getFutureParsedModule = asks' futureParsedModule
getModuleName :: PState ModName
getModuleName = gets moduleName
| dzotokan/SourceGraph | Parsing/State.hs | gpl-3.0 | 2,791 | 0 | 9 | 642 | 351 | 198 | 153 | 40 | 1 |
{-
- Copyright (c) 2017 The Agile Monkeys S.L. <[email protected]>
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-}
module Foreign.JQuery where
import GHCJS.Types
import Data.JSString
foreign import javascript unsafe "$($1).val()"
js_getValueFromId :: JSString -> IO JSString
foreign import javascript unsafe "$($1).val($2);"
js_setValueForId :: JSString -> JSString -> IO ()
foreign import javascript unsafe "$($1).html($2);"
js_setHtmlForId :: JSString -> JSString -> IO ()
foreign import javascript unsafe "$($1).show();"
js_show :: JSString -> IO ()
foreign import javascript unsafe "$($1).hide();"
js_hide :: JSString -> IO ()
foreign import javascript unsafe "$($1).effect('shake');"
js_shake :: JSString -> IO ()
-- go through script tags, loading each one in order
-- the deferred object and $.when make sure scripts are executed
-- sequentially
foreign import javascript unsafe "setTimeout(function() { \
var scripts = []; \
$($1).find('script').each(function() { \
var $e = $(this); \
$.when.apply($, scripts).then(function() { \
if ($e.attr('src')) { \
var d = $.Deferred(); \
$.getScript($e.attr('src'), function() { d.resolve() }); \
scripts.push(d); \
} else { \
eval($e.html()); \
} \
}) \
}) \
}, 0);"
js_activateScriptTags :: JSString -> IO ()
foreign import javascript unsafe "setTimeout(function() { $($1).height($($2).height()) }, 0);"
js_setHeightFromElement :: JSString -> JSString -> IO ()
getValueFromId :: String -> IO String
getValueFromId s = do
r <- js_getValueFromId $ pack s
return $ unpack r
setValueForId :: String -> String -> IO ()
setValueForId id' s = js_setValueForId (pack id') (pack s)
setHtmlForId :: String -> String -> IO ()
setHtmlForId id' s = js_setHtmlForId (pack id') (pack s)
activateScriptTags :: String -> IO ()
activateScriptTags id' = js_activateScriptTags (pack id')
setHeightFromElement :: String -> String -> IO ()
setHeightFromElement id' id'' = js_setHeightFromElement (pack id') (pack id'')
show :: String -> IO ()
show = js_show . pack
hide :: String -> IO ()
hide = js_hide . pack
shake :: String -> IO ()
shake = js_shake . pack
| J2RGEZ/haskell-do | src/ghcjs-specific/Foreign/JQuery.hs | apache-2.0 | 3,184 | 80 | 7 | 994 | 693 | 378 | 315 | -1 | -1 |
import Distribution.Simple
import Distribution.Simple.Program.Types
import System.Exit
import System.Process
main = defaultMain
| balangs/eTeak | Setup.hs | bsd-3-clause | 170 | 0 | 4 | 53 | 28 | 17 | 11 | 5 | 1 |
-- Work stealing scheduler and thread pools
--
-- Visibility: HdpH.Internal
-- Author: Patrick Maier <[email protected]>
-- Created: 06 Jul 2011
--
-----------------------------------------------------------------------------
{-# LANGUAGE GeneralizedNewtypeDeriving #-} -- req'd for type 'RTS'
{-# LANGUAGE ScopedTypeVariables #-} -- req'd for type annotations
{-# LANGUAGE FlexibleContexts #-} -- req'd for type annotations
module Control.Parallel.HdpH.Internal.Scheduler
( -- * abstract run-time system monad
RTS, -- instances: Monad, Functor
run_, -- :: RTSConf -> RTS () -> IO ()
liftThreadM, -- :: ThreadM RTS a -> RTS a
liftSparkM, -- :: SparkM RTS a -> RTS a
liftCommM, -- :: CommM a -> RTS a
liftIO, -- :: IO a -> RTS a
-- * converting and executing threads
mkThread, -- :: ParM RTS a -> Thread RTS
execThread, -- :: Thread RTS -> RTS ()
-- * pushing sparks and values
sendPUSH -- :: Spark RTS -> NodeId -> RTS ()
) where
import Prelude hiding (error)
import Control.Concurrent (ThreadId, forkIO, killThread)
import Control.Monad (unless,void,foldM,when,replicateM_,replicateM_)
import Data.Functor ((<$>))
import Data.Maybe (fromJust,isJust)
import Control.Parallel.HdpH.Closure (unClosure,toClosure)
import Control.Parallel.HdpH.Conf (RTSConf(scheds, wakeupDly))
import Control.Parallel.HdpH.Internal.Comm (CommM)
import qualified Control.Parallel.HdpH.Internal.Comm as Comm
(myNode,rmNode,send, receive, run_, waitShutdown)
import qualified Control.Parallel.HdpH.Internal.Data.Deque as Deque (emptyIO)
import qualified Control.Parallel.HdpH.Internal.Data.Sem as Sem (new, signalPeriodically)
import qualified Control.Parallel.HdpH.Internal.Location
as Location (debug)
import Control.Parallel.HdpH.Internal.Location
(dbgStats, dbgMsgSend, dbgMsgRcvd, dbgFailure, error, NodeId)
import Control.Parallel.HdpH.Internal.Misc
(encodeLazy, decodeLazy, ActionServer, newServer, killServer)
import Control.Parallel.HdpH.Internal.Sparkpool
(SparkM, blockSched, putSpark, getSpark,popGuardPostToSparkpool,
dispatch, readPoolSize,readFishSentCtr, readSparkRcvdCtr,
readSparkGenCtr, readMaxSparkCtr,clearFishingFlag,
getSparkRecCtr,getThreadRecCtr,waitingFishingReplyFrom,
incCtr,readSparkRec,readThreadRec,readTaskNotRec)
import qualified Control.Parallel.HdpH.Internal.Sparkpool as Sparkpool (run)
import Control.Parallel.HdpH.Internal.Threadpool
(ThreadM, forkThreadM, stealThread, readMaxThreadCtrs)
import qualified Control.Parallel.HdpH.Internal.Threadpool as Threadpool
(run, liftSparkM, liftCommM, liftIO)
import Control.Parallel.HdpH.Internal.Type.Par
import Control.Parallel.HdpH.Internal.IVar
import Data.IORef
import Control.Parallel.HdpH.Internal.Type.Msg
-----------------------------------------------------------------------------
-- RTS monad
-- The RTS monad hides monad stack (IO, CommM, SparkM, ThreadM) as abstract.
newtype RTS a = RTS { unRTS :: ThreadM RTS a }
deriving (Functor, Monad)
-- Fork a new thread to execute the given 'RTS' action; the integer 'n'
-- dictates how much to rotate the thread pools (so as to avoid contention
-- due to concurrent access).
forkRTS :: Int -> RTS () -> RTS ThreadId
forkRTS n = liftThreadM . forkThreadM n . unRTS
-- Eliminate the whole RTS monad stack down the IO monad by running the given
-- RTS action 'main'; aspects of the RTS's behaviour are controlled by
-- the respective parameters in the given RTSConf.
-- NOTE: This function start various threads (for executing schedulers,
-- a message handler, and various timeouts). On normal termination,
-- all these threads are killed. However, there is no cleanup in the
-- event of aborting execution due to an exception. The functions
-- for doing so (see Control.Execption) all live in the IO monad.
-- Maybe they could be lifted to the RTS monad by using the monad-peel
-- package.
run_ :: RTSConf -> RTS () -> IO ()
run_ conf main = do
let n = scheds conf
unless (n > 0) $
error "HdpH.Internal.Scheduler.run_: no schedulers"
-- allocate n+1 empty thread pools (numbered from 0 to n)
pools <- mapM (\ k -> do { pool <- Deque.emptyIO; return (k,pool) }) [0 .. n]
-- fork nowork server (for clearing the "FISH outstanding" flag on NOWORK)
noWorkServer <- newServer
-- create semaphore for idle schedulers
idleSem <- Sem.new
-- fork wakeup server (periodically waking up racey sleeping scheds)
wakeupServerTid <- forkIO $ Sem.signalPeriodically idleSem (wakeupDly conf)
-- start the RTS
Comm.run_ conf $
Sparkpool.run conf noWorkServer idleSem $
Threadpool.run pools $
unRTS $
rts n noWorkServer wakeupServerTid
where
-- RTS action
rts :: Int -> ActionServer -> ThreadId -> RTS ()
rts schds noWorkServer wakeupServerTid = do
-- fork message handler (accessing thread pool 0)
handlerTid <- forkRTS 0 handler
-- fork schedulers (each accessing thread pool k, 1 <= k <= scheds)
schedulerTids <- mapM (`forkRTS` scheduler) [1 .. schds]
-- run main RTS action
main
-- block waiting for shutdown barrier
liftCommM Comm.waitShutdown
-- print stats
printFinalStats
-- kill nowork server
liftIO $ killServer noWorkServer
-- kill wakeup server
liftIO $ killThread wakeupServerTid
-- kill message handler
liftIO $ killThread handlerTid
-- kill schedulers
liftIO $ mapM_ killThread schedulerTids
-- lifting lower layers
liftThreadM :: ThreadM RTS a -> RTS a
liftThreadM = RTS
liftSparkM :: SparkM RTS a -> RTS a
liftSparkM = liftThreadM . Threadpool.liftSparkM
liftCommM :: CommM a -> RTS a
liftCommM = liftThreadM . Threadpool.liftCommM
liftIO :: IO a -> RTS a
liftIO = liftThreadM . Threadpool.liftIO
-- Return scheduler ID, that is ID of scheduler's own thread pool.
--schedulerID :: RTS Int
--schedulerID = liftThreadM poolID
-----------------------------------------------------------------------------
-- cooperative scheduling
-- Execute the given thread until it blocks or terminates.
execThread :: Thread RTS -> RTS ()
execThread (Atom m) = m >>= maybe (return ()) execThread
-- Try to get a thread from a thread pool or the spark pool and execute it
-- until it blocks or terminates, whence repeat forever; if there is no
-- thread to execute then block the scheduler (ie. its underlying IO thread).
scheduler :: RTS ()
scheduler = getThread >>= scheduleThread
-- Execute given thread until it blocks or terminates, whence call 'scheduler'.
scheduleThread :: Thread RTS -> RTS ()
scheduleThread (Atom m) = m >>= maybe scheduler scheduleThread
-- Try to steal a thread from any thread pool (with own pool preferred);
-- if there is none, try to convert a spark from the spark pool;
-- if there is none too, block the scheduler such that the 'getThread'
-- action will be repeated on wake up.
-- NOTE: Sleeping schedulers should be woken up
-- * after new threads have been added to a thread pool,
-- * after new sparks have been added to the spark pool, and
-- * once the delay after a NOWORK message has expired.
getThread :: RTS (Thread RTS)
getThread = do
maybe_thread <- liftThreadM stealThread
case maybe_thread of
Just thread -> return thread
Nothing -> do
maybe_spark <- liftSparkM getSpark
case maybe_spark of
Just sparkClosure ->
case sparkClosure of
(Left supSparkClo) -> do
return $ mkThread $ unClosure $ clo $ unClosure supSparkClo
(Right spark) -> do
return $ mkThread $ unClosure spark
Nothing -> liftSparkM blockSched >> getThread
-- Converts 'Par' computations into threads.
mkThread :: ParM RTS a -> Thread RTS
mkThread p = unPar p $ \ _c -> Atom (return Nothing)
-----------------------------------------------------------------------------
-- pushed sparks
sendPUSH :: Task RTS -> NodeId -> RTS ()
sendPUSH spark target = do
here <- liftCommM Comm.myNode
if target == here
then do
-- short cut PUSH msg locally
execSpark spark
else do
-- now send PUSH message to write IVar value to host
let pushMsg = PUSH spark :: Msg RTS
debug dbgMsgSend $
show pushMsg ++ " ->> " ++ show target
void $ liftCommM $ Comm.send target $ encodeLazy pushMsg
-- |Handle a PUSH message by converting the spark into a thread and
-- executing it immediately.
-- handlePUSH :: Msg RTS -> RTS ()
handlePUSH :: Msg RTS -> RTS ()
handlePUSH (PUSH spark) =
-- Then convert the spark to a thread.
-- This task is now going nowhere, it will
-- either be evaluated here, or will be lost
-- if this node dies
execSpark spark
-- | Handles DEADNODE messages. Perform 3 procedures:
-- 1) If it is waiting for a fish reply from the deadNode,
-- then stop waiting, and begin fishing again.
-- 2) If spark in guard post was destined for failed node,
-- then empty the guard post. Do not put this spark back
-- into local sparkpool - it is the supervisors job to
-- reschedule the spark (which it does within its own sparkpool).
-- This is necessary to allow this node to once again
-- accept FISH messages ('waitingReqResponse' returns False again).
-- 3) Then, establish if the dead node was hosting any of
-- the supervised spark I created.
-- 3a) identify all at-risk futures
-- 3b) create replicas
-- 3c) re-schedule non-evalauted tasks (empty associated IVars)
handleDEADNODE :: Msg RTS -> RTS ()
handleDEADNODE (DEADNODE deadNode) = do
-- remove node from virtual machine
liftCommM $ Comm.rmNode deadNode
debug dbgFailure $
"dead node detected: " ++ show deadNode
-- 1) if waiting for FISH response from dead node, reset
maybe_fishingReplyNode <- liftSparkM waitingFishingReplyFrom
when (isJust maybe_fishingReplyNode) $ do
let fishingReplyNode = fromJust maybe_fishingReplyNode
when (fishingReplyNode == deadNode) $ do
liftSparkM clearFishingFlag
-- 2) If spark in guard post was destined for
-- the failed node, put spark back in sparkpool
liftSparkM $ popGuardPostToSparkpool deadNode
-- 3a) identify all empty vulnerable futures
emptyIVars <- liftIO $ vulnerableEmptyFutures deadNode :: RTS [(Int,IVar m a)]
(emptyIVarsSparked,emptyIVarsPushed) <- partitionM wasSparked emptyIVars
-- 3b) create replicas
replicatedSparks <- mapM (liftIO . replicateSpark) emptyIVarsSparked
replicatedThreads <- mapM (liftIO . replicateThread) emptyIVarsPushed
-- 3c) schedule replicas
mapM_ (liftSparkM . putSpark . Left . toClosure . fromJust) replicatedSparks
mapM_ (execThread . mkThread . unClosure . fromJust) replicatedThreads
-- for RTS stats
replicateM_ (length emptyIVarsSparked) $ liftSparkM $ getSparkRecCtr >>= incCtr
replicateM_ (length emptyIVarsPushed) $ liftSparkM $ getThreadRecCtr >>= incCtr
-- for chaos monkey stats
unless (null replicatedSparks) $ do
debug dbgFailure $
("replicating sparks: " ++ show (length replicatedSparks))
liftIO $ putStrLn ("replicating sparks: " ++ show (length replicatedSparks))
unless (null replicatedThreads) $ do
debug dbgFailure $
("replicating threads: " ++ show (length replicatedThreads))
liftIO $ putStrLn ("replicating threads: " ++ show (length replicatedThreads))
where
wasSparked (_,v) = do
e <- liftIO $ readIORef v
let (Empty _ maybe_st) = e
st = fromJust maybe_st
return $ scheduling st == Sparked
handleHEARTBEAT :: Msg RTS -> RTS ()
handleHEARTBEAT (HEARTBEAT) = return ()
-- | Execute a spark (by converting it to a thread and executing).
execSpark :: Task RTS -> RTS ()
execSpark sparkClosure =
case sparkClosure of
(Left supSpClo) -> do
let spark = unClosure supSpClo
execThread $ mkThread $ unClosure (clo spark)
(Right spark) -> do
execThread $ mkThread $ unClosure spark
-----------------------------------------------------------------------------
-- message handler; only PUSH messages are actually handled here in this
-- module, other messages are relegated to module Sparkpool.
-- Message handler, running continously (in its own thread) receiving
-- and handling messages (some of which may unblock threads or create sparks)
-- as they arrive.
handler :: RTS ()
handler = do
msg <- decodeLazy <$> liftCommM Comm.receive
sparks <- liftSparkM readPoolSize
debug dbgMsgRcvd $
">> " ++ show msg ++ " #sparks=" ++ show sparks
case msg of
-- eager placement
PUSH{} -> handlePUSH msg
-- scheduling
FISH{} -> liftSparkM $ dispatch msg
SCHEDULE{} -> liftSparkM $ dispatch msg
NOWORK{} -> liftSparkM $ dispatch msg
-- fault tolerance
REQ{} -> liftSparkM $ dispatch msg
AUTH{} -> liftSparkM $ dispatch msg
DENIED{} -> liftSparkM $ dispatch msg
ACK{} -> liftSparkM $ dispatch msg
OBSOLETE{} -> liftSparkM $ dispatch msg
DEADNODE{} -> handleDEADNODE msg
HEARTBEAT{} -> handleHEARTBEAT msg
handler
-----------------------------------------------------------------------------
-- auxiliary stuff
-- Print stats (#sparks, threads, FISH, ...) at appropriate debug level.
printFinalStats :: RTS ()
printFinalStats = do
fishes <- liftSparkM $ readFishSentCtr
schds <- liftSparkM $ readSparkRcvdCtr
sparks <- liftSparkM $ readSparkGenCtr
recoveredSparks <- liftSparkM $ readSparkRec
recoveredThreads <- liftSparkM $ readThreadRec
lostCompletedTasks <- liftSparkM $ readTaskNotRec
max_sparks <- liftSparkM $ readMaxSparkCtr
maxs_threads <- liftThreadM $ readMaxThreadCtrs
debug dbgStats $ "#SPARK=" ++ show sparks ++ " " ++
"max_SPARK=" ++ show max_sparks ++ " " ++
"max_THREAD=" ++ show maxs_threads
debug dbgStats $ "#FISH_sent=" ++ show fishes ++ " " ++
"#SCHED_rcvd=" ++ show schds
debug dbgStats $ "#Recovered_SPARK=" ++ show recoveredSparks ++ " " ++
"#Recovered_THREAD=" ++ show recoveredThreads ++ " " ++
"#NotRecovered_TASK=" ++ show lostCompletedTasks
debug :: Int -> String -> RTS ()
debug level message = liftIO $ Location.debug level message
-- | Used to split those remote tasks that have and have not
-- been completely evaluated i.e. the associated IVar is empty.
partitionM :: Monad m => (a -> m Bool) -> [a] -> m ([a],[a])
partitionM p xs = do
(f,g) <- pMHelper p xs
return (f [], g [])
where
pMHelper _ = foldM help (id,id)
help (f,g) x = do
b <- p x
return (if b then (f . (x:),g) else (f,g . (x:)))
| bitemyapp/hdph-rs | src/Control/Parallel/HdpH/Internal/Scheduler.hs | bsd-3-clause | 14,924 | 0 | 23 | 3,274 | 2,924 | 1,549 | 1,375 | 210 | 11 |
{-# LANGUAGE PatternGuards, ScopedTypeVariables, ExistentialQuantification, DeriveDataTypeable #-}
-- | This module captures annotations on a value, and builds a 'Capture' value.
-- This module has two ways of writing annotations:
--
-- /Impure/: The impure method of writing annotations is susceptible to over-optimisation by GHC
-- - sometimes @\{\-\# OPTIONS_GHC -fno-cse \#\-\}@ will be required.
--
-- /Pure/: The pure method is more verbose, and lacks some type safety.
--
-- As an example of the two styles:
--
-- > data Foo = Foo {foo :: Int, bar :: Int}
--
-- @ impure = 'capture' $ Foo {foo = 12, bar = 'many' [1 '&=' \"inner\", 2]} '&=' \"top\"@
--
-- @ pure = 'capture_' $ 'record' Foo{} [foo := 12, bar :=+ ['atom' 1 '+=' \"inner\", 'atom' 2]] '+=' \"top\"@
--
-- Both evaluate to:
--
-- > Capture (Ann "top") (Ctor (Foo 12 1) [Value 12, Many [Ann "inner" (Value 1), Value 2]]
module System.Console.CmdArgs.Annotate(
-- * Capture framework
Capture(..), Any(..), fromCapture, defaultMissing,
-- * Impure
capture, many, (&=),
-- * Pure
capture_, many_, (+=), atom, record, Annotate((:=),(:=+))
) where
import Control.Monad
import Control.Monad.Trans.State
import Data.Data(Data,Typeable)
import Data.List
import Data.Maybe
import Data.IORef
import System.IO.Unsafe
import Control.Exception
import Data.Generics.Any
infixl 2 &=, +=
infix 3 :=
-- | The result of capturing some annotations.
data Capture ann
= Many [Capture ann] -- ^ Many values collapsed ('many' or 'many_')
| Ann ann (Capture ann) -- ^ An annotation attached to a value ('&=' or '+=')
| Value Any -- ^ A value (just a value, or 'atom')
| Missing Any -- ^ A missing field (a 'RecConError' exception, or missing from 'record')
| Ctor Any [Capture ann] -- ^ A constructor (a constructor, or 'record')
deriving Show
instance Functor Capture where
fmap f (Many xs) = Many $ map (fmap f) xs
fmap f (Ann a x) = Ann (f a) $ fmap f x
fmap f (Value x) = Value x
fmap f (Missing x) = Missing x
fmap f (Ctor x xs) = Ctor x $ map (fmap f) xs
-- | Return the value inside a capture.
fromCapture :: Capture ann -> Any
fromCapture (Many (x:_)) = fromCapture x
fromCapture (Ann _ x) = fromCapture x
fromCapture (Value x) = x
fromCapture (Missing x) = x
fromCapture (Ctor x _) = x
-- | Remove all Missing values by using any previous instances as default values
defaultMissing :: Capture ann -> Capture ann
defaultMissing x = evalState (f Nothing Nothing x) []
where
f ctor field (Many xs) = fmap Many $ mapM (f ctor field) xs
f ctor field (Ann a x) = fmap (Ann a) $ f ctor field x
f ctor field (Value x) = return $ Value x
f (Just ctor) (Just field) (Missing x) = do
s <- get
return $ head $
[x2 | (ctor2,field2,x2) <- s, typeOf ctor == typeOf ctor2, field == field2] ++
err ("missing value encountered, no field for " ++ field ++ " (of type " ++ show x ++ ")")
f _ _ (Missing x) = err $ "missing value encountered, but not as a field (of type " ++ show x ++ ")"
f _ _ (Ctor x xs) | length (fields x) == length xs = do
ys <- zipWithM (g x) (fields x) xs
return $ Ctor (recompose x $ map fromCapture ys) ys
f _ _ (Ctor x xs) = fmap (Ctor x) $ mapM (f Nothing Nothing) xs
g ctor field x = do
y <- f (Just ctor) (Just field) x
modify ((ctor,field,y):)
return y
err x = error $ "System.Console.CmdArgs.Annotate.defaultMissing, " ++ x
---------------------------------------------------------------------
-- IMPURE BIT
-- test = show $ capture $ many [Just ((66::Int) &= P 1 &= P 2), Nothing &= P 8] &= P 3
{-
Notes On Purity
---------------
There is a risk that things that are unsafe will be inlined. That can generally be
removed by NOININE on everything.
There is also a risk that things get commoned up. For example:
foo = trace "1" 1
bar = trace "1" 1
main = do
evaluate foo
evaluate bar
Will print "1" only once, since foo and bar share the same pattern. However, if
anything in the value is a lambda they are not seen as equal. We exploit this by
defining const_ and id_ as per this module.
Now anything wrapped in id_ looks different from anything else.
-}
{-
The idea is to keep a stack of either continuations, or values
If you encounter 'many' you become a value
If you encounter '&=' you increase the continuation
-}
{-# NOINLINE ref #-}
ref :: IORef [Either (Capture Any -> Capture Any) (Capture Any)]
ref = unsafePerformIO $ newIORef []
push = modifyIORef ref (Left id :)
pop = do x:xs <- readIORef ref; writeIORef ref xs; return x
change f = modifyIORef ref $ \x -> case x of Left g : rest -> f g : rest ; _ -> error "Internal error in Capture"
add f = change $ \x -> Left $ x . f
set x = change $ \f -> Right $ f x
-- | Collapse multiple values in to one.
{-# NOINLINE many #-}
many :: Data val => [val] -> val
many xs = unsafePerformIO $ do
ys <- mapM (force . Any) xs
set $ Many ys
return $ head xs
{-# NOINLINE addAnn #-}
addAnn :: (Data val, Data ann) => val -> ann -> val
addAnn x y = unsafePerformIO $ do
add (Ann $ Any y)
evaluate x
return x
-- | Capture a value. Note that if the value is evaluated
-- more than once the result may be different, i.e.
--
-- > capture x /= capture x
{-# NOINLINE capture #-}
capture :: (Data val, Data ann) => val -> Capture ann
capture x = unsafePerformIO $ fmap (fmap fromAny) $ force $ Any x
force :: Any -> IO (Capture Any)
force x@(Any xx) = do
push
res <- try $ evaluate xx
y <- pop
case y of
_ | Left (_ :: RecConError) <- res -> return $ Missing x
Right r -> return r
Left f | not $ isAlgType x -> return $ f $ Value x
| otherwise -> do
cs <- mapM force $ children x
return $ f $ Ctor x cs
-- | Add an annotation to a value.
--
-- It is recommended that anyone making use of this function redefine
-- it with a more restrictive type signature to control the type of the
-- annotation (the second argument). Any redefinitions of this function
-- should add an INLINE pragma, to reduce the chance of incorrect
-- optimisations.
{-# INLINE (&=) #-}
(&=) :: (Data val, Data ann) => val -> ann -> val
(&=) x y = addAnn (id_ x) (id_ y)
{-# INLINE id_ #-}
id_ :: a -> a
id_ x = case unit of () -> x
where unit = reverse "" `seq` ()
---------------------------------------------------------------------
-- PURE PART
-- | This type represents an annotated value. The type of the underlying value is not specified.
data Annotate ann
= forall c f . (Data c, Data f) => (c -> f) := f -- ^ Construct a field, @fieldname := value@.
| forall c f . (Data c, Data f) => (c -> f) :=+ [Annotate ann] -- ^ Add annotations to a field.
| AAnn ann (Annotate ann)
| AMany [Annotate ann]
| AAtom Any
| ACtor Any [Annotate ann]
deriving Typeable
-- specifically DOES NOT derive Data, to avoid people accidentally including it
-- | Add an annotation to a value.
(+=) :: Annotate ann -> ann -> Annotate ann
(+=) = flip AAnn
-- | Collapse many annotated values in to one.
many_ :: [Annotate a] -> Annotate a
many_ = AMany
-- | Lift a pure value to an annotation.
atom :: Data val => val -> Annotate ann
atom = AAtom . Any
-- | Create a constructor/record. The first argument should be
-- the type of field, the second should be a list of fields constructed
-- originally defined by @:=@ or @:=+@.
--
-- This operation is not type safe, and may raise an exception at runtime
-- if any field has the wrong type or label.
record :: Data a => a -> [Annotate ann] -> Annotate ann
record a b = ACtor (Any a) b
-- | Capture the annotations from an annotated value.
capture_ :: Show a => Annotate a -> Capture a
capture_ (AAnn a x) = Ann a (capture_ x)
capture_ (AMany xs) = Many (map capture_ xs)
capture_ (AAtom x) = Value x
capture_ (_ := c) = Value $ Any c
capture_ (_ :=+ c) = Many $ map capture_ c
capture_ (ACtor x xs)
| not $ null rep = error $ "Some fields got repeated under " ++ show x ++ "." ++ ctor x ++ ": " ++ show rep
| otherwise = Ctor x2 xs2
where
x2 = recompose x $ map fromCapture xs2
xs2 = [fromMaybe (Missing c) $ lookup i is | let is = zip inds $ map capture_ xs, (i,c) <- zip [0..] $ children x]
inds = zipWith fromMaybe [0..] $ map (fieldIndex x) xs
rep = inds \\ nub inds
fieldIndex :: Any -> Annotate a -> Maybe Int
fieldIndex ctor (AAnn a x) = fieldIndex ctor x
fieldIndex ctor (f := _) = fieldIndex ctor (f :=+ [])
fieldIndex ctor (f :=+ _) | isJust res = res
| otherwise = error $ "Couldn't resolve field for " ++ show ctor
where c = recompose ctor [Any $ throwInt i `asTypeOf` x | (i,Any x) <- zip [0..] (children ctor)]
res = catchInt $ f $ fromAny c
fieldIndex _ _ = Nothing
data ExceptionInt = ExceptionInt Int deriving (Show, Typeable)
instance Exception ExceptionInt
throwInt :: Int -> a
throwInt i = throw (ExceptionInt i)
{-# NOINLINE catchInt #-}
catchInt :: a -> Maybe Int
catchInt x = unsafePerformIO $ do
y <- try (evaluate x)
return $ case y of
Left (ExceptionInt z) -> Just z
_ -> Nothing
| copland/cmdargs | System/Console/CmdArgs/Annotate.hs | bsd-3-clause | 9,331 | 0 | 16 | 2,322 | 2,663 | 1,368 | 1,295 | 148 | 7 |
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
-}
{-# LANGUAGE CPP #-}
module TcValidity (
Rank, UserTypeCtxt(..), checkValidType, checkValidMonoType,
expectedKindInCtxt,
checkValidTheta, checkValidFamPats,
checkValidInstance, validDerivPred,
checkInstTermination, checkValidTyFamInst, checkTyFamFreeness,
checkConsistentFamInst, sizeTypes,
arityErr, badATErr
) where
#include "HsVersions.h"
-- friends:
import TcUnify ( tcSubType_NC )
import TcSimplify ( simplifyAmbiguityCheck )
import TypeRep
import TcType
import TcMType
import TysWiredIn ( coercibleClass )
import Type
import Unify( tcMatchTyX )
import Kind
import CoAxiom
import Class
import TyCon
-- others:
import HsSyn -- HsType
import TcRnMonad -- TcType, amongst others
import FunDeps
import Name
import VarEnv
import VarSet
import ErrUtils
import DynFlags
import Util
import ListSetOps
import SrcLoc
import Outputable
import FastString
import Control.Monad
import Data.Maybe
import Data.List ( (\\) )
{-
************************************************************************
* *
Checking for ambiguity
* *
************************************************************************
-}
checkAmbiguity :: UserTypeCtxt -> Type -> TcM ()
checkAmbiguity ctxt ty
| GhciCtxt <- ctxt -- Allow ambiguous types in GHCi's :kind command
= return () -- E.g. type family T a :: * -- T :: forall k. k -> *
-- Then :k T should work in GHCi, not complain that
-- (T k) is ambiguous!
| InfSigCtxt {} <- ctxt -- See Note [Validity of inferred types] in TcBinds
= return ()
| otherwise
= do { traceTc "Ambiguity check for" (ppr ty)
; let free_tkvs = varSetElemsKvsFirst (closeOverKinds (tyVarsOfType ty))
; (subst, _tvs) <- tcInstSkolTyVars free_tkvs
; let ty' = substTy subst ty
-- The type might have free TyVars, esp when the ambiguity check
-- happens during a call to checkValidType,
-- so we skolemise them as TcTyVars.
-- Tiresome; but the type inference engine expects TcTyVars
-- NB: The free tyvar might be (a::k), so k is also free
-- and we must skolemise it as well. Hence closeOverKinds.
-- (Trac #9222)
-- Solve the constraints eagerly because an ambiguous type
-- can cause a cascade of further errors. Since the free
-- tyvars are skolemised, we can safely use tcSimplifyTop
; (_wrap, wanted) <- addErrCtxtM (mk_msg ty') $
captureConstraints $
tcSubType_NC ctxt ty' ty'
; simplifyAmbiguityCheck ty wanted
; traceTc "Done ambiguity check for" (ppr ty) }
where
mk_msg ty tidy_env
= do { allow_ambiguous <- xoptM Opt_AllowAmbiguousTypes
; (tidy_env', tidy_ty) <- zonkTidyTcType tidy_env ty
; return (tidy_env', mk_msg tidy_ty $$ ppWhen (not allow_ambiguous) ambig_msg) }
where
mk_msg ty = pprSigCtxt ctxt (ptext (sLit "the ambiguity check for")) (ppr ty)
ambig_msg = ptext (sLit "To defer the ambiguity check to use sites, enable AllowAmbiguousTypes")
{-
************************************************************************
* *
Checking validity of a user-defined type
* *
************************************************************************
When dealing with a user-written type, we first translate it from an HsType
to a Type, performing kind checking, and then check various things that should
be true about it. We don't want to perform these checks at the same time
as the initial translation because (a) they are unnecessary for interface-file
types and (b) when checking a mutually recursive group of type and class decls,
we can't "look" at the tycons/classes yet. Also, the checks are are rather
diverse, and used to really mess up the other code.
One thing we check for is 'rank'.
Rank 0: monotypes (no foralls)
Rank 1: foralls at the front only, Rank 0 inside
Rank 2: foralls at the front, Rank 1 on left of fn arrow,
basic ::= tyvar | T basic ... basic
r2 ::= forall tvs. cxt => r2a
r2a ::= r1 -> r2a | basic
r1 ::= forall tvs. cxt => r0
r0 ::= r0 -> r0 | basic
Another thing is to check that type synonyms are saturated.
This might not necessarily show up in kind checking.
type A i = i
data T k = MkT (k Int)
f :: T A -- BAD!
-}
checkValidType :: UserTypeCtxt -> Type -> TcM ()
-- Checks that the type is valid for the given context
-- Not used for instance decls; checkValidInstance instead
checkValidType ctxt ty
= do { traceTc "checkValidType" (ppr ty <+> text "::" <+> ppr (typeKind ty))
; rankn_flag <- xoptM Opt_RankNTypes
; let gen_rank :: Rank -> Rank
gen_rank r | rankn_flag = ArbitraryRank
| otherwise = r
rank1 = gen_rank r1
rank0 = gen_rank r0
r0 = rankZeroMonoType
r1 = LimitedRank True r0
rank
= case ctxt of
DefaultDeclCtxt-> MustBeMonoType
ResSigCtxt -> MustBeMonoType
PatSigCtxt -> rank0
RuleSigCtxt _ -> rank1
TySynCtxt _ -> rank0
ExprSigCtxt -> rank1
FunSigCtxt _ _ -> rank1
InfSigCtxt _ -> ArbitraryRank -- Inferred type
ConArgCtxt _ -> rank1 -- We are given the type of the entire
-- constructor, hence rank 1
ForSigCtxt _ -> rank1
SpecInstCtxt -> rank1
ThBrackCtxt -> rank1
GhciCtxt -> ArbitraryRank
_ -> panic "checkValidType"
-- Can't happen; not used for *user* sigs
-- Check the internal validity of the type itself
; check_type ctxt rank ty
-- Check that the thing has kind Type, and is lifted if necessary.
-- Do this *after* check_type, because we can't usefully take
-- the kind of an ill-formed type such as (a~Int)
; check_kind ctxt ty
; traceTc "checkValidType done" (ppr ty <+> text "::" <+> ppr (typeKind ty)) }
checkValidMonoType :: Type -> TcM ()
checkValidMonoType ty = check_mono_type SigmaCtxt MustBeMonoType ty
check_kind :: UserTypeCtxt -> TcType -> TcM ()
-- Check that the type's kind is acceptable for the context
check_kind ctxt ty
| TySynCtxt {} <- ctxt
, returnsConstraintKind actual_kind
= do { ck <- xoptM Opt_ConstraintKinds
; if ck
then when (isConstraintKind actual_kind)
(do { dflags <- getDynFlags
; check_pred_ty dflags ctxt ty })
else addErrTc (constraintSynErr actual_kind) }
| Just k <- expectedKindInCtxt ctxt
= checkTc (tcIsSubKind actual_kind k) (kindErr actual_kind)
| otherwise
= return () -- Any kind will do
where
actual_kind = typeKind ty
-- Depending on the context, we might accept any kind (for instance, in a TH
-- splice), or only certain kinds (like in type signatures).
expectedKindInCtxt :: UserTypeCtxt -> Maybe Kind
expectedKindInCtxt (TySynCtxt _) = Nothing -- Any kind will do
expectedKindInCtxt ThBrackCtxt = Nothing
expectedKindInCtxt GhciCtxt = Nothing
expectedKindInCtxt (ForSigCtxt _) = Just liftedTypeKind
expectedKindInCtxt InstDeclCtxt = Just constraintKind
expectedKindInCtxt SpecInstCtxt = Just constraintKind
expectedKindInCtxt _ = Just openTypeKind
{-
Note [Higher rank types]
~~~~~~~~~~~~~~~~~~~~~~~~
Technically
Int -> forall a. a->a
is still a rank-1 type, but it's not Haskell 98 (Trac #5957). So the
validity checker allow a forall after an arrow only if we allow it
before -- that is, with Rank2Types or RankNTypes
-}
data Rank = ArbitraryRank -- Any rank ok
| LimitedRank -- Note [Higher rank types]
Bool -- Forall ok at top
Rank -- Use for function arguments
| MonoType SDoc -- Monotype, with a suggestion of how it could be a polytype
| MustBeMonoType -- Monotype regardless of flags
rankZeroMonoType, tyConArgMonoType, synArgMonoType :: Rank
rankZeroMonoType = MonoType (ptext (sLit "Perhaps you intended to use RankNTypes or Rank2Types"))
tyConArgMonoType = MonoType (ptext (sLit "Perhaps you intended to use ImpredicativeTypes"))
synArgMonoType = MonoType (ptext (sLit "Perhaps you intended to use LiberalTypeSynonyms"))
funArgResRank :: Rank -> (Rank, Rank) -- Function argument and result
funArgResRank (LimitedRank _ arg_rank) = (arg_rank, LimitedRank (forAllAllowed arg_rank) arg_rank)
funArgResRank other_rank = (other_rank, other_rank)
forAllAllowed :: Rank -> Bool
forAllAllowed ArbitraryRank = True
forAllAllowed (LimitedRank forall_ok _) = forall_ok
forAllAllowed _ = False
----------------------------------------
check_mono_type :: UserTypeCtxt -> Rank
-> KindOrType -> TcM () -- No foralls anywhere
-- No unlifted types of any kind
check_mono_type ctxt rank ty
| isKind ty = return () -- IA0_NOTE: Do we need to check kinds?
| otherwise
= do { check_type ctxt rank ty
; checkTc (not (isUnLiftedType ty)) (unliftedArgErr ty) }
check_type :: UserTypeCtxt -> Rank -> Type -> TcM ()
-- The args say what the *type context* requires, independent
-- of *flag* settings. You test the flag settings at usage sites.
--
-- Rank is allowed rank for function args
-- Rank 0 means no for-alls anywhere
check_type ctxt rank ty
| not (null tvs && null theta)
= do { checkTc (forAllAllowed rank) (forAllTyErr rank ty)
-- Reject e.g. (Maybe (?x::Int => Int)),
-- with a decent error message
; check_valid_theta ctxt theta
; check_type ctxt rank tau -- Allow foralls to right of arrow
; checkAmbiguity ctxt ty }
where
(tvs, theta, tau) = tcSplitSigmaTy ty
check_type _ _ (TyVarTy _) = return ()
check_type ctxt rank (FunTy arg_ty res_ty)
= do { check_type ctxt arg_rank arg_ty
; check_type ctxt res_rank res_ty }
where
(arg_rank, res_rank) = funArgResRank rank
check_type ctxt rank (AppTy ty1 ty2)
= do { check_arg_type ctxt rank ty1
; check_arg_type ctxt rank ty2 }
check_type ctxt rank ty@(TyConApp tc tys)
| isTypeSynonymTyCon tc || isTypeFamilyTyCon tc
= check_syn_tc_app ctxt rank ty tc tys
| isUnboxedTupleTyCon tc = check_ubx_tuple ctxt ty tys
| otherwise = mapM_ (check_arg_type ctxt rank) tys
check_type _ _ (LitTy {}) = return ()
check_type _ _ ty = pprPanic "check_type" (ppr ty)
----------------------------------------
check_syn_tc_app :: UserTypeCtxt -> Rank -> KindOrType
-> TyCon -> [KindOrType] -> TcM ()
-- Used for type synonyms and type synonym families,
-- which must be saturated,
-- but not data families, which need not be saturated
check_syn_tc_app ctxt rank ty tc tys
| tc_arity <= n_args -- Saturated
-- Check that the synonym has enough args
-- This applies equally to open and closed synonyms
-- It's OK to have an *over-applied* type synonym
-- data Tree a b = ...
-- type Foo a = Tree [a]
-- f :: Foo a b -> ...
= do { -- See Note [Liberal type synonyms]
; liberal <- xoptM Opt_LiberalTypeSynonyms
; if not liberal || isTypeFamilyTyCon tc then
-- For H98 and synonym families, do check the type args
mapM_ check_arg tys
else -- In the liberal case (only for closed syns), expand then check
case tcView ty of
Just ty' -> check_type ctxt rank ty'
Nothing -> pprPanic "check_tau_type" (ppr ty) }
| GhciCtxt <- ctxt -- Accept under-saturated type synonyms in
-- GHCi :kind commands; see Trac #7586
= mapM_ check_arg tys
| otherwise
= failWithTc (arityErr flavour (tyConName tc) tc_arity n_args)
where
flavour | isTypeFamilyTyCon tc = "Type family"
| otherwise = "Type synonym"
n_args = length tys
tc_arity = tyConArity tc
check_arg | isTypeFamilyTyCon tc = check_arg_type ctxt rank
| otherwise = check_mono_type ctxt synArgMonoType
----------------------------------------
check_ubx_tuple :: UserTypeCtxt -> KindOrType
-> [KindOrType] -> TcM ()
check_ubx_tuple ctxt ty tys
= do { ub_tuples_allowed <- xoptM Opt_UnboxedTuples
; checkTc ub_tuples_allowed (ubxArgTyErr ty)
; impred <- xoptM Opt_ImpredicativeTypes
; let rank' = if impred then ArbitraryRank else tyConArgMonoType
-- c.f. check_arg_type
-- However, args are allowed to be unlifted, or
-- more unboxed tuples, so can't use check_arg_ty
; mapM_ (check_type ctxt rank') tys }
----------------------------------------
check_arg_type :: UserTypeCtxt -> Rank -> KindOrType -> TcM ()
-- The sort of type that can instantiate a type variable,
-- or be the argument of a type constructor.
-- Not an unboxed tuple, but now *can* be a forall (since impredicativity)
-- Other unboxed types are very occasionally allowed as type
-- arguments depending on the kind of the type constructor
--
-- For example, we want to reject things like:
--
-- instance Ord a => Ord (forall s. T s a)
-- and
-- g :: T s (forall b.b)
--
-- NB: unboxed tuples can have polymorphic or unboxed args.
-- This happens in the workers for functions returning
-- product types with polymorphic components.
-- But not in user code.
-- Anyway, they are dealt with by a special case in check_tau_type
check_arg_type ctxt rank ty
| isKind ty = return () -- IA0_NOTE: Do we need to check a kind?
| otherwise
= do { impred <- xoptM Opt_ImpredicativeTypes
; let rank' = case rank of -- Predictive => must be monotype
MustBeMonoType -> MustBeMonoType -- Monotype, regardless
_other | impred -> ArbitraryRank
| otherwise -> tyConArgMonoType
-- Make sure that MustBeMonoType is propagated,
-- so that we don't suggest -XImpredicativeTypes in
-- (Ord (forall a.a)) => a -> a
-- and so that if it Must be a monotype, we check that it is!
; check_type ctxt rank' ty
; checkTc (not (isUnLiftedType ty)) (unliftedArgErr ty) }
-- NB the isUnLiftedType test also checks for
-- T State#
-- where there is an illegal partial application of State# (which has
-- kind * -> #); see Note [The kind invariant] in TypeRep
----------------------------------------
forAllTyErr :: Rank -> Type -> SDoc
forAllTyErr rank ty
= vcat [ hang (ptext (sLit "Illegal polymorphic or qualified type:")) 2 (ppr ty)
, suggestion ]
where
suggestion = case rank of
LimitedRank {} -> ptext (sLit "Perhaps you intended to use RankNTypes or Rank2Types")
MonoType d -> d
_ -> Outputable.empty -- Polytype is always illegal
unliftedArgErr, ubxArgTyErr :: Type -> SDoc
unliftedArgErr ty = sep [ptext (sLit "Illegal unlifted type:"), ppr ty]
ubxArgTyErr ty = sep [ptext (sLit "Illegal unboxed tuple type as function argument:"), ppr ty]
kindErr :: Kind -> SDoc
kindErr kind = sep [ptext (sLit "Expecting an ordinary type, but found a type of kind"), ppr kind]
{-
Note [Liberal type synonyms]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If -XLiberalTypeSynonyms is on, expand closed type synonyms *before*
doing validity checking. This allows us to instantiate a synonym defn
with a for-all type, or with a partially-applied type synonym.
e.g. type T a b = a
type S m = m ()
f :: S (T Int)
Here, T is partially applied, so it's illegal in H98. But if you
expand S first, then T we get just
f :: Int
which is fine.
IMPORTANT: suppose T is a type synonym. Then we must do validity
checking on an appliation (T ty1 ty2)
*either* before expansion (i.e. check ty1, ty2)
*or* after expansion (i.e. expand T ty1 ty2, and then check)
BUT NOT BOTH
If we do both, we get exponential behaviour!!
data TIACons1 i r c = c i ::: r c
type TIACons2 t x = TIACons1 t (TIACons1 t x)
type TIACons3 t x = TIACons2 t (TIACons1 t x)
type TIACons4 t x = TIACons2 t (TIACons2 t x)
type TIACons7 t x = TIACons4 t (TIACons3 t x)
************************************************************************
* *
\subsection{Checking a theta or source type}
* *
************************************************************************
Note [Implicit parameters in instance decls]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Implicit parameters _only_ allowed in type signatures; not in instance
decls, superclasses etc. The reason for not allowing implicit params in
instances is a bit subtle. If we allowed
instance (?x::Int, Eq a) => Foo [a] where ...
then when we saw
(e :: (?x::Int) => t)
it would be unclear how to discharge all the potential uses of the ?x
in e. For example, a constraint Foo [Int] might come out of e, and
applying the instance decl would show up two uses of ?x. Trac #8912.
-}
checkValidTheta :: UserTypeCtxt -> ThetaType -> TcM ()
checkValidTheta ctxt theta
= addErrCtxt (checkThetaCtxt ctxt theta) (check_valid_theta ctxt theta)
-------------------------
check_valid_theta :: UserTypeCtxt -> [PredType] -> TcM ()
check_valid_theta _ []
= return ()
check_valid_theta ctxt theta
= do { dflags <- getDynFlags
; warnTc (wopt Opt_WarnDuplicateConstraints dflags &&
notNull dups) (dupPredWarn dups)
; mapM_ (check_pred_ty dflags ctxt) theta }
where
(_,dups) = removeDups cmpPred theta
-------------------------
check_pred_ty :: DynFlags -> UserTypeCtxt -> PredType -> TcM ()
-- Check the validity of a predicate in a signature
-- Do not look through any type synonyms; any constraint kinded
-- type synonyms have been checked at their definition site
-- C.f. Trac #9838
check_pred_ty dflags ctxt pred
= do { checkValidMonoType pred
; check_pred_help False dflags ctxt pred }
check_pred_help :: Bool -- True <=> under a type synonym
-> DynFlags -> UserTypeCtxt
-> PredType -> TcM ()
check_pred_help under_syn dflags ctxt pred
| Just pred' <- coreView pred
= check_pred_help True dflags ctxt pred'
| otherwise
= case classifyPredType pred of
ClassPred cls tys -> check_class_pred dflags ctxt pred cls tys
EqPred NomEq _ _ -> check_eq_pred dflags pred
EqPred ReprEq ty1 ty2 -> check_repr_eq_pred dflags ctxt pred ty1 ty2
TuplePred tys -> check_tuple_pred under_syn dflags ctxt pred tys
IrredPred _ -> check_irred_pred under_syn dflags ctxt pred
check_class_pred :: DynFlags -> UserTypeCtxt -> PredType -> Class -> [TcType] -> TcM ()
check_class_pred dflags ctxt pred cls tys
= do { -- Class predicates are valid in all contexts
; checkTc (arity == n_tys) arity_err
; checkTc (not (isIPClass cls) || okIPCtxt ctxt)
(badIPPred pred)
-- Check the form of the argument types
; check_class_pred_tys dflags ctxt pred tys
}
where
class_name = className cls
arity = classArity cls
n_tys = length tys
arity_err = arityErr "Class" class_name arity n_tys
check_eq_pred :: DynFlags -> PredType -> TcM ()
check_eq_pred dflags pred
= -- Equational constraints are valid in all contexts if type
-- families are permitted
checkTc (xopt Opt_TypeFamilies dflags || xopt Opt_GADTs dflags)
(eqPredTyErr pred)
check_repr_eq_pred :: DynFlags -> UserTypeCtxt -> PredType
-> TcType -> TcType -> TcM ()
check_repr_eq_pred dflags ctxt pred ty1 ty2
= check_class_pred_tys dflags ctxt pred tys
where
tys = [ty1, ty2]
check_tuple_pred :: Bool -> DynFlags -> UserTypeCtxt -> PredType -> [PredType] -> TcM ()
check_tuple_pred under_syn dflags ctxt pred ts
= do { -- See Note [ConstraintKinds in predicates]
checkTc (under_syn || xopt Opt_ConstraintKinds dflags)
(predTupleErr pred)
; mapM_ (check_pred_help under_syn dflags ctxt) ts }
-- This case will not normally be executed because without
-- -XConstraintKinds tuple types are only kind-checked as *
check_irred_pred :: Bool -> DynFlags -> UserTypeCtxt -> PredType -> TcM ()
check_irred_pred under_syn dflags ctxt pred
-- The predicate looks like (X t1 t2) or (x t1 t2) :: Constraint
-- where X is a type function
= do { -- If it looks like (x t1 t2), require ConstraintKinds
-- see Note [ConstraintKinds in predicates]
-- But (X t1 t2) is always ok because we just require ConstraintKinds
-- at the definition site (Trac #9838)
checkTc (under_syn || xopt Opt_ConstraintKinds dflags || not (tyvar_head pred))
(predIrredErr pred)
-- Make sure it is OK to have an irred pred in this context
-- See Note [Irreducible predicates in superclasses]
; checkTc (xopt Opt_UndecidableInstances dflags || not (dodgy_superclass ctxt))
(predIrredBadCtxtErr pred) }
where
dodgy_superclass ctxt
= case ctxt of { ClassSCCtxt _ -> True; InstDeclCtxt -> True; _ -> False }
{- Note [ConstraintKinds in predicates]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Don't check for -XConstraintKinds under a type synonym, because that
was done at the type synonym definition site; see Trac #9838
e.g. module A where
type C a = (Eq a, Ix a) -- Needs -XConstraintKinds
module B where
import A
f :: C a => a -> a -- Does *not* need -XConstraintKinds
Note [Irreducible predicates in superclasses]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Allowing irreducible predicates in class superclasses is somewhat dangerous
because we can write:
type family Fooish x :: * -> Constraint
type instance Fooish () = Foo
class Fooish () a => Foo a where
This will cause the constraint simplifier to loop because every time we canonicalise a
(Foo a) class constraint we add a (Fooish () a) constraint which will be immediately
solved to add+canonicalise another (Foo a) constraint.
It is equally dangerous to allow them in instance heads because in that case the
Paterson conditions may not detect duplication of a type variable or size change. -}
-------------------------
check_class_pred_tys :: DynFlags -> UserTypeCtxt
-> PredType -> [KindOrType] -> TcM ()
check_class_pred_tys dflags ctxt pred kts
= checkTc pred_ok (predTyVarErr pred $$ how_to_allow)
where
(_, tys) = span isKind kts -- see Note [Kind polymorphic type classes]
flexible_contexts = xopt Opt_FlexibleContexts dflags
undecidable_ok = xopt Opt_UndecidableInstances dflags
pred_ok = case ctxt of
SpecInstCtxt -> True -- {-# SPECIALISE instance Eq (T Int) #-} is fine
InstDeclCtxt -> flexible_contexts || undecidable_ok || all tcIsTyVarTy tys
-- Further checks on head and theta in
-- checkInstTermination
_ -> flexible_contexts || all tyvar_head tys
how_to_allow = parens (ptext (sLit "Use FlexibleContexts to permit this"))
-------------------------
tyvar_head :: Type -> Bool
tyvar_head ty -- Haskell 98 allows predicates of form
| tcIsTyVarTy ty = True -- C (a ty1 .. tyn)
| otherwise -- where a is a type variable
= case tcSplitAppTy_maybe ty of
Just (ty, _) -> tyvar_head ty
Nothing -> False
-------------------------
okIPCtxt :: UserTypeCtxt -> Bool
-- See Note [Implicit parameters in instance decls]
okIPCtxt (ClassSCCtxt {}) = False
okIPCtxt (InstDeclCtxt {}) = False
okIPCtxt (SpecInstCtxt {}) = False
okIPCtxt _ = True
badIPPred :: PredType -> SDoc
badIPPred pred = ptext (sLit "Illegal implicit parameter") <+> quotes (ppr pred)
{-
Note [Kind polymorphic type classes]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
MultiParam check:
class C f where... -- C :: forall k. k -> Constraint
instance C Maybe where...
The dictionary gets type [C * Maybe] even if it's not a MultiParam
type class.
Flexibility check:
class C f where... -- C :: forall k. k -> Constraint
data D a = D a
instance C D where
The dictionary gets type [C * (D *)]. IA0_TODO it should be
generalized actually.
Note [The ambiguity check for type signatures]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
checkAmbiguity is a check on user-supplied type signatures. It is
*purely* there to report functions that cannot possibly be called. So for
example we want to reject:
f :: C a => Int
The idea is there can be no legal calls to 'f' because every call will
give rise to an ambiguous constraint. We could soundly omit the
ambiguity check on type signatures entirely, at the expense of
delaying ambiguity errors to call sites. Indeed, the flag
-XAllowAmbiguousTypes switches off the ambiguity check.
What about things like this:
class D a b | a -> b where ..
h :: D Int b => Int
The Int may well fix 'b' at the call site, so that signature should
not be rejected. Moreover, using *visible* fundeps is too
conservative. Consider
class X a b where ...
class D a b | a -> b where ...
instance D a b => X [a] b where...
h :: X a b => a -> a
Here h's type looks ambiguous in 'b', but here's a legal call:
...(h [True])...
That gives rise to a (X [Bool] beta) constraint, and using the
instance means we need (D Bool beta) and that fixes 'beta' via D's
fundep!
Behind all these special cases there is a simple guiding principle.
Consider
f :: <type>
f = ...blah...
g :: <type>
g = f
You would think that the definition of g would surely typecheck!
After all f has exactly the same type, and g=f. But in fact f's type
is instantiated and the instantiated constraints are solved against
the originals, so in the case an ambiguous type it won't work.
Consider our earlier example f :: C a => Int. Then in g's definition,
we'll instantiate to (C alpha) and try to deduce (C alpha) from (C a),
and fail.
So in fact we use this as our *definition* of ambiguity. We use a
very similar test for *inferred* types, to ensure that they are
unambiguous. See Note [Impedence matching] in TcBinds.
This test is very conveniently implemented by calling
tcSubType <type> <type>
This neatly takes account of the functional dependecy stuff above,
and implicit parameter (see Note [Implicit parameters and ambiguity]).
What about this, though?
g :: C [a] => Int
Is every call to 'g' ambiguous? After all, we might have
intance C [a] where ...
at the call site. So maybe that type is ok! Indeed even f's
quintessentially ambiguous type might, just possibly be callable:
with -XFlexibleInstances we could have
instance C a where ...
and now a call could be legal after all! Well, we'll reject this
unless the instance is available *here*.
Side note: the ambiguity check is only used for *user* types, not for
types coming from inteface files. The latter can legitimately have
ambiguous types. Example
class S a where s :: a -> (Int,Int)
instance S Char where s _ = (1,1)
f:: S a => [a] -> Int -> (Int,Int)
f (_::[a]) x = (a*x,b)
where (a,b) = s (undefined::a)
Here the worker for f gets the type
fw :: forall a. S a => Int -> (# Int, Int #)
Note [Implicit parameters and ambiguity]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Only a *class* predicate can give rise to ambiguity
An *implicit parameter* cannot. For example:
foo :: (?x :: [a]) => Int
foo = length ?x
is fine. The call site will suppply a particular 'x'
Furthermore, the type variables fixed by an implicit parameter
propagate to the others. E.g.
foo :: (Show a, ?x::[a]) => Int
foo = show (?x++?x)
The type of foo looks ambiguous. But it isn't, because at a call site
we might have
let ?x = 5::Int in foo
and all is well. In effect, implicit parameters are, well, parameters,
so we can take their type variables into account as part of the
"tau-tvs" stuff. This is done in the function 'FunDeps.grow'.
-}
checkThetaCtxt :: UserTypeCtxt -> ThetaType -> SDoc
checkThetaCtxt ctxt theta
= vcat [ptext (sLit "In the context:") <+> pprTheta theta,
ptext (sLit "While checking") <+> pprUserTypeCtxt ctxt ]
eqPredTyErr, predTyVarErr, predTupleErr, predIrredErr, predIrredBadCtxtErr :: PredType -> SDoc
eqPredTyErr pred = ptext (sLit "Illegal equational constraint") <+> pprType pred
$$
parens (ptext (sLit "Use GADTs or TypeFamilies to permit this"))
predTyVarErr pred = hang (ptext (sLit "Non type-variable argument"))
2 (ptext (sLit "in the constraint:") <+> pprType pred)
predTupleErr pred = hang (ptext (sLit "Illegal tuple constraint:") <+> pprType pred)
2 (parens constraintKindsMsg)
predIrredErr pred = hang (ptext (sLit "Illegal constraint:") <+> pprType pred)
2 (parens constraintKindsMsg)
predIrredBadCtxtErr pred = hang (ptext (sLit "Illegal constraint") <+> quotes (pprType pred)
<+> ptext (sLit "in a superclass/instance context"))
2 (parens undecidableMsg)
constraintSynErr :: Type -> SDoc
constraintSynErr kind = hang (ptext (sLit "Illegal constraint synonym of kind:") <+> quotes (ppr kind))
2 (parens constraintKindsMsg)
dupPredWarn :: [[PredType]] -> SDoc
dupPredWarn dups = ptext (sLit "Duplicate constraint(s):") <+> pprWithCommas pprType (map head dups)
arityErr :: Outputable a => String -> a -> Int -> Int -> SDoc
arityErr kind name n m
= hsep [ text kind, quotes (ppr name), ptext (sLit "should have"),
n_arguments <> comma, text "but has been given",
if m==0 then text "none" else int m]
where
n_arguments | n == 0 = ptext (sLit "no arguments")
| n == 1 = ptext (sLit "1 argument")
| True = hsep [int n, ptext (sLit "arguments")]
{-
************************************************************************
* *
\subsection{Checking for a decent instance head type}
* *
************************************************************************
@checkValidInstHead@ checks the type {\em and} its syntactic constraints:
it must normally look like: @instance Foo (Tycon a b c ...) ...@
The exceptions to this syntactic checking: (1)~if the @GlasgowExts@
flag is on, or (2)~the instance is imported (they must have been
compiled elsewhere). In these cases, we let them go through anyway.
We can also have instances for functions: @instance Foo (a -> b) ...@.
-}
checkValidInstHead :: UserTypeCtxt -> Class -> [Type] -> TcM ()
checkValidInstHead ctxt clas cls_args
= do { dflags <- getDynFlags
; checkTc (clas `notElem` abstractClasses)
(instTypeErr clas cls_args abstract_class_msg)
-- Check language restrictions;
-- but not for SPECIALISE isntance pragmas
; let ty_args = dropWhile isKind cls_args
; unless spec_inst_prag $
do { checkTc (xopt Opt_TypeSynonymInstances dflags ||
all tcInstHeadTyNotSynonym ty_args)
(instTypeErr clas cls_args head_type_synonym_msg)
; checkTc (xopt Opt_FlexibleInstances dflags ||
all tcInstHeadTyAppAllTyVars ty_args)
(instTypeErr clas cls_args head_type_args_tyvars_msg)
; checkTc (xopt Opt_MultiParamTypeClasses dflags ||
length ty_args == 1 || -- Only count type arguments
(xopt Opt_NullaryTypeClasses dflags &&
null ty_args))
(instTypeErr clas cls_args head_one_type_msg) }
-- May not contain type family applications
; mapM_ checkTyFamFreeness ty_args
; mapM_ checkValidMonoType ty_args
-- For now, I only allow tau-types (not polytypes) in
-- the head of an instance decl.
-- E.g. instance C (forall a. a->a) is rejected
-- One could imagine generalising that, but I'm not sure
-- what all the consequences might be
}
where
spec_inst_prag = case ctxt of { SpecInstCtxt -> True; _ -> False }
head_type_synonym_msg = parens (
text "All instance types must be of the form (T t1 ... tn)" $$
text "where T is not a synonym." $$
text "Use TypeSynonymInstances if you want to disable this.")
head_type_args_tyvars_msg = parens (vcat [
text "All instance types must be of the form (T a1 ... an)",
text "where a1 ... an are *distinct type variables*,",
text "and each type variable appears at most once in the instance head.",
text "Use FlexibleInstances if you want to disable this."])
head_one_type_msg = parens (
text "Only one type can be given in an instance head." $$
text "Use MultiParamTypeClasses if you want to allow more, or zero.")
abstract_class_msg =
text "The class is abstract, manual instances are not permitted."
abstractClasses :: [ Class ]
abstractClasses = [ coercibleClass ] -- See Note [Coercible Instances]
instTypeErr :: Class -> [Type] -> SDoc -> SDoc
instTypeErr cls tys msg
= hang (hang (ptext (sLit "Illegal instance declaration for"))
2 (quotes (pprClassPred cls tys)))
2 msg
{-
validDeivPred checks for OK 'deriving' context. See Note [Exotic
derived instance contexts] in TcDeriv. However the predicate is
here because it uses sizeTypes, fvTypes.
Also check for a bizarre corner case, when the derived instance decl
would look like
instance C a b => D (T a) where ...
Note that 'b' isn't a parameter of T. This gives rise to all sorts of
problems; in particular, it's hard to compare solutions for equality
when finding the fixpoint, and that means the inferContext loop does
not converge. See Trac #5287.
-}
validDerivPred :: TyVarSet -> PredType -> Bool
validDerivPred tv_set pred
= case classifyPredType pred of
ClassPred _ tys -> check_tys tys
TuplePred ps -> all (validDerivPred tv_set) ps
EqPred {} -> False -- reject equality constraints
_ -> True -- Non-class predicates are ok
where
check_tys tys = hasNoDups fvs
&& sizeTypes tys == fromIntegral (length fvs)
&& all (`elemVarSet` tv_set) fvs
fvs = fvType pred
{-
************************************************************************
* *
\subsection{Checking instance for termination}
* *
************************************************************************
-}
checkValidInstance :: UserTypeCtxt -> LHsType Name -> Type
-> TcM ([TyVar], ThetaType, Class, [Type])
checkValidInstance ctxt hs_type ty
| Just (clas,inst_tys) <- getClassPredTys_maybe tau
, inst_tys `lengthIs` classArity clas
= do { setSrcSpan head_loc (checkValidInstHead ctxt clas inst_tys)
; checkValidTheta ctxt theta
-- The Termination and Coverate Conditions
-- Check that instance inference will terminate (if we care)
-- For Haskell 98 this will already have been done by checkValidTheta,
-- but as we may be using other extensions we need to check.
--
-- Note that the Termination Condition is *more conservative* than
-- the checkAmbiguity test we do on other type signatures
-- e.g. Bar a => Bar Int is ambiguous, but it also fails
-- the termination condition, because 'a' appears more often
-- in the constraint than in the head
; undecidable_ok <- xoptM Opt_UndecidableInstances
; if undecidable_ok
then checkAmbiguity ctxt ty
else checkInstTermination inst_tys theta
; case (checkInstCoverage undecidable_ok clas theta inst_tys) of
IsValid -> return () -- Check succeeded
NotValid msg -> addErrTc (instTypeErr clas inst_tys msg)
; return (tvs, theta, clas, inst_tys) }
| otherwise
= failWithTc (ptext (sLit "Malformed instance head:") <+> ppr tau)
where
(tvs, theta, tau) = tcSplitSigmaTy ty
-- The location of the "head" of the instance
head_loc = case hs_type of
L _ (HsForAllTy _ _ _ _ (L loc _)) -> loc
L loc _ -> loc
{-
Note [Paterson conditions]
~~~~~~~~~~~~~~~~~~~~~~~~~~
Termination test: the so-called "Paterson conditions" (see Section 5 of
"Understanding functionsl dependencies via Constraint Handling Rules,
JFP Jan 2007).
We check that each assertion in the context satisfies:
(1) no variable has more occurrences in the assertion than in the head, and
(2) the assertion has fewer constructors and variables (taken together
and counting repetitions) than the head.
This is only needed with -fglasgow-exts, as Haskell 98 restrictions
(which have already been checked) guarantee termination.
The underlying idea is that
for any ground substitution, each assertion in the
context has fewer type constructors than the head.
-}
checkInstTermination :: [TcType] -> ThetaType -> TcM ()
-- See Note [Paterson conditions]
checkInstTermination tys theta
= check_preds theta
where
fvs = fvTypes tys
size = sizeTypes tys
check_preds :: [PredType] -> TcM ()
check_preds preds = mapM_ check preds
check :: PredType -> TcM ()
check pred
= case classifyPredType pred of
TuplePred preds -> check_preds preds -- Look inside tuple predicates; Trac #8359
EqPred {} -> return () -- You can't get from equalities
-- to class predicates, so this is safe
_other -- ClassPred, IrredPred
| not (null bad_tvs)
-> addErrTc (predUndecErr pred (nomoreMsg bad_tvs) $$ parens undecidableMsg)
| sizePred pred >= size
-> addErrTc (predUndecErr pred smallerMsg $$ parens undecidableMsg)
| otherwise
-> return ()
where
bad_tvs = filterOut isKindVar (fvType pred \\ fvs)
-- Rightly or wrongly, we only check for
-- excessive occurrences of *type* variables.
-- e.g. type instance Demote {T k} a = T (Demote {k} (Any {k}))
predUndecErr :: PredType -> SDoc -> SDoc
predUndecErr pred msg = sep [msg,
nest 2 (ptext (sLit "in the constraint:") <+> pprType pred)]
nomoreMsg :: [TcTyVar] -> SDoc
nomoreMsg tvs
= sep [ ptext (sLit "Variable") <> plural tvs <+> quotes (pprWithCommas ppr tvs)
, (if isSingleton tvs then ptext (sLit "occurs")
else ptext (sLit "occur"))
<+> ptext (sLit "more often than in the instance head") ]
smallerMsg, undecidableMsg, constraintKindsMsg :: SDoc
smallerMsg = ptext (sLit "Constraint is no smaller than the instance head")
undecidableMsg = ptext (sLit "Use UndecidableInstances to permit this")
constraintKindsMsg = ptext (sLit "Use ConstraintKinds to permit this")
{-
Note [Associated type instances]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We allow this:
class C a where
type T x a
instance C Int where
type T (S y) Int = y
type T Z Int = Char
Note that
a) The variable 'x' is not bound by the class decl
b) 'x' is instantiated to a non-type-variable in the instance
c) There are several type instance decls for T in the instance
All this is fine. Of course, you can't give any *more* instances
for (T ty Int) elsewhere, because it's an *associated* type.
Note [Checking consistent instantiation]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class C a b where
type T a x b
instance C [p] Int
type T [p] y Int = (p,y,y) -- Induces the family instance TyCon
-- type TR p y = (p,y,y)
So we
* Form the mini-envt from the class type variables a,b
to the instance decl types [p],Int: [a->[p], b->Int]
* Look at the tyvars a,x,b of the type family constructor T
(it shares tyvars with the class C)
* Apply the mini-evnt to them, and check that the result is
consistent with the instance types [p] y Int
We do *not* assume (at this point) the the bound variables of
the assoicated type instance decl are the same as for the parent
instance decl. So, for example,
instance C [p] Int
type T [q] y Int = ...
would work equally well. Reason: making the *kind* variables line
up is much harder. Example (Trac #7282):
class Foo (xs :: [k]) where
type Bar xs :: *
instance Foo '[] where
type Bar '[] = Int
Here the instance decl really looks like
instance Foo k ('[] k) where
type Bar k ('[] k) = Int
but the k's are not scoped, and hence won't match Uniques.
So instead we just match structure, with tcMatchTyX, and check
that distinct type variables match 1-1 with distinct type variables.
HOWEVER, we *still* make the instance type variables scope over the
type instances, to pick up non-obvious kinds. Eg
class Foo (a :: k) where
type F a
instance Foo (b :: k -> k) where
type F b = Int
Here the instance is kind-indexed and really looks like
type F (k->k) (b::k->k) = Int
But if the 'b' didn't scope, we would make F's instance too
poly-kinded.
-}
checkConsistentFamInst
:: Maybe ( Class
, VarEnv Type ) -- ^ Class of associated type
-- and instantiation of class TyVars
-> TyCon -- ^ Family tycon
-> [TyVar] -- ^ Type variables of the family instance
-> [Type] -- ^ Type patterns from instance
-> TcM ()
-- See Note [Checking consistent instantiation]
checkConsistentFamInst Nothing _ _ _ = return ()
checkConsistentFamInst (Just (clas, mini_env)) fam_tc at_tvs at_tys
= do { -- Check that the associated type indeed comes from this class
checkTc (Just clas == tyConAssoc_maybe fam_tc)
(badATErr (className clas) (tyConName fam_tc))
-- See Note [Checking consistent instantiation] in TcTyClsDecls
-- Check right to left, so that we spot type variable
-- inconsistencies before (more confusing) kind variables
; discardResult $ foldrM check_arg emptyTvSubst $
tyConTyVars fam_tc `zip` at_tys }
where
at_tv_set = mkVarSet at_tvs
check_arg :: (TyVar, Type) -> TvSubst -> TcM TvSubst
check_arg (fam_tc_tv, at_ty) subst
| Just inst_ty <- lookupVarEnv mini_env fam_tc_tv
= case tcMatchTyX at_tv_set subst at_ty inst_ty of
Just subst | all_distinct subst -> return subst
_ -> failWithTc $ wrongATArgErr at_ty inst_ty
-- No need to instantiate here, because the axiom
-- uses the same type variables as the assocated class
| otherwise
= return subst -- Allow non-type-variable instantiation
-- See Note [Associated type instances]
all_distinct :: TvSubst -> Bool
-- True if all the variables mapped the substitution
-- map to *distinct* type *variables*
all_distinct subst = go [] at_tvs
where
go _ [] = True
go acc (tv:tvs) = case lookupTyVar subst tv of
Nothing -> go acc tvs
Just ty | Just tv' <- tcGetTyVar_maybe ty
, tv' `notElem` acc
-> go (tv' : acc) tvs
_other -> False
badATErr :: Name -> Name -> SDoc
badATErr clas op
= hsep [ptext (sLit "Class"), quotes (ppr clas),
ptext (sLit "does not have an associated type"), quotes (ppr op)]
wrongATArgErr :: Type -> Type -> SDoc
wrongATArgErr ty instTy =
sep [ ptext (sLit "Type indexes must match class instance head")
, ptext (sLit "Found") <+> quotes (ppr ty)
<+> ptext (sLit "but expected") <+> quotes (ppr instTy)
]
{-
************************************************************************
* *
Checking type instance well-formedness and termination
* *
************************************************************************
-}
-- Check that a "type instance" is well-formed (which includes decidability
-- unless -XUndecidableInstances is given).
--
checkValidTyFamInst :: Maybe ( Class, VarEnv Type )
-> TyCon -> CoAxBranch -> TcM ()
checkValidTyFamInst mb_clsinfo fam_tc
(CoAxBranch { cab_tvs = tvs, cab_lhs = typats
, cab_rhs = rhs, cab_loc = loc })
= setSrcSpan loc $
do { checkValidFamPats fam_tc tvs typats
-- The argument patterns, and RHS, are all boxed tau types
-- E.g Reject type family F (a :: k1) :: k2
-- type instance F (forall a. a->a) = ...
-- type instance F Int# = ...
-- type instance F Int = forall a. a->a
-- type instance F Int = Int#
-- See Trac #9357
; mapM_ checkValidMonoType typats
; checkValidMonoType rhs
-- We have a decidable instance unless otherwise permitted
; undecidable_ok <- xoptM Opt_UndecidableInstances
; unless undecidable_ok $
mapM_ addErrTc (checkFamInstRhs typats (tcTyFamInsts rhs))
-- Check that type patterns match the class instance head
; checkConsistentFamInst mb_clsinfo fam_tc tvs typats }
-- Make sure that each type family application is
-- (1) strictly smaller than the lhs,
-- (2) mentions no type variable more often than the lhs, and
-- (3) does not contain any further type family instances.
--
checkFamInstRhs :: [Type] -- lhs
-> [(TyCon, [Type])] -- type family instances
-> [MsgDoc]
checkFamInstRhs lhsTys famInsts
= mapMaybe check famInsts
where
size = sizeTypes lhsTys
fvs = fvTypes lhsTys
check (tc, tys)
| not (all isTyFamFree tys)
= Just (famInstUndecErr famInst nestedMsg $$ parens undecidableMsg)
| not (null bad_tvs)
= Just (famInstUndecErr famInst (nomoreMsg bad_tvs) $$ parens undecidableMsg)
| size <= sizeTypes tys
= Just (famInstUndecErr famInst smallerAppMsg $$ parens undecidableMsg)
| otherwise
= Nothing
where
famInst = TyConApp tc tys
bad_tvs = filterOut isKindVar (fvTypes tys \\ fvs)
-- Rightly or wrongly, we only check for
-- excessive occurrences of *type* variables.
-- e.g. type instance Demote {T k} a = T (Demote {k} (Any {k}))
checkValidFamPats :: TyCon -> [TyVar] -> [Type] -> TcM ()
-- Patterns in a 'type instance' or 'data instance' decl should
-- a) contain no type family applications
-- (vanilla synonyms are fine, though)
-- b) properly bind all their free type variables
-- e.g. we disallow (Trac #7536)
-- type T a = Int
-- type instance F (T a) = a
-- c) Have the right number of patterns
checkValidFamPats fam_tc tvs ty_pats
= ASSERT( length ty_pats == tyConArity fam_tc )
-- A family instance must have exactly the same number of type
-- parameters as the family declaration. You can't write
-- type family F a :: * -> *
-- type instance F Int y = y
-- because then the type (F Int) would be like (\y.y)
-- But this is checked at the time the axiom is created
do { mapM_ checkTyFamFreeness ty_pats
; let unbound_tvs = filterOut (`elemVarSet` exactTyVarsOfTypes ty_pats) tvs
; checkTc (null unbound_tvs) (famPatErr fam_tc unbound_tvs ty_pats) }
-- Ensure that no type family instances occur in a type.
checkTyFamFreeness :: Type -> TcM ()
checkTyFamFreeness ty
= checkTc (isTyFamFree ty) $
tyFamInstIllegalErr ty
-- Check that a type does not contain any type family applications.
--
isTyFamFree :: Type -> Bool
isTyFamFree = null . tcTyFamInsts
-- Error messages
tyFamInstIllegalErr :: Type -> SDoc
tyFamInstIllegalErr ty
= hang (ptext (sLit "Illegal type synonym family application in instance") <>
colon) 2 $
ppr ty
famInstUndecErr :: Type -> SDoc -> SDoc
famInstUndecErr ty msg
= sep [msg,
nest 2 (ptext (sLit "in the type family application:") <+>
pprType ty)]
famPatErr :: TyCon -> [TyVar] -> [Type] -> SDoc
famPatErr fam_tc tvs pats
= hang (ptext (sLit "Family instance purports to bind type variable") <> plural tvs
<+> pprQuotedList tvs)
2 (hang (ptext (sLit "but the real LHS (expanding synonyms) is:"))
2 (pprTypeApp fam_tc (map expandTypeSynonyms pats) <+> ptext (sLit "= ...")))
nestedMsg, smallerAppMsg :: SDoc
nestedMsg = ptext (sLit "Nested type family application")
smallerAppMsg = ptext (sLit "Application is no smaller than the instance head")
{-
************************************************************************
* *
The "Paterson size" of a type
* *
************************************************************************
-}
{-
Note [Paterson conditions on PredTypes]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We are considering whether *class* constraints terminate
(see Note [Paterson conditions]). Precisely, the Paterson conditions
would have us check that "the constraint has fewer constructors and variables
(taken together and counting repetitions) than the head.".
However, we can be a bit more refined by looking at which kind of constraint
this actually is. There are two main tricks:
1. It seems like it should be OK not to count the tuple type constructor
for a PredType like (Show a, Eq a) :: Constraint, since we don't
count the "implicit" tuple in the ThetaType itself.
In fact, the Paterson test just checks *each component* of the top level
ThetaType against the size bound, one at a time. By analogy, it should be
OK to return the size of the *largest* tuple component as the size of the
whole tuple.
2. Once we get into an implicit parameter or equality we
can't get back to a class constraint, so it's safe
to say "size 0". See Trac #4200.
NB: we don't want to detect PredTypes in sizeType (and then call
sizePred on them), or we might get an infinite loop if that PredType
is irreducible. See Trac #5581.
-}
data TypeSize = TS Int | TSBig -- TSBig behaves like positive infinity
-- Used when we encounter a type function
instance Num TypeSize where
fromInteger n = TS (fromInteger n)
TS a + TS b = TS (a+b)
_ + _ = TSBig
negate = panic "TypeSize:negate"
abs = panic "TypeSize:abs"
signum = panic "TypeSize:signum"
(*) = panic "TypeSize:*"
(-) = panic "TypeSize:-"
instance Eq TypeSize where
TS a == TS b = a==b
TSBig == TSBig = True
_ == _ = False
instance Ord TypeSize where
TS a `compare` TS b = a `compare` b
TS _ `compare` TSBig = LT
TSBig `compare` TS _ = GT
TSBig `compare` TSBig = EQ
sizeType :: Type -> TypeSize
-- Size of a type: the number of variables and constructors
sizeType ty | Just exp_ty <- tcView ty = sizeType exp_ty
sizeType (TyVarTy {}) = 1
sizeType (TyConApp tc tys)
| isTypeFamilyTyCon tc = TSBig -- Type-family applications can
-- expand to any arbitrary size
| otherwise = sizeTypes tys + 1
sizeType (LitTy {}) = 1
sizeType (FunTy arg res) = sizeType arg + sizeType res + 1
sizeType (AppTy fun arg) = sizeType fun + sizeType arg
sizeType (ForAllTy _ ty) = sizeType ty
sizeTypes :: [Type] -> TypeSize
-- IA0_NOTE: Avoid kinds.
sizeTypes xs = sum (map sizeType tys)
where tys = filter (not . isKind) xs
-- Note [Size of a predicate]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~
-- We are considering whether class constraints terminate.
-- Equality constraints and constraints for the implicit
-- parameter class always termiante so it is safe to say "size 0".
-- (Implicit parameter constraints always terminate because
-- there are no instances for them---they are only solved by
-- "local instances" in expressions).
-- See Trac #4200.
sizePred :: PredType -> TypeSize
sizePred p = go (classifyPredType p)
where
go (ClassPred cls tys')
| isIPClass cls = 0 -- See Note [Size of a predicate]
| otherwise = sizeTypes tys'
go (EqPred {}) = 0 -- See Note [Size of a predicate]
go (TuplePred ts) = sum (map sizePred ts)
go (IrredPred ty) = sizeType ty
{-
************************************************************************
* *
\subsection{Auxiliary functions}
* *
************************************************************************
-}
-- Free variables of a type, retaining repetitions, and expanding synonyms
fvType :: Type -> [TyVar]
fvType ty | Just exp_ty <- tcView ty = fvType exp_ty
fvType (TyVarTy tv) = [tv]
fvType (TyConApp _ tys) = fvTypes tys
fvType (LitTy {}) = []
fvType (FunTy arg res) = fvType arg ++ fvType res
fvType (AppTy fun arg) = fvType fun ++ fvType arg
fvType (ForAllTy tyvar ty) = filter (/= tyvar) (fvType ty)
fvTypes :: [Type] -> [TyVar]
fvTypes tys = concat (map fvType tys)
| green-haskell/ghc | compiler/typecheck/TcValidity.hs | bsd-3-clause | 55,441 | 5 | 16 | 15,730 | 8,264 | 4,212 | 4,052 | -1 | -1 |
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
Typechecking class declarations
-}
{-# LANGUAGE CPP #-}
module TcClassDcl ( tcClassSigs, tcClassDecl2,
findMethodBind, instantiateMethod,
tcClassMinimalDef,
HsSigFun, mkHsSigFun, lookupHsSig, emptyHsSigs,
tcMkDeclCtxt, tcAddDeclCtxt, badMethodErr,
tcATDefault
) where
#include "HsVersions.h"
import HsSyn
import TcEnv
import TcPat( addInlinePrags, lookupPragEnv, emptyPragEnv )
import TcEvidence( idHsWrapper )
import TcBinds
import TcUnify
import TcHsType
import TcMType
import Type ( getClassPredTys_maybe, varSetElemsWellScoped )
import TcType
import TcRnMonad
import BuildTyCl( TcMethInfo )
import Class
import Coercion ( pprCoAxiom )
import DynFlags
import FamInst
import FamInstEnv
import Id
import Name
import NameEnv
import NameSet
import Var
import VarEnv
import VarSet
import Outputable
import SrcLoc
import TyCon
import Maybes
import BasicTypes
import Bag
import FastString
import BooleanFormula
import Util
import Control.Monad
import Data.List ( mapAccumL )
{-
Dictionary handling
~~~~~~~~~~~~~~~~~~~
Every class implicitly declares a new data type, corresponding to dictionaries
of that class. So, for example:
class (D a) => C a where
op1 :: a -> a
op2 :: forall b. Ord b => a -> b -> b
would implicitly declare
data CDict a = CDict (D a)
(a -> a)
(forall b. Ord b => a -> b -> b)
(We could use a record decl, but that means changing more of the existing apparatus.
One step at at time!)
For classes with just one superclass+method, we use a newtype decl instead:
class C a where
op :: forallb. a -> b -> b
generates
newtype CDict a = CDict (forall b. a -> b -> b)
Now DictTy in Type is just a form of type synomym:
DictTy c t = TyConTy CDict `AppTy` t
Death to "ExpandingDicts".
************************************************************************
* *
Type-checking the class op signatures
* *
************************************************************************
-}
tcClassSigs :: Name -- Name of the class
-> [LSig Name]
-> LHsBinds Name
-> TcM [TcMethInfo] -- Exactly one for each method
tcClassSigs clas sigs def_methods
= do { traceTc "tcClassSigs 1" (ppr clas)
; gen_dm_prs <- concat <$> mapM (addLocM tc_gen_sig) gen_sigs
; let gen_dm_env :: NameEnv Type
gen_dm_env = mkNameEnv gen_dm_prs
; op_info <- concat <$> mapM (addLocM (tc_sig gen_dm_env)) vanilla_sigs
; let op_names = mkNameSet [ n | (n,_,_) <- op_info ]
; sequence_ [ failWithTc (badMethodErr clas n)
| n <- dm_bind_names, not (n `elemNameSet` op_names) ]
-- Value binding for non class-method (ie no TypeSig)
; sequence_ [ failWithTc (badGenericMethod clas n)
| (n,_) <- gen_dm_prs, not (n `elem` dm_bind_names) ]
-- Generic signature without value binding
; traceTc "tcClassSigs 2" (ppr clas)
; return op_info }
where
vanilla_sigs = [L loc (nm,ty) | L loc (ClassOpSig False nm ty) <- sigs]
gen_sigs = [L loc (nm,ty) | L loc (ClassOpSig True nm ty) <- sigs]
dm_bind_names :: [Name] -- These ones have a value binding in the class decl
dm_bind_names = [op | L _ (FunBind {fun_id = L _ op}) <- bagToList def_methods]
tc_sig :: NameEnv Type -> ([Located Name], LHsSigType Name)
-> TcM [TcMethInfo]
tc_sig gen_dm_env (op_names, op_hs_ty)
= do { traceTc "ClsSig 1" (ppr op_names)
; op_ty <- tcClassSigType op_names op_hs_ty -- Class tyvars already in scope
; traceTc "ClsSig 2" (ppr op_names)
; return [ (op_name, op_ty, f op_name) | L _ op_name <- op_names ] }
where
f nm | Just ty <- lookupNameEnv gen_dm_env nm = Just (GenericDM ty)
| nm `elem` dm_bind_names = Just VanillaDM
| otherwise = Nothing
tc_gen_sig (op_names, gen_hs_ty)
= do { gen_op_ty <- tcClassSigType op_names gen_hs_ty
; return [ (op_name, gen_op_ty) | L _ op_name <- op_names ] }
{-
************************************************************************
* *
Class Declarations
* *
************************************************************************
-}
tcClassDecl2 :: LTyClDecl Name -- The class declaration
-> TcM (LHsBinds Id)
tcClassDecl2 (L loc (ClassDecl {tcdLName = class_name, tcdSigs = sigs,
tcdMeths = default_binds}))
= recoverM (return emptyLHsBinds) $
setSrcSpan loc $
do { clas <- tcLookupLocatedClass class_name
-- We make a separate binding for each default method.
-- At one time I used a single AbsBinds for all of them, thus
-- AbsBind [d] [dm1, dm2, dm3] { dm1 = ...; dm2 = ...; dm3 = ... }
-- But that desugars into
-- ds = \d -> (..., ..., ...)
-- dm1 = \d -> case ds d of (a,b,c) -> a
-- And since ds is big, it doesn't get inlined, so we don't get good
-- default methods. Better to make separate AbsBinds for each
; let (tyvars, _, _, op_items) = classBigSig clas
prag_fn = mkPragEnv sigs default_binds
sig_fn = mkHsSigFun sigs
clas_tyvars = snd (tcSuperSkolTyVars tyvars)
pred = mkClassPred clas (mkTyVarTys clas_tyvars)
; this_dict <- newEvVar pred
; let tc_item = tcDefMeth clas clas_tyvars this_dict
default_binds sig_fn prag_fn
; dm_binds <- tcExtendTyVarEnv clas_tyvars $
mapM tc_item op_items
; return (unionManyBags dm_binds) }
tcClassDecl2 d = pprPanic "tcClassDecl2" (ppr d)
tcDefMeth :: Class -> [TyVar] -> EvVar -> LHsBinds Name
-> HsSigFun -> TcPragEnv -> ClassOpItem
-> TcM (LHsBinds TcId)
-- Generate code for default methods
-- This is incompatible with Hugs, which expects a polymorphic
-- default method for every class op, regardless of whether or not
-- the programmer supplied an explicit default decl for the class.
-- (If necessary we can fix that, but we don't have a convenient Id to hand.)
tcDefMeth _ _ _ _ _ prag_fn (sel_id, Nothing)
= do { -- No default method
mapM_ (addLocM (badDmPrag sel_id))
(lookupPragEnv prag_fn (idName sel_id))
; return emptyBag }
tcDefMeth clas tyvars this_dict binds_in hs_sig_fn prag_fn
(sel_id, Just (dm_name, dm_spec))
| Just (L bind_loc dm_bind, bndr_loc) <- findMethodBind sel_name binds_in
= do { -- First look up the default method -- It should be there!
global_dm_id <- tcLookupId dm_name
; global_dm_id <- addInlinePrags global_dm_id prags
; local_dm_name <- setSrcSpan bndr_loc (newLocalName sel_name)
-- Base the local_dm_name on the selector name, because
-- type errors from tcInstanceMethodBody come from here
; spec_prags <- discardConstraints $
tcSpecPrags global_dm_id prags
; warnTc (not (null spec_prags))
(text "Ignoring SPECIALISE pragmas on default method"
<+> quotes (ppr sel_name))
; let hs_ty = lookupHsSig hs_sig_fn sel_name
`orElse` pprPanic "tc_dm" (ppr sel_name)
-- We need the HsType so that we can bring the right
-- type variables into scope
--
-- Eg. class C a where
-- op :: forall b. Eq b => a -> [b] -> a
-- gen_op :: a -> a
-- generic gen_op :: D a => a -> a
-- The "local_dm_ty" is precisely the type in the above
-- type signatures, ie with no "forall a. C a =>" prefix
local_dm_ty = instantiateMethod clas global_dm_id (mkTyVarTys tyvars)
lm_bind = dm_bind { fun_id = L bind_loc local_dm_name }
-- Substitute the local_meth_name for the binder
-- NB: the binding is always a FunBind
warn_redundant = case dm_spec of
GenericDM {} -> True
VanillaDM -> False
-- For GenericDM, warn if the user specifies a signature
-- with redundant constraints; but not for VanillaDM, where
-- the default method may well be 'error' or something
ctxt = FunSigCtxt sel_name warn_redundant
; local_dm_sig <- instTcTySig ctxt hs_ty local_dm_ty local_dm_name
; (ev_binds, (tc_bind, _))
<- checkConstraints (ClsSkol clas) tyvars [this_dict] $
tcPolyCheck NonRecursive no_prag_fn local_dm_sig
(L bind_loc lm_bind)
; let export = ABE { abe_poly = global_dm_id
-- We have created a complete type signature in
-- instTcTySig, hence it is safe to call
-- completeSigPolyId
, abe_mono = completeIdSigPolyId local_dm_sig
, abe_wrap = idHsWrapper
, abe_inst_wrap = idHsWrapper
, abe_prags = IsDefaultMethod }
full_bind = AbsBinds { abs_tvs = tyvars
, abs_ev_vars = [this_dict]
, abs_exports = [export]
, abs_ev_binds = [ev_binds]
, abs_binds = tc_bind }
; return (unitBag (L bind_loc full_bind)) }
| otherwise = pprPanic "tcDefMeth" (ppr sel_id)
where
sel_name = idName sel_id
prags = lookupPragEnv prag_fn sel_name
no_prag_fn = emptyPragEnv -- No pragmas for local_meth_id;
-- they are all for meth_id
---------------
tcClassMinimalDef :: Name -> [LSig Name] -> [TcMethInfo] -> TcM ClassMinimalDef
tcClassMinimalDef _clas sigs op_info
= case findMinimalDef sigs of
Nothing -> return defMindef
Just mindef -> do
-- Warn if the given mindef does not imply the default one
-- That is, the given mindef should at least ensure that the
-- class ops without default methods are required, since we
-- have no way to fill them in otherwise
whenIsJust (isUnsatisfied (mindef `impliesAtom`) defMindef) $
(\bf -> addWarnTc (warningMinimalDefIncomplete bf))
return mindef
where
-- By default require all methods without a default
-- implementation whose names don't start with '_'
defMindef :: ClassMinimalDef
defMindef = mkAnd [ noLoc (mkVar name)
| (name, _, Nothing) <- op_info
, not (startsWithUnderscore (getOccName name)) ]
instantiateMethod :: Class -> Id -> [TcType] -> TcType
-- Take a class operation, say
-- op :: forall ab. C a => forall c. Ix c => (b,c) -> a
-- Instantiate it at [ty1,ty2]
-- Return the "local method type":
-- forall c. Ix x => (ty2,c) -> ty1
instantiateMethod clas sel_id inst_tys
= ASSERT( ok_first_pred ) local_meth_ty
where
(sel_tyvars,sel_rho) = tcSplitForAllTys (idType sel_id)
rho_ty = ASSERT( length sel_tyvars == length inst_tys )
substTyWith sel_tyvars inst_tys sel_rho
(first_pred, local_meth_ty) = tcSplitPredFunTy_maybe rho_ty
`orElse` pprPanic "tcInstanceMethod" (ppr sel_id)
ok_first_pred = case getClassPredTys_maybe first_pred of
Just (clas1, _tys) -> clas == clas1
Nothing -> False
-- The first predicate should be of form (C a b)
-- where C is the class in question
---------------------------
type HsSigFun = NameEnv (LHsSigType Name)
emptyHsSigs :: HsSigFun
emptyHsSigs = emptyNameEnv
mkHsSigFun :: [LSig Name] -> HsSigFun
mkHsSigFun sigs = mkNameEnv [(n, hs_ty)
| L _ (ClassOpSig False ns hs_ty) <- sigs
, L _ n <- ns ]
lookupHsSig :: HsSigFun -> Name -> Maybe (LHsSigType Name)
lookupHsSig = lookupNameEnv
---------------------------
findMethodBind :: Name -- Selector name
-> LHsBinds Name -- A group of bindings
-> Maybe (LHsBind Name, SrcSpan)
-- Returns the binding, and the binding
-- site of the method binder
findMethodBind sel_name binds
= foldlBag mplus Nothing (mapBag f binds)
where
f bind@(L _ (FunBind { fun_id = L bndr_loc op_name }))
| op_name == sel_name
= Just (bind, bndr_loc)
f _other = Nothing
---------------------------
findMinimalDef :: [LSig Name] -> Maybe ClassMinimalDef
findMinimalDef = firstJusts . map toMinimalDef
where
toMinimalDef :: LSig Name -> Maybe ClassMinimalDef
toMinimalDef (L _ (MinimalSig _ (L _ bf))) = Just (fmap unLoc bf)
toMinimalDef _ = Nothing
{-
Note [Polymorphic methods]
~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
class Foo a where
op :: forall b. Ord b => a -> b -> b -> b
instance Foo c => Foo [c] where
op = e
When typechecking the binding 'op = e', we'll have a meth_id for op
whose type is
op :: forall c. Foo c => forall b. Ord b => [c] -> b -> b -> b
So tcPolyBinds must be capable of dealing with nested polytypes;
and so it is. See TcBinds.tcMonoBinds (with type-sig case).
Note [Silly default-method bind]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When we pass the default method binding to the type checker, it must
look like op2 = e
not $dmop2 = e
otherwise the "$dm" stuff comes out error messages. But we want the
"$dm" to come out in the interface file. So we typecheck the former,
and wrap it in a let, thus
$dmop2 = let op2 = e in op2
This makes the error messages right.
************************************************************************
* *
Error messages
* *
************************************************************************
-}
tcMkDeclCtxt :: TyClDecl Name -> SDoc
tcMkDeclCtxt decl = hsep [text "In the", pprTyClDeclFlavour decl,
text "declaration for", quotes (ppr (tcdName decl))]
tcAddDeclCtxt :: TyClDecl Name -> TcM a -> TcM a
tcAddDeclCtxt decl thing_inside
= addErrCtxt (tcMkDeclCtxt decl) thing_inside
badMethodErr :: Outputable a => a -> Name -> SDoc
badMethodErr clas op
= hsep [text "Class", quotes (ppr clas),
text "does not have a method", quotes (ppr op)]
badGenericMethod :: Outputable a => a -> Name -> SDoc
badGenericMethod clas op
= hsep [text "Class", quotes (ppr clas),
text "has a generic-default signature without a binding", quotes (ppr op)]
{-
badGenericInstanceType :: LHsBinds Name -> SDoc
badGenericInstanceType binds
= vcat [text "Illegal type pattern in the generic bindings",
nest 2 (ppr binds)]
missingGenericInstances :: [Name] -> SDoc
missingGenericInstances missing
= text "Missing type patterns for" <+> pprQuotedList missing
dupGenericInsts :: [(TyCon, InstInfo a)] -> SDoc
dupGenericInsts tc_inst_infos
= vcat [text "More than one type pattern for a single generic type constructor:",
nest 2 (vcat (map ppr_inst_ty tc_inst_infos)),
text "All the type patterns for a generic type constructor must be identical"
]
where
ppr_inst_ty (_,inst) = ppr (simpleInstInfoTy inst)
-}
badDmPrag :: Id -> Sig Name -> TcM ()
badDmPrag sel_id prag
= addErrTc (text "The" <+> hsSigDoc prag <+> ptext (sLit "for default method")
<+> quotes (ppr sel_id)
<+> text "lacks an accompanying binding")
warningMinimalDefIncomplete :: ClassMinimalDef -> SDoc
warningMinimalDefIncomplete mindef
= vcat [ text "The MINIMAL pragma does not require:"
, nest 2 (pprBooleanFormulaNice mindef)
, text "but there is no default implementation." ]
tcATDefault :: Bool -- If a warning should be emitted when a default instance
-- definition is not provided by the user
-> SrcSpan
-> TCvSubst
-> NameSet
-> ClassATItem
-> TcM [FamInst]
-- ^ Construct default instances for any associated types that
-- aren't given a user definition
-- Returns [] or singleton
tcATDefault emit_warn loc inst_subst defined_ats (ATI fam_tc defs)
-- User supplied instances ==> everything is OK
| tyConName fam_tc `elemNameSet` defined_ats
= return []
-- No user instance, have defaults ==> instatiate them
-- Example: class C a where { type F a b :: *; type F a b = () }
-- instance C [x]
-- Then we want to generate the decl: type F [x] b = ()
| Just (rhs_ty, _loc) <- defs
= do { let (subst', pat_tys') = mapAccumL subst_tv inst_subst
(tyConTyVars fam_tc)
rhs' = substTyUnchecked subst' rhs_ty
tcv_set' = tyCoVarsOfTypes pat_tys'
(tv_set', cv_set') = partitionVarSet isTyVar tcv_set'
tvs' = varSetElemsWellScoped tv_set'
cvs' = varSetElemsWellScoped cv_set'
; rep_tc_name <- newFamInstTyConName (L loc (tyConName fam_tc)) pat_tys'
; let axiom = mkSingleCoAxiom Nominal rep_tc_name tvs' cvs'
fam_tc pat_tys' rhs'
-- NB: no validity check. We check validity of default instances
-- in the class definition. Because type instance arguments cannot
-- be type family applications and cannot be polytypes, the
-- validity check is redundant.
; traceTc "mk_deflt_at_instance" (vcat [ ppr fam_tc, ppr rhs_ty
, pprCoAxiom axiom ])
; fam_inst <- ASSERT( tyCoVarsOfType rhs' `subVarSet` tv_set' )
newFamInst SynFamilyInst axiom
; return [fam_inst] }
-- No defaults ==> generate a warning
| otherwise -- defs = Nothing
= do { when emit_warn $ warnMissingAT (tyConName fam_tc)
; return [] }
where
subst_tv subst tc_tv
| Just ty <- lookupVarEnv (getTvSubstEnv subst) tc_tv
= (subst, ty)
| otherwise
= (extendTCvSubst subst tc_tv ty', ty')
where
ty' = mkTyVarTy (updateTyVarKind (substTyUnchecked subst) tc_tv)
warnMissingAT :: Name -> TcM ()
warnMissingAT name
= do { warn <- woptM Opt_WarnMissingMethods
; traceTc "warn" (ppr name <+> ppr warn)
; warnTc warn -- Warn only if -Wmissing-methods
(text "No explicit" <+> text "associated type"
<+> text "or default declaration for "
<+> quotes (ppr name)) }
| nushio3/ghc | compiler/typecheck/TcClassDcl.hs | bsd-3-clause | 19,623 | 0 | 15 | 6,370 | 3,392 | 1,777 | 1,615 | 255 | 2 |
module Lets.GetSetLens (
Lens(..)
, getsetLaw
, setgetLaw
, setsetLaw
, get
, set
, modify
, (%~)
, fmodify
, (|=)
, fstL
, sndL
, mapL
, setL
, compose
, (|.)
, identity
, product
, (***)
, choice
, (|||)
, cityL
, countryL
, streetL
, suburbL
, localityL
, ageL
, nameL
, addressL
, getSuburb
, setStreet
, getAgeAndCountry
, setCityAndLocality
, getSuburbOrCity
, setStreetOrState
, modifyCityUppercase
) where
import Control.Applicative(Applicative((<*>)))
import Data.Char(toUpper)
import Data.Map(Map)
import qualified Data.Map as Map(insert, delete, lookup)
import Data.Set(Set)
import qualified Data.Set as Set(insert, delete, member)
import Lets.Data(Person(Person), Locality(Locality), Address(Address), bool)
import Prelude hiding (product)
-- $setup
-- >>> import qualified Data.Map as Map(fromList)
-- >>> import qualified Data.Set as Set(fromList)
-- >>> import Data.Char(ord)
-- >>> import Lets.Data
data Lens a b =
Lens
(a -> b -> a)
(a -> b)
-- |
--
-- >>> get fstL (0 :: Int, "abc")
-- 0
--
-- >>> get sndL ("abc", 0 :: Int)
-- 0
--
-- prop> let types = (x :: Int, y :: String) in get fstL (x, y) == x
--
-- prop> let types = (x :: Int, y :: String) in get sndL (x, y) == y
get ::
Lens a b
-> a
-> b
get (Lens _ g) =
g
-- |
--
-- >>> set fstL (0 :: Int, "abc") 1
-- (1,"abc")
--
-- >>> set sndL ("abc", 0 :: Int) 1
-- ("abc",1)
--
-- prop> let types = (x :: Int, y :: String) in set fstL (x, y) z == (z, y)
--
-- prop> let types = (x :: Int, y :: String) in set sndL (x, y) z == (x, z)
set ::
Lens a b
-> a
-> b
-> a
set (Lens s _) a =
s a
-- | The get/set law of lenses. This function should always return @True@.
getsetLaw ::
Eq a =>
Lens a b
-> a
-> Bool
getsetLaw l =
\a -> set l a (get l a) == a
-- | The set/get law of lenses. This function should always return @True@.
setgetLaw ::
Eq b =>
Lens a b
-> a
-> b
-> Bool
setgetLaw l a b =
get l (set l a b) == b
-- | The set/set law of lenses. This function should always return @True@.
setsetLaw ::
Eq a =>
Lens a b
-> a
-> b
-> b
-> Bool
setsetLaw l a b1 b2 =
set l (set l a b1) b2 == set l a b2
----
-- |
--
-- >>> modify fstL (+1) (0 :: Int, "abc")
-- (1,"abc")
--
-- >>> modify sndL (+1) ("abc", 0 :: Int)
-- ("abc",1)
--
-- prop> let types = (x :: Int, y :: String) in modify fstL id (x, y) == (x, y)
--
-- prop> let types = (x :: Int, y :: String) in modify sndL id (x, y) == (x, y)
modify ::
Lens a b
-> (b -> b)
-> a
-> a
modify =
error "todo: modify"
-- | An alias for @modify@.
(%~) ::
Lens a b
-> (b -> b)
-> a
-> a
(%~) =
modify
infixr 4 %~
-- |
--
-- >>> fstL .~ 1 $ (0 :: Int, "abc")
-- (1,"abc")
--
-- >>> sndL .~ 1 $ ("abc", 0 :: Int)
-- ("abc",1)
--
-- prop> let types = (x :: Int, y :: String) in set fstL (x, y) z == (fstL .~ z $ (x, y))
--
-- prop> let types = (x :: Int, y :: String) in set sndL (x, y) z == (sndL .~ z $ (x, y))
(.~) ::
Lens a b
-> b
-> a
-> a
(.~) =
error "todo: (.~)"
infixl 5 .~
-- |
--
-- >>> fmodify fstL (+) (5 :: Int, "abc") 8
-- (13,"abc")
--
-- >>> fmodify fstL (\n -> bool Nothing (Just (n * 2)) (even n)) (10, "abc")
-- Just (20,"abc")
--
-- >>> fmodify fstL (\n -> bool Nothing (Just (n * 2)) (even n)) (11, "abc")
-- Nothing
fmodify ::
Functor f =>
Lens a b
-> (b -> f b)
-> a
-> f a
fmodify =
error "todo: fmodify"
-- |
--
-- >>> fstL |= Just 3 $ (7, "abc")
-- Just (3,"abc")
--
-- >>> (fstL |= (+1) $ (3, "abc")) 17
-- (18,"abc")
(|=) ::
Functor f =>
Lens a b
-> f b
-> a
-> f a
(|=) =
error "todo: (|=)"
infixl 5 |=
-- |
--
-- >>> modify fstL (*10) (3, "abc")
-- (30,"abc")
--
-- prop> let types = (x :: Int, y :: String) in getsetLaw fstL (x, y)
--
-- prop> let types = (x :: Int, y :: String) in setgetLaw fstL (x, y) z
--
-- prop> let types = (x :: Int, y :: String) in setsetLaw fstL (x, y) z
fstL ::
Lens (x, y) x
fstL =
error "todo: fstL"
-- |
--
-- >>> modify sndL (++ "def") (13, "abc")
-- (13,"abcdef")
--
-- prop> let types = (x :: Int, y :: String) in getsetLaw sndL (x, y)
--
-- prop> let types = (x :: Int, y :: String) in setgetLaw sndL (x, y) z
--
-- prop> let types = (x :: Int, y :: String) in setsetLaw sndL (x, y) z
sndL ::
Lens (x, y) y
sndL =
error "todo: sndL"
-- |
--
-- >>> get (mapL 3) (Map.fromList (map (\c -> (ord c - 96, c)) ['a'..'d']))
-- Just 'c'
--
-- >>> get (mapL 33) (Map.fromList (map (\c -> (ord c - 96, c)) ['a'..'d']))
-- Nothing
--
-- >>> set (mapL 3) (Map.fromList (map (\c -> (ord c - 96, c)) ['a'..'d'])) (Just 'X')
-- fromList [(1,'a'),(2,'b'),(3,'X'),(4,'d')]
--
-- >>> set (mapL 33) (Map.fromList (map (\c -> (ord c - 96, c)) ['a'..'d'])) (Just 'X')
-- fromList [(1,'a'),(2,'b'),(3,'c'),(4,'d'),(33,'X')]
--
-- >>> set (mapL 3) (Map.fromList (map (\c -> (ord c - 96, c)) ['a'..'d'])) Nothing
-- fromList [(1,'a'),(2,'b'),(4,'d')]
--
-- >>> set (mapL 33) (Map.fromList (map (\c -> (ord c - 96, c)) ['a'..'d'])) Nothing
-- fromList [(1,'a'),(2,'b'),(3,'c'),(4,'d')]
mapL ::
Ord k =>
k
-> Lens (Map k v) (Maybe v)
mapL =
error "todo: mapL"
-- |
--
-- >>> get (setL 3) (Set.fromList [1..5])
-- True
--
-- >>> get (setL 33) (Set.fromList [1..5])
-- False
--
-- >>> set (setL 3) (Set.fromList [1..5]) True
-- fromList [1,2,3,4,5]
--
-- >>> set (setL 3) (Set.fromList [1..5]) False
-- fromList [1,2,4,5]
--
-- >>> set (setL 33) (Set.fromList [1..5]) True
-- fromList [1,2,3,4,5,33]
--
-- >>> set (setL 33) (Set.fromList [1..5]) False
-- fromList [1,2,3,4,5]
setL ::
Ord k =>
k
-> Lens (Set k) Bool
setL =
error "todo: setL"
-- |
--
-- >>> get (compose fstL sndL) ("abc", (7, "def"))
-- 7
--
-- >>> set (compose fstL sndL) ("abc", (7, "def")) 8
-- ("abc",(8,"def"))
compose ::
Lens b c
-> Lens a b
-> Lens a c
compose =
error "todo: compose"
-- | An alias for @compose@.
(|.) ::
Lens b c
-> Lens a b
-> Lens a c
(|.) =
compose
infixr 9 |.
-- |
--
-- >>> get identity 3
-- 3
--
-- >>> set identity 3 4
-- 4
identity ::
Lens a a
identity =
error "todo: identity"
-- |
--
-- >>> get (product fstL sndL) (("abc", 3), (4, "def"))
-- ("abc","def")
--
-- >>> set (product fstL sndL) (("abc", 3), (4, "def")) ("ghi", "jkl")
-- (("ghi",3),(4,"jkl"))
product ::
Lens a b
-> Lens c d
-> Lens (a, c) (b, d)
product =
error "todo: product"
-- | An alias for @product@.
(***) ::
Lens a b
-> Lens c d
-> Lens (a, c) (b, d)
(***) =
product
infixr 3 ***
-- |
--
-- >>> get (choice fstL sndL) (Left ("abc", 7))
-- "abc"
--
-- >>> get (choice fstL sndL) (Right ("abc", 7))
-- 7
--
-- >>> set (choice fstL sndL) (Left ("abc", 7)) "def"
-- Left ("def",7)
--
-- >>> set (choice fstL sndL) (Right ("abc", 7)) 8
-- Right ("abc",8)
choice ::
Lens a x
-> Lens b x
-> Lens (Either a b) x
choice =
error "todo: choice"
-- | An alias for @choice@.
(|||) ::
Lens a x
-> Lens b x
-> Lens (Either a b) x
(|||) =
choice
infixr 2 |||
----
cityL ::
Lens Locality String
cityL =
Lens
(\(Locality _ t y) c -> Locality c t y)
(\(Locality c _ _) -> c)
stateL ::
Lens Locality String
stateL =
Lens
(\(Locality c _ y) t -> Locality c t y)
(\(Locality _ t _) -> t)
countryL ::
Lens Locality String
countryL =
Lens
(\(Locality c t _) y -> Locality c t y)
(\(Locality _ _ y) -> y)
streetL ::
Lens Address String
streetL =
Lens
(\(Address _ s l) t -> Address t s l)
(\(Address t _ _) -> t)
suburbL ::
Lens Address String
suburbL =
Lens
(\(Address t _ l) s -> Address t s l)
(\(Address _ s _) -> s)
localityL ::
Lens Address Locality
localityL =
Lens
(\(Address t s _) l -> Address t s l)
(\(Address _ _ l) -> l)
ageL ::
Lens Person Int
ageL =
Lens
(\(Person _ n d) a -> Person a n d)
(\(Person a _ _) -> a)
nameL ::
Lens Person String
nameL =
Lens
(\(Person a _ d) n -> Person a n d)
(\(Person _ n _) -> n)
addressL ::
Lens Person Address
addressL =
Lens
(\(Person a n _) d -> Person a n d)
(\(Person _ _ d) -> d)
-- |
--
-- >>> getSuburb fred
-- "Fredville"
--
-- >>> getSuburb mary
-- "Maryland"
getSuburb ::
Person
-> String
getSuburb =
error "todo: getSuburb"
-- |
--
-- >>> setStreet fred "Some Other St"
-- Person 24 "Fred" (Address "Some Other St" "Fredville" (Locality "Fredmania" "New South Fred" "Fredalia"))
--
-- >>> setStreet mary "Some Other St"
-- Person 28 "Mary" (Address "Some Other St" "Maryland" (Locality "Mary Mary" "Western Mary" "Maristan"))
setStreet ::
Person
-> String
-> Person
setStreet =
error "todo: setStreet"
-- |
--
-- >>> getAgeAndCountry (fred, maryLocality)
-- (24,"Maristan")
--
-- >>> getAgeAndCountry (mary, fredLocality)
-- (28,"Fredalia")
getAgeAndCountry ::
(Person, Locality)
-> (Int, String)
getAgeAndCountry =
error "todo: getAgeAndCountry"
-- |
--
-- >>> setCityAndLocality (fred, maryAddress) ("Some Other City", fredLocality)
-- (Person 24 "Fred" (Address "15 Fred St" "Fredville" (Locality "Some Other City" "New South Fred" "Fredalia")),Address "83 Mary Ln" "Maryland" (Locality "Fredmania" "New South Fred" "Fredalia"))
--
-- >>> setCityAndLocality (mary, fredAddress) ("Some Other City", maryLocality)
-- (Person 28 "Mary" (Address "83 Mary Ln" "Maryland" (Locality "Some Other City" "Western Mary" "Maristan")),Address "15 Fred St" "Fredville" (Locality "Mary Mary" "Western Mary" "Maristan"))
setCityAndLocality ::
(Person, Address) -> (String, Locality) -> (Person, Address)
setCityAndLocality =
error "todo: setCityAndLocality"
-- |
--
-- >>> getSuburbOrCity (Left maryAddress)
-- "Maryland"
--
-- >>> getSuburbOrCity (Right fredLocality)
-- "Fredmania"
getSuburbOrCity ::
Either Address Locality
-> String
getSuburbOrCity =
error "todo: getSuburbOrCity"
-- |
--
-- >>> setStreetOrState (Right maryLocality) "Some Other State"
-- Right (Locality "Mary Mary" "Some Other State" "Maristan")
--
-- >>> setStreetOrState (Left fred) "Some Other St"
-- Left (Person 24 "Fred" (Address "Some Other St" "Fredville" (Locality "Fredmania" "New South Fred" "Fredalia")))
setStreetOrState ::
Either Person Locality
-> String
-> Either Person Locality
setStreetOrState =
error "todo: setStreetOrState"
-- |
--
-- >>> modifyCityUppercase fred
-- Person 24 "Fred" (Address "15 Fred St" "Fredville" (Locality "FREDMANIA" "New South Fred" "Fredalia"))
--
-- >>> modifyCityUppercase mary
-- Person 28 "Mary" (Address "83 Mary Ln" "Maryland" (Locality "MARY MARY" "Western Mary" "Maristan"))
modifyCityUppercase ::
Person
-> Person
modifyCityUppercase =
error "todo: modifyCityUppercase"
| bitemyapp/lets-lens | src/Lets/GetSetLens.hs | bsd-3-clause | 10,549 | 0 | 10 | 2,395 | 2,170 | 1,272 | 898 | 279 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module GitHub.ReposSpec where
import GitHub
(Auth (..), FetchCount (..), Repo (..), RepoPublicity (..), github,
repositoryR)
import GitHub.Endpoints.Repos (currentUserReposR, languagesForR, userReposR)
import Data.Either.Compat (isRight)
import Data.String (fromString)
import System.Environment (lookupEnv)
import Test.Hspec
(Spec, describe, it, pendingWith, shouldBe, shouldSatisfy)
import qualified Data.HashMap.Strict as HM
fromRightS :: Show a => Either a b -> b
fromRightS (Right b) = b
fromRightS (Left a) = error $ "Expected a Right and got a Left" ++ show a
withAuth :: (Auth -> IO ()) -> IO ()
withAuth action = do
mtoken <- lookupEnv "GITHUB_TOKEN"
case mtoken of
Nothing -> pendingWith "no GITHUB_TOKEN"
Just token -> action (OAuth $ fromString token)
spec :: Spec
spec = do
describe "repositoryR" $ do
it "works" $ withAuth $ \auth -> do
er <- github auth repositoryR "phadej" "github"
er `shouldSatisfy` isRight
let Right r = er
-- https://github.com/phadej/github/pull/219
repoDefaultBranch r `shouldBe` Just "master"
describe "currentUserRepos" $ do
it "works" $ withAuth $ \auth -> do
cs <- github auth currentUserReposR RepoPublicityAll FetchAll
cs `shouldSatisfy` isRight
describe "userRepos" $ do
it "works" $ withAuth $ \auth -> do
cs <- github auth userReposR "phadej" RepoPublicityAll FetchAll
cs `shouldSatisfy` isRight
describe "languagesFor'" $ do
it "works" $ withAuth $ \auth -> do
ls <- github auth languagesForR "phadej" "github"
ls `shouldSatisfy` isRight
fromRightS ls `shouldSatisfy` HM.member "Haskell"
| jwiegley/github | spec/GitHub/ReposSpec.hs | bsd-3-clause | 1,720 | 0 | 17 | 370 | 544 | 280 | 264 | 42 | 2 |
module Graceful.Test
where
import Graceful.Graceful
import Graceful.Labeling
import Graph.Graph
import Graph.Viz
main =
--writeFile "./graph.out" (getGraphviz Graceful bsp_einfach_g bsp_einfach_l)
--transGtoGV bsp_einfach_g bsp_einfach_t
--getBeweis Graceful bsp_einfach_g bsp_einfach_l "graph"
--getBeweis Graceful bsp_graph_g bsp_graph_l "graph"
--getBeweis Graceful bsp_krebs_g bsp_krebs_l "krebs"
--validiere Graceful bsp_graph_g bsp_graph_l
verifiziere Graceful bsp_graph_g bsp_graph_l
-------------------------------------------------------------------------------
-- hier folgen Beispiele
-------------------------------------------------------------------------------
bsp_einfach_g = Graph {
knoten = mkSet ["A", "B", "C", "D"],
kanten = mkSet [kante "A" "B", kante "B" "C", kante "C" "D"]
}
bsp_einfach_l = mkLabeling [("A", 3), ("B", 0), ("C", 2), ("D", 1)]
bsp_graph_g = Graph
{ knoten = mkSet ['B', 'C', 'A', 'D']
, kanten = mkSet
[ kante 'C' 'B'
, kante 'A' 'B'
, kante 'D' 'B'
, kante 'C' 'A'
, kante 'A' 'D'
, kante 'D' 'C'
]
}
bsp_graph_l = mkLabeling
[ ('B', 6), ('C', 4), ('A', 0), ('D', 1)]
{-bsp_krebs_g = Graph
{ knoten = mkSet [0..11]
, kanten = mkSet
[ kante 10 0
, kante 9 0
, kante 0 11
, kante 11 3
, kante 3 8
, kante 8 1
, kante 8 2
, kante 3 6
, kante 6 7
, kante 7 4
, kante 7 5
]
}-}
bsp_krebs_g = Graph
{ knoten = mkSet [0,1,2,3,4,5,6,7,8,9,10,11]
, kanten = mkSet
[ kante 10 0
, kante 9 0
, kante 0 11
, kante 11 3
, kante 3 8
, kante 8 1
, kante 8 2
, kante 3 7
, kante 7 4
, kante 4 5
, kante 4 6
]
}
bsp_krebs_l = mkLabeling
[ (0,0)
, (1,1)
, (2,2)
, (2,2)
, (3,3)
, (4,4)
, (5,5)
, (6,6)
, (7,7)
, (8,8)
, (9,9)
, (10,10)
, (11,11)
]
| Erdwolf/autotool-bonn | src/Graph/Graceful/Test.hs | gpl-2.0 | 1,788 | 24 | 9 | 402 | 580 | 344 | 236 | 50 | 1 |
{-| Generic code to work with jobs, e.g. submit jobs and check their status.
-}
{-
Copyright (C) 2009, 2010, 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.Jobs
( submitJobs
, Annotator
, execWithCancel
, execJobsWait
, execJobsWaitOk
, waitForJobs
) where
import Control.Concurrent (threadDelay)
import Control.Exception (bracket)
import Data.List
import Data.IORef
import System.Exit
import System.Posix.Process
import System.Posix.Signals
import Ganeti.BasicTypes
import Ganeti.Errors
import qualified Ganeti.Luxi as L
import Ganeti.OpCodes
import Ganeti.Types
import Ganeti.Utils
-- | A simple type alias for clearer signature.
type Annotator = OpCode -> MetaOpCode
--- | Wrapper over execJobSet checking for early termination via an IORef.
execCancelWrapper :: Annotator -> String -> IORef Int
-> [([[OpCode]], String)] -> IO (Result ())
execCancelWrapper _ _ _ [] = return $ Ok ()
execCancelWrapper anno master cref jobs = do
cancel <- readIORef cref
if cancel > 0
then do
putStrLn $ "Exiting early due to user request, " ++
show (length jobs) ++ " jobset(s) remaining."
return $ Ok ()
else execJobSet anno master cref jobs
--- | Execute an entire jobset.
execJobSet :: Annotator -> String -> IORef Int
-> [([[OpCode]], String)] -> IO (Result ())
execJobSet _ _ _ [] = return $ Ok ()
execJobSet anno master cref ((opcodes, descr):jobs) = do
putStrLn descr
jrs <- bracket (L.getLuxiClient master) L.closeClient $
execJobsWait metaopcodes logfn
case jrs of
Bad x -> return $ Bad x
Ok x -> let failures = filter ((/= JOB_STATUS_SUCCESS) . snd) x in
if null failures
then execCancelWrapper anno master cref jobs
else return . Bad . unlines $ [
"Not all jobs completed successfully: " ++ show failures,
"Aborting."]
where metaopcodes = map (map anno) opcodes
logfn = putStrLn . ("Got job IDs " ++)
. commaJoin . map (show . fromJobId)
-- | Signal handler for graceful termination.
handleSigInt :: IORef Int -> IO ()
handleSigInt cref = do
writeIORef cref 1
putStrLn ("Cancel request registered, will exit at" ++
" the end of the current job set...")
-- | Signal handler for immediate termination.
handleSigTerm :: IORef Int -> IO ()
handleSigTerm cref = do
-- update the cref to 2, just for consistency
writeIORef cref 2
putStrLn "Double cancel request, exiting now..."
exitImmediately $ ExitFailure 2
-- | Prepares to run a set of jobsets with handling of signals and early
-- termination.
execWithCancel :: Annotator -> String -> [([[OpCode]], String)]
-> IO (Result ())
execWithCancel anno master cmd_jobs = do
cref <- newIORef 0
mapM_ (\(hnd, sig) -> installHandler sig (Catch (hnd cref)) Nothing)
[(handleSigTerm, softwareTermination), (handleSigInt, keyboardSignal)]
execCancelWrapper anno master cref cmd_jobs
-- | Submits a set of jobs and returns their job IDs without waiting for
-- completion.
submitJobs :: [[MetaOpCode]] -> L.Client -> IO (Result [L.JobId])
submitJobs opcodes client = do
jids <- L.submitManyJobs client opcodes
return (case jids of
Bad e -> Bad $ "Job submission error: " ++ formatError e
Ok jids' -> Ok jids')
-- | Executes a set of jobs and waits for their completion, returning their
-- status.
execJobsWait :: [[MetaOpCode]] -- ^ The list of jobs
-> ([L.JobId] -> IO ()) -- ^ Post-submission callback
-> L.Client -- ^ The Luxi client
-> IO (Result [(L.JobId, JobStatus)])
execJobsWait opcodes callback client = do
jids <- submitJobs opcodes client
case jids of
Bad e -> return $ Bad e
Ok jids' -> do
callback jids'
waitForJobs jids' client
-- | Polls a set of jobs at an increasing interval until all are finished one
-- way or another.
waitForJobs :: [L.JobId] -> L.Client -> IO (Result [(L.JobId, JobStatus)])
waitForJobs jids client = waitForJobs' 500000 15000000
where
waitForJobs' delay maxdelay = do
-- TODO: this should use WaitForJobChange once it's available in Haskell
-- land, instead of a fixed schedule of sleeping intervals.
threadDelay delay
sts <- L.queryJobsStatus client jids
case sts of
Bad e -> return . Bad $ "Checking job status: " ++ formatError e
Ok sts' -> if any (<= JOB_STATUS_RUNNING) sts' then
waitForJobs' (min (delay * 2) maxdelay) maxdelay
else
return . Ok $ zip jids sts'
-- | Execute jobs and return @Ok@ only if all of them succeeded.
execJobsWaitOk :: [[MetaOpCode]] -> L.Client -> IO (Result ())
execJobsWaitOk opcodes client = do
let nullog = const (return () :: IO ())
failed = filter ((/=) JOB_STATUS_SUCCESS . snd)
fmtfail (i, s) = show (fromJobId i) ++ "=>" ++ jobStatusToRaw s
sts <- execJobsWait opcodes nullog client
case sts of
Bad e -> return $ Bad e
Ok sts' -> return (if null $ failed sts' then
Ok ()
else
Bad ("The following jobs failed: " ++
(intercalate ", " . map fmtfail $ failed sts')))
| apyrgio/ganeti | src/Ganeti/Jobs.hs | bsd-2-clause | 6,601 | 0 | 19 | 1,636 | 1,459 | 745 | 714 | 106 | 3 |
{-# LANGUAGE TemplateHaskell, MultiParamTypeClasses, TypeSynonymInstances #-}
-- | Hackish Haddock module.
module Plugin.Haddock (theModule) where
import Plugin
import qualified Data.Map as M
import qualified Data.ByteString.Char8 as P
import Data.ByteString.Char8 (ByteString,pack)
$(plugin "Haddock")
type HaddockState = M.Map ByteString [ByteString]
instance Module HaddockModule HaddockState where
moduleCmds _ = ["index"]
moduleHelp _ _ = "index <ident>. Returns the Haskell modules in which <ident> is defined"
moduleDefState _ = return M.empty
moduleSerialize _ = Just (readOnly readPacked)
fprocess_ _ _ k = readMS >>= \m -> box $ maybe
(pack "bzzt")
(P.intercalate (pack ", "))
(M.lookup (stripPs k) m)
where
-- make \@index ($) work.
stripPs :: ByteString -> ByteString
stripPs = fst . P.spanEnd (==')') . snd . P.span (=='(')
| zeekay/lambdabot | Plugin/Haddock.hs | mit | 935 | 0 | 13 | 215 | 249 | 136 | 113 | 19 | 0 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeSynonymInstances #-}
module IHaskell.Display.Widgets.Int.BoundedInt.IntProgress (
-- * The IntProgress Widget
IntProgress,
-- * Constructor
mkIntProgress) where
-- To keep `cabal repl` happy when running from the ihaskell repo
import Prelude
import Data.Aeson
import Data.IORef (newIORef)
import Data.Vinyl (Rec(..), (<+>))
import IHaskell.Display
import IHaskell.Eval.Widgets
import IHaskell.IPython.Message.UUID as U
import IHaskell.Display.Widgets.Types
import IHaskell.Display.Widgets.Common
-- | 'IntProgress' represents an IntProgress widget from IPython.html.widgets.
type IntProgress = IPythonWidget IntProgressType
-- | Create a new widget
mkIntProgress :: IO IntProgress
mkIntProgress = do
-- Default properties, with a random uuid
uuid <- U.random
let boundedIntAttrs = defaultBoundedIntWidget "ProgressView"
progressAttrs = (Orientation =:: HorizontalOrientation)
:& (BarStyle =:: DefaultBar)
:& RNil
widgetState = WidgetState $ boundedIntAttrs <+> progressAttrs
stateIO <- newIORef widgetState
let widget = IPythonWidget uuid stateIO
-- Open a comm for this widget, and store it in the kernel state
widgetSendOpen widget $ toJSON widgetState
-- Return the widget
return widget
instance IHaskellDisplay IntProgress where
display b = do
widgetSendView b
return $ Display []
instance IHaskellWidget IntProgress where
getCommUUID = uuid
| artuuge/IHaskell | ihaskell-display/ihaskell-widgets/src/IHaskell/Display/Widgets/Int/BoundedInt/IntProgress.hs | mit | 1,677 | 0 | 13 | 398 | 274 | 155 | 119 | 35 | 1 |
import Control.Concurrent
import Control.Monad
import Data.Char
import Data.IORef
import System.Environment
import System.IO
import GHC.Conc
import Foreign hiding (complement)
newtype Color = C Int deriving (Storable,Enum)
#define Y (C 2)
#define R (C 1)
#define B (C 0)
instance Show Color where
show Y = "yellow"
show R = "red"
show B = "blue"
complement :: Color -> Color -> Color
complement !a !b = case a of
B -> case b of R -> Y; B -> B; _ -> R
R -> case b of B -> Y; R -> R; _ -> B
Y -> case b of B -> R; Y -> Y; _ -> B
type Chameneous = Ptr Color
data MP = Nobody !Int | Somebody !Int !Chameneous !(MVar Chameneous)
arrive :: MVar MP -> MVar (Int, Int) -> Chameneous -> IO ()
arrive !mpv !finish !ch = do
waker <- newEmptyMVar
let inc x = (fromEnum (ch == x) +)
go !t !(b::Int) = do
w <- takeMVar mpv
case w of
Nobody 0 -> do
putMVar mpv w
putMVar finish (t, b)
Nobody q -> do
putMVar mpv $ Somebody q ch waker
ch' <- takeMVar waker
go (t+1) $ inc ch' b
Somebody q ch' waker' -> do
let !q' = q-1
putMVar mpv $ Nobody q'
c <- peek ch
c' <- peek ch'
let !c'' = complement c c'
poke ch c''
poke ch' c''
putMVar waker' ch
go (t+1) $ inc ch' b
go 0 0
showN = unwords . map ((digits !!) . digitToInt) . show
digits = words "zero one two three four five six seven eight nine"
run :: Int -> Int -> [Color] -> IO (IO ())
run n cpu cs = do
fs <- replicateM (length cs) newEmptyMVar
mpv <- newMVar (Nobody n)
withArrayLen cs $ \ n cols -> do
zipWithM_ ((forkOn cpu .) . arrive mpv) fs (take n (iterate (`advancePtr` 1) cols))
return $ do
putStrLn . map toLower . unwords . ([]:) . map show $ cs
ns <- mapM takeMVar fs
putStr . map toLower . unlines $ [unwords [show n, showN b] | (n, b) <- ns]
putStrLn . (" "++) . showN . sum . map fst $ ns
putStrLn ""
main = do
putStrLn . map toLower . unlines $
[unwords [show a, "+", show b, "->", show $ complement a b]
| a <- [B..Y], b <- [B..Y]]
n <- readIO . head =<< getArgs
actions <- zipWithM (run n) [0..] [[B..Y],[B,R,Y,R,Y,B,R,Y,R,B]]
sequence_ actions
| kayceesrk/effects-examples | mvar/chameneos.hs | isc | 2,525 | 0 | 20 | 946 | 1,081 | 532 | 549 | -1 | -1 |
{-
Check that we aren't making gcc misinterpret our strings as trigraphs.
#2968.
http://gcc.gnu.org/onlinedocs/cpp/Initial-processing.html
-}
module Main where
main :: IO ()
main = do putStrLn "??("
putStrLn "??)"
putStrLn "??<"
putStrLn "??>"
putStrLn "??="
putStrLn "??/"
putStrLn "??'"
putStrLn "??!"
putStrLn "??-"
| sdiehl/ghc | testsuite/tests/codeGen/should_run/cgrun063.hs | bsd-3-clause | 403 | 0 | 7 | 126 | 74 | 30 | 44 | 11 | 1 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE CPP
, NoImplicitPrelude
, BangPatterns
, AutoDeriveTypeable
#-}
{-# OPTIONS_GHC -fno-warn-identities #-}
-- Whether there are identities depends on the platform
{-# OPTIONS_HADDOCK hide #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.IO.FD
-- Copyright : (c) The University of Glasgow, 1994-2008
-- License : see libraries/base/LICENSE
--
-- Maintainer : [email protected]
-- Stability : internal
-- Portability : non-portable
--
-- Raw read/write operations on file descriptors
--
-----------------------------------------------------------------------------
module GHC.IO.FD (
FD(..),
openFile, mkFD, release,
setNonBlockingMode,
readRawBufferPtr, readRawBufferPtrNoBlock, writeRawBufferPtr,
stdin, stdout, stderr
) where
import GHC.Base
import GHC.Num
import GHC.Real
import GHC.Show
import GHC.Enum
import Data.Typeable
import GHC.IO
import GHC.IO.IOMode
import GHC.IO.Buffer
import GHC.IO.BufferedIO
import qualified GHC.IO.Device
import GHC.IO.Device (SeekMode(..), IODeviceType(..))
import GHC.Conc.IO
import GHC.IO.Exception
#ifdef mingw32_HOST_OS
import GHC.Windows
#endif
import Foreign
import Foreign.C
import qualified System.Posix.Internals
import System.Posix.Internals hiding (FD, setEcho, getEcho)
import System.Posix.Types
#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
c_DEBUG_DUMP :: Bool
c_DEBUG_DUMP = False
-- -----------------------------------------------------------------------------
-- The file-descriptor IO device
data FD = FD {
fdFD :: {-# UNPACK #-} !CInt,
#ifdef mingw32_HOST_OS
-- On Windows, a socket file descriptor needs to be read and written
-- using different functions (send/recv).
fdIsSocket_ :: {-# UNPACK #-} !Int
#else
-- On Unix we need to know whether this FD has O_NONBLOCK set.
-- If it has, then we can use more efficient routines to read/write to it.
-- It is always safe for this to be off.
fdIsNonBlocking :: {-# UNPACK #-} !Int
#endif
}
deriving Typeable
#ifdef mingw32_HOST_OS
fdIsSocket :: FD -> Bool
fdIsSocket fd = fdIsSocket_ fd /= 0
#endif
instance Show FD where
show fd = show (fdFD fd)
instance GHC.IO.Device.RawIO FD where
read = fdRead
readNonBlocking = fdReadNonBlocking
write = fdWrite
writeNonBlocking = fdWriteNonBlocking
instance GHC.IO.Device.IODevice FD where
ready = ready
close = close
isTerminal = isTerminal
isSeekable = isSeekable
seek = seek
tell = tell
getSize = getSize
setSize = setSize
setEcho = setEcho
getEcho = getEcho
setRaw = setRaw
devType = devType
dup = dup
dup2 = dup2
-- We used to use System.Posix.Internals.dEFAULT_BUFFER_SIZE, which is
-- taken from the value of BUFSIZ on the current platform. This value
-- varies too much though: it is 512 on Windows, 1024 on OS X and 8192
-- on Linux. So let's just use a decent size on every platform:
dEFAULT_FD_BUFFER_SIZE :: Int
dEFAULT_FD_BUFFER_SIZE = 8096
instance BufferedIO FD where
newBuffer _dev state = newByteBuffer dEFAULT_FD_BUFFER_SIZE state
fillReadBuffer fd buf = readBuf' fd buf
fillReadBuffer0 fd buf = readBufNonBlocking fd buf
flushWriteBuffer fd buf = writeBuf' fd buf
flushWriteBuffer0 fd buf = writeBufNonBlocking fd buf
readBuf' :: FD -> Buffer Word8 -> IO (Int, Buffer Word8)
readBuf' fd buf = do
when c_DEBUG_DUMP $
puts ("readBuf fd=" ++ show fd ++ " " ++ summaryBuffer buf ++ "\n")
(r,buf') <- readBuf fd buf
when c_DEBUG_DUMP $
puts ("after: " ++ summaryBuffer buf' ++ "\n")
return (r,buf')
writeBuf' :: FD -> Buffer Word8 -> IO (Buffer Word8)
writeBuf' fd buf = do
when c_DEBUG_DUMP $
puts ("writeBuf fd=" ++ show fd ++ " " ++ summaryBuffer buf ++ "\n")
writeBuf fd buf
-- -----------------------------------------------------------------------------
-- opening files
-- | Open a file and make an 'FD' for it. Truncates the file to zero
-- size when the `IOMode` is `WriteMode`.
openFile
:: FilePath -- ^ file to open
-> IOMode -- ^ mode in which to open the file
-> Bool -- ^ open the file in non-blocking mode?
-> IO (FD,IODeviceType)
openFile filepath iomode non_blocking =
withFilePath filepath $ \ f ->
let
oflags1 = case iomode of
ReadMode -> read_flags
WriteMode -> write_flags
ReadWriteMode -> rw_flags
AppendMode -> append_flags
#ifdef mingw32_HOST_OS
binary_flags = o_BINARY
#else
binary_flags = 0
#endif
oflags2 = oflags1 .|. binary_flags
oflags | non_blocking = oflags2 .|. nonblock_flags
| otherwise = oflags2
in do
-- the old implementation had a complicated series of three opens,
-- which is perhaps because we have to be careful not to open
-- directories. However, the man pages I've read say that open()
-- always returns EISDIR if the file is a directory and was opened
-- for writing, so I think we're ok with a single open() here...
fd <- throwErrnoIfMinus1Retry "openFile"
(if non_blocking then c_open f oflags 0o666
else c_safe_open f oflags 0o666)
(fD,fd_type) <- mkFD fd iomode Nothing{-no stat-}
False{-not a socket-}
non_blocking
`catchAny` \e -> do _ <- c_close fd
throwIO e
-- we want to truncate() if this is an open in WriteMode, but only
-- if the target is a RegularFile. ftruncate() fails on special files
-- like /dev/null.
when (iomode == WriteMode && fd_type == RegularFile) $
setSize fD 0
return (fD,fd_type)
std_flags, output_flags, read_flags, write_flags, rw_flags,
append_flags, nonblock_flags :: CInt
std_flags = o_NOCTTY
output_flags = std_flags .|. o_CREAT
read_flags = std_flags .|. o_RDONLY
write_flags = output_flags .|. o_WRONLY
rw_flags = output_flags .|. o_RDWR
append_flags = write_flags .|. o_APPEND
nonblock_flags = o_NONBLOCK
-- | Make a 'FD' from an existing file descriptor. Fails if the FD
-- refers to a directory. If the FD refers to a file, `mkFD` locks
-- the file according to the Haskell 2010 single writer/multiple reader
-- locking semantics (this is why we need the `IOMode` argument too).
mkFD :: CInt
-> IOMode
-> Maybe (IODeviceType, CDev, CIno)
-- the results of fdStat if we already know them, or we want
-- to prevent fdToHandle_stat from doing its own stat.
-- These are used for:
-- - we fail if the FD refers to a directory
-- - if the FD refers to a file, we lock it using (cdev,cino)
-> Bool -- ^ is a socket (on Windows)
-> Bool -- ^ is in non-blocking mode on Unix
-> IO (FD,IODeviceType)
mkFD fd iomode mb_stat is_socket is_nonblock = do
let _ = (is_socket, is_nonblock) -- warning suppression
(fd_type,dev,ino) <-
case mb_stat of
Nothing -> fdStat fd
Just stat -> return stat
let write = case iomode of
ReadMode -> False
_ -> True
case fd_type of
Directory ->
ioException (IOError Nothing InappropriateType "openFile"
"is a directory" Nothing Nothing)
-- regular files need to be locked
RegularFile -> do
-- On Windows we need an additional call to get a unique device id
-- and inode, since fstat just returns 0 for both.
(unique_dev, unique_ino) <- getUniqueFileInfo fd dev ino
r <- lockFile fd unique_dev unique_ino (fromBool write)
when (r == -1) $
ioException (IOError Nothing ResourceBusy "openFile"
"file is locked" Nothing Nothing)
_other_type -> return ()
#ifdef mingw32_HOST_OS
when (not is_socket) $ setmode fd True >> return ()
#endif
return (FD{ fdFD = fd,
#ifndef mingw32_HOST_OS
fdIsNonBlocking = fromEnum is_nonblock
#else
fdIsSocket_ = fromEnum is_socket
#endif
},
fd_type)
getUniqueFileInfo :: CInt -> CDev -> CIno -> IO (Word64, Word64)
#ifndef mingw32_HOST_OS
getUniqueFileInfo _ dev ino = return (fromIntegral dev, fromIntegral ino)
#else
getUniqueFileInfo fd _ _ = do
with 0 $ \devptr -> do
with 0 $ \inoptr -> do
c_getUniqueFileInfo fd devptr inoptr
liftM2 (,) (peek devptr) (peek inoptr)
#endif
#ifdef mingw32_HOST_OS
foreign import ccall unsafe "__hscore_setmode"
setmode :: CInt -> Bool -> IO CInt
#endif
-- -----------------------------------------------------------------------------
-- Standard file descriptors
stdFD :: CInt -> FD
stdFD fd = FD { fdFD = fd,
#ifdef mingw32_HOST_OS
fdIsSocket_ = 0
#else
fdIsNonBlocking = 0
-- We don't set non-blocking mode on standard handles, because it may
-- confuse other applications attached to the same TTY/pipe
-- see Note [nonblock]
#endif
}
stdin, stdout, stderr :: FD
stdin = stdFD 0
stdout = stdFD 1
stderr = stdFD 2
-- -----------------------------------------------------------------------------
-- Operations on file descriptors
close :: FD -> IO ()
close fd =
do let closer realFd =
throwErrnoIfMinus1Retry_ "GHC.IO.FD.close" $
#ifdef mingw32_HOST_OS
if fdIsSocket fd then
c_closesocket (fromIntegral realFd)
else
#endif
c_close (fromIntegral realFd)
-- release the lock *first*, because otherwise if we're preempted
-- after closing but before releasing, the FD may have been reused.
-- (#7646)
release fd
closeFdWith closer (fromIntegral (fdFD fd))
release :: FD -> IO ()
release fd = do _ <- unlockFile (fdFD fd)
return ()
#ifdef mingw32_HOST_OS
foreign import WINDOWS_CCONV unsafe "HsBase.h closesocket"
c_closesocket :: CInt -> IO CInt
#endif
isSeekable :: FD -> IO Bool
isSeekable fd = do
t <- devType fd
return (t == RegularFile || t == RawDevice)
seek :: FD -> SeekMode -> Integer -> IO ()
seek fd mode off = do
throwErrnoIfMinus1Retry_ "seek" $
c_lseek (fdFD fd) (fromIntegral off) seektype
where
seektype :: CInt
seektype = case mode of
AbsoluteSeek -> sEEK_SET
RelativeSeek -> sEEK_CUR
SeekFromEnd -> sEEK_END
tell :: FD -> IO Integer
tell fd =
fromIntegral `fmap`
(throwErrnoIfMinus1Retry "hGetPosn" $
c_lseek (fdFD fd) 0 sEEK_CUR)
getSize :: FD -> IO Integer
getSize fd = fdFileSize (fdFD fd)
setSize :: FD -> Integer -> IO ()
setSize fd size = do
throwErrnoIf_ (/=0) "GHC.IO.FD.setSize" $
c_ftruncate (fdFD fd) (fromIntegral size)
devType :: FD -> IO IODeviceType
devType fd = do (ty,_,_) <- fdStat (fdFD fd); return ty
dup :: FD -> IO FD
dup fd = do
newfd <- throwErrnoIfMinus1 "GHC.IO.FD.dup" $ c_dup (fdFD fd)
return fd{ fdFD = newfd }
dup2 :: FD -> FD -> IO FD
dup2 fd fdto = do
-- Windows' dup2 does not return the new descriptor, unlike Unix
throwErrnoIfMinus1_ "GHC.IO.FD.dup2" $
c_dup2 (fdFD fd) (fdFD fdto)
return fd{ fdFD = fdFD fdto } -- original FD, with the new fdFD
setNonBlockingMode :: FD -> Bool -> IO FD
setNonBlockingMode fd set = do
setNonBlockingFD (fdFD fd) set
#if defined(mingw32_HOST_OS)
return fd
#else
return fd{ fdIsNonBlocking = fromEnum set }
#endif
ready :: FD -> Bool -> Int -> IO Bool
ready fd write msecs = do
r <- throwErrnoIfMinus1Retry "GHC.IO.FD.ready" $
fdReady (fdFD fd) (fromIntegral $ fromEnum $ write)
(fromIntegral msecs)
#if defined(mingw32_HOST_OS)
(fromIntegral $ fromEnum $ fdIsSocket fd)
#else
0
#endif
return (toEnum (fromIntegral r))
foreign import ccall safe "fdReady"
fdReady :: CInt -> CInt -> CInt -> CInt -> IO CInt
-- ---------------------------------------------------------------------------
-- Terminal-related stuff
isTerminal :: FD -> IO Bool
isTerminal fd =
c_isatty (fdFD fd) >>= return.toBool
setEcho :: FD -> Bool -> IO ()
setEcho fd on = System.Posix.Internals.setEcho (fdFD fd) on
getEcho :: FD -> IO Bool
getEcho fd = System.Posix.Internals.getEcho (fdFD fd)
setRaw :: FD -> Bool -> IO ()
setRaw fd raw = System.Posix.Internals.setCooked (fdFD fd) (not raw)
-- -----------------------------------------------------------------------------
-- Reading and Writing
fdRead :: FD -> Ptr Word8 -> Int -> IO Int
fdRead fd ptr bytes
= do { r <- readRawBufferPtr "GHC.IO.FD.fdRead" fd ptr 0 (fromIntegral bytes)
; return (fromIntegral r) }
fdReadNonBlocking :: FD -> Ptr Word8 -> Int -> IO (Maybe Int)
fdReadNonBlocking fd ptr bytes = do
r <- readRawBufferPtrNoBlock "GHC.IO.FD.fdReadNonBlocking" fd ptr
0 (fromIntegral bytes)
case fromIntegral r of
(-1) -> return (Nothing)
n -> return (Just n)
fdWrite :: FD -> Ptr Word8 -> Int -> IO ()
fdWrite fd ptr bytes = do
res <- writeRawBufferPtr "GHC.IO.FD.fdWrite" fd ptr 0 (fromIntegral bytes)
let res' = fromIntegral res
if res' < bytes
then fdWrite fd (ptr `plusPtr` res') (bytes - res')
else return ()
-- XXX ToDo: this isn't non-blocking
fdWriteNonBlocking :: FD -> Ptr Word8 -> Int -> IO Int
fdWriteNonBlocking fd ptr bytes = do
res <- writeRawBufferPtrNoBlock "GHC.IO.FD.fdWriteNonBlocking" fd ptr 0
(fromIntegral bytes)
return (fromIntegral res)
-- -----------------------------------------------------------------------------
-- FD operations
-- Low level routines for reading/writing to (raw)buffers:
#ifndef mingw32_HOST_OS
{-
NOTE [nonblock]:
Unix has broken semantics when it comes to non-blocking I/O: you can
set the O_NONBLOCK flag on an FD, but it applies to the all other FDs
attached to the same underlying file, pipe or TTY; there's no way to
have private non-blocking behaviour for an FD. See bug #724.
We fix this by only setting O_NONBLOCK on FDs that we create; FDs that
come from external sources or are exposed externally are left in
blocking mode. This solution has some problems though. We can't
completely simulate a non-blocking read without O_NONBLOCK: several
cases are wrong here. The cases that are wrong:
* reading/writing to a blocking FD in non-threaded mode.
In threaded mode, we just make a safe call to read().
In non-threaded mode we call select() before attempting to read,
but that leaves a small race window where the data can be read
from the file descriptor before we issue our blocking read().
* readRawBufferNoBlock for a blocking FD
NOTE [2363]:
In the threaded RTS we could just make safe calls to read()/write()
for file descriptors in blocking mode without worrying about blocking
other threads, but the problem with this is that the thread will be
uninterruptible while it is blocked in the foreign call. See #2363.
So now we always call fdReady() before reading, and if fdReady
indicates that there's no data, we call threadWaitRead.
-}
readRawBufferPtr :: String -> FD -> Ptr Word8 -> Int -> CSize -> IO Int
readRawBufferPtr loc !fd buf off len
| isNonBlocking fd = unsafe_read -- unsafe is ok, it can't block
| otherwise = do r <- throwErrnoIfMinus1 loc
(unsafe_fdReady (fdFD fd) 0 0 0)
if r /= 0
then read
else do threadWaitRead (fromIntegral (fdFD fd)); read
where
do_read call = fromIntegral `fmap`
throwErrnoIfMinus1RetryMayBlock loc call
(threadWaitRead (fromIntegral (fdFD fd)))
read = if threaded then safe_read else unsafe_read
unsafe_read = do_read (c_read (fdFD fd) (buf `plusPtr` off) len)
safe_read = do_read (c_safe_read (fdFD fd) (buf `plusPtr` off) len)
-- return: -1 indicates EOF, >=0 is bytes read
readRawBufferPtrNoBlock :: String -> FD -> Ptr Word8 -> Int -> CSize -> IO Int
readRawBufferPtrNoBlock loc !fd buf off len
| isNonBlocking fd = unsafe_read -- unsafe is ok, it can't block
| otherwise = do r <- unsafe_fdReady (fdFD fd) 0 0 0
if r /= 0 then safe_read
else return 0
-- XXX see note [nonblock]
where
do_read call = do r <- throwErrnoIfMinus1RetryOnBlock loc call (return (-1))
case r of
(-1) -> return 0
0 -> return (-1)
n -> return (fromIntegral n)
unsafe_read = do_read (c_read (fdFD fd) (buf `plusPtr` off) len)
safe_read = do_read (c_safe_read (fdFD fd) (buf `plusPtr` off) len)
writeRawBufferPtr :: String -> FD -> Ptr Word8 -> Int -> CSize -> IO CInt
writeRawBufferPtr loc !fd buf off len
| isNonBlocking fd = unsafe_write -- unsafe is ok, it can't block
| otherwise = do r <- unsafe_fdReady (fdFD fd) 1 0 0
if r /= 0
then write
else do threadWaitWrite (fromIntegral (fdFD fd)); write
where
do_write call = fromIntegral `fmap`
throwErrnoIfMinus1RetryMayBlock loc call
(threadWaitWrite (fromIntegral (fdFD fd)))
write = if threaded then safe_write else unsafe_write
unsafe_write = do_write (c_write (fdFD fd) (buf `plusPtr` off) len)
safe_write = do_write (c_safe_write (fdFD fd) (buf `plusPtr` off) len)
writeRawBufferPtrNoBlock :: String -> FD -> Ptr Word8 -> Int -> CSize -> IO CInt
writeRawBufferPtrNoBlock loc !fd buf off len
| isNonBlocking fd = unsafe_write -- unsafe is ok, it can't block
| otherwise = do r <- unsafe_fdReady (fdFD fd) 1 0 0
if r /= 0 then write
else return 0
where
do_write call = do r <- throwErrnoIfMinus1RetryOnBlock loc call (return (-1))
case r of
(-1) -> return 0
n -> return (fromIntegral n)
write = if threaded then safe_write else unsafe_write
unsafe_write = do_write (c_write (fdFD fd) (buf `plusPtr` off) len)
safe_write = do_write (c_safe_write (fdFD fd) (buf `plusPtr` off) len)
isNonBlocking :: FD -> Bool
isNonBlocking fd = fdIsNonBlocking fd /= 0
foreign import ccall unsafe "fdReady"
unsafe_fdReady :: CInt -> CInt -> CInt -> CInt -> IO CInt
#else /* mingw32_HOST_OS.... */
readRawBufferPtr :: String -> FD -> Ptr Word8 -> Int -> CSize -> IO CInt
readRawBufferPtr loc !fd buf off len
| threaded = blockingReadRawBufferPtr loc fd buf off len
| otherwise = asyncReadRawBufferPtr loc fd buf off len
writeRawBufferPtr :: String -> FD -> Ptr Word8 -> Int -> CSize -> IO CInt
writeRawBufferPtr loc !fd buf off len
| threaded = blockingWriteRawBufferPtr loc fd buf off len
| otherwise = asyncWriteRawBufferPtr loc fd buf off len
readRawBufferPtrNoBlock :: String -> FD -> Ptr Word8 -> Int -> CSize -> IO CInt
readRawBufferPtrNoBlock = readRawBufferPtr
writeRawBufferPtrNoBlock :: String -> FD -> Ptr Word8 -> Int -> CSize -> IO CInt
writeRawBufferPtrNoBlock = writeRawBufferPtr
-- Async versions of the read/write primitives, for the non-threaded RTS
asyncReadRawBufferPtr :: String -> FD -> Ptr Word8 -> Int -> CSize -> IO CInt
asyncReadRawBufferPtr loc !fd buf off len = do
(l, rc) <- asyncRead (fromIntegral (fdFD fd)) (fdIsSocket_ fd)
(fromIntegral len) (buf `plusPtr` off)
if l == (-1)
then
ioError (errnoToIOError loc (Errno (fromIntegral rc)) Nothing Nothing)
else return (fromIntegral l)
asyncWriteRawBufferPtr :: String -> FD -> Ptr Word8 -> Int -> CSize -> IO CInt
asyncWriteRawBufferPtr loc !fd buf off len = do
(l, rc) <- asyncWrite (fromIntegral (fdFD fd)) (fdIsSocket_ fd)
(fromIntegral len) (buf `plusPtr` off)
if l == (-1)
then
ioError (errnoToIOError loc (Errno (fromIntegral rc)) Nothing Nothing)
else return (fromIntegral l)
-- Blocking versions of the read/write primitives, for the threaded RTS
blockingReadRawBufferPtr :: String -> FD -> Ptr Word8 -> Int -> CSize -> IO CInt
blockingReadRawBufferPtr loc fd buf off len
= fmap fromIntegral $ throwErrnoIfMinus1Retry loc $
if fdIsSocket fd
then c_safe_recv (fdFD fd) (buf `plusPtr` off) len 0
else c_safe_read (fdFD fd) (buf `plusPtr` off) len
blockingWriteRawBufferPtr :: String -> FD -> Ptr Word8-> Int -> CSize -> IO CInt
blockingWriteRawBufferPtr loc fd buf off len
= fmap fromIntegral $ throwErrnoIfMinus1Retry loc $
if fdIsSocket fd
then c_safe_send (fdFD fd) (buf `plusPtr` off) len 0
else do
r <- c_safe_write (fdFD fd) (buf `plusPtr` off) len
when (r == -1) c_maperrno
return r
-- we don't trust write() to give us the correct errno, and
-- instead do the errno conversion from GetLastError()
-- ourselves. The main reason is that we treat ERROR_NO_DATA
-- (pipe is closing) as EPIPE, whereas write() returns EINVAL
-- for this case. We need to detect EPIPE correctly, because it
-- shouldn't be reported as an error when it happens on stdout.
-- NOTE: "safe" versions of the read/write calls for use by the threaded RTS.
-- These calls may block, but that's ok.
foreign import WINDOWS_CCONV safe "recv"
c_safe_recv :: CInt -> Ptr Word8 -> CSize -> CInt{-flags-} -> IO CSsize
foreign import WINDOWS_CCONV safe "send"
c_safe_send :: CInt -> Ptr Word8 -> CSize -> CInt{-flags-} -> IO CSsize
#endif
foreign import ccall "rtsSupportsBoundThreads" threaded :: Bool
-- -----------------------------------------------------------------------------
-- utils
#ifndef mingw32_HOST_OS
throwErrnoIfMinus1RetryOnBlock :: String -> IO CSsize -> IO CSsize -> IO CSsize
throwErrnoIfMinus1RetryOnBlock loc f on_block =
do
res <- f
if (res :: CSsize) == -1
then do
err <- getErrno
if err == eINTR
then throwErrnoIfMinus1RetryOnBlock loc f on_block
else if err == eWOULDBLOCK || err == eAGAIN
then do on_block
else throwErrno loc
else return res
#endif
-- -----------------------------------------------------------------------------
-- Locking/unlocking
foreign import ccall unsafe "lockFile"
lockFile :: CInt -> Word64 -> Word64 -> CInt -> IO CInt
foreign import ccall unsafe "unlockFile"
unlockFile :: CInt -> IO CInt
#ifdef mingw32_HOST_OS
foreign import ccall unsafe "get_unique_file_info"
c_getUniqueFileInfo :: CInt -> Ptr Word64 -> Ptr Word64 -> IO ()
#endif
| beni55/haste-compiler | libraries/ghc-7.10/base/GHC/IO/FD.hs | bsd-3-clause | 23,093 | 3 | 17 | 5,933 | 4,273 | 2,228 | 2,045 | 322 | 5 |
{-# LANGUAGE TypeFamilies #-}
module OverDirectThisModB
where
import OverDirectThisModA (C, D)
data instance C [Int] [a] = CListList2
type instance D [Int] [a] = Int
| shlevy/ghc | testsuite/tests/indexed-types/should_fail/OverDirectThisModB.hs | bsd-3-clause | 169 | 0 | 6 | 28 | 54 | 33 | 21 | 5 | 0 |
module Gen.Phonology
( makeDiphInventory
, makeConsonantMap
, makeConsonants
, makeVowelMap
, makeVowels
, makeTones
, makeStresses
) where
-- Import
import ClassyPrelude
import Data.RVar
import Data.Random.Extras
import Data.Random hiding (sample)
import Data.Phoneme
import HelperFunctions
import Constants
-- Make diphthongs
makeDiphInventory :: Int -> [Phoneme] -> RVar [Phoneme]
makeDiphInventory n vs = fromMaybe (return []) (join $ safeSample n <$> subseq) where
subseq = mapM makeDiph $ filter (\(Vowel h1 b1 _ l1, Vowel h2 b2 _ l2) -> (h1 /= h2 || b1 /= b2) && l1 == l2) ((,) <$> vs <*> vs)
makeDiph :: (Phoneme, Phoneme) -> Maybe Phoneme
makeDiph (Vowel h1 b1 r1 _, Vowel h2 b2 r2 _) = Just $ Diphthong h1 b1 r1 h2 b2 r2 NORMAL
makeDiph (_,_) = Nothing
-- Returns a list of places, manners, phonations, and exceptions
makeConsonantMap :: RVar ([Place], [Manner], [Phonation], [Airstream], [Phoneme])
makeConsonantMap = do
-- Pick places, manners, and phonation
places <- makePlaces
manners <- makeManners
phonations <- makePhonations
airstreams <- makeAirstream
let combos = Consonant <$> places <*> manners <*> phonations <*> airstreams
-- Make exceptions for the place, manner, and airstream dimensions
rPlaces <- join $ sample <$> uniform 0 (length places - 1) <*> return places
rManners <- join $ sample <$> uniform 0 (length manners - 1) <*> return manners
rPhonations <- join $ sample <$> uniform 0 (length phonations - 1) <*> return phonations
rAirstreams <- join $ sample <$> uniform 0 (length airstreams - 1) <*> return airstreams
-- Create exceptions
let exceptions = Consonant <$> rPlaces <*> rManners <*> rPhonations <*> rAirstreams
-- Add impossible consonants to exceptions
let exceptions_ = exceptions ++ filter impConsonants combos
-- This might result in some manners and places being unused...
return (places, manners, phonations, airstreams, exceptions_)
-- Make the consonant inventory from the consonant map
makeConsonants :: [Place] -> [Manner] -> [Phonation] -> [Airstream] -> [Phoneme] -> [Phoneme]
makeConsonants places manners phonations airstreams exceptions = output where
-- Create all possible consonants from place, manner, phonation, and phonations
cns = Consonant <$> places <*> manners <*> phonations <*> airstreams
-- Filter out exceptions
output = filter (`notElem` exceptions) cns
-- Make the places of articulation for consonants
makePlaces :: RVar [Place]
makePlaces = do
n1 <- uniform 0 2
labial <- sample n1 [BILABIAL, LABIODENTAL]
n2 <- uniform 1 3
coronal <- sample n2 [INTERDENTAL, DENTAL, DENTIALVEOLAR, LAMINALALVEOLAR, APICOALVEOLAR, PALATOALVEOLAR, APICALRETROFLEX, RETROFLEX]
n3 <- uniform 1 3
dorsal <- sample n3 [ALVEOLOPALATAL, PALATAL, VELAR, UVULAR]
rad <- choice [[], [PHARYNGEAL]]
n4 <- uniform 0 2
laryn <- sample n4 [GLOTTAL, EPIPHARYNGEAL, EPIGLOTTAL]
let monoPlaces = concat [labial, coronal, dorsal, rad, laryn]
n5 <- uniform 0 2
coartPlaces <- replicateM n5 (makeCoart monoPlaces)
return $ monoPlaces ++ coartPlaces
-- Make a Coarticulated Place
makeCoart :: [Place] -> RVar Place
makeCoart places = do
n <- uniform 1 (length places - 1)
let (p1s, p2s) = splitAt n places
p1 <- choice p1s
p2 <- choice p2s
return $ COARTICULATED p1 p2
-- Make the manners of articulation for consonants
makeManners :: RVar [Manner]
makeManners = do
let stop = [STOP]
nasal <- choice [[], [NASAL]]
lflap <- choice [[], [LFLAP]]
let flap2 = FLAP:lflap
flap <- choice [[], flap2]
lat <- choice [[], [LFRICATIVE]]
sib <- choice [[], [SILIBANT]]
laff <- choice [[], [LAFFRICATE]]
saff <- choice [[], [SAFFRICATE]]
let aff2 = concat [[AFFRICATE], saff, laff]
aff <- choice [[], aff2]
let fric2 = concat [[FRICATIVE], aff, sib, lat]
fric <- choice [[], fric2]
lapprox <- choice [[], [LAPPROXIMANT]]
let approx2 = APPROXIMANT:lapprox
approx <- choice [[], approx2]
trill <- choice [[], [TRILL]]
return $ concat [stop, nasal, flap, fric, approx, trill, [CLICK]]
-- Make the phonations (and aspiration) for consonants
makePhonations :: RVar [Phonation]
makePhonations = triangleChoice [ [MODAL]
, [VOICELESS, MODAL]
, [MODAL, ASPIRATED]
, [VOICELESS, MODAL, ASPIRATED]
, [BREATHY, MODAL, CREAKY]
, [SLACK, MODAL, STIFF]
]
makeAirstream :: RVar [Airstream]
makeAirstream = triangleChoice [ [PULMONIC]
, [PULMONIC, EJECTIVE]
, [PULMONIC, IMPLOSIVE]
, [PULMONIC, LINGUAL]
, [PULMONIC, EJECTIVE, IMPLOSIVE]
, [PULMONIC, EJECTIVE, LINGUAL]
, [PULMONIC, IMPLOSIVE, LINGUAL]
, [PULMONIC, EJECTIVE, IMPLOSIVE, LINGUAL]
]
-- Returns a list of heights, backnesses, roundnesss, lengths, tones, and exceptions
makeVowelMap :: RVar ([Height], [Backness], [Roundedness], [Length], [Phoneme])
makeVowelMap = do
-- pick heights, backnesses, roundnesss, lengths, and tones
heights <- makeHeights
backs <- makeBacknesses
rounds <- makeRoundedneses
lengths <- makeLengths
-- make exceptions for the height and backness dimensions
rHeights <- join $ sample <$> uniform 0 (length heights - 1) <*> return heights
rBacks <- join $ sample <$> uniform 0 (length backs - 1) <*> return backs
-- create exceptions
let exceptions = Vowel <$> rHeights <*> rBacks <*> rounds <*> lengths
return (heights, backs, rounds, lengths, exceptions)
-- Make the vowel inventory from the vowel map
makeVowels :: [Height] -> [Backness] -> [Roundedness] -> [Length] -> [Phoneme] -> [Phoneme]
makeVowels heights backs rounds lengths exceptions = output where
-- Create all possible vowels from picked heights, backnesses, roundnesses, lengths, and tones
vows = Vowel <$> heights <*> backs <*> rounds <*> lengths
-- Filter out exceptions
output = filter (`notElem` exceptions) vows
-- Decides how height will be contrasted for vowels
makeHeights :: RVar [Height]
makeHeights = triangleChoice [ [MID]
, [CLOSE, OPEN]
, [CLOSE, MID, OPEN]
, [CLOSE, CLOSEMID, OPENMID, OPEN]
, [CLOSE, CLOSEMID, MID, OPENMID, OPEN]
, [CLOSE, NEARCLOSE, CLOSEMID, OPENMID, NEAROPEN, OPEN]
, [CLOSE, NEARCLOSE, CLOSEMID, MID, OPENMID, NEAROPEN, OPEN]
]
-- Decides how backness will be contrasted for vowels
makeBacknesses :: RVar [Backness]
makeBacknesses = triangleChoice [ [CENTRAL]
, [FRONT, BACK]
, [FRONT, CENTRAL, BACK]
, [FRONT, NEARFRONT, CENTRAL, NEARBACK, BACK]
]
-- Decides how roundedness will be contrasted for vowels
makeRoundedneses :: RVar [Roundedness]
makeRoundedneses = choice [ [UNROUNDED, ROUNDED]
]
-- Decides how length will be contrasted for vowels
makeLengths :: RVar [Length]
makeLengths = triangleChoice [ [NORMAL]
, [NORMAL, LONG]
, [SHORT, NORMAL]
, [SHORT, NORMAL, LONG]
]
-- Tones for syllables
makeTones :: RVar [Tone]
makeTones = triangleChoice [ [NONET]
, [HIGHT, FALLT, NONET]
, [FALLT, PEAKT, NONET]
, [LOWT, FALLT, NONET]
, [HIGHT, LOWT, NONET]
, [HIGHT, MIDT, LOWT]
, [HIGHT, MIDT, LOWT, NONET]
, [HIGHT, RISET, DIPT, FALLT]
, [HIGHT, RISET, DIPT, FALLT, NONET]
, [MIDT, LFALLT, HRISET, DIPT]
, [MIDT, LFALLT, HRISET, DIPT, NONET]
, [MIDT, LOWT, FALLT, HIGHT, RISET]
, [MIDT, LOWT, FALLT, HIGHT, RISET, NONET]
, [LOWT, MIDT, HIGHT, TOPT, RISET, FALLT]
, [LOWT, MIDT, HIGHT, TOPT, RISET, FALLT, NONET]
]
-- Stress for syllables
makeStresses :: RVar [Stress]
makeStresses = triangleChoice [ [NONES]
, [NONES, PRIMARYS]
, [NONES, PRIMARYS, SECONDARYS]
]
| Brightgalrs/con-lang-gen | src/Gen/Phonology.hs | mit | 8,761 | 0 | 16 | 2,688 | 2,496 | 1,396 | 1,100 | 151 | 1 |
{-# LANGUAGE ScopedTypeVariables, FlexibleContexts, MultiParamTypeClasses, FlexibleInstances, GADTs #-}
module Vn where
import Vector
import DepTypes
data VNil a = VNil
data VCons v a = VCons a (v a)
type V0 = VNil
type V1 = VCons V0
type V2 = VCons V1
type V3 = VCons V2
type V4 = VCons V3
type V5 = VCons V4
type V6 = VCons V5
type V7 = VCons V6
type V8 = VCons V7
type V9 = VCons V8
type V10 = VCons V9
type V11 = VCons V10
type V12 = VCons V11
type V13 = VCons V12
type V14 = VCons V13
type V15 = VCons V14
type V16 = VCons V15
type V17 = VCons V16
type V18 = VCons V17
type V19 = VCons V18
instance Nat (VNil a) where
toInt _ = 0
instance (Nat (a n)) => Nat (VCons a n) where
toInt (VCons _ n) = 1 + toInt n
instance Functor VNil where
fmap _ VNil = VNil
instance (Functor v) => Functor (VCons v) where
fmap f (VCons x xs) = VCons (f x) (fmap f xs)
instance Unlistable VNil where
fromList _ = VNil
instance (Unlistable v) => Unlistable (VCons v) where
fromList [] = error "List too short!"
fromList (x:xs) = VCons x (fromList xs)
instance Collection VNil where
toList _ = []
instance (Collection v) => Collection (VCons v) where
toList (VCons x xs) = x : toList xs
instance (Show a) => Show (VNil a) where
show _ = ")"
instance (Show (v a), Show a) => Show (VCons v a) where
show (VCons x xs) = ", " ++ show x ++ show xs
instance Applicative VNil where
pure _ = VNil
_ <*> _ = VNil
instance (Applicative v) => Applicative (VCons v) where
pure x = VCons x (pure x)
(VCons f fs) <*> (VCons x xs) = VCons (f x) (fs <*> xs)
instance Num a => Vector VNil a
instance (Vector v a, Num a) => Vector (VCons v) a
v1 = fromList [1, 2, 3] :: V3 Int
v2 = fromList [2, 3, 4] :: V3 Int
--main :: IO ()
--main = print (v1 + v2) | plneappl/HaskellVectorsETC | Vn.hs | mit | 1,845 | 0 | 8 | 493 | 819 | 427 | 392 | 57 | 1 |
{-# LANGUAGE UnicodeSyntax #-}
module Main (main) where
import Data.List (genericLength)
import Data.Maybe (catMaybes)
import System.Exit (exitFailure, exitSuccess)
import System.Process (readProcess)
import Text.Regex (matchRegex, mkRegex)
import Prelude.Unicode
import Control.Monad.Unicode
arguments ∷ [String]
arguments = [ "haddock" ]
average ∷ (Fractional a, Real b) ⇒ [b] → a
average xs = realToFrac (sum xs) / genericLength xs
expected ∷ Fractional a ⇒ a
expected = 90
main ∷ IO ()
main = do
output ← readProcess "cabal" arguments ""
if average (match output) >= expected
then exitSuccess
else putStr output ≫ exitFailure
match :: String -> [Int]
match = fmap read ∘ concat ∘ catMaybes ∘ fmap (matchRegex pattern) ∘ lines
where pattern = mkRegex "^ *([0-9]*)% "
| odis-project/odis-core | test-suite/Haddock.hs | mit | 843 | 2 | 11 | 164 | 278 | 151 | 127 | 24 | 2 |
module Handler.SetSkillLevel where
import Import
import qualified Network.Wai as WAI
skillLevelForm :: Maybe SkillLevel -> Form (Maybe SkillLevel)
skillLevelForm sl = renderDivs $
aopt (selectField optionsEnum) "Skill level" (Just sl)
postSetSkillLevelR :: TutorialId -> Handler ()
postSetSkillLevelR tid = do
Entity _ user <- requireAuth
app <- getYesod
ia <- isAdmin app user
unless ia $ permissionDenied "Page requires admin access"
Tutorial {..} <- $runDB $ get404 tid
((res, _), _) <- runFormPost $ skillLevelForm tutorialSkill
case res of
FormSuccess msl -> do
$runDB $ update tid [TutorialSkill =. msl]
setMessage "Skill level updated"
_ -> setMessage "Invalid submission"
req <- waiRequest
case lookup "referer" $ WAI.requestHeaders req of
Nothing -> redirect HomeR
Just t -> redirect $ decodeUtf8 t
| fpco/schoolofhaskell.com | src/Handler/SetSkillLevel.hs | mit | 907 | 0 | 15 | 219 | 284 | 133 | 151 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
{-|
Write binary data out to .tap format.
The BASIC code for the loader is based on that from bin2tap,
downloaded from here: http://metalbrain.speccy.org/link-eng.htm.
.tap files support concatenation, so you can join them together using `mappend`
For example, assuming you are using this package in conjunction with the 'Z80'
assembler, the following is enough to output a .tap file containing an insulting
program:
@
encodeBlock :: ASMBlock -> Either String ByteString
encodeBlock (ASMBlock orgAddr asm) =
mappend \<$\> loader "youresilly" orgAddr orgAddr
\<*\> codeBlock "silly" orgAddr asm
main = either putStrLn (BS.writeFile "test.tap") . encodeBlock . org 0x6000 $ mdo
ld a 2 -- upper screen
call 5633 -- open channel
withLabel $ \loop -> do
ld de string -- address of string
ld bc (eostr-string) -- length of string to print
call 8252 -- print our string
jp loop -- repeat until screen is full
string <- labelled $ db "You are a silly "
eostr <- label
end
@
Example based on that listed here: https://chuntey.wordpress.com/2012/12/18/how-to-write-zx-spectrum-games-chapter-1/
-}
module ZXSpectrum.TAP
( loader
, codeBlock
) where
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import Data.Word
import Data.Bits
import Data.String
import Control.Monad.Except
import Data.Monoid
data BlockType = Program | NumberArray | CharacterArray | Code
data Flags = Hdr | Data
data Header = Header
{ hdrType :: BlockType
, hdrName :: String
, hdrLength :: Word16
, hdrParam1 :: Word16
, hdrParam2 :: Word16
}
encodeBlockType :: BlockType -> ByteString
encodeBlockType Program = BS.pack [0]
encodeBlockType NumberArray = BS.pack [1]
encodeBlockType CharacterArray = BS.pack [2]
encodeBlockType Code = BS.pack [3]
encodeFlags :: Flags -> ByteString
encodeFlags Hdr = BS.pack [0x00]
encodeFlags Data = BS.pack [0xff]
encodeHeader :: (IsString s, Monoid s, MonadError s m) => Header -> m ByteString
encodeHeader hdr = withCheckedName (hdrName hdr) . mconcat $
[ encodeBlockType (hdrType hdr)
, fullName
, BS.pack $ encodeWord (hdrLength hdr)
, BS.pack $ encodeWord (hdrParam1 hdr)
, BS.pack $ encodeWord (hdrParam2 hdr)
]
where fullName = encodeName $ hdrName hdr
withHeader :: (IsString s, Monoid s, MonadError s m)
=> Header -> ByteString -> m ByteString
withHeader hdr bs = (<> bs) . tapBlock Hdr <$> encodeHeader hdr
tapBlock :: Flags -> ByteString -> ByteString
tapBlock flags bs = blockLength <> bs'
where appendParity x = BS.snoc x $ BS.foldr xor 0 x
blockLength = BS.pack . encodeWord . fromIntegral $ BS.length bs'
bs' = appendParity $ encodeFlags flags <> bs
{-| A simple loader, which sets us up for running machine code from an address in memory. -}
loader :: (IsString s, Monoid s, MonadError s m)
=> String -- ^ Name of the loader program (max. 10 characters).
-> Word16 -- ^ Where to load the machine code into in memory.
-> Word16 -- ^ Address to begin execution (often matches the previous parameter).
-> m ByteString -- ^ Raw loader code data, ready to be written to a file.
loader name datastart exeat = withHeader hdr $ tapBlock Data loaderCode
where hdr = Header Program name lineLength (fromIntegral lineNumber) lineLength
lineLength = fromIntegral $ BS.length loaderCode
lineNumber = 10
loaderCode = basic lineNumber . basicSeq $ map BS.pack
[ [border, val] <> quotedNum 0
, [paper, val] <> quotedNum 0
, [ink, val] <> quotedNum 7
, [clear, val] <> quotedNum (datastart-1)
, [load] <> quoted [] <> [screen]
, [poke, val] <> quotedNum 23739 <> [encodeChar ','] <> [val] <> quotedNum 111
, [load] <> quoted [] <> [code]
, [randomize, usr, val] <> quotedNum exeat ]
{-| Encode machine code into .tap format, ready for loading. -}
codeBlock :: (IsString s, Monoid s, MonadError s m)
=> String -- ^ Name of the program (max. 10 characters).
-> Word16 -- ^ Where to load the machine code into in memory.
-> ByteString -- ^ The raw machine code as output from an assembler
-> m ByteString -- ^ The data in .tap form, ready to be written to a file.
codeBlock name datastart asm = withHeader hdr $ tapBlock Data asm
where hdr = Header Code name len datastart 32768
len = fromIntegral $ BS.length asm
withCheckedName :: (IsString s, Monoid s, MonadError s m) => String -> a -> m a
withCheckedName n x
| length n > 10 = throwError $ "Filename too long! (max. 10 letters): " <> fromString n
| otherwise = return x
-- ENCODING HELPERS
encodeName :: String -> ByteString
encodeName = BS.pack . map encodeChar . take 10 . (++ repeat ' ')
encodeChar :: Char -> Word8
encodeChar = fromIntegral . fromEnum
encodeWord :: Word16 -> [Word8]
encodeWord w = [lo w, hi w]
encodeLineNumber :: Word16 -> [Word8]
encodeLineNumber w = [hi w, lo w]
encodeDecimal :: Word16 -> [Word8]
encodeDecimal = map encodeChar . show
lo, hi :: Word16 -> Word8
lo w = fromIntegral $ w `mod` 256
hi w = fromIntegral $ w `div` 256
-- ZX BASIC HELPERS
-- These functions are here to make writing the BASIC code for the loader a little
-- easier. Of course, some sort of fully-fledged DSL for writing BASIC code would
-- be even better, but for now these serve as a useful stop-gap
basic :: Word16 -> ByteString -> ByteString
basic ln c = lineNumber <> lineLength <> code'
where lineLength = BS.pack . encodeWord . fromIntegral $ BS.length code'
lineNumber = BS.pack . encodeLineNumber $ ln
code' = c <> BS.pack [cr]
clear, val, load, code, screen, border, paper, ink :: Word8
poke, randomize, usr, quote, cr :: Word8
clear = 0xfd
val = 0xb0
load = 0xef
code = 0xaf
screen = 0xaa
border = 0xe7
paper = 0xda
ink = 0xd9
poke = 0xf4
randomize = 0xf9
usr = 0xc0
quote = encodeChar '\"'
cr = encodeChar '\r'
quoted :: [Word8] -> [Word8]
quoted s = [quote] <> s <> [quote]
quotedNum :: Word16 -> [Word8]
quotedNum n = quoted $ encodeDecimal n
basicSeq :: [ByteString] -> ByteString
basicSeq = BS.intercalate (BS.pack $ [encodeChar ':'])
| dpwright/zxspectrum | src/ZXSpectrum/TAP.hs | mit | 6,500 | 0 | 14 | 1,637 | 1,537 | 832 | 705 | 112 | 1 |
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE ViewPatterns #-}
-- Copyright (c) 2009 Daniel Schoepe
--
-- 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.
--
-- 3. Neither the name of the author nor the names of his contributors
-- may be used to endorse or promote products derived from this software
-- without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 HWB.Plugin.Utilities.ExtensibleState (
get,
put
) where
import Prelude hiding (lookup)
import Control.Monad.Trans.Class (MonadTrans(lift))
import Control.Monad.Trans.State (modify, gets)
import Data.Functor.Infix ((<&>))
import Data.Map (insert, lookup)
import Data.Maybe (fromMaybe)
import Data.Typeable (Typeable(..), typeOf, cast)
import XMonad.Core (ExtensionClass(..), StateExtension(..))
import HWB.Core (H)
put :: ExtensionClass a => a -> H ()
put value = lift . modify $ insert (show $ typeOf value) (extensionType value)
get :: ExtensionClass a => H a
get = getState undefined
where getState :: ExtensionClass a => a -> H a
getState (show . typeOf -> key) = lift (gets $ lookup key) <&> fromMaybe initialValue . \case
Just (StateExtension val) -> cast val
Just (PersistentExtension val) -> cast val
_ -> return initialValue
| fmap/hwb | src/HWB/Plugin/Utilities/ExtensibleState.hs | mit | 2,599 | 0 | 13 | 550 | 367 | 217 | 150 | -1 | -1 |
{- arch-tag: Euither utilities
Copyright (c) 2004-2011 John Goerzen <[email protected]>
All rights reserved.
For license and copyright information, see the file LICENSE
-}
{- |
Module : Data.Either.Utils
Copyright : Copyright (C) 2004-2011 John Goerzen
License : BSD3
Maintainer : John Goerzen <[email protected]>
Stability : provisional
Portability: portable
Utilities for working with the Either data type
-}
module Data.Either.Utils
(
maybeToEither,
forceEither,
forceEitherMsg,
eitherToMonadError,
fromLeft, fromRight, fromEither
) where
import Control.Monad.Error
{- | Converts a Maybe value to an Either value, using the supplied parameter
as the Left value if the Maybe is Nothing.
This function can be interpreted as:
@maybeToEither :: e -> Maybe a -> Either e a@
Its definition is given as it is so that it can be used in the Error and related monads.
-}
maybeToEither :: MonadError e m =>
e -- ^ (Left e) will be returned if the Maybe value is Nothing
-> Maybe a -- ^ (Right a) will be returned if this is (Just a)
-> m a
maybeToEither errorval Nothing = throwError errorval
maybeToEither _ (Just normalval) = return normalval
{- | Pulls a "Right" value out of an Either value. If the Either value is
Left, raises an exception with "error". -}
forceEither :: Show e => Either e a -> a
forceEither (Left x) = error (show x)
forceEither (Right x) = x
{- | Like 'forceEither', but can raise a specific message with the error. -}
forceEitherMsg :: Show e => String -> Either e a -> a
forceEitherMsg msg (Left x) = error $ msg ++ ": " ++ show x
forceEitherMsg _ (Right x) = x
{- | Takes an either and transforms it into something of the more generic
MonadError class. -}
eitherToMonadError :: MonadError e m => Either e a -> m a
eitherToMonadError (Left x) = throwError x
eitherToMonadError (Right x) = return x
-- | Take a Left to a value, crashes on a Right
fromLeft :: Either a b -> a
fromLeft (Left a) = a
fromLeft _ = error "Data.Either.Utils.fromLeft: Right"
-- | Take a Right to a value, crashes on a Left
fromRight :: Either a b -> b
fromRight (Right a) = a
fromRight _ = error "Data.Either.Utils.fromRight: Left"
-- | Take an Either, and return the value inside it
fromEither :: Either a a -> a
fromEither (Left a) = a
fromEither (Right a) = a
| haskellbr/missingh | missingh-all/src/Data/Either/Utils.hs | mit | 2,424 | 0 | 8 | 559 | 417 | 213 | 204 | 32 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Y2021.M02.D02.Exercise where
import Data.Aeson
import Data.Aeson.WikiDatum (Name)
import Data.Relation
import Graph.Query
import Graph.JSON.Cypher (matchSet)
{--
With this neo4j cypher query against a CSV file of wine-tasters and wines:
LOAD CSV WITH HEADERS
FROM 'https://raw.githubusercontent.com/lju-lazarevic/wine/master/data/winemag-data-130k-v2.csv' AS row
WITH CASE row.taster_twitter_handle
WHEN null
THEN null
ELSE [row.taster_name, row.taster_twitter_handle]
END as twitterz
RETURN DISTINCT twitterz
we get the following file:
--}
twitterzDir, twitterzJSON :: FilePath
twitterzDir = "Y2021/M02/D02/"
twitterzJSON = "twitterz.json"
fetchTwitterz :: FilePath -> IO [Taster]
fetchTwitterz = undefined
data Taster = Taster { name :: Name, twitter :: Name }
deriving (Eq, Ord, Show)
instance Node Taster where
asNode = undefined
instance FromJSON Taster where
parseJSON = undefined
-- using the matchSet function, upload the twitter handles to the graph store
toCyph :: Taster -> Cypher
toCyph = undefined
| geophf/1HaskellADay | exercises/HAD/Y2021/M02/D02/Exercise.hs | mit | 1,111 | 0 | 8 | 191 | 161 | 97 | 64 | 20 | 1 |
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.SVGAnimatedLengthList
(js_getBaseVal, getBaseVal, js_getAnimVal, getAnimVal,
SVGAnimatedLengthList, castToSVGAnimatedLengthList,
gTypeSVGAnimatedLengthList)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSVal(..), JSString)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSVal(..), FromJSVal(..))
import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.JSFFI.Generated.Enums
foreign import javascript unsafe "$1[\"baseVal\"]" js_getBaseVal ::
SVGAnimatedLengthList -> IO (Nullable SVGLengthList)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGAnimatedLengthList.baseVal Mozilla SVGAnimatedLengthList.baseVal documentation>
getBaseVal ::
(MonadIO m) => SVGAnimatedLengthList -> m (Maybe SVGLengthList)
getBaseVal self
= liftIO (nullableToMaybe <$> (js_getBaseVal (self)))
foreign import javascript unsafe "$1[\"animVal\"]" js_getAnimVal ::
SVGAnimatedLengthList -> IO (Nullable SVGLengthList)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGAnimatedLengthList.animVal Mozilla SVGAnimatedLengthList.animVal documentation>
getAnimVal ::
(MonadIO m) => SVGAnimatedLengthList -> m (Maybe SVGLengthList)
getAnimVal self
= liftIO (nullableToMaybe <$> (js_getAnimVal (self))) | manyoo/ghcjs-dom | ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/SVGAnimatedLengthList.hs | mit | 1,911 | 12 | 10 | 235 | 460 | 283 | 177 | 31 | 1 |
{-
Somehwat modified ghc-pkg, customizes default database locations and lib names
based on GHC repository revision 1c0b7362068d05b68bd7e05c4d2ef51da9533bf7
-}
{-# LANGUAGE CPP, TypeSynonymInstances, FlexibleInstances, RecordWildCards,
GeneralizedNewtypeDeriving, StandaloneDeriving #-}
{-# 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 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 (depends, installedPackageId)
import Distribution.Text
import Distribution.Version
import Distribution.Simple.Utils (fromUTF8, toUTF8)
import System.FilePath as FilePath
import qualified System.FilePath.Posix as FilePath.Posix
import System.Process
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 Data.Ord (comparing)
import Control.Monad
import System.Directory ( doesDirectoryExist, getDirectoryContents,
doesFileExist, renameFile, 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.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
import qualified Compiler.Info as Info
-- -----------------------------------------------------------------------------
-- Entry point
main :: IO ()
main = do
args <- Info.getFullArguments -- for extra args on Windows, see Compiler.Info
case getOpt Permute (flags ++ deprecFlags) args of
(cli,_,[]) | FlagHelp `elem` cli -> do
prog <- getProgramName
bye (usageInfo (usageHeader prog) flags)
(cli,_,[]) | FlagGhcVersion `elem` cli ->
bye ourCopyright
(cli,_,[]) | FlagGhcjsVersion `elem` cli ->
bye ("GHCJS package manager version " ++ Info.getCompilerVersion ++ "\n")
(cli,_,[]) | FlagNumericGhcVersion `elem` cli ->
bye (Info.getGhcCompilerVersion ++ "\n")
(cli,_,[]) | FlagNumericGhcjsVersion `elem` cli ->
bye (Info.getCompilerVersion ++ "\n")
(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
| FlagGhcVersion
| FlagNumericGhcVersion
| FlagGhcjsVersion
| FlagNumericGhcjsVersion
| FlagConfig FilePath
| FlagGlobalConfig FilePath
| FlagUserConfig FilePath
| FlagForce
| FlagForceFiles
| FlagAutoGHCiLibs
| FlagMultiInstance
| FlagExpandEnvVars
| FlagExpandPkgroot
| FlagNoExpandPkgroot
| FlagSimpleOutput
| FlagNamesOnly
| FlagIgnoreCase
| FlagNoUserDb
| FlagVerbosity (Maybe String)
| FlagIPId
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 ['g'] ["auto-ghci-libs"] (NoArg FlagAutoGHCiLibs)
"automatically build libs for GHCi (with register)",
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'] ["ghc-version", "version"] (NoArg FlagGhcVersion)
"output GHC version information and exit",
Option [] ["numeric-ghc-version"] (NoArg FlagNumericGhcVersion)
"output numeric GHC version information and exit",
Option [] ["ghcjs-version"] (NoArg FlagGhcjsVersion)
"output GHCJS version information and exit",
Option [] ["numeric-ghcjs-version"] (NoArg FlagNumericGhcjsVersion)
"output numeric GHCJS 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"] (NoArg FlagIPId)
"interpret package arguments as 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 = "GHCJS package manager version " ++ Info.getGhcCompilerVersion ++ "\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 package.\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: ghcjs-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" ++
" \"ghcjs-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), ghcjs-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)
-- | Represents how a package may be specified by a user on the command line.
data PackageArg
-- | A package identifier foo-0.1; the version might be a glob.
= Id PackageIdentifier
-- | An installed package ID foo-0.1-HASH. This is guaranteed to uniquely
-- match a single entry in the package database.
| IPId InstalledPackageId
-- | A glob against the package name. The first string is the literal
-- glob, the second is a function which returns @True@ if the the argument
-- matches.
| Substring String (String->Bool)
runit :: Verbosity -> [Flag] -> [String] -> IO ()
runit verbosity cli nonopts = do
installSignalHandlers -- catch ^C and clean up
prog <- getProgramName
let
force
| FlagForce `elem` cli = ForceAll
| FlagForceFiles `elem` cli = ForceFiles
| otherwise = NoForce
as_ipid = FlagIPId `elem` cli
auto_ghci_libs = FlagAutoGHCiLibs `elem` cli
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
auto_ghci_libs multi_instance
expand_env_vars False force
["update", filename] ->
registerPackage filename verbosity cli
auto_ghci_libs multi_instance
expand_env_vars True force
["unregister", pkgarg_str] -> do
pkgarg <- readPackageArg as_ipid pkgarg_str
unregisterPackage pkgarg verbosity cli force
["expose", pkgarg_str] -> do
pkgarg <- readPackageArg as_ipid pkgarg_str
exposePackage pkgarg verbosity cli force
["hide", pkgarg_str] -> do
pkgarg <- readPackageArg as_ipid pkgarg_str
hidePackage pkgarg verbosity cli force
["trust", pkgarg_str] -> do
pkgarg <- readPackageArg as_ipid pkgarg_str
trustPackage pkgarg verbosity cli force
["distrust", pkgarg_str] -> do
pkgarg <- readPackageArg as_ipid 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_ipid 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", moduleName] -> do
let match = maybe (==moduleName) id (substringCheck moduleName)
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_ipid 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_ipid 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)
readGlobPkgId :: String -> IO PackageIdentifier
readGlobPkgId str = parseCheck parseGlobPackageId str "package identifier"
parseGlobPackageId :: ReadP r PackageIdentifier
parseGlobPackageId =
parse
+++
(do n <- parse
_ <- string "-*"
return (PackageIdentifier{ pkgName = n, pkgVersion = globVersion }))
readPackageArg :: Bool -> String -> IO PackageArg
readPackageArg True str =
parseCheck (IPId `fmap` parse) str "installed package id"
readPackageArg False str = Id `fmap` readGlobPkgId str
-- globVersion means "all versions"
globVersion :: Version
globVersion = Version{ versionBranch=[], versionTags=["*"] }
-- -----------------------------------------------------------------------------
-- 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
[] -> die err_msg
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 $ Info.getUserPackageDir' -- 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 -- 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 "GHCJS_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 ->
die ("ghc no longer supports single-file style package databases "
++ "(" ++ path ++ ") use 'ghcjs-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. " ++
"Use 'ghcjs-pkg recache' to fix.")
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. Use 'ghcjs-pkg recache' to fix.")
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
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 (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),
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
-- -----------------------------------------------------------------------------
-- 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 -- auto_ghci_libs
-> Bool -- multi_instance
-> Bool -- expand_env_vars
-> Bool -- update
-> Force
-> IO ()
registerPackage input verbosity my_flags auto_ghci_libs 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
--
when (auto_ghci_libs && verbosity >= Silent) $
warn "Warning: --auto-ghci-libs is deprecated and will be removed in GHC 7.4"
--
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 [] 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
auto_ghci_libs 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 ]
--
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 { packageKey = packageKey' }
where
packageKey'
| OldPackageKey (PackageIdentifier (PackageName "") _) <- packageKey ipi
= OldPackageKey (sourcePackageId ipi)
| otherwise = packageKey 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
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 ((/= installedPackageId p) . installedPackageId) 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 (installedPackageId p) <.> "conf"
when (verbosity > Normal) $ infoLn ("removing " ++ file)
removeFileSafe file
do_cmd (AddPackage p) = do
let file = location db </> display (installedPackageId p) <.> "conf"
when (verbosity > Normal) $ infoLn ("writing " ++ file)
writeFileUtf8Atomic 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
#ifndef mingw32_HOST_OS
status <- getFileStatus filename
setFileTimes (location db) (accessTime status) (modificationTime status)
#endif
type PackageCacheFormat = GhcPkg.InstalledPackageInfo
String -- installed package id
String -- src package id
String -- package name
String -- package key
ModuleName -- module name
convertPackageInfoToCacheFormat :: InstalledPackageInfo -> PackageCacheFormat
convertPackageInfoToCacheFormat pkg =
GhcPkg.InstalledPackageInfo {
GhcPkg.installedPackageId = display (installedPackageId pkg),
GhcPkg.sourcePackageId = display (sourcePackageId pkg),
GhcPkg.packageName = display (packageName pkg),
GhcPkg.packageVersion = packageVersion pkg,
GhcPkg.packageKey = display (packageKey pkg),
GhcPkg.depends = map display (depends pkg),
GhcPkg.importDirs = importDirs pkg,
GhcPkg.hsLibraries = hsLibraries pkg,
GhcPkg.extraLibraries = extraLibraries pkg,
GhcPkg.extraGHCiLibraries = extraGHCiLibraries pkg,
GhcPkg.libraryDirs = libraryDirs 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.instantiatedWith = map convertInst (instantiatedWith pkg),
GhcPkg.exposed = exposed pkg,
GhcPkg.trusted = trusted pkg
}
where convertExposed (ExposedModule n reexport sig) =
GhcPkg.ExposedModule n (fmap convertOriginal reexport)
(fmap convertOriginal sig)
convertOriginal (OriginalModule ipid m) =
GhcPkg.OriginalModule (display ipid) m
convertInst (m, o) = (m, convertOriginal o)
instance GhcPkg.BinaryStringRep ModuleName where
fromStringRep = ModuleName.fromString . fromUTF8 . BS.unpack
toStringRep = BS.pack . toUTF8 . display
instance GhcPkg.BinaryStringRep String where
fromStringRep = fromUTF8 . BS.unpack
toStringRep = BS.pack . toUTF8
-- -----------------------------------------------------------------------------
-- 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 packageKey ps
cmds = [ fn pkg | pkg <- pkgs, packageKey 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 packageKey old_broken)
. packageKey) new_broken
--
let displayQualPkgId pkg
| [_] <- filter ((== pkgid) . sourcePackageId)
(allPackagesInStack db_stack)
= display pkgid
| otherwise = display pkgid ++ "@" ++ display (packageKey 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 -> packageKey pkg1 `compare` packageKey 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 packageKey (brokenPackages pkg_map)
show_normal PackageDB{ location = db_name, packages = pkg_confs } =
do hPutStrLn stdout (db_name ++ ":")
if null pp_pkgs
then hPutStrLn stdout " (no packages)"
else hPutStrLn stdout $ unlines (map (" " ++) pp_pkgs)
where
-- Sort using instance Ord PackageId
pp_pkgs = map pp_pkg . sortBy (comparing installedPackageId) $ pkg_confs
pp_pkg p
| packageKey p `elem` broken = printf "{%s}" doc
| exposed p = doc
| otherwise = printf "(%s)" doc
where doc | verbosity >= Verbose = printf "%s (%s)" pkg ipid
| otherwise = pkg
where
InstalledPackageId ipid = installedPackageId p
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 =
mconcat $ map (<#> termText "\n") $
(termText (location db) :
map (termText " " <#>) (map pp_pkg (packages db)))
where
pp_pkg p
| packageKey p `elem` broken = withF Red doc
| exposed p = doc
| otherwise = withF Blue doc
where doc | verbosity >= Verbose
= termText (printf "%s (%s)" pkg ipid)
| otherwise
= termText pkg
where
InstalledPackageId ipid = installedPackageId p
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
-- Sort using instance Ord PackageId
strs = map showPkg $ sort $ 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),
depid <- depends p,
Just dep <- [PackageIndex.lookupInstalledPackageId ipix depid],
let to = display (sourcePackageId dep)
]
putStrLn "}"
-- -----------------------------------------------------------------------------
-- Prints the highest (hidden or exposed) version of a package
-- ToDo: This is no longer well-defined with package keys, because the
-- dependencies may be varying versions
latestPackage :: Verbosity -> [Flag] -> PackageIdentifier -> 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) = display pkgid
pkg_msg (IPId ipid) = display ipid
pkg_msg (Substring pkgpat _) = "matching " ++ pkgpat
matches :: PackageIdentifier -> PackageIdentifier -> Bool
pid `matches` pid'
= (pkgName pid == pkgName pid')
&& (pkgVersion pid == pkgVersion pid' || not (realVersion pid))
realVersion :: PackageIdentifier -> Bool
realVersion pkgid = versionBranch (pkgVersion pkgid) /= []
-- when versionBranch == [], this is a glob
matchesPkg :: PackageArg -> InstalledPackageInfo -> Bool
(Id pid) `matchesPkg` pkg = pid `matches` sourcePackageId pkg
(IPId ipid) `matchesPkg` pkg = ipid == installedPackageId 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
False True True
if null es
then do when (not simple_output) $ do
_ <- reportValidateErrors [] ws "" Nothing
return ()
return []
else do
when (not simple_output) $ do
reportError ("There are problems in package " ++ display (sourcePackageId p) ++ ":")
_ <- reportValidateErrors 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 installedPackageId 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 = return
(<*>) = ap
instance Monad Validate where
return a = V $ return (a, [], [])
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 :: [ValidateError] -> [ValidateWarning]
-> String -> Maybe Force -> IO Bool
reportValidateErrors 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 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 -- auto-ghc-libs
-> Bool -- multi_instance
-> Bool -- update, or check
-> Force
-> IO ()
validatePackageConfig pkg verbosity db_stack auto_ghci_libs
multi_instance update force = do
(_,es,ws) <- runValidate $
checkPackageConfig pkg verbosity db_stack
auto_ghci_libs multi_instance update
ok <- reportValidateErrors es ws (display (sourcePackageId pkg) ++ ": ") (Just force)
when (not ok) $ exitWith (ExitFailure 1)
checkPackageConfig :: InstalledPackageInfo
-> Verbosity
-> PackageDBStack
-> Bool -- auto-ghc-libs
-> Bool -- multi_instance
-> Bool -- update, or check
-> Validate ()
checkPackageConfig pkg verbosity db_stack auto_ghci_libs
multi_instance update = do
checkInstalledPackageId pkg db_stack update
checkPackageId pkg
checkPackageKey pkg
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 "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
-- disabled for GHCJS since native libraries are optional.
-- fixme: detect dynamic-too mode and enable for that
-- mapM_ (checkHSLib verbosity (libraryDirs pkg) auto_ghci_libs) (hsLibraries pkg)
-- ToDo: check these somehow?
-- extra_libraries :: [String],
-- c_includes :: [String],
checkInstalledPackageId :: InstalledPackageInfo -> PackageDBStack -> Bool
-> Validate ()
checkInstalledPackageId ipi db_stack update = do
let ipid@(InstalledPackageId str) = installedPackageId ipi
when (null str) $ verror CannotForce "missing id field"
let dups = [ p | p <- allPackagesInStack db_stack,
installedPackageId p == ipid ]
when (not update && not (null dups)) $
verror CannotForce $
"package(s) with this id already exist: " ++
unwords (map (display.packageId) dups)
-- 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)
checkPackageKey :: InstalledPackageInfo -> Validate ()
checkPackageKey ipi =
let str = display (packageKey ipi) in
case [ x :: PackageKey | (x,ys) <- readP_to_S parse str, all isSpace ys ] of
[_] -> return ()
[] -> verror CannotForce ("invalid package key: " ++ str)
_ -> verror CannotForce ("ambiguous package key: " ++ str)
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 (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 -> InstalledPackageId -> 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 installedPackageId all_pkgs
checkDuplicateDepends :: [InstalledPackageId] -> 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] -> Bool -> String -> Validate ()
checkHSLib verbosity dirs auto_ghci_libs lib = do
let batch_lib_file = "lib" ++ lib ++ ".a"
filenames = ["lib" ++ lib ++ ".a",
"lib" ++ lib ++ ".p_a",
"lib" ++ lib ++ "-ghcjs" ++ Info.getGhcCompilerVersion ++ ".so",
"lib" ++ lib ++ "-ghcjs" ++ Info.getGhcCompilerVersion ++ ".dylib",
lib ++ "-ghcjs" ++ Info.getGhcCompilerVersion ++ ".dll"]
m <- liftIO $ doesFileExistOnPath filenames dirs
case m of
Nothing -> verror ForceFiles ("cannot find any of " ++ show filenames ++
" on library path")
Just dir -> liftIO $ checkGHCiLib verbosity dir batch_lib_file lib auto_ghci_libs
doesFileExistOnPath :: [FilePath] -> [FilePath] -> IO (Maybe FilePath)
doesFileExistOnPath filenames paths = go fullFilenames
where fullFilenames = [ (path, path </> filename)
| filename <- filenames
, path <- paths ]
go [] = return Nothing
go ((p, fp) : xs) = do b <- doesFileExist fp
if b then return (Just p) else go xs
-- | 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 _sig) = do
let checkOriginal = checkModuleFile pkg modl
checkReexport = checkOriginalModule "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", "js_hi", "js_p_hi" ] ]
m <- liftIO $ doesFileExistOnPath files (importDirs pkg)
when (isNothing m) $
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.)
checkOriginalModule :: String
-> PackageDBStack
-> InstalledPackageInfo
-> OriginalModule
-> Validate ()
checkOriginalModule fieldName db_stack pkg
(OriginalModule definingPkgId definingModule) =
let mpkg = if definingPkgId == installedPackageId pkg
then Just pkg
else PackageIndex.lookupInstalledPackageId ipix definingPkgId
in case mpkg of
Nothing
-> verror ForceAll (fieldName ++ " refers to a non-existent " ++
"defining package: " ++
display definingPkgId)
Just definingPkg
| not (isIndirectDependency definingPkgId)
-> verror ForceAll (fieldName ++ " 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 (fieldName ++ " refers to a module " ++
display definingModule ++ " " ++
"that is not exposed in the " ++
"defining package " ++ display definingPkgId)
Just (ExposedModule {exposedReexport = Just _} ) ->
verror ForceAll (fieldName ++ " 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 (installedPackageId pkg)
otherpkg <- graphVertex pkgid
return (Graph.path depgraph thispkg otherpkg)
(depgraph, _, graphVertex) =
PackageIndex.dependencyGraph (PackageIndex.insert pkg ipix)
checkGHCiLib :: Verbosity -> String -> String -> String -> Bool -> IO ()
checkGHCiLib verbosity batch_lib_dir batch_lib_file lib auto_build
| auto_build = autoBuildGHCiLib verbosity batch_lib_dir batch_lib_file ghci_lib_file
| otherwise = return ()
where
ghci_lib_file = lib <.> "o"
-- automatically build the GHCi version of a batch lib,
-- using ld --whole-archive.
autoBuildGHCiLib :: Verbosity -> String -> String -> String -> IO ()
autoBuildGHCiLib verbosity dir batch_file ghci_file = do
let ghci_lib_file = dir ++ '/':ghci_file
batch_lib_file = dir ++ '/':batch_file
when (verbosity >= Normal) $
info ("building GHCi library " ++ ghci_lib_file ++ "...")
#if defined(darwin_HOST_OS)
r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"-all_load",batch_lib_file]
#elif defined(mingw32_HOST_OS)
execDir <- getLibDir
r <- rawSystem (maybe "" (++"/gcc-lib/") execDir++"ld") ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
#else
r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
#endif
when (r /= ExitSuccess) $ exitWith r
when (verbosity >= Normal) $
infoLn (" done.")
-- -----------------------------------------------------------------------------
-- Searching for modules
#if not_yet
findModules :: [FilePath] -> IO [String]
findModules paths =
mms <- mapM searchDir paths
return (concat mms)
searchDir path prefix = do
fs <- getDirectoryEntries path `catchIO` \_ -> return []
searchEntries path prefix fs
searchEntries path prefix [] = return []
searchEntries path prefix (f:fs)
| looks_like_a_module = do
ms <- searchEntries path prefix fs
return (prefix `joinModule` f : ms)
| looks_like_a_component = do
ms <- searchDir (path </> f) (prefix `joinModule` f)
ms' <- searchEntries path prefix fs
return (ms ++ ms')
| otherwise
searchEntries path prefix fs
where
(base,suffix) = splitFileExt f
looks_like_a_module =
suffix `elem` haskell_suffixes &&
all okInModuleName base
looks_like_a_component =
null suffix && all okInModuleName base
okInModuleName c
#endif
-- ---------------------------------------------------------------------------
-- 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/ghcjs-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
#if mingw32_HOST_OS || mingw32_TARGET_OS
throwIOIO :: Exception.IOException -> IO a
throwIOIO = Exception.throwIO
#endif
catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a
catchIO = Exception.catch
tryIO :: IO a -> IO (Either Exception.IOException a)
tryIO = Exception.try
writeFileUtf8Atomic :: FilePath -> String -> IO ()
writeFileUtf8Atomic targetFile content =
withFileAtomic targetFile $ \h -> do
hSetEncoding h utf8
hPutStr h content
-- copied from Cabal's Distribution.Simple.Utils, except that we want
-- to use text files here, rather than binary files.
withFileAtomic :: FilePath -> (Handle -> IO ()) -> IO ()
withFileAtomic targetFile write_content = do
(newFile, newHandle) <- openNewFile targetDir template
do write_content newHandle
hClose newHandle
#if mingw32_HOST_OS || mingw32_TARGET_OS
renameFile newFile targetFile
-- If the targetFile exists then renameFile will fail
`catchIO` \err -> do
exists <- doesFileExist targetFile
if exists
then do removeFileSafe targetFile
-- Big fat hairy race condition
renameFile newFile targetFile
-- If the removeFile succeeds and the renameFile fails
-- then we've lost the atomic property.
else throwIOIO err
#else
renameFile newFile targetFile
#endif
`Exception.onException` do hClose newHandle
removeFileSafe newFile
where
template = targetName <.> "tmp"
targetDir | null targetDir_ = "."
| otherwise = targetDir_
--TODO: remove this when takeDirectory/splitFileName is fixed
-- to always return a valid dir
(targetDir_,targetName) = splitFileName targetFile
openNewFile :: FilePath -> String -> IO (FilePath, Handle)
openNewFile dir template = do
-- this was added to System.IO in 6.12.1
-- we must use this version because the version below opens the file
-- in binary mode.
openTempFileWithDefaultPermissions dir template
readUTF8File :: FilePath -> IO String
readUTF8File file = do
h <- openFile file ReadMode
-- fix the encoding to UTF-8
hSetEncoding h utf8
hGetContents h
-- 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
absolutePath :: FilePath -> IO FilePath
absolutePath path = return . normalise . (</> path) =<< getCurrentDirectory
| forked-upstream-packages-for-ghcjs/ghcjs | ghcjs/src-bin/Pkg.hs | mit | 83,270 | 49 | 100 | 23,389 | 18,097 | 9,199 | 8,898 | 1,388 | 32 |
{-# LANGUAGE OverloadedStrings #-}
import Prelude hiding ((**), div, span)
import Control.Monad
import Clay
import qualified Clay.Media as M
import Data.Monoid
import qualified Data.Text.Lazy.IO as T
-- colors
blogRed = "#6D3B34"
blogLightGray = "#E7E4E7"
blogGreen = "#9F9B5C"
blogBlue = "#1E335A"
blogDarkGray = "#7A707B"
syntaxBgColor = "#303030"
syntaxFontColor = "#CCCCCC"
-- fonts
headerFontStack = ["Roboto Slab"]
syntaxFontStack = ["Droid Sans Mono", "Lucida Console", "Monaco"]
hs = h1 <> h2 <> h3 <> h4 <> h5 <> h6
linkStates = a
<> (a # link)
<> (a # visited)
<> (a # active)
<> (a # hover)
blog :: Css
blog = do
hs ? do
fontFamily headerFontStack [serif]
a ? do
textDecoration none
hover & textDecoration underline
hs ** span <> ".date-stamp" ? do
color blogDarkGray
fontSize $ pct 40
".date-stamp" ? lineHeight (px 10)
h2 ** linkStates ? color blogRed
".pull-right" ? float floatRight
ul # ".inline" ** li ? display inline
header ** h1 ? do
borderBottom solid (px 1) blogLightGray
marginBottom (px 20)
marginTop (px 40)
paddingBottom (px 10)
ul ** li ? do
display inline
".separateable" ? do
li ? do
borderRight solid (px 1) blogDarkGray
float floatLeft
lineHeight (px 14)
marginRight (px 10)
padding (px 0) (px 10) (px 0) (px 0)
":last-child" & do
borderRightStyle none
marginRight (px 0)
paddingRight (px 0)
"#be-social" ** li ? do
fontSize (px 14)
marginLeft (px 15)
marginRight 0
linkStates ? do
color blogDarkGray
fontSizeCustom smaller
div # ".post" ? do
h2 ? do
marginBottom (px 20)
".subtitle" ? do
color blogDarkGray
fontSizeCustom smaller
borderBottom solid (px 1) blogLightGray
marginBottom (px 30)
":last-child" & do
borderBottomStyle none
marginBottom 0
".read-more" ? do
marginBottom (px 10)
a ? do
color blogRed
fontSizeCustom smaller
textDecoration none
a # hover ? textDecoration underline
ul ? do
"list-style" -: "disc inside"
let refs = ".references"
refs ? fontSize (px 17)
refs |+ ul ? do
"list-style" -: "circle inside"
li ? marginBottom (px 0)
footer ? do
borderTop solid (px 1) blogLightGray
fontSizeCustom smaller
marginTop (px 40)
sym2 padding (px 10) 0
tabletsAndPhones
syntax
tabletsAndPhones = queryOnly M.screen [M.maxWidth (px 959)] $ do
"#be-social" <> "#made-with" ? display displayNone
syntaxMap =
[ (".kw", "#f0dfaf")
, (".dt", "#dfdfbf")
, (".dv", "#dcdccc")
, (".bn", "#dca3a3")
, (".fl", "#c0bed1")
, (".ch", "#dca3a3")
, (".st", "#cc9393")
, (".co", "#7f9f7f")
, (".ot", "#efef8f")
, (".al", "#ffcfaf")
, (".fu", "#efef8f")
, (".re", "#ffd7a7")
, (".er", "#c3bf9f")
]
syntax :: Css
syntax = do
pre # ".sourceCode" <> table # ".sourceCode" ? do
backgroundColor syntaxBgColor
sym borderRadius (px 10)
color syntaxFontColor
display block
fontFamily syntaxFontStack [monospace, sansSerif]
sym2 margin (px 20) (px 0)
overflowX scroll
sym padding (px 10)
".lineNumbers" ? do
paddingRight (px 15)
textAlign (alignSide sideRight)
".sourceCode" ? do
forM_ syntaxMap $ \(s,c) -> span # s ? color c
code # ":not(.sourceCode)" ? do
backgroundColor syntaxBgColor
sym borderRadius (px 2)
color syntaxFontColor
sym2 padding (px 2) (px 4)
main :: IO ()
main = T.putStr $ render blog
| rjregenold/blog | css/blog.hs | mit | 3,641 | 0 | 18 | 1,013 | 1,322 | 631 | 691 | -1 | -1 |
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.AudioStreamTrack
(js_newAudioStreamTrack, newAudioStreamTrack, AudioStreamTrack,
castToAudioStreamTrack, gTypeAudioStreamTrack)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSRef(..), JSString, castRef)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSRef(..), FromJSRef(..))
import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.Enums
foreign import javascript unsafe
"new window[\"AudioStreamTrack\"]($1)" js_newAudioStreamTrack ::
JSRef Dictionary -> IO (JSRef AudioStreamTrack)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/AudioStreamTrack Mozilla AudioStreamTrack documentation>
newAudioStreamTrack ::
(MonadIO m, IsDictionary audioConstraints) =>
Maybe audioConstraints -> m AudioStreamTrack
newAudioStreamTrack audioConstraints
= liftIO
(js_newAudioStreamTrack
(maybe jsNull (unDictionary . toDictionary) audioConstraints)
>>= fromJSRefUnchecked) | plow-technologies/ghcjs-dom | src/GHCJS/DOM/JSFFI/Generated/AudioStreamTrack.hs | mit | 1,619 | 6 | 12 | 237 | 387 | 243 | 144 | 29 | 1 |
{- |
Module : Control.Monad.Levels.Writer.Lazy
Description : Lazy writer monad
Copyright : (c) Ivan Lazar Miljenovic
License : MIT
Maintainer : [email protected]
-}
module Control.Monad.Levels.Writer.Lazy
( writer
, tell
, HasWriter
, listen
, CanListen
, ListenFn
, pass
, CanPass
, PassFn
, WriterT(..)
, IsWriter
) where
import Control.Monad.Levels.Writer
import Control.Monad.Trans.Writer.Lazy (WriterT (..))
| ivan-m/monad-levels | Control/Monad/Levels/Writer/Lazy.hs | mit | 477 | 0 | 6 | 111 | 73 | 51 | 22 | 14 | 0 |
{-|
Module : Main
Description : Runs the program.
Copyright : (c) Christopher Wells, 2016
License : MIT
Maintainer : [email protected]
-}
module Main where
import Test.SystemTest.Main
-- | Runs the main function of the program.
main :: IO ()
main = progMain
| ExcaliburZero/system-test-haskell | Main.hs | mit | 276 | 0 | 6 | 57 | 27 | 17 | 10 | 4 | 1 |
module Main where
import Control.Monad.Except
import Data.IORef
import Data.Logic.Propositional
import Data.Logic.Propositional.Class
import Data.String
testThm = Theorem (Conjunction (Variable "A") (Negation (Variable "A")))
varA = Variable "A"
varB = Variable "B"
-- This tests the basic non-bindings proving. True *should* true, at
-- least in this universe.
testProof1 = Proof newBindings
[(Theorem (Equivalence (Value True) (Value True)))]
-- If the prover can't prove that A == A, time to pack it up and go home.
testProof2 = Proof newBindings
[Axiom "A" True, (Theorem (Equivalence varA varA))]
-- A basic sanity check: given an axiom (A <- True), will a basic
-- proof be shown as consistent?
testProof3 = Proof newBindings [Axiom "A" True, testThm]
-- An empty set of bindings and no axioms should be unprovable.
testProof4 = Proof newBindings [testThm]
-- Trying to prove true = false should fail.
testProof5 = Proof newBindings
[Axiom "A" True, Axiom "B" False,
Theorem
(Equivalence (Variable "A") (Variable "B"))]
-- The following proof should demonstrate that ordering theorems matters.
testProof6 = Proof newBindings
[Axiom "A" True,
Theorem
(Equivalence (Variable "A") (Variable "B")),
Axiom "B" True]
-- The following proof is a little longer.
testProof7 = Proof newBindings
[Axiom "A" True
,Axiom "B" True
,Theorem (Implies
(Disjunction varA (Negation varA))
(Equivalence varA varB))]
testProofs = [testProof1, testProof2, testProof3, testProof4, testProof5
,testProof6]
checkProof :: Proof -> IO String
checkProof proof = do
result <- runExceptT $ prove proof
case result of
Left err -> return $ "Proof is invalid: " ++ (show err)
Right p -> return $ "Proof is valid\n" ++ (show p)
runProof :: Proof -> IO ()
runProof proof = do
putStrLn "\nChecking proof"
putStrLn $ show proof
checkProof proof >>= putStrLn
runProofs :: [Proof] -> IO ()
runProofs (p:p') = runProof p >> runProofs p'
runProofs [] = return ()
main = interactive newBindings
| kisom/plc | src/Main.hs | mit | 2,203 | 0 | 13 | 546 | 589 | 304 | 285 | 47 | 2 |
{-# LANGUAGE TemplateHaskell #-}
module Examples.Diffs.FirstDiff where
import CornerPoints.Radius(Radius(..))
import CornerPoints.HorizontalFaces(createBottomFaces, createTopFaces)
import CornerPoints.Create(Angle(..), flatXSlope, flatYSlope, Origin(..))
import CornerPoints.CornerPoints((|@+++#@|), (|+++|), CornerPoints(..), (+++))
import CornerPoints.Points(Point(..))
import CornerPoints.CornerPointsWithDegrees(DegreeRange(..), CornerPointsWithDegrees(..), newCornerPointsWithDegreesList )
import CornerPoints.FaceExtraction(extractFrontFace, extractFrontLeftLine, extractFrontRightLine, extractLeftFace,
extractRightFace, extractBackRightLine)
import CornerPoints.FaceConversions(toBackFace, invertFace, toFrontFace, backFaceFromFrontFace)
import CornerPoints.FaceExtractAndConvert(getFrontFaceAsBackFace, getFrontLeftLineAsBackFace, getLeftFaceAsBackFace,
getFrontRightLineAsBackFace, getRightFaceAsBackFace, getBackRightLineAsBackFace)
import Stl.StlCornerPointsWithDegrees(FacesWithRange(..), FacesWithRange(..), (|@~?+++^|) )
import Stl.StlCornerPoints(Faces(..), (+++^))
import Stl.StlFileWriter(writeStlToFile)
import Stl.StlBase (StlShape(..), newStlShape)
import qualified Builder.Sequence as S (newCornerPointsWithDegreesBuilder, (||@~+++^||), (@~+++#@|>), (@~+++@|>))
import qualified Builder.List as L ((||@~+++^||))
import Test.HUnit
import qualified Data.Foldable as F
import qualified Data.Sequence as S
--imports for arrows
import Control.Arrow hiding ((+++))
import Control.Category
import Prelude hiding ((.), id)
import qualified Data.Map as M
import Control.Lens
{-------------------------------------- overview ---------------------------------------
Create a simple radial shape with 40-45-90...360 angles.
Create at origin.
Create as second smaller simple radial shape that is offeset from the origin,
such that it will be located withing 1 triangle of large shape.
Subtract the small shape from the triangle of large shape:
so far:
Have removed the faces of large triangle
Have moved small triangle over to large triangle space, and displayed it as a self contained shape.
next: ??????
-}
angles = map Angle [0,45..360]
largeRadius = [(Radius x) | x <- [20,20..]]
largeShape =
createBottomFaces (Point 0 0 0) largeRadius angles flatXSlope flatYSlope
|+++|
createTopFaces (Point 0 0 10) largeRadius angles flatXSlope flatYSlope
largeShapeBuilder = S.newCornerPointsWithDegreesBuilder 45 largeShape
largeTriangles =
largeShapeBuilder
S.||@~+++^||
[[(FacesWithRange FacesNada (DegreeRange 0 45)), (FacesWithRange FacesBottomFrontTop (DegreeRange 45 360))]]
writeLargeShape = writeStlToFile $ newStlShape "largeShape" largeTriangles
{-Create a smaller radial shape with same angles.
Change the origin so that it is moved inside of a single cube of large shape.-}
smallRadius = [(Radius x) | x <- [2,2..]]
smallShape =
createBottomFaces (Point (5) (-10) 0) smallRadius angles flatXSlope flatYSlope
|+++|
createTopFaces (Point (5) (-10) 10) smallRadius angles flatXSlope flatYSlope
smallShapeBuilder = S.newCornerPointsWithDegreesBuilder 45 smallShape
smallShapeWithDegrees = newCornerPointsWithDegreesList 45 smallShape
smallShapeMap = M.fromList $ cornerPointsMap smallShapeWithDegrees
smallTriangles =
smallShapeBuilder
S.||@~+++^||
[[(FacesWithRange FacesAll (DegreeRange 0 360))]]
writeSmallShape = writeStlToFile $ newStlShape "smallShape" smallTriangles
{--}
writeBothShapes = writeStlToFile $ newStlShape "smallShape" $ smallTriangles ++ largeTriangles
tests = do
let seeAngles = TestCase $ assertEqual
"seeAngles"
([Angle 0])
(angles)
runTestTT seeAngles
-- =================================================== arrow:: build a single layer ==================================
--create the structure from [CornerPointsWithDegrees] required to make a map
cornerPointsMap = map (\(CubesWithStartEndDegrees cube degreeRange) -> (degreeRange,cube))
--make the CornerPointsWithDegreesList:
largeShapeWithDegrees = newCornerPointsWithDegreesList 45 largeShape
--cornerPointsWithDegreesSeq = S.newCornerPointsWithDegreesBuilder 45 largeShape
--make a map of the largeShape with DegreeRange as key and CornerPoints as value
largeShapeMap = M.fromList $ cornerPointsMap largeShapeWithDegrees
writeLargeShapeWithMap = do
let piePiece = largeShapeMap^.at (DegreeRange 0 45)
extractFromMap (Just cpt) = cpt
piePieceTriangle = FacesAll +++^ (extractFromMap piePiece)
writeStlToFile $ newStlShape "largeShape" piePieceTriangle
{-Extract the CornerPoint from the map Maybe result. Gives CornerPointsError on Nothing -}
maybeMapResult :: Maybe CornerPoints -> CornerPoints
maybeMapResult (Just a) = a
maybeMapResult Nothing = CornerPointsError "error" -- F1 (Point 1 2 3)
{-
Using arrows and map and lense:
Create 2 pieces of the large shape and output then w/o errors.
The Faces are added as it is processed.
Note the use of <<< makes it backwards
-}
writeLargeShapeWithMapAndArrowsReversed = do
let
f = Kleisli (\triangles -> writeStlToFile $ newStlShape "largeShape" triangles)
--create faces for 135-360
<<< arr (\triangles ->
( [largeShapeWithDegrees]
L.||@~+++^||
[[FacesWithRange FacesBottomFrontTop (DegreeRange 135 360)]]
)
++ triangles
)
--right of gap triangle
<<< arr (\triangles -> (FacesBottomFrontRightTop +++^ (maybeMapResult (largeShapeMap^.at (DegreeRange 90 135)))) ++ triangles)
--left of gap cube
<<< arr (\(Just cube) -> FacesBottomFrontLeftTop +++^ cube)
<<< arr Just
runKleisli f (maybeMapResult $ largeShapeMap^.at (DegreeRange 0 45))
{-same as writeLargeShapeWithMapAndArrowsReverse except with >>>
The first call of arr Just: gets its params from the last line, as params to f.
Maybe get around this by passing in () to a lambda, and ignore it. -}
writeLargeShapeWithMapAndArrowsForward = do
let f = arr (\_ -> Just (maybeMapResult $ largeShapeMap^.at (DegreeRange 0 45)))
>>> arr (\(Just cube) -> S.fromList (FacesBottomFrontLeftTop +++^ cube))
>>> arr (\triangles -> (S.fromList(FacesBottomFrontRightTop +++^
(maybeMapResult (largeShapeMap^.at (DegreeRange 90 135))))) S.>< triangles)
>>> arr (\triangles ->
(S.fromList
( [largeShapeWithDegrees]
L.||@~+++^||
[[FacesWithRange FacesBottomFrontTop (DegreeRange 135 360)]]
)
)
S.>< triangles
)
>>> Kleisli (\triangles -> writeStlToFile $ newStlShape "largeShape" (F.toList triangles))
runKleisli f ()
{-The only way to have it compile is to have the f 4. If 4 or Just is moved, no compile-}
testMaybe = do
let f = Kleisli print <<< arr Just
runKleisli f 4
testMaybeForwards = do
let f = arr Just >>> Kleisli print
runKleisli f 4
{- ========================= the big one ============================
Build the large shape with the small shape removed from the 0-45 degree cube.
-}
buildHoleInSingleTriangle = do
let
--access large shape cubes
largeCube :: Double -> Double -> CornerPoints
largeCube start end = getCubeBase largeShapeMap start end
--access small shape(hole) cubes
smallCube :: Double -> Double -> CornerPoints
smallCube start end = getCubeBase smallShapeMap start end
--keep large/smallCube DRY
getCubeBase :: M.Map DegreeRange CornerPoints -> Double -> Double -> CornerPoints
getCubeBase map start end = maybeMapResult $ map^.at (DegreeRange start end)
f = -- 0-45 degrees of hole
arr (\triangles ->
let largeCube' = getFrontFaceAsBackFace $ largeCube 0 45
smallCube' = invertFace $ extractFrontFace $ smallCube 0 45
in triangles S.>< (S.fromList (FacesBackBottomFrontTop +++^ (largeCube' +++ smallCube')))
)
-- 45-90 degrees of hole
>>> arr (\triangles ->
let largeCube' = getFrontRightLineAsBackFace $ largeCube 45 90
smallCube' = invertFace $ extractFrontFace $ smallCube 45 90
in triangles S.>< (S.fromList (FacesBottomFrontTop +++^ (largeCube' +++ smallCube')))
)
-- 90-135 degrees of hole
>>> arr (\triangles ->
let largeCube' = getFrontRightLineAsBackFace $ largeCube 45 90
smallCube' = invertFace $ extractFrontFace $ smallCube 90 135
in triangles S.>< (S.fromList (FacesBottomFrontTop +++^ (largeCube' +++ smallCube')))
)
-- 135-180 degrees of hole
>>> arr (\triangles ->
let largeCube' = getRightFaceAsBackFace $ largeCube 45 90
smallCube' = invertFace $ extractFrontFace $ smallCube 135 180
in triangles S.>< (S.fromList (FacesBottomFrontTop +++^ (largeCube' +++ smallCube')))
)
-- 180-225 degrees of hole
>>> arr (\triangles ->
let largeCube' = getBackRightLineAsBackFace $ largeCube 45 90
smallCube' = invertFace $ extractFrontFace $ smallCube 180 225
in triangles S.>< (S.fromList (FacesBottomFrontTop +++^ (largeCube' +++ smallCube')))
)
-- 225-270 degrees of hole
>>> arr (\triangles ->
let largeCube' = getBackRightLineAsBackFace $ largeCube 45 90
smallCube' = invertFace $ extractFrontFace $ smallCube 225 270
in triangles S.>< (S.fromList (FacesBottomFrontTop +++^ (largeCube' +++ smallCube')))
)
-- 270 315 degrees of hole
>>> arr (\triangles ->
let largeCube' = invertFace $ getLeftFaceAsBackFace $ largeCube 315 360
smallCube' = invertFace $ extractFrontFace $ (smallCube 270 315)
in triangles S.>< (S.fromList(FacesBottomFrontTop +++^ (largeCube' +++ smallCube')))
)
-- 315-360 degrees of hole
>>> arr (\triangles ->
let largeCube' = invertFace $ getFrontLeftLineAsBackFace $ largeCube 315 360
smallCube' = invertFace $ extractFrontFace $ (smallCube 315 360)
in triangles S.>< (S.fromList(FacesBottomFrontTop +++^ (largeCube' +++ smallCube')))
)
-- show the rest of the large triangle
>>> arr (\triangles -> (S.fromList(FacesBottomFrontTop +++^ (largeCube 45 90))) S.>< triangles)
>>> arr (\triangles ->
(S.fromList
( [largeShapeWithDegrees]
L.||@~+++^||
[[FacesWithRange FacesBottomFrontTop (DegreeRange 90 315)]]
)
)
S.>< triangles
)
>>> arr (\triangles ->
let largeCube' = largeCube 315 360
in triangles S.>< (S.fromList (FacesBottomFrontTop +++^ largeCube'))
)
--print stl
>>> Kleisli (\triangles -> writeStlToFile $ newStlShape "hole in the wall" (F.toList triangles))
runKleisli f (S.fromList [])
buildHoleInSingleTriangleTest = do
let largeRightFaceTest = TestCase $ assertEqual
"largeRightFaceTest"
(RightFace {b3 = Point {x_axis = 0.0, y_axis = 0.0, z_axis = 10.0}, b4 = Point {x_axis = 0.0, y_axis = 0.0, z_axis = 0.0},
f3 = Point {x_axis = 14.14213562373095, y_axis = -14.142135623730951, z_axis = 10.0},
f4 = Point {x_axis = 14.14213562373095, y_axis = -14.142135623730951, z_axis = 0.0}})
(extractRightFace $ maybeMapResult $ largeShapeMap^.at (DegreeRange 45 90)
)
runTestTT largeRightFaceTest
let largeRightFaceAsBackFaceTest = TestCase $ assertEqual
"largeRightFaceAsBackFaceTest"
(BackFace {b1 = Point {x_axis = 14.14213562373095, y_axis = -14.142135623730951, z_axis = 0.0},
b2 = Point {x_axis = 14.14213562373095, y_axis = -14.142135623730951, z_axis = 10.0},
b3 = Point {x_axis = 0.0, y_axis = 0.0, z_axis = 10.0},
b4 = Point {x_axis = 0.0, y_axis = 0.0, z_axis = 0.0}})
(let largeTriangle = maybeMapResult $ largeShapeMap^.at (DegreeRange 45 90)
in getRightFaceAsBackFace $ largeTriangle
)
runTestTT largeRightFaceAsBackFaceTest
let smallCubeFrontFaceTest = TestCase $ assertEqual
"smallCubeFrontFaceTest"
(FrontFace {f1 = Point {x_axis = 5.0, y_axis = -8.0, z_axis = 0.0},
f2 = Point {x_axis = 5.0, y_axis = -8.0, z_axis = 10.0},
f3 = Point {x_axis = 6.414213562373095, y_axis = -8.585786437626904, z_axis = 10.0},
f4 = Point {x_axis = 6.414213562373095, y_axis = -8.585786437626904, z_axis = 0.0}})
(extractFrontFace $ maybeMapResult $ smallShapeMap^.at (DegreeRange 135 180))
runTestTT smallCubeFrontFaceTest
let smallCubeFrontFaceInvertedTest = TestCase $ assertEqual
"smallCubeFrontFaceInvertedTest"
(FrontFace {f1 = Point {x_axis = 6.414213562373095, y_axis = -8.585786437626904, z_axis = 0.0},
f2 = Point {x_axis = 6.414213562373095, y_axis = -8.585786437626904, z_axis = 10.0},
f3 = Point {x_axis = 5.0, y_axis = -8.0, z_axis = 10.0},
f4 = Point {x_axis = 5.0, y_axis = -8.0, z_axis = 0.0}})
(invertFace $ extractFrontFace $ maybeMapResult $ smallShapeMap^.at (DegreeRange 135 180))
runTestTT smallCubeFrontFaceInvertedTest
let addTheFacesTest = TestCase $ assertEqual
"addTheFacesTest"
(CubePoints {f1 = Point {x_axis = 6.414213562373095, y_axis = -8.585786437626904, z_axis = 0.0},
f2 = Point {x_axis = 6.414213562373095, y_axis = -8.585786437626904, z_axis = 10.0},
f3 = Point {x_axis = 5.0, y_axis = -8.0, z_axis = 10.0},
f4 = Point {x_axis = 5.0, y_axis = -8.0, z_axis = 0.0},
b1 = Point {x_axis = 14.14213562373095, y_axis = -14.142135623730951, z_axis = 0.0},
b2 = Point {x_axis = 14.14213562373095, y_axis = -14.142135623730951, z_axis = 10.0},
b3 = Point {x_axis = 0.0, y_axis = 0.0, z_axis = 10.0},
b4 = Point {x_axis = 0.0, y_axis = 0.0, z_axis = 0.0}})
(let
invertedFrontFace = invertFace $ extractFrontFace $ maybeMapResult $ smallShapeMap^.at (DegreeRange 135 180)
largeTriangle = maybeMapResult $ largeShapeMap^.at (DegreeRange 45 90)
rightFaceAsBackFace = getRightFaceAsBackFace $ largeTriangle
in rightFaceAsBackFace +++ invertedFrontFace
)
runTestTT addTheFacesTest
writeNFGCubeFromTest = do
writeStlToFile $ newStlShape "hole in the wall"
(FaceBottom +++^
(CubePoints {f1 = Point {x_axis = 6.414213562373095, y_axis = -8.585786437626904, z_axis = 0.0},
f2 = Point {x_axis = 6.414213562373095, y_axis = -8.585786437626904, z_axis = 10.0},
f3 = Point {x_axis = 5.0, y_axis = -8.0, z_axis = 10.0},
f4 = Point {x_axis = 5.0, y_axis = -8.0, z_axis = 0.0},
b1 = Point {x_axis = 14.14213562373095, y_axis = -14.142135623730951, z_axis = 0.0},
b2 = Point {x_axis = 14.14213562373095, y_axis = -14.142135623730951, z_axis = 10.0},
b3 = Point {x_axis = 0.0, y_axis = 0.0, z_axis = 10.0},
b4 = Point {x_axis = 0.0, y_axis = 0.0, z_axis = 0.0}})
)
| heathweiss/Tricad | src/Examples/Diffs/FirstDiff.hs | gpl-2.0 | 16,452 | 0 | 32 | 4,662 | 3,751 | 2,096 | 1,655 | 214 | 1 |
module Language.Mulang.Analyzer.TestsAnalyzer (
analyseTests) where
import Language.Mulang
import Language.Mulang.Analyzer.Analysis (TestAnalysisType(..))
import Language.Mulang.Analyzer.FragmentParser (parseFragment')
import Language.Mulang.Builder (merge)
import Language.Mulang.Interpreter.Runner (runTests, TestResult(..))
import Language.Mulang.Transform.Normalizer (NormalizationOptions)
import Data.Maybe (fromMaybe)
analyseTests :: Expression -> Maybe TestAnalysisType -> Maybe NormalizationOptions -> IO [TestResult]
analyseTests e analysis options = analyseTests' e (fromMaybe NoTests analysis) options
analyseTests' _ NoTests _ = return []
analyseTests' e (EmbeddedTests _) _ = runTests e e
analyseTests' e (ExternalTests test extra _) options = runTests (merge e extraFragment) testFragment
where
testFragment = parse test
extraFragment = fromMaybe None . fmap parse $ extra
parse = parseFragment' options
| mumuki/mulang | src/Language/Mulang/Analyzer/TestsAnalyzer.hs | gpl-3.0 | 991 | 0 | 9 | 169 | 266 | 146 | 120 | 17 | 1 |
module Dsgen.SetSelect
(
-- * Types
Emphasis(..),
Filter,
ComplexityFilterOption(..),
Rule,
ReactionRuleOption(..),
TrasherRuleOption(..),
Addition,
ColPlatAdditionOption(..),
SheltersAdditionOption(..),
SetSelectOptions(..),
SetSelectResult(..),
SetSelectError,
-- * Filters
actionFilter,
complexityFilter,
-- * Rules
costVarietyRule,
interactivityRule,
reactionRule,
trasherRule,
mkEmphasisRule,
-- * Additions
colPlatAddition,
sheltersAddition,
-- * Set selection functions
selectSet
) where
import Dsgen.SetSelect.Internals
| pshendry/dsgen | src/Dsgen/SetSelect.hs | gpl-3.0 | 650 | 0 | 5 | 168 | 117 | 82 | 35 | 25 | 0 |
{-# LANGUAGE DeriveDataTypeable #-}
module InnerEar.Exercises.ThresholdOfSilence (thresholdOfSilenceExercise) where
import Reflex
import Reflex.Dom
import Data.Map
import Text.JSON
import Text.JSON.Generic
import Sound.MusicW
import InnerEar.Exercises.MultipleChoice
import InnerEar.Types.ExerciseId
import InnerEar.Types.Exercise
import InnerEar.Types.Score
import InnerEar.Types.MultipleChoiceStore
import InnerEar.Types.Data hiding (Time)
import InnerEar.Types.Sound
import InnerEar.Widgets.Config
import InnerEar.Widgets.SpecEval
import InnerEar.Widgets.AnswerButton
import InnerEar.Widgets.Utility
type Config = Int -- gain value for attenuated sounds
configs :: [Config]
configs = [-20,-30,-40,-50,-60,-70,-80,-90,-100,-110]
configMap::Map Int (String, Config)
configMap = fromList $ zip [(0::Int),1..]$ fmap (\x-> (show x ++ " dB",x)) configs
data Answer = Answer Bool deriving (Eq,Ord,Data,Typeable)
answers :: [Answer]
answers = [Answer True,Answer False]
instance Show Answer where
show (Answer True) = "Attenuated Sound"
show (Answer False) = "No sound at all"
instance Buttonable Answer where
makeButton = showAnswerButton
renderAnswer :: Map String AudioBuffer -> Config -> (SourceNodeSpec, Maybe Time) -> Maybe Answer -> Synth ()
renderAnswer _ db (src, dur) (Just (Answer True)) = buildSynth $ do
let env = maybe (return EmptyGraph) (unitRectEnv (Millis 1)) dur
synthSource src >> gain (Db $ fromIntegral db) >> env >> destination
maybeDelete (fmap (+ Sec 0.2) dur)
renderAnswer _ db _ (Just (Answer False)) = buildSynth_ $ silent >> destination
renderAnswer _ db (src, dur) Nothing = buildSynth $ do
let env = maybe (return EmptyGraph) (unitRectEnv (Millis 1)) dur
synthSource src >> gain (Db $ fromIntegral db) >> env >> destination
maybeDelete (fmap (+ Sec 0.2) dur)
instructionsText = "In this exercise, the system either makes no sound at all \
\or it plays a sound that has been reduced in level by some specific amount \
\of attenuation. As you make the level lower and lower (ie. lower and lower values \
\for attenuation), it should become more difficult to tell when the system is playing \
\a sound versus when it is playing nothing."
data MyTabs = Instructions | Other deriving (Eq,Show)
instructions :: MonadWidget t m => m ()
instructions = elClass "div" "instructionsText" $ text instructionsText
{- instructions = elClass "div" "instructionsText" $ do
tab <- simpleTabBar [Instructions,Other] Instructions
tabAVisible <- mapDyn (== Instructions) tab
visibleWhen tabAVisible $ text "This would be the text of the instructions."
tabBVisible <- mapDyn (== Other) tab
visibleWhen tabBVisible $ text "Now we are displaying some other text instead!"
-}
displayEval :: MonadWidget t m => Dynamic t (Map Answer Score) -> Dynamic t (MultipleChoiceStore Config Answer) -> m ()
displayEval e _ = displayMultipleChoiceEvaluationGraph ("scoreBarWrapper","svgBarContainer","svgFaintedLine", "xLabel") "Session Performance" "" answers e
generateQ :: Config -> [ExerciseDatum] -> IO ([Answer],Answer)
generateQ _ _ = randomMultipleChoiceQuestion answers
sourcesMap :: Map Int (String, SoundSourceConfigOption)
sourcesMap = fromList $ [
(0, ("Pink noise", Resource "pinknoise.wav" (Just $ Sec 2))),
(1, ("White noise", Resource "whitenoise.wav" (Just $ Sec 2))),
(2, ("Load a sound file", UserProvidedResource))
]
xpFunction :: XpFunction Config Answer -- MultipleChoiceStore c a -> (Int, Int)
xpFunction m = (ceiling normalizedScore,100)
where
m' = scores m
rawScore = sum $ fmap (uncurry (scoreForConfig m')) $ zip configs [100,200,300,400,500,600,700,800,900,1000]
clippedScore = min rawScore 4320
normalizedScore = clippedScore / 4320 * 100
thresholdOfSilenceExercise :: MonadWidget t m => Exercise t m Int [Answer] Answer (Map Answer Score) (MultipleChoiceStore Config Answer)
thresholdOfSilenceExercise = multipleChoiceExercise
1
answers
instructions
(configWidget "thresholdOfSilenceExercise" sourcesMap 0 "Attenuation: " configMap) -- (dynRadioConfigWidget "fiveBandBoostCutExercise" sourcesMap 0 configMap)
renderAnswer
ThresholdOfSilence
(-20)
(\_ _ -> return ())
generateQ
xpFunction
| d0kt0r0/InnerEar | src/InnerEar/Exercises/ThresholdOfSilence.hs | gpl-3.0 | 4,227 | 0 | 15 | 662 | 1,188 | 641 | 547 | 73 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Main (main) where
import GI.Gtk
(widgetShowAll, onWidgetDestroy, setContainerChild, setWindowTitle,
windowNew, mainQuit, menuItemNewWithLabel, menuItemNewWithMnemonic,
onMenuItemActivate, menuShellAppend, menuItemSetSubmenu, menuNew,
menuBarNew)
import qualified GI.Gtk as Gtk (main, init)
import GI.Gtk.Enums (WindowType(..))
import qualified Data.Text as T (unpack)
{-
widgets that go into making a menubar and submenus:
* menu item (what the user wants to select)
* menu (acts as a container for the menu items)
* menubar (container for each of the individual menus)
menuitem widgets are used for two different things:
* they are packed into the menu
* they are packed into the menubar, which, when selected, activates the menu
Functions:
* menuBarNew
creates a new menubar, which can be packed into a container like a
window or a box
* menuNew
creates a new menu, which is never actually shown; it is just a
container for the menu items
* menuItemNew, menuItemNewWithLabel, menuItemMenuWithMnemonic
create the menu items that are to be displayed; they are actually
buttons with associated actions
Once a menu item has been created, it should be put into a menu with
the menuShellAppend function.
In order to capture when the item is selected by the user, the
activate signal need to be connected in the usual way.
-}
createMenuBar descr
= do bar <- menuBarNew
mapM_ (createMenu bar) descr
return bar
where
createMenu bar (name,items)
= do menu <- menuNew
item <- menuItemNewWithLabelOrMnemonic name
menuItemSetSubmenu item (Just menu)
menuShellAppend bar item
mapM_ (createMenuItem menu) items
createMenuItem menu (name,action)
= do item <- menuItemNewWithLabelOrMnemonic name
menuShellAppend menu item
case action of
Just act -> onMenuItemActivate item act
Nothing -> onMenuItemActivate item (return ())
menuItemNewWithLabelOrMnemonic name
| '_' `elem` T.unpack name = menuItemNewWithMnemonic name
| otherwise = menuItemNewWithLabel name
menuBarDescr
= [ ("_File", [ ("Open", Nothing)
, ("Save", Nothing)
, ("_Quit", Just mainQuit)
]
)
, ("Help", [ ("_Help", Nothing)
]
)
]
main =
do Gtk.init Nothing
window <- windowNew WindowTypeToplevel
menuBar <- createMenuBar menuBarDescr
setWindowTitle window "Demo"
setContainerChild window menuBar
onWidgetDestroy window mainQuit
widgetShowAll window
Gtk.main
| haskell-gi/gi-gtk-examples | menu/MenuDemo.hs | lgpl-2.1 | 2,828 | 0 | 15 | 814 | 451 | 234 | 217 | 43 | 2 |
{-# LANGUAGE OverloadedStrings #-}
import Test.HUnit (runTestTT)
import TestComboLoads (testComboLoads)
import TestDistLoads (testDistLoads)
import TestPointLoads (testPointLoads)
import TestNodes (testNodes)
import TestLoads (testLoads)
main = do
runTestTT testNodes
runTestTT testLoads
runTestTT testDistLoads
runTestTT testPointLoads
runTestTT testComboLoads
| baalbek/stearnswharf | t/testStearnsWharf.hs | lgpl-3.0 | 384 | 0 | 7 | 57 | 87 | 45 | 42 | 13 | 1 |
import LLVM.General.AST hiding (type')
import LLVM.General.AST.Global
import qualified LLVM.General.AST as AST
import qualified LLVM.General.AST.Type as T
import qualified LLVM.General.AST.Linkage as L
import qualified LLVM.General.AST.Constant as C
import qualified LLVM.General.AST.CallingConvention as CC
import LLVM.General.Module (withModuleFromAST, moduleLLVMAssembly)
import LLVM.General.Context (withContext)
import Data.Char (ord)
import Control.Monad.Except (runExceptT)
constStr :: String -> C.Constant
constStr = C.Array T.i8 . map (C.Int 8 . fromIntegral . ord)
global :: T.Type -> String -> C.Constant
global tp nm = C.GlobalReference tp $ Name nm
prog :: AST.Module
prog = defaultModule { moduleName = "main", moduleDefinitions = [str, puts, main'] }
where str = GlobalDefinition $ globalVariableDefaults {
name = Name "str"
, linkage = L.Internal
, isConstant = True
, type' = ArrayType 13 T.i8
, initializer = Just $ constStr "Hello world!\0"
}
puts = GlobalDefinition $ functionDefaults {
name = Name "puts"
, parameters = ([Parameter (T.ptr T.i8) (UnName 0) []] , False)
, returnType = T.i32
}
main' = GlobalDefinition $ functionDefaults {
name = Name "main"
, returnType = T.i32
, basicBlocks =
[BasicBlock
(UnName 0)
[Do $ Call False CC.C []
(Right . ConstantOperand $ global T.i32 "puts")
[( ConstantOperand
(C.GetElementPtr True
(global (T.ptr (ArrayType 13 T.i8)) "str")
[C.Int 32 0, C.Int 32 0])
, [])]
[] []]
(Do $ Ret (Just .ConstantOperand $ C.Int 32 0) [])]
}
main :: IO ()
main = withContext $ \ctx -> do
runExceptT $ withModuleFromAST ctx prog $ \m -> do
llstr <- moduleLLVMAssembly m
putStrLn llstr
return ()
| scturtle/fun.hs | helloworld.hs | unlicense | 2,249 | 1 | 26 | 853 | 637 | 355 | 282 | 48 | 1 |
module Topical.VSpace.IO where
| erochest/topical | src/Topical/VSpace/IO.hs | apache-2.0 | 31 | 0 | 3 | 3 | 7 | 5 | 2 | 1 | 0 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TupleSections #-}
-- Copyright 2014 (c) Diego Souza <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
module Leela.Storage.Passwd
( Passwd ()
, can_
, can
, zero
, parse
, parseFile
, readSecret
) where
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.Text as T
import System.IO
import Data.Aeson
import Data.Maybe
import qualified Data.Vector as V
import Control.Monad
import qualified Data.ByteString as B
import Leela.Data.Types
import Data.Text.Encoding
import Control.Applicative
import qualified Data.HashMap.Strict as H
import qualified Data.ByteString.Lazy as L
import Leela.Data.Signature
import qualified Data.ByteString.Base16 as B16
import Data.ByteString.Builder
data Acl = RGraph
| WGraph
| RAttrs
| WAttrs
deriving (Ord, Eq, Show)
data UserInfo = UserInfo { secret :: Secret
, acl :: M.Map L.ByteString (S.Set Acl)
}
deriving (Eq, Show)
data Passwd = Passwd (M.Map User UserInfo)
deriving (Eq, Show)
zero :: Passwd
zero = Passwd M.empty
can_ :: User -> Tree -> Acl -> UserInfo -> Bool
can_ (User u) (Tree t) perm info = let userOnly = S.member perm <$> M.lookup u (acl info)
userTree = S.member perm <$> M.lookup (L.intercalate "::" [u, t]) (acl info)
in fromMaybe (fromMaybe False userOnly) userTree
can :: Passwd -> User -> User -> Tree -> Acl -> Bool
can (Passwd db) caller user tree perm = fromMaybe False (can_ user tree perm <$> (M.lookup caller db))
readSecret :: Passwd -> User -> Maybe Secret
readSecret (Passwd db) user = secret <$> M.lookup user db
parse :: B.ByteString -> Maybe Passwd
parse = decodeStrict
parseFile :: FilePath -> IO (Maybe Passwd)
parseFile fh = withFile fh ReadMode
(fmap parse . flip B.hGetSome (1024 * 1024))
parsePerms :: String -> [Acl]
parsePerms = go [('r', RGraph), ('w', WGraph), ('r', RAttrs), ('w', WAttrs)]
where
go [] _ = []
go _ [] = []
go ((flag,perm):perms) (bit:bits)
| bit == flag = perm : go perms bits
| otherwise = go perms bits
parseAcl :: (T.Text, T.Text) -> (L.ByteString, S.Set Acl)
parseAcl (what, perms) = (toLazyByteString $ encodeUtf8Builder what, S.fromList $ parsePerms $ T.unpack perms)
parseSecret :: B.ByteString -> Secret
parseSecret = initSecret . fst . B16.decode
instance FromJSON UserInfo where
parseJSON (Array v) = UserInfo <$> ((parseSecret . encodeUtf8) <$> jsonSecret) <*> ((M.fromList . map parseAcl) <$> jsonAcls)
where
jsonSecret
| V.length v == 2 = parseJSON $ v V.! 0
| otherwise = mzero
jsonAcls
| V.length v == 2 = parseJSON $ v V.! 1
| otherwise = mzero
parseJSON _ = mzero
instance FromJSON Passwd where
parseJSON (Object o) = (Passwd . M.fromList) <$> mapM parseEntry (H.toList o)
where
parseEntry (k0, v0) = (User $ toLazyByteString $ encodeUtf8Builder k0,) <$> parseJSON v0
parseJSON _ = mzero
| locaweb/leela | src/warpdrive/src/Leela/Storage/Passwd.hs | apache-2.0 | 3,825 | 0 | 13 | 1,055 | 1,114 | 609 | 505 | 79 | 3 |
module Data where
-- A data type of expression forms
data Exp = Lit Int | Add Exp Exp
| egaburov/funstuff | Haskell/tytag/xproblem_src/samples/expressions/Haskell/ClosedDatatype/Data.hs | apache-2.0 | 88 | 0 | 6 | 21 | 21 | 13 | 8 | 2 | 0 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QFtp.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:31
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Network.QFtp (
QqFtp(..)
,clearPendingCommands
,currentCommand
,currentDevice
,hasPendingCommands
,Qlist(..)
,Qlogin(..)
,Qput(..)
,rawCommand
,setTransferMode
,qFtp_delete
,qFtp_deleteLater
)
where
import Foreign.C.Types
import Qth.ClassTypes.Core
import Qtc.Enums.Base
import Qtc.Enums.Network.QFtp
import Qtc.Classes.Base
import Qtc.Classes.Qccs
import Qtc.Classes.Core
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Network
import Qtc.ClassTypes.Network
instance QuserMethod (QFtp ()) (()) (IO ()) where
userMethod qobj evid ()
= withObjectPtr qobj $ \cobj_qobj ->
qtc_QFtp_userMethod cobj_qobj (toCInt evid)
foreign import ccall "qtc_QFtp_userMethod" qtc_QFtp_userMethod :: Ptr (TQFtp a) -> CInt -> IO ()
instance QuserMethod (QFtpSc a) (()) (IO ()) where
userMethod qobj evid ()
= withObjectPtr qobj $ \cobj_qobj ->
qtc_QFtp_userMethod cobj_qobj (toCInt evid)
instance QuserMethod (QFtp ()) (QVariant ()) (IO (QVariant ())) where
userMethod qobj evid qvoj
= withObjectRefResult $
withObjectPtr qobj $ \cobj_qobj ->
withObjectPtr qvoj $ \cobj_qvoj ->
qtc_QFtp_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj
foreign import ccall "qtc_QFtp_userMethodVariant" qtc_QFtp_userMethodVariant :: Ptr (TQFtp a) -> CInt -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
instance QuserMethod (QFtpSc a) (QVariant ()) (IO (QVariant ())) where
userMethod qobj evid qvoj
= withObjectRefResult $
withObjectPtr qobj $ \cobj_qobj ->
withObjectPtr qvoj $ \cobj_qvoj ->
qtc_QFtp_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj
class QqFtp x1 where
qFtp :: x1 -> IO (QFtp ())
instance QqFtp (()) where
qFtp ()
= withQFtpResult $
qtc_QFtp
foreign import ccall "qtc_QFtp" qtc_QFtp :: IO (Ptr (TQFtp ()))
instance QqFtp ((QObject t1)) where
qFtp (x1)
= withQFtpResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QFtp1 cobj_x1
foreign import ccall "qtc_QFtp1" qtc_QFtp1 :: Ptr (TQObject t1) -> IO (Ptr (TQFtp ()))
instance Qabort (QFtp a) (()) (IO ()) where
abort x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QFtp_abort cobj_x0
foreign import ccall "qtc_QFtp_abort" qtc_QFtp_abort :: Ptr (TQFtp a) -> IO ()
instance QbytesAvailable (QFtp a) (()) where
bytesAvailable x0 ()
= withLongLongResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QFtp_bytesAvailable cobj_x0
foreign import ccall "qtc_QFtp_bytesAvailable" qtc_QFtp_bytesAvailable :: Ptr (TQFtp a) -> IO CLLong
instance Qcd (QFtp a) ((String)) (IO (Int)) where
cd x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QFtp_cd cobj_x0 cstr_x1
foreign import ccall "qtc_QFtp_cd" qtc_QFtp_cd :: Ptr (TQFtp a) -> CWString -> IO CInt
clearPendingCommands :: QFtp a -> (()) -> IO ()
clearPendingCommands x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QFtp_clearPendingCommands cobj_x0
foreign import ccall "qtc_QFtp_clearPendingCommands" qtc_QFtp_clearPendingCommands :: Ptr (TQFtp a) -> IO ()
instance Qclose (QFtp a) (()) (IO (Int)) where
close x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QFtp_close cobj_x0
foreign import ccall "qtc_QFtp_close" qtc_QFtp_close :: Ptr (TQFtp a) -> IO CInt
instance QconnectToHost (QFtp a) ((String)) (IO (Int)) where
connectToHost x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QFtp_connectToHost cobj_x0 cstr_x1
foreign import ccall "qtc_QFtp_connectToHost" qtc_QFtp_connectToHost :: Ptr (TQFtp a) -> CWString -> IO CInt
instance QconnectToHost (QFtp a) ((String, Int)) (IO (Int)) where
connectToHost x0 (x1, x2)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QFtp_connectToHost1 cobj_x0 cstr_x1 (toCUShort x2)
foreign import ccall "qtc_QFtp_connectToHost1" qtc_QFtp_connectToHost1 :: Ptr (TQFtp a) -> CWString -> CUShort -> IO CInt
currentCommand :: QFtp a -> (()) -> IO (Command)
currentCommand x0 ()
= withQEnumResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QFtp_currentCommand cobj_x0
foreign import ccall "qtc_QFtp_currentCommand" qtc_QFtp_currentCommand :: Ptr (TQFtp a) -> IO CLong
currentDevice :: QFtp a -> (()) -> IO (QIODevice ())
currentDevice x0 ()
= withQIODeviceResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QFtp_currentDevice cobj_x0
foreign import ccall "qtc_QFtp_currentDevice" qtc_QFtp_currentDevice :: Ptr (TQFtp a) -> IO (Ptr (TQIODevice ()))
instance QcurrentId (QFtp a) (()) where
currentId x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QFtp_currentId cobj_x0
foreign import ccall "qtc_QFtp_currentId" qtc_QFtp_currentId :: Ptr (TQFtp a) -> IO CInt
instance Qqerror (QFtp a) (()) (IO (QFtpError)) where
qerror x0 ()
= withQEnumResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QFtp_error cobj_x0
foreign import ccall "qtc_QFtp_error" qtc_QFtp_error :: Ptr (TQFtp a) -> IO CLong
instance QerrorString (QFtp a) (()) where
errorString x0 ()
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QFtp_errorString cobj_x0
foreign import ccall "qtc_QFtp_errorString" qtc_QFtp_errorString :: Ptr (TQFtp a) -> IO (Ptr (TQString ()))
instance Qqget (QFtp a) ((String)) where
qget x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QFtp_get cobj_x0 cstr_x1
foreign import ccall "qtc_QFtp_get" qtc_QFtp_get :: Ptr (TQFtp a) -> CWString -> IO CInt
instance Qqget (QFtp a) ((String, QIODevice t2)) where
qget x0 (x1, x2)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QFtp_get1 cobj_x0 cstr_x1 cobj_x2
foreign import ccall "qtc_QFtp_get1" qtc_QFtp_get1 :: Ptr (TQFtp a) -> CWString -> Ptr (TQIODevice t2) -> IO CInt
instance Qqget (QFtp a) ((String, QIODevice t2, TransferType)) where
qget x0 (x1, x2, x3)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QFtp_get2 cobj_x0 cstr_x1 cobj_x2 (toCLong $ qEnum_toInt x3)
foreign import ccall "qtc_QFtp_get2" qtc_QFtp_get2 :: Ptr (TQFtp a) -> CWString -> Ptr (TQIODevice t2) -> CLong -> IO CInt
hasPendingCommands :: QFtp a -> (()) -> IO (Bool)
hasPendingCommands x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QFtp_hasPendingCommands cobj_x0
foreign import ccall "qtc_QFtp_hasPendingCommands" qtc_QFtp_hasPendingCommands :: Ptr (TQFtp a) -> IO CBool
class Qlist x1 where
list :: QFtp a -> x1 -> IO (Int)
instance Qlist (()) where
list x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QFtp_list cobj_x0
foreign import ccall "qtc_QFtp_list" qtc_QFtp_list :: Ptr (TQFtp a) -> IO CInt
instance Qlist ((String)) where
list x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QFtp_list1 cobj_x0 cstr_x1
foreign import ccall "qtc_QFtp_list1" qtc_QFtp_list1 :: Ptr (TQFtp a) -> CWString -> IO CInt
class Qlogin x1 where
login :: QFtp a -> x1 -> IO (Int)
instance Qlogin (()) where
login x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QFtp_login cobj_x0
foreign import ccall "qtc_QFtp_login" qtc_QFtp_login :: Ptr (TQFtp a) -> IO CInt
instance Qlogin ((String)) where
login x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QFtp_login1 cobj_x0 cstr_x1
foreign import ccall "qtc_QFtp_login1" qtc_QFtp_login1 :: Ptr (TQFtp a) -> CWString -> IO CInt
instance Qlogin ((String, String)) where
login x0 (x1, x2)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
withCWString x2 $ \cstr_x2 ->
qtc_QFtp_login2 cobj_x0 cstr_x1 cstr_x2
foreign import ccall "qtc_QFtp_login2" qtc_QFtp_login2 :: Ptr (TQFtp a) -> CWString -> CWString -> IO CInt
instance Qmkdir (QFtp a) ((String)) (IO (Int)) where
mkdir x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QFtp_mkdir cobj_x0 cstr_x1
foreign import ccall "qtc_QFtp_mkdir" qtc_QFtp_mkdir :: Ptr (TQFtp a) -> CWString -> IO CInt
class Qput x1 where
put :: QFtp a -> x1 -> IO (Int)
instance Qput ((QIODevice t1, String)) where
put x0 (x1, x2)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withCWString x2 $ \cstr_x2 ->
qtc_QFtp_put1 cobj_x0 cobj_x1 cstr_x2
foreign import ccall "qtc_QFtp_put1" qtc_QFtp_put1 :: Ptr (TQFtp a) -> Ptr (TQIODevice t1) -> CWString -> IO CInt
instance Qput ((QIODevice t1, String, TransferType)) where
put x0 (x1, x2, x3)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withCWString x2 $ \cstr_x2 ->
qtc_QFtp_put2 cobj_x0 cobj_x1 cstr_x2 (toCLong $ qEnum_toInt x3)
foreign import ccall "qtc_QFtp_put2" qtc_QFtp_put2 :: Ptr (TQFtp a) -> Ptr (TQIODevice t1) -> CWString -> CLong -> IO CInt
instance Qput ((String, String)) where
put x0 (x1, x2)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
withCWString x2 $ \cstr_x2 ->
qtc_QFtp_put cobj_x0 cstr_x1 cstr_x2
foreign import ccall "qtc_QFtp_put" qtc_QFtp_put :: Ptr (TQFtp a) -> CWString -> CWString -> IO CInt
instance Qput ((String, String, TransferType)) where
put x0 (x1, x2, x3)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
withCWString x2 $ \cstr_x2 ->
qtc_QFtp_put3 cobj_x0 cstr_x1 cstr_x2 (toCLong $ qEnum_toInt x3)
foreign import ccall "qtc_QFtp_put3" qtc_QFtp_put3 :: Ptr (TQFtp a) -> CWString -> CWString -> CLong -> IO CInt
rawCommand :: QFtp a -> ((String)) -> IO (Int)
rawCommand x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QFtp_rawCommand cobj_x0 cstr_x1
foreign import ccall "qtc_QFtp_rawCommand" qtc_QFtp_rawCommand :: Ptr (TQFtp a) -> CWString -> IO CInt
instance QreadAll (QFtp a) (()) where
readAll x0 ()
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QFtp_readAll cobj_x0
foreign import ccall "qtc_QFtp_readAll" qtc_QFtp_readAll :: Ptr (TQFtp a) -> IO (Ptr (TQString ()))
instance Qremove (QFtp a) ((String)) (IO (Int)) where
remove x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QFtp_remove cobj_x0 cstr_x1
foreign import ccall "qtc_QFtp_remove" qtc_QFtp_remove :: Ptr (TQFtp a) -> CWString -> IO CInt
instance Qrename (QFtp a) ((String, String)) (IO (Int)) where
rename x0 (x1, x2)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
withCWString x2 $ \cstr_x2 ->
qtc_QFtp_rename cobj_x0 cstr_x1 cstr_x2
foreign import ccall "qtc_QFtp_rename" qtc_QFtp_rename :: Ptr (TQFtp a) -> CWString -> CWString -> IO CInt
instance Qrmdir (QFtp a) ((String)) (IO (Int)) where
rmdir x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QFtp_rmdir cobj_x0 cstr_x1
foreign import ccall "qtc_QFtp_rmdir" qtc_QFtp_rmdir :: Ptr (TQFtp a) -> CWString -> IO CInt
instance QsetProxy (QFtp a) ((String, Int)) (IO (Int)) where
setProxy x0 (x1, x2)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QFtp_setProxy cobj_x0 cstr_x1 (toCUShort x2)
foreign import ccall "qtc_QFtp_setProxy" qtc_QFtp_setProxy :: Ptr (TQFtp a) -> CWString -> CUShort -> IO CInt
setTransferMode :: QFtp a -> ((TransferMode)) -> IO (Int)
setTransferMode x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QFtp_setTransferMode cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QFtp_setTransferMode" qtc_QFtp_setTransferMode :: Ptr (TQFtp a) -> CLong -> IO CInt
instance Qstate (QFtp a) (()) (IO (QFtpState)) where
state x0 ()
= withQEnumResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QFtp_state cobj_x0
foreign import ccall "qtc_QFtp_state" qtc_QFtp_state :: Ptr (TQFtp a) -> IO CLong
qFtp_delete :: QFtp a -> IO ()
qFtp_delete x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QFtp_delete cobj_x0
foreign import ccall "qtc_QFtp_delete" qtc_QFtp_delete :: Ptr (TQFtp a) -> IO ()
qFtp_deleteLater :: QFtp a -> IO ()
qFtp_deleteLater x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QFtp_deleteLater cobj_x0
foreign import ccall "qtc_QFtp_deleteLater" qtc_QFtp_deleteLater :: Ptr (TQFtp a) -> IO ()
instance QchildEvent (QFtp ()) ((QChildEvent t1)) where
childEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QFtp_childEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QFtp_childEvent" qtc_QFtp_childEvent :: Ptr (TQFtp a) -> Ptr (TQChildEvent t1) -> IO ()
instance QchildEvent (QFtpSc a) ((QChildEvent t1)) where
childEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QFtp_childEvent cobj_x0 cobj_x1
instance QconnectNotify (QFtp ()) ((String)) where
connectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QFtp_connectNotify cobj_x0 cstr_x1
foreign import ccall "qtc_QFtp_connectNotify" qtc_QFtp_connectNotify :: Ptr (TQFtp a) -> CWString -> IO ()
instance QconnectNotify (QFtpSc a) ((String)) where
connectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QFtp_connectNotify cobj_x0 cstr_x1
instance QcustomEvent (QFtp ()) ((QEvent t1)) where
customEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QFtp_customEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QFtp_customEvent" qtc_QFtp_customEvent :: Ptr (TQFtp a) -> Ptr (TQEvent t1) -> IO ()
instance QcustomEvent (QFtpSc a) ((QEvent t1)) where
customEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QFtp_customEvent cobj_x0 cobj_x1
instance QdisconnectNotify (QFtp ()) ((String)) where
disconnectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QFtp_disconnectNotify cobj_x0 cstr_x1
foreign import ccall "qtc_QFtp_disconnectNotify" qtc_QFtp_disconnectNotify :: Ptr (TQFtp a) -> CWString -> IO ()
instance QdisconnectNotify (QFtpSc a) ((String)) where
disconnectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QFtp_disconnectNotify cobj_x0 cstr_x1
instance Qevent (QFtp ()) ((QEvent t1)) where
event x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QFtp_event_h cobj_x0 cobj_x1
foreign import ccall "qtc_QFtp_event_h" qtc_QFtp_event_h :: Ptr (TQFtp a) -> Ptr (TQEvent t1) -> IO CBool
instance Qevent (QFtpSc a) ((QEvent t1)) where
event x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QFtp_event_h cobj_x0 cobj_x1
instance QeventFilter (QFtp ()) ((QObject t1, QEvent t2)) where
eventFilter x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QFtp_eventFilter_h cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QFtp_eventFilter_h" qtc_QFtp_eventFilter_h :: Ptr (TQFtp a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool
instance QeventFilter (QFtpSc a) ((QObject t1, QEvent t2)) where
eventFilter x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QFtp_eventFilter_h cobj_x0 cobj_x1 cobj_x2
instance Qreceivers (QFtp ()) ((String)) where
receivers x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QFtp_receivers cobj_x0 cstr_x1
foreign import ccall "qtc_QFtp_receivers" qtc_QFtp_receivers :: Ptr (TQFtp a) -> CWString -> IO CInt
instance Qreceivers (QFtpSc a) ((String)) where
receivers x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QFtp_receivers cobj_x0 cstr_x1
instance Qsender (QFtp ()) (()) where
sender x0 ()
= withQObjectResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QFtp_sender cobj_x0
foreign import ccall "qtc_QFtp_sender" qtc_QFtp_sender :: Ptr (TQFtp a) -> IO (Ptr (TQObject ()))
instance Qsender (QFtpSc a) (()) where
sender x0 ()
= withQObjectResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QFtp_sender cobj_x0
instance QtimerEvent (QFtp ()) ((QTimerEvent t1)) where
timerEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QFtp_timerEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QFtp_timerEvent" qtc_QFtp_timerEvent :: Ptr (TQFtp a) -> Ptr (TQTimerEvent t1) -> IO ()
instance QtimerEvent (QFtpSc a) ((QTimerEvent t1)) where
timerEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QFtp_timerEvent cobj_x0 cobj_x1
| keera-studios/hsQt | Qtc/Network/QFtp.hs | bsd-2-clause | 17,395 | 0 | 15 | 3,288 | 6,169 | 3,148 | 3,021 | -1 | -1 |
{-# LANGUAGE BangPatterns #-}
module Main (main) where
import Data.Word
import qualified Data.ByteString.Char8 as C
import Data.Hashabler
-- neat; ghc fully evaluates this hash at compile time before core:
-- main = print $ siphash64 (SipKey 1 2) (1::Word64, 2::Word32, 3::Word16, 4::Word8)
main =
C.getLine >>= print . siphash64 (SipKey 1 2)
{-
main = print $ (hash32Times 1000000000) (9999::Word32)
hash32Times :: Hashable a=> Int -> a -> Word32
{-# INLINE hash32Times #-}
hash32Times iters =
\a-> let go !h !0 = h
go !h !n = go (h `hash` a) (n-1)
in fnv32 $ go fnvOffsetBasis32 iters
-}
| jberryman/hashabler | core.hs | bsd-3-clause | 633 | 0 | 8 | 142 | 58 | 36 | 22 | 7 | 1 |
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE FlexibleContexts #-}
-- ^
-- Facade that provides consistent access to persistence functionality
module Persistence.Facade
( dbDelete
, dbDeleteByQuery
, dbDeleteMulti
, dbGetExisting
, dbGetExistingMulti
, dbInsert
, dbInsertMulti
, dbModify
, dbModifyMulti
, dbPipe
, dbReplace
, dbReplaceMulti
, dbUpdateMulti
, esGetExisting
, esGetExistingMulti
, mergeFromMap
, mkIdIndexedMap
, mkRecordMap
, runAction
, runDb
, runEs
, runEsAndExtract
, toMulti
, toSingle
, validateDbIdMulti
, validateEsIdMulti
, validateMulti
, validateMulti'
) where
import Control.Monad.Except
import Control.Monad.Reader
import Control.Monad.Trans.Control
import Data.Aeson (encode)
import Data.Bifunctor
import Data.Bson (Label, Field)
import Data.Either
import qualified Data.Map.Strict as Map
import Data.Maybe
import qualified Data.Set as Set
import Data.Text (Text)
import Database.MongoDB (Pipe, Database, Failure)
import Database.V5.Bloodhound.Types (EsError, SearchResult)
import Network.HTTP.Types.Status
import Persistence.Common
import qualified Persistence.ElasticSearch as ES
import qualified Persistence.MongoDB as DB
import Types.Common
import Util.Constants
import Util.Error
dbInsert
:: (MonadIO m, MonadReader ApiConfig m, MonadBaseControl IO m)
=> RecordDefinition -> Record -> ExceptT ApiError m Record
dbInsert = toSingle . dbInsertMulti
dbReplace
:: (MonadIO m, MonadReader ApiConfig m, MonadBaseControl IO m)
=> RecordDefinition -> Record -> ExceptT ApiError m Record
dbReplace = toSingle . dbReplaceMulti
dbModify
:: (MonadIO m, MonadReader ApiConfig m, MonadBaseControl IO m)
=> RecordDefinition -> Record -> ExceptT ApiError m Record
dbModify = toSingle . dbModifyMulti
dbDelete
:: (MonadIO m, MonadReader ApiConfig m, MonadBaseControl IO m)
=> RecordDefinition -> RecordId -> ExceptT ApiError m Record
dbDelete = toSingle . dbDeleteMulti
dbDeleteByQuery
:: (MonadIO m, MonadReader ApiConfig m, MonadBaseControl IO m)
=> RecordDefinition -> [Field] -> ExceptT ApiError m ()
dbDeleteByQuery def query = runDb (DB.dbDeleteByQuery def query)
dbGetExisting
:: (MonadBaseControl IO m, MonadReader ApiConfig m, MonadIO m)
=> RecordDefinition -> RecordId -> ExceptT ApiError m Record
dbGetExisting = toSingle . dbGetExistingMulti
esGetExisting
:: (MonadBaseControl IO m, MonadReader ApiConfig m, MonadIO m)
=> RecordDefinition -> RecordId -> ExceptT ApiError m Record
esGetExisting = toSingle . esGetExistingMulti
dbReplaceMulti
:: (MonadIO m, MonadReader ApiConfig m, MonadBaseControl IO m)
=> RecordDefinition -> [Record] -> ApiResultsT m
dbReplaceMulti = dbUpdateMulti True
dbModifyMulti
:: (MonadIO m, MonadReader ApiConfig m, MonadBaseControl IO m)
=> RecordDefinition -> [Record] -> ApiResultsT m
dbModifyMulti = dbUpdateMulti False
-- ^
-- Insert multiple records
dbInsertMulti
:: (MonadIO m, MonadReader ApiConfig m, MonadBaseControl IO m)
=> RecordDefinition -> [Record] -> ApiResultsT m
dbInsertMulti _ [] = return []
dbInsertMulti def input = do
valid <- validateMulti def input
let records = populateDefaults def <$> valid
savedIds <- runDbMulti (dbAction DB.dbInsert def records)
saved <- runDbMulti (dbAction DB.dbGetById def savedIds)
return (fromJust <$> saved)
-- ^
-- Update multiple records
dbUpdateMulti
:: (MonadIO m, MonadReader ApiConfig m, MonadBaseControl IO m)
=> Bool -> RecordDefinition -> [Record] -> ApiResultsT m
dbUpdateMulti _ _ [] = return []
dbUpdateMulti replace def input = do
valid1 <- validateDbIdMulti input
existing <- dbGetExistingMulti def $ getIdValue' <$> valid1
let merged = mergeFromMap replace (mkIdIndexedMap valid1) <$> existing
valid2 <- validateMulti def merged
let records = populateDefaults def <$> valid2
savedIds <- runDbMulti (dbAction DB.dbUpdate def records)
saved <- runDbMulti (dbAction DB.dbGetById def savedIds)
return (fromJust <$> saved)
-- ^
-- Delete multiple records
dbDeleteMulti
:: (MonadIO m, MonadReader ApiConfig m, MonadBaseControl IO m)
=> RecordDefinition -> [RecordId] -> ApiItemsT [ApiError] m [Record]
dbDeleteMulti def ids = do
existing <- dbGetExistingMulti def ids
_ <- runDbMulti (dbAction DB.dbDeleteById def ids)
return existing
-- ^
-- Merge a new record from the given map with the specified existing record
mergeFromMap :: Bool -> Map.Map RecordId Record -> Record -> Record
mergeFromMap replace newMap existing = mergeRecords' replace existing new
where
get r = fromJust . Map.lookup (getIdValue' r)
new = get existing newMap
-- ^
-- Get multiple records by id
dbGetExistingMulti
:: (MonadIO m, MonadReader ApiConfig m, MonadBaseControl IO m)
=> RecordDefinition -> [RecordId] -> ApiResultsT m
dbGetExistingMulti def ids = do
records <- runDbMulti (dbAction DB.dbGetById def ids)
let tuples = zip records ids
let result (record, rid) = maybe (Left $ mk404IdErr def rid) Right record
eitherToItemsT (result <$> tuples)
-- ^
-- Get multiple records by id
esGetExistingMulti
:: (MonadIO m, MonadReader ApiConfig m, MonadBaseControl IO m)
=> RecordDefinition -> [RecordId] -> ApiResultsT m
esGetExistingMulti def ids = do
existing <- toMulti $ runEsAndExtract (ES.getByIds ids $ recordCollection def)
let idSet = Set.fromList ids
let result r =
if Set.member (getIdValue' r) idSet
then Right r
else Left (mk404IdErr def $ getIdValue' r)
eitherToItemsT (result <$> existing)
-- ^
-- Convert an action that could result in multiple errors
-- into one that could result in a single error
toSingle
:: (MonadIO m, MonadReader ApiConfig m, MonadBaseControl IO m)
=> ([a] -> ApiItemsT [e] m [b]) -> a -> ExceptT e m b
toSingle action input =
ExceptT $ do
records <- runApiItemsT $ action [input]
return $ head (itemsToEither records)
-- ^
-- Convert an action that could result in a single error
-- into one that could result in multiple errors
toMulti
:: (MonadBaseControl IO m, MonadReader ApiConfig m, MonadIO m)
=> ExceptT a (ApiItemsT [a] m) [t] -> ApiItemsT [a] m [t]
toMulti action = do
results <- runExceptT action
ApiItemsT . return $
either (flip ApiItems [] . (: [])) (ApiItems []) results
-- ^
-- Run a MongoDB action that could result in multiple errors
runDbMulti
:: (MonadIO m, MonadReader ApiConfig m, MonadBaseControl IO m)
=> (Database -> Pipe -> m [Either Failure a]) -> ApiItemsT [ApiError] m [a]
runDbMulti action = do
results <- runDb' action
let items = first DB.dbToApiError <$> results
ApiItemsT . return $ ApiItems (lefts items) (rights items)
-- ^
-- Run a MongoDB action that could result in a single error
runDb
:: (MonadIO m, MonadReader ApiConfig m, MonadBaseControl IO m)
=> (Database -> Pipe -> m (Either Failure a)) -> ExceptT ApiError m a
runDb action = do
results <- runDb' action
ExceptT (return $ first DB.dbToApiError results)
runDb'
:: (Monad m, MonadTrans t, MonadIO (t m), MonadReader ApiConfig (t m))
=> (Database -> Pipe -> m b) -> t m b
runDb' action = do
conf <- ask
pipe <- dbPipe conf
lift $ action (mongoDatabase conf) pipe
-- ^
-- Run an elastic-search action
runEs
:: (MonadIO m, MonadReader ApiConfig m, MonadBaseControl IO m)
=> (Text -> Text -> IO (Either EsError a)) -> ExceptT ApiError m a
runEs action = do
conf <- ask
results <- liftIO $ action (esServer conf) (esIndex conf)
ExceptT (return $ first ES.esToApiError results)
-- ^
-- Run a search action and extract the results
runEsAndExtract
:: (MonadIO m, MonadReader ApiConfig m, MonadBaseControl IO m)
=> (Text -> Text -> IO (Either EsError (SearchResult Record)))
-> ExceptT ApiError m [Record]
runEsAndExtract = fmap (ES.extractRecords []) . runEs
-- ^
-- Run multiple MongoDB actions and return all results
dbAction
:: (Monad m)
=> (RecordDefinition -> b -> Database -> Pipe -> m (Either Failure e))
-> RecordDefinition
-> [b]
-> Database
-> Pipe
-> m [Either Failure e]
dbAction singleAction def rs dbName pipe =
mapM (\r -> singleAction def r dbName pipe) rs
-- ^
-- Run an action over a list of inputs and return all
-- results and errors
runAction
:: Monad m
=> (a -> m (Either e b)) -> [a] -> ApiItemsT [e] m [b]
runAction f input = lift (mapM f input) >>= eitherToItemsT
-- ^
-- Validate multiple records against their definition
validateMulti
:: Monad m
=> RecordDefinition -> [Record] -> ApiItemsT [ApiError] m [Record]
validateMulti def = validateMulti' id (validateRecord def)
-- ^
-- Ensure that all records specified have a valid id
validateDbIdMulti
:: Monad m
=> [Record] -> ApiItemsT [ApiError] m [Record]
validateDbIdMulti = validateMulti' id DB.validateRecordHasId
-- ^
-- Ensure that all records specified have a valid id
validateEsIdMulti
:: Monad m
=> [Record] -> ApiItemsT [ApiError] m [Record]
validateEsIdMulti = validateMulti' id ES.validateRecordHasId
validateMulti'
:: (Monad m)
=> (a -> Record)
-> (a -> (a, ValidationResult))
-> [a]
-> ApiItemsT [ApiError] m [a]
validateMulti' f v records =
ApiItemsT . return . concatItems $ vResultToItems f . v <$> records
vResultToItems :: (a -> Record)
-> (a, ValidationResult)
-> ApiItems [ApiError] [a]
vResultToItems _ (a, ValidationErrors []) = ApiItems [] [a]
vResultToItems f (a, err) =
ApiItems [ApiError (Just $ f a) status400 (encode err)] []
-- ^
-- Create a MongoDB connection pipe
dbPipe
:: MonadIO m
=> ApiConfig -> m Pipe
dbPipe conf = liftIO $ DB.mkPipe (mongoServer conf)
-- ^
-- Make a make a map with the ids as keys and records as values
mkIdIndexedMap :: [Record] -> Map.Map RecordId Record
mkIdIndexedMap = mkRecordMap idLabel
-- ^
-- Merge an existing and an updated record according to the 'replace' flag
mergeRecords' :: Bool -> Record -> Record -> Record
mergeRecords' True = replaceRecords [createdAtLabel, idLabel]
mergeRecords' False = mergeRecords
-- ^
-- Make a make a map keyed by the specified field and having records as values
mkRecordMap :: Label -> [Record] -> Map.Map RecordId Record
mkRecordMap label xs = Map.fromList (addId <$> xs)
where
addId r = (getValue' label r, r)
| gabesoft/kapi | src/Persistence/Facade.hs | bsd-3-clause | 10,201 | 0 | 14 | 1,890 | 3,198 | 1,661 | 1,537 | 238 | 2 |
module Main where
import qualified Language.TransactSql.Parser as P
main :: IO ()
main = do
str <- readLn
print (P.run P.parseQuery "stdin" str)
| asztal/transact-sql | app/Main.hs | bsd-3-clause | 151 | 0 | 10 | 29 | 55 | 30 | 25 | 6 | 1 |
module Main where
import List (isPrefixOf)
import Text.XML.HaXml.XmlContent
import Text.XML.HaXml.Types
import Text.PrettyPrint.HughesPJ (render)
import Text.XML.HaXml.Pretty (document)
-- Test stuff
--value1 :: ([(Bool,Int)],(String,Maybe Char))
value1 = True
--main = do (putStrLn . render . document . toXml) value2
main = fWriteXml "/dev/tty" value1
| FranklinChen/hugs98-plus-Sep2006 | packages/HaXml/examples/SimpleTestBool.hs | bsd-3-clause | 371 | 0 | 5 | 59 | 67 | 44 | 23 | 8 | 1 |
module FPNLA.Operations.BLAS_M.Strategies.GEMM.Utils (
asTrans,
asNoTrans
) where
import FPNLA.Matrix_M (Matrix(dim_m, elem_m, generate_m))
import FPNLA.Operations.Parameters (Elt(..), TransType(..))
-- ConjTrans could be optimized
asTrans :: (Elt e, Matrix mon m e) => TransType (m e) -> mon (m e)
asTrans mt =
case mt of
NoTrans m -> apply m (\i j -> elem_m j i m)
Trans m -> return m
ConjTrans m -> apply m (\i j -> getConjugate <$> elem_m i j m)
where
apply m f =
do
(r, c) <- dim_m m
generate_m r c f
asNoTrans :: (Elt e, Matrix mon m e) => TransType (m e) -> mon (m e)
asNoTrans mt =
case mt of
NoTrans m -> return m
Trans m -> apply m (\i j -> elem_m j i m)
ConjTrans m -> apply m (\i j -> getConjugate <$> elem_m j i m)
where
apply m f =
do
(r, c) <- dim_m m
generate_m r c f
| mauroblanco/fpnla-examples | src/FPNLA/Operations/BLAS_M/Strategies/GEMM/Utils.hs | bsd-3-clause | 1,030 | 0 | 12 | 403 | 407 | 210 | 197 | 25 | 3 |
{-# LANGUAGE RecordWildCards #-}
module Internal.ARM (toolChain) where
import Internal.ToolChain
import System.FilePath
samDir :: FilePath
samDir = "c:/Users/marten/AppData/Local/Arduino15/packages/arduino/hardware/sam/1.6.11"
toolChain :: ToolConfig -> ToolChain
toolChain tc@ToolConfig{..} = ToolChain{..}
where name = "arm-none-eabi-gcc"
cc = ("arm-none-eabi-gcc", \_ -> ccFlags tc)
cpp = ("arm-none-eabi-g++", \_ -> ccFlags tc ++ cppFlags mcu)
asm = ("arm-none-eabi-gcc", \_ -> ccFlags tc ++ asmFlags mcu)
ld = ("arm-none-eabi-gcc", \objs -> ldFlags tc objs)
ar = ("arm-none-eabi-ar", \_ -> [])
objcopy = ("arm-none-eabi-objcopy", \_ -> copyFlags mcu)
objdump = ("arm-none-eabi-objdump", \_ -> [ "--disassemble-all" ])
size = ("arm-none-eabi-size", \_ -> [])
format = Binary
ccFlags ToolConfig{..} = mcuFlags mcu ++
[ "-mthumb"
, "-ffunction-sections"
, "-fdata-sections"
]
mcuFlags STM32F051 =
[ "-DSTM32F051"
, "-DSTM32F0"
, "-mcpu=cortex-m0"
]
mcuFlags STM32F072 =
[ "-DSTM32F072"
, "-DSTM32F0"
, "-mcpu=cortex-m0"
]
mcuFlags STM32F103 =
[ "-DSTM32F103"
, "-DSTM32F1"
, "-mcpu=cortex-m3"
]
mcuFlags STM32F411 =
[ "-DSTM32F411"
, "-DSTM32F4"
, "-mcpu=cortex-m4"
]
mcuFlags STM32F767 =
[ "-DSTM32F767"
, "-DSTM32F7"
, "-mcpu=cortex-m7"
]
mcuFlags STM32H743 =
[ "-DSTM32H743"
, "-DSTM32H7"
, "-mcpu=cortex-m7"
]
mcuFlags STM32G070 =
[ "-DSTM32G070"
, "-DSTM32G0"
, "-mcpu=cortex-m0plus" -- .small-multiply"
]
mcuFlags STM32G431 =
[ "-DSTM32G431"
, "-DSTM32G4"
, "-mcpu=cortex-m4"
, "-mfloat-abi=hard"
, "-mfpu=fpv4-sp-d16"
, "-fsingle-precision-constant"
]
mcuFlags SAM3X8E =
[ "-D__SAM3X8E__"
, "-mcpu=cortex-m3"
, "-I../ARM"
, "-I" ++ samDir ++ "/system/CMSIS/CMSIS/include"
, "-I" ++ samDir ++ "/system/CMSIS/Device/ATMEL"
, "-I" ++ samDir ++ "/system/CMSIS/Device/ATMEL/sam3xa/include"
, "-I" ++ samDir ++ "/system/libsam"
, "-I" ++ samDir ++ "/cores/arduino"
]
mcuFlags mcu =
[ "-nostdlib"
, "-mcpu=cortex-m4"
, "-mfloat-abi=hard"
, "-mfpu=fpv4-sp-d16"
, "-fsingle-precision-constant"
, "-D__" ++ show mcu ++ "__"
, "-DUSB_SERIAL"
, "-DLAYOUT_US_ENGLISH"
, "-DARDUINO=10600"
, "-DTEENSYDUINO=121"
, "-I../Teensy3"
]
cppFlags _ =
[ "-std=gnu++17"
, "-fno-threadsafe-statics"
, "-fno-exceptions"
, "-fno-rtti"
]
asmFlags _ =
[ "-xassembler-with-cpp"
]
ldFlags ToolConfig{..} objs = ldFlagsMCU mcu ++
[ "-mthumb"
, "-specs=nosys.specs" -- to get gcc _sbrk, etc to link
, "-Wl,--gc-sections"
, "-T" ++ link
, "-Wl,--check-sections"
, "-Wl,--entry=" ++ entry
, "-Wl,--unresolved-symbols=report-all"
, "-Wl,--warn-common"
, "-Wl,--warn-section-align"
, "-Wl,--start-group"
] ++ objs ++
[ "-Wl,--end-group"
, "-lm"
]
ldFlagsMCU STM32F051 = [ "-mcpu=cortex-m0" ]
ldFlagsMCU STM32F072 = [ "-mcpu=cortex-m0" ]
ldFlagsMCU STM32F103 = [ "-mcpu=cortex-m3" ]
ldFlagsMCU STM32F411 = [ "-mcpu=cortex-m4" ]
ldFlagsMCU STM32F767 = [ "-mcpu=cortex-m7" ]
ldFlagsMCU STM32H743 = [ "-mcpu=cortex-m7" ]
ldFlagsMCU STM32G070 = [ "-mcpu=cortex-m0plus" ]
ldFlagsMCU STM32G431 = [ "-mcpu=cortex-m4", "-mfloat-abi=hard", "-mfpu=fpv4-sp-d16", "-fsingle-precision-constant" ]
ldFlagsMCU SAM3X8E = [ "-mcpu=cortex-m3" ]
--ldFlags _ mcu@MK64FX512 objs = ("-T../Teensy3/" ++ mcuStr mcu ++ ".ld") : ldFlagsMK6 objs -- FIXME: need this file somewhere!
--ldFlags _ mcu@MK66FX1M0 objs = ("-T../Teensy3/" ++ mcuStr mcu ++ ".ld") : ldFlagsMK6 objs -- FIXME: need this file somewhere!
ldFlagsMK6 _ objs =
[ "-Wl,--gc-sections,--relax,--defsym=__rtc_localtime=1476636451"
, "-mthumb"
, "-mcpu=cortex-m4"
, "-mfloat-abi=hard"
, "-mfpu=fpv4-sp-d16"
, "-fsingle-precision-constant"
] ++ objs
copyFlags _ =
[
]
| marangisto/karakul | src/Internal/ARM.hs | bsd-3-clause | 4,046 | 0 | 10 | 926 | 800 | 462 | 338 | 118 | 1 |
{-# LANGUAGE GADTs #-}
module Network.LambNyaa.Item where
import Data.Hashable
import Control.Monad.Identity
-- | Vanity type for URLs.
type URL = String
-- | A data item. What, exactly, a data item represents depends on the source.
-- Eq and Ord instances are based on the item's itmIdentifier field for
-- performance reasons.
data Item = Item {
itmIdentifier :: Int, -- ^ A unique identifier for Items, used to
-- decide whether an Item has been previously
-- encountered. This value is a hash of the
-- itmName, itmURL, itmTags and
-- itmDescription fields.
itmName :: String, -- ^ The human readable name of the item.
itmURL :: URL, -- ^ The URL associated with an item.
itmSource :: String, -- ^ Name of the source that produced the item.
itmDescription :: Maybe String, -- ^ An optional plaintext description of
-- the item.
itmTags :: [String], -- ^ A list of tags that somehow apply to
-- the item. How this is filled is up to the
-- Source that produces it. For instance, the
-- NyaaTorrents source treats each phrase
-- inside square brackets within an item name
-- as a tag, to create tags for fansub group
-- names, resolution, checksum, etc.
itmSeenBefore :: Bool -- ^ Has this item been seen before? This field
-- is filled in automatically.
} deriving Show
instance Eq Item where
a == b = itmIdentifier a == itmIdentifier b
instance Ord Item where
compare a b = compare (itmIdentifier a) (itmIdentifier b)
a > b = itmIdentifier a > itmIdentifier b
a < b = itmIdentifier a < itmIdentifier b
a >= b = itmIdentifier a >= itmIdentifier b
a <= b = itmIdentifier a <= itmIdentifier b
data AnyItem where
AnyItem :: ItemLike a => a -> AnyItem
instance Hashable Item where
hashWithSalt salt item =
salt `hashWithSalt`
itmName item `hashWithSalt`
itmURL item `hashWithSalt`
itmTags item `hashWithSalt` itmDescription item
class ItemLike a where
-- | Convert an item-ish value to an actual Item.
toItem :: a -> Item
-- | Modify an item-ish value as if it were an actual item.
asItemM :: Monad m => (Item -> m Item) -> a -> m a
asItem :: ItemLike a => (Item -> Item) -> a -> a
asItem f = runIdentity . asItemM (return . f)
instance ItemLike Item where
toItem = id
asItemM f = f
instance ItemLike AnyItem where
toItem (AnyItem i) = toItem i
asItemM f (AnyItem i) = asItemM f i >>= return . AnyItem
| valderman/lambnyaa | Network/LambNyaa/Item.hs | bsd-3-clause | 2,886 | 0 | 11 | 1,005 | 507 | 273 | 234 | 41 | 1 |
{-|
Copyright : (c) Dave Laing, 2017
License : BSD3
Maintainer : [email protected]
Stability : experimental
Portability : non-portable
-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
module Ast.Type.Var (
HasTyVarSupply(..)
, ToTyVar(..)
, freshTyVar
) where
import Control.Monad.State (MonadState)
import Control.Lens (Lens', use, (%=))
import qualified Data.Text as T
class HasTyVarSupply s where
tyVarSupply :: Lens' s Int
instance HasTyVarSupply Int where
tyVarSupply = id
class ToTyVar a where
toTyVar :: Int -> a
instance ToTyVar String where
toTyVar x = 'x' : show x
instance ToTyVar T.Text where
toTyVar x = T.append "x" (T.pack . show $ x)
freshTyVar :: (MonadState s m, HasTyVarSupply s, ToTyVar a) => m a
freshTyVar = do
x <- use tyVarSupply
tyVarSupply %= succ
return $ toTyVar x
| dalaing/type-systems | src/Ast/Type/Var.hs | bsd-3-clause | 904 | 0 | 10 | 174 | 241 | 132 | 109 | 25 | 1 |
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.Raw.ARB.MatrixPalette
-- Copyright : (c) Sven Panne 2015
-- License : BSD3
--
-- Maintainer : Sven Panne <[email protected]>
-- Stability : stable
-- Portability : portable
--
-- The <https://www.opengl.org/registry/specs/ARB/matrix_palette.txt ARB_matrix_palette> extension.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.Raw.ARB.MatrixPalette (
-- * Enums
gl_CURRENT_MATRIX_INDEX_ARB,
gl_CURRENT_PALETTE_MATRIX_ARB,
gl_MATRIX_INDEX_ARRAY_ARB,
gl_MATRIX_INDEX_ARRAY_POINTER_ARB,
gl_MATRIX_INDEX_ARRAY_SIZE_ARB,
gl_MATRIX_INDEX_ARRAY_STRIDE_ARB,
gl_MATRIX_INDEX_ARRAY_TYPE_ARB,
gl_MATRIX_PALETTE_ARB,
gl_MAX_MATRIX_PALETTE_STACK_DEPTH_ARB,
gl_MAX_PALETTE_MATRICES_ARB,
-- * Functions
glCurrentPaletteMatrixARB,
glMatrixIndexPointerARB,
glMatrixIndexubvARB,
glMatrixIndexuivARB,
glMatrixIndexusvARB
) where
import Graphics.Rendering.OpenGL.Raw.Tokens
import Graphics.Rendering.OpenGL.Raw.Functions
| phaazon/OpenGLRaw | src/Graphics/Rendering/OpenGL/Raw/ARB/MatrixPalette.hs | bsd-3-clause | 1,149 | 0 | 4 | 127 | 88 | 66 | 22 | 18 | 0 |
{-# LANGUAGE FlexibleContexts #-}
module Scale.Tests
( tests
) where
import Test.HUnit
import Text.Parsec (parse)
import Turtle.Options.Scale (Scale(..), scale)
scaleTest :: Test
scaleTest = TestList $ map testCase cases
where
cases =
[ ("5", Percentage 5)
, ("10%", Percentage 0.1)
, ("480x320", Size (480, 320))
, ("x480", Height 480)
, ("x320", Height 320)
]
testCase (str, res) = TestCase $ case (parse scale "Test" str) of
Left err -> assertFailure $ show err
Right r -> assertEqual "Scale parsing" res r
tests :: Test
tests = TestList
[ scaleTest
] | elaye/turtle-options | test/Scale/Tests.hs | bsd-3-clause | 622 | 0 | 12 | 157 | 217 | 122 | 95 | 20 | 2 |
{-# LANGUAGE OverloadedStrings #-}
import qualified Control.Monad.Remote.JSON as Remote
import Control.Monad.Remote.JSON
import Data.Aeson
import Control.Monad (void)
import qualified VChanUtil as VChan
import VChanUtil
createSession :: LibXenVChan -> Session
createSession chan = defaultSession Strong (\v-> do
putStrLn $ "Sync: " ++ (show v)
VChan.send chan (encode v)
val <- receive chan
let res = decode val :: Maybe Value
putStrLn $ "Sync Got back: "++(show res)
case res of
Just x -> return x
Nothing -> return Null
)
(\v ->do
putStrLn $ "Async: " ++ (show v)
VChan.send chan (encode v)
_ <- receive chan ::IO String
return ()
)
prompt:: IO (Int)
prompt= loop
where loop = do putStrLn "Which Domain ID would you like to talk to?"
input <- getLine
case reads input of
[(id,_)] -> return id
_ -> do putStrLn "Error: Please Enter a Number."
loop
main = do id <- getDomId
putStrLn $ "ID: "++(show id)
other <- prompt
chan <- client_init other
let session = createSession chan
t<- Remote.send session $ do
notification "say" [String "Hello"]
notification "say" [String "Howdy"]
notification "say" [String "GoodDay"]
method "temperature" []
putStr "Temperature: "
print t
| roboguy13/remote-json | example/Strong/VChanClient.hs | bsd-3-clause | 2,181 | 0 | 14 | 1,197 | 463 | 221 | 242 | 42 | 2 |
module System.Build.Access.AnnotationOptions where
import System.Build.Data.KeyPValue
class AnnotationOptions r where
annotationOptions ::
Maybe KeyPValue
-> r
-> r
getAnnotationOptions ::
r
-> Maybe KeyPValue
| tonymorris/lastik | System/Build/Access/AnnotationOptions.hs | bsd-3-clause | 237 | 0 | 8 | 50 | 52 | 29 | 23 | 10 | 0 |
module GHCApi (
withGHC
, withGHCDummyFile
, initializeFlags
, initializeFlagsWithCradle
, setTargetFile
, getDynamicFlags
, checkSlowAndSet
) where
import CabalApi
import Control.Applicative
import Control.Exception
import Control.Monad
import CoreMonad
import Data.Maybe (isJust)
import DynFlags
import ErrMsg
import Exception
import GHC
import GHC.Paths (libdir)
import System.Exit
import System.IO
import Types
----------------------------------------------------------------
withGHCDummyFile :: Alternative m => Ghc (m a) -> IO (m a)
withGHCDummyFile = withGHC "Dummy"
withGHC :: Alternative m => FilePath -> Ghc (m a) -> IO (m a)
withGHC file body = ghandle ignore $ runGhc (Just libdir) $ do
dflags <- getSessionDynFlags
defaultCleanupHandler dflags body
where
ignore :: Alternative m => SomeException -> IO (m a)
ignore e = do
hPutStr stderr $ file ++ ":0:0:Error:"
hPrint stderr e
exitSuccess
----------------------------------------------------------------
importDirs :: [IncludeDir]
importDirs = [".","..","../..","../../..","../../../..","../../../../.."]
initializeFlagsWithCradle :: Options -> Cradle -> [GHCOption] -> Bool -> Ghc LogReader
initializeFlagsWithCradle opt cradle ghcOptions logging
| cabal = do
(gopts,idirs,depPkgs) <- liftIO $ fromCabalFile ghcOptions cradle
initSession opt gopts idirs (Just depPkgs) logging
| otherwise =
initSession opt ghcOptions importDirs Nothing logging
where
cabal = isJust $ cradleCabalFile cradle
----------------------------------------------------------------
initSession :: Options
-> [GHCOption]
-> [IncludeDir]
-> Maybe [Package]
-> Bool
-> Ghc LogReader
initSession opt cmdOpts idirs mDepPkgs logging = do
dflags0 <- getSessionDynFlags
(dflags1,readLog) <- setupDynamicFlags dflags0
_ <- setSessionDynFlags dflags1
return readLog
where
setupDynamicFlags df0 = do
df1 <- modifyFlagsWithOpts df0 cmdOpts
let fast = True
let df2 = modifyFlags df1 idirs mDepPkgs fast (expandSplice opt)
df3 <- modifyFlagsWithOpts df2 $ ghcOpts opt
liftIO $ setLogger logging df3
----------------------------------------------------------------
initializeFlags :: Options -> Ghc ()
initializeFlags opt = do
dflags0 <- getSessionDynFlags
dflags1 <- modifyFlagsWithOpts dflags0 $ ghcOpts opt
void $ setSessionDynFlags dflags1
----------------------------------------------------------------
-- FIXME removing Options
modifyFlags :: DynFlags -> [IncludeDir] -> Maybe [Package] -> Bool -> Bool -> DynFlags
modifyFlags d0 idirs mDepPkgs fast splice
| splice = setSplice d3
| otherwise = d3
where
d1 = d0 { importPaths = idirs }
d2 = setFastOrNot d1 fast
d3 = maybe d2 (addDevPkgs d2) mDepPkgs
setSplice :: DynFlags -> DynFlags
setSplice dflag = dopt_set dflag Opt_D_dump_splices
addDevPkgs :: DynFlags -> [Package] -> DynFlags
addDevPkgs df pkgs = df''
where
df' = dopt_set df Opt_HideAllPackages
df'' = df' {
packageFlags = map ExposePackage pkgs ++ packageFlags df
}
----------------------------------------------------------------
setFastOrNot :: DynFlags -> Bool -> DynFlags
setFastOrNot dflags False = dflags {
ghcLink = LinkInMemory
, hscTarget = HscInterpreted
}
setFastOrNot dflags True = dflags {
ghcLink = NoLink
, hscTarget = HscNothing
}
setSlowDynFlags :: Ghc ()
setSlowDynFlags = (flip setFastOrNot False <$> getSessionDynFlags)
>>= void . setSessionDynFlags
-- To check TH, a session module graph is necessary.
-- "load" sets a session module graph using "depanal".
-- But we have to set "-fno-code" to DynFlags before "load".
-- So, this is necessary redundancy.
checkSlowAndSet :: Ghc ()
checkSlowAndSet = do
slow <- needsTemplateHaskell <$> depanal [] False
when slow setSlowDynFlags
----------------------------------------------------------------
modifyFlagsWithOpts :: DynFlags -> [String] -> Ghc DynFlags
modifyFlagsWithOpts dflags cmdOpts =
tfst <$> parseDynamicFlags dflags (map noLoc cmdOpts)
where
tfst (a,_,_) = a
----------------------------------------------------------------
setTargetFile :: (GhcMonad m) => String -> m ()
setTargetFile file = do
target <- guessTarget file Nothing
setTargets [target]
----------------------------------------------------------------
getDynamicFlags :: IO DynFlags
getDynamicFlags = runGhc (Just libdir) getSessionDynFlags
| eagletmt/ghc-mod | GHCApi.hs | bsd-3-clause | 4,585 | 0 | 14 | 896 | 1,160 | 591 | 569 | 103 | 1 |
-- Copyright (c) 1998 Chris Okasaki.
-- See COPYRIGHT file for terms and conditions.
module ListSeq (
-- type synonym
Seq,
-- sequence operations
empty,single,cons,snoc,append,lview,lhead,ltail,rview,rhead,rtail,
null,size,concat,reverse,reverseOnto,fromList,toList,
map,concatMap,foldr,foldl,foldr1,foldl1,reducer,reducel,reduce1,
copy,tabulate,inBounds,lookup,lookupM,lookupWithDefault,update,adjust,
mapWithIndex,foldrWithIndex,foldlWithIndex,
take,drop,splitAt,subseq,filter,partition,takeWhile,dropWhile,splitWhile,
zip,zip3,zipWith,zipWith3,unzip,unzip3,unzipWith,unzipWith3,
-- documentation
moduleName,
-- re-export view type from EdisonPrelude for convenience
Maybe2(Just2,Nothing2)
) where
import Prelude hiding (concat,reverse,map,concatMap,foldr,foldl,foldr1,foldl1,
filter,takeWhile,dropWhile,lookup,take,drop,splitAt,
zip,zip3,zipWith,zipWith3,unzip,unzip3,null)
import qualified Prelude
import EdisonPrelude(Maybe2(Just2,Nothing2))
import qualified List(partition)
import qualified Sequence as S ( Sequence(..) )
-- signatures for exported functions
moduleName :: String
empty :: [a]
single :: a -> [a]
cons :: a -> [a] -> [a]
snoc :: [a] -> a -> [a]
append :: [a] -> [a] -> [a]
lview :: [a] -> Maybe2 a ([a])
lhead :: [a] -> a
ltail :: [a] -> [a]
rview :: [a] -> Maybe2 ([a]) a
rhead :: [a] -> a
rtail :: [a] -> [a]
null :: [a] -> Bool
size :: [a] -> Int
concat :: [[a]] -> [a]
reverse :: [a] -> [a]
reverseOnto :: [a] -> [a] -> [a]
fromList :: [a] -> [a]
toList :: [a] -> [a]
map :: (a -> b) -> [a] -> [b]
concatMap :: (a -> [b]) -> [a] -> [b]
foldr :: (a -> b -> b) -> b -> [a] -> b
foldl :: (b -> a -> b) -> b -> [a] -> b
foldr1 :: (a -> a -> a) -> [a] -> a
foldl1 :: (a -> a -> a) -> [a] -> a
reducer :: (a -> a -> a) -> a -> [a] -> a
reducel :: (a -> a -> a) -> a -> [a] -> a
reduce1 :: (a -> a -> a) -> [a] -> a
copy :: Int -> a -> [a]
tabulate :: Int -> (Int -> a) -> [a]
inBounds :: [a] -> Int -> Bool
lookup :: [a] -> Int -> a
lookupM :: [a] -> Int -> Maybe a
lookupWithDefault :: a -> [a] -> Int -> a
update :: Int -> a -> [a] -> [a]
adjust :: (a -> a) -> Int -> [a] -> [a]
mapWithIndex :: (Int -> a -> b) -> [a] -> [b]
foldrWithIndex :: (Int -> a -> b -> b) -> b -> [a] -> b
foldlWithIndex :: (b -> Int -> a -> b) -> b -> [a] -> b
take :: Int -> [a] -> [a]
drop :: Int -> [a] -> [a]
splitAt :: Int -> [a] -> ([a], [a])
subseq :: Int -> Int -> [a] -> [a]
filter :: (a -> Bool) -> [a] -> [a]
partition :: (a -> Bool) -> [a] -> ([a], [a])
takeWhile :: (a -> Bool) -> [a] -> [a]
dropWhile :: (a -> Bool) -> [a] -> [a]
splitWhile :: (a -> Bool) -> [a] -> ([a], [a])
zip :: [a] -> [b] -> [(a,b)]
zip3 :: [a] -> [b] -> [c] -> [(a,b,c)]
zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
zipWith3 :: (a -> b -> c -> d) -> [a] -> [b] -> [c] -> [d]
unzip :: [(a,b)] -> ([a], [b])
unzip3 :: [(a,b,c)] -> ([a], [b], [c])
unzipWith :: (a -> b) -> (a -> c) -> [a] -> ([b], [c])
unzipWith3 :: (a -> b) -> (a -> c) -> (a -> d) -> [a] -> ([b], [c], [d])
moduleName = "ListSeq"
type Seq a = [a]
empty = []
single x = [x]
cons = (:)
snoc s x = s ++ [x]
append = (++)
lview [] = Nothing2
lview (x:xs) = Just2 x xs
lhead [] = error "ListSeq.lhead: empty sequence"
lhead (x:xs) = x
ltail [] = []
ltail (x:xs) = xs
rview [] = Nothing2
rview xs = Just2 (rtail xs) (rhead xs)
rhead [] = error "ListSeq.rhead: empty sequence"
rhead (x:xs) = rh x xs
where rh y [] = y
rh y (x:xs) = rh x xs
rtail [] = []
rtail (x:xs) = rt x xs
where rt y [] = []
rt y (x:xs) = y : rt x xs
null = Prelude.null
size = length
concat = foldr append empty
reverse = Prelude.reverse
reverseOnto [] ys = ys
reverseOnto (x:xs) ys = reverseOnto xs (x:ys)
fromList xs = xs
toList xs = xs
map = Prelude.map
concatMap = Prelude.concatMap
foldr = Prelude.foldr
foldl = Prelude.foldl
foldr1 f [] = error "ListSeq.foldr1: empty sequence"
foldr1 f (x:xs) = fr x xs
where fr y [] = y
fr y (x:xs) = f y (fr x xs)
foldl1 f [] = error "ListSeq.foldl1: empty sequence"
foldl1 f (x:xs) = foldl f x xs
reducer f e [] = e
reducer f e xs = f (reduce1 f xs) e
reducel f e [] = e
reducel f e xs = f e (reduce1 f xs)
reduce1 f [] = error "ListSeq.reduce1: empty sequence"
reduce1 f [x] = x
reduce1 f (x1 : x2 : xs) = reduce1 f (f x1 x2 : pairup xs)
where pairup (x1 : x2 : xs) = f x1 x2 : pairup xs
pairup xs = xs
-- can be improved using a counter and bit ops!
copy n x | n <= 0 = []
| otherwise = x : copy (n-1) x
-- depends on n to be unboxed, should test this!
tabulate n f = tab 0
where tab i | i >= n = []
| otherwise = f i : tab (i+1)
-- depends on i (and n?) being unboxed, should check this!
inBounds xs i
| i >= 0 = not (null (drop i xs))
| otherwise = False
lookup xs i
| i < 0 = error "ListSeq.lookup: bad subscript"
| otherwise = case drop i xs of
[] -> error "ListSeq.lookup: bad subscript"
(x:_) -> x
lookupM xs i
| i < 0 = Nothing
| otherwise = case drop i xs of
[] -> Nothing
(x:_) -> Just x
lookupWithDefault d xs i
| i < 0 = d
| otherwise = case drop i xs of
[] -> d
(x:_) -> x
update i y xs
| i < 0 = xs
| otherwise = upd i xs
where upd _ [] = []
upd i (x:xs)
| i > 0 = x : upd (i - 1) xs
| otherwise = y : xs
adjust f i xs
| i < 0 = xs
| otherwise = adj i xs
where adj _ [] = []
adj i (x:xs)
| i > 0 = x : adj (i - 1) xs
| otherwise = f x : xs
mapWithIndex f = mapi 0
where mapi i [] = []
mapi i (x:xs) = f i x : mapi (i + 1) xs
foldrWithIndex f e = foldi 0
where foldi i [] = e
foldi i (x:xs) = f i x (foldi (i + 1) xs)
foldlWithIndex f = foldi 0
where foldi i e [] = e
foldi i e (x:xs) = foldi (i + 1) (f e i x) xs
take i xs | i <= 0 = []
| otherwise = Prelude.take i xs
drop i xs | i <= 0 = xs
| otherwise = Prelude.drop i xs
splitAt i xs | i <= 0 = ([], xs)
| otherwise = Prelude.splitAt i xs
subseq i len xs = take len (drop i xs)
filter = Prelude.filter
partition = List.partition
takeWhile = Prelude.takeWhile
dropWhile = Prelude.dropWhile
splitWhile = Prelude.span
zip = Prelude.zip
zip3 = Prelude.zip3
zipWith = Prelude.zipWith
zipWith3 = Prelude.zipWith3
unzip = Prelude.unzip
unzip3 = Prelude.unzip3
unzipWith f g = foldr consfg ([], [])
where consfg a (bs, cs) = (f a : bs, g a : cs)
-- could put ~ on tuple
unzipWith3 f g h = foldr consfgh ([], [], [])
where consfgh a (bs, cs, ds) = (f a : bs, g a : cs, h a : ds)
-- could put ~ on tuple
-- declare the instance
instance S.Sequence [] where
{empty = empty; single = single; cons = cons; snoc = snoc;
append = append; lview = lview; lhead = lhead; ltail = ltail;
rview = rview; rhead = rhead; rtail = rtail; null = null;
size = size; concat = concat; reverse = reverse;
reverseOnto = reverseOnto; fromList = fromList; toList = toList;
map = map; concatMap = concatMap; foldr = foldr; foldl = foldl;
foldr1 = foldr1; foldl1 = foldl1; reducer = reducer;
reducel = reducel; reduce1 = reduce1; copy = copy;
tabulate = tabulate; inBounds = inBounds; lookup = lookup;
lookupM = lookupM; lookupWithDefault = lookupWithDefault;
update = update; adjust = adjust;
mapWithIndex = mapWithIndex;
foldrWithIndex = foldrWithIndex; foldlWithIndex = foldlWithIndex;
take = take; drop = drop; splitAt = splitAt; subseq = subseq;
filter = filter; partition = partition; takeWhile = takeWhile;
dropWhile = dropWhile; splitWhile = splitWhile; zip = zip;
zip3 = zip3; zipWith = zipWith; zipWith3 = zipWith3; unzip = unzip;
unzip3 = unzip3; unzipWith = unzipWith; unzipWith3 = unzipWith3;
instanceName s = moduleName}
| OS2World/DEV-UTIL-HUGS | oldlib/ListSeq.hs | bsd-3-clause | 8,312 | 0 | 11 | 2,485 | 3,925 | 2,178 | 1,747 | 214 | 2 |
{-# LANGUAGE CPP #-}
-- We cannot actually specify all the language pragmas, see ghc ticket #
-- If we could, these are what they would be:
{- LANGUAGE MagicHash, UnboxedTuples,
NamedFieldPuns, BangPatterns, RecordWildCards -}
{-# OPTIONS_HADDOCK prune #-}
-- |
-- Module : Data.ByteString
-- Copyright : (c) The University of Glasgow 2001,
-- (c) David Roundy 2003-2005,
-- (c) Simon Marlow 2005
-- (c) Bjorn Bringert 2006
-- (c) Don Stewart 2005-2008
--
-- Array fusion code:
-- (c) 2001,2002 Manuel M T Chakravarty & Gabriele Keller
-- (c) 2006 Manuel M T Chakravarty & Roman Leshchinskiy
--
-- License : BSD-style
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- A time and space-efficient implementation of byte vectors using
-- packed Word8 arrays, suitable for high performance use, both in terms
-- of large data quantities, or high speed requirements. Byte vectors
-- are encoded as strict 'Word8' arrays of bytes, held in a 'ForeignPtr',
-- and can be passed between C and Haskell with little effort.
--
-- This module is intended to be imported @qualified@, to avoid name
-- clashes with "Prelude" functions. eg.
--
-- > import qualified Data.ByteString as B
--
-- Original GHC implementation by Bryan O\'Sullivan.
-- Rewritten to use 'Data.Array.Unboxed.UArray' by Simon Marlow.
-- Rewritten to support slices and use 'ForeignPtr' by David Roundy.
-- Polished and extended by Don Stewart.
--
module Data.ByteString (
-- * The @ByteString@ type
ByteString, -- abstract, instances: Eq, Ord, Show, Read, Data, Typeable, Monoid
-- * Introducing and eliminating 'ByteString's
empty, -- :: ByteString
singleton, -- :: Word8 -> ByteString
pack, -- :: [Word8] -> ByteString
unpack, -- :: ByteString -> [Word8]
-- * Basic interface
cons, -- :: Word8 -> ByteString -> ByteString
snoc, -- :: ByteString -> Word8 -> ByteString
append, -- :: ByteString -> ByteString -> ByteString
head, -- :: ByteString -> Word8
uncons, -- :: ByteString -> Maybe (Word8, ByteString)
last, -- :: ByteString -> Word8
tail, -- :: ByteString -> ByteString
init, -- :: ByteString -> ByteString
null, -- :: ByteString -> Bool
length, -- :: ByteString -> Int
-- * Transforming ByteStrings
map, -- :: (Word8 -> Word8) -> ByteString -> ByteString
reverse, -- :: ByteString -> ByteString
intersperse, -- :: Word8 -> ByteString -> ByteString
intercalate, -- :: ByteString -> [ByteString] -> ByteString
transpose, -- :: [ByteString] -> [ByteString]
-- * Reducing 'ByteString's (folds)
foldl, -- :: (a -> Word8 -> a) -> a -> ByteString -> a
foldl', -- :: (a -> Word8 -> a) -> a -> ByteString -> a
foldl1, -- :: (Word8 -> Word8 -> Word8) -> ByteString -> Word8
foldl1', -- :: (Word8 -> Word8 -> Word8) -> ByteString -> Word8
foldr, -- :: (Word8 -> a -> a) -> a -> ByteString -> a
foldr', -- :: (Word8 -> a -> a) -> a -> ByteString -> a
foldr1, -- :: (Word8 -> Word8 -> Word8) -> ByteString -> Word8
foldr1', -- :: (Word8 -> Word8 -> Word8) -> ByteString -> Word8
-- ** Special folds
concat, -- :: [ByteString] -> ByteString
concatMap, -- :: (Word8 -> ByteString) -> ByteString -> ByteString
any, -- :: (Word8 -> Bool) -> ByteString -> Bool
all, -- :: (Word8 -> Bool) -> ByteString -> Bool
maximum, -- :: ByteString -> Word8
minimum, -- :: ByteString -> Word8
-- * Building ByteStrings
-- ** Scans
scanl, -- :: (Word8 -> Word8 -> Word8) -> Word8 -> ByteString -> ByteString
scanl1, -- :: (Word8 -> Word8 -> Word8) -> ByteString -> ByteString
scanr, -- :: (Word8 -> Word8 -> Word8) -> Word8 -> ByteString -> ByteString
scanr1, -- :: (Word8 -> Word8 -> Word8) -> ByteString -> ByteString
-- ** Accumulating maps
mapAccumL, -- :: (acc -> Word8 -> (acc, Word8)) -> acc -> ByteString -> (acc, ByteString)
mapAccumR, -- :: (acc -> Word8 -> (acc, Word8)) -> acc -> ByteString -> (acc, ByteString)
-- ** Generating and unfolding ByteStrings
replicate, -- :: Int -> Word8 -> ByteString
unfoldr, -- :: (a -> Maybe (Word8, a)) -> a -> ByteString
unfoldrN, -- :: Int -> (a -> Maybe (Word8, a)) -> a -> (ByteString, Maybe a)
-- * Substrings
-- ** Breaking strings
take, -- :: Int -> ByteString -> ByteString
drop, -- :: Int -> ByteString -> ByteString
splitAt, -- :: Int -> ByteString -> (ByteString, ByteString)
takeWhile, -- :: (Word8 -> Bool) -> ByteString -> ByteString
dropWhile, -- :: (Word8 -> Bool) -> ByteString -> ByteString
span, -- :: (Word8 -> Bool) -> ByteString -> (ByteString, ByteString)
spanEnd, -- :: (Word8 -> Bool) -> ByteString -> (ByteString, ByteString)
break, -- :: (Word8 -> Bool) -> ByteString -> (ByteString, ByteString)
breakEnd, -- :: (Word8 -> Bool) -> ByteString -> (ByteString, ByteString)
group, -- :: ByteString -> [ByteString]
groupBy, -- :: (Word8 -> Word8 -> Bool) -> ByteString -> [ByteString]
inits, -- :: ByteString -> [ByteString]
tails, -- :: ByteString -> [ByteString]
-- ** Breaking into many substrings
split, -- :: Word8 -> ByteString -> [ByteString]
splitWith, -- :: (Word8 -> Bool) -> ByteString -> [ByteString]
-- * Predicates
isPrefixOf, -- :: ByteString -> ByteString -> Bool
isSuffixOf, -- :: ByteString -> ByteString -> Bool
isInfixOf, -- :: ByteString -> ByteString -> Bool
-- ** Search for arbitrary substrings
breakSubstring, -- :: ByteString -> ByteString -> (ByteString,ByteString)
findSubstring, -- :: ByteString -> ByteString -> Maybe Int
findSubstrings, -- :: ByteString -> ByteString -> [Int]
-- * Searching ByteStrings
-- ** Searching by equality
elem, -- :: Word8 -> ByteString -> Bool
notElem, -- :: Word8 -> ByteString -> Bool
-- ** Searching with a predicate
find, -- :: (Word8 -> Bool) -> ByteString -> Maybe Word8
filter, -- :: (Word8 -> Bool) -> ByteString -> ByteString
partition, -- :: (Word8 -> Bool) -> ByteString -> (ByteString, ByteString)
-- * Indexing ByteStrings
index, -- :: ByteString -> Int -> Word8
elemIndex, -- :: Word8 -> ByteString -> Maybe Int
elemIndices, -- :: Word8 -> ByteString -> [Int]
elemIndexEnd, -- :: Word8 -> ByteString -> Maybe Int
findIndex, -- :: (Word8 -> Bool) -> ByteString -> Maybe Int
findIndices, -- :: (Word8 -> Bool) -> ByteString -> [Int]
count, -- :: Word8 -> ByteString -> Int
-- * Zipping and unzipping ByteStrings
zip, -- :: ByteString -> ByteString -> [(Word8,Word8)]
zipWith, -- :: (Word8 -> Word8 -> c) -> ByteString -> ByteString -> [c]
unzip, -- :: [(Word8,Word8)] -> (ByteString,ByteString)
-- * Ordered ByteStrings
sort, -- :: ByteString -> ByteString
-- * Low level conversions
-- ** Copying ByteStrings
copy, -- :: ByteString -> ByteString
-- ** Packing 'CString's and pointers
packCString, -- :: CString -> IO ByteString
packCStringLen, -- :: CStringLen -> IO ByteString
-- ** Using ByteStrings as 'CString's
useAsCString, -- :: ByteString -> (CString -> IO a) -> IO a
useAsCStringLen, -- :: ByteString -> (CStringLen -> IO a) -> IO a
-- * I\/O with 'ByteString's
-- ** Standard input and output
getLine, -- :: IO ByteString
getContents, -- :: IO ByteString
putStr, -- :: ByteString -> IO ()
putStrLn, -- :: ByteString -> IO ()
interact, -- :: (ByteString -> ByteString) -> IO ()
-- ** Files
readFile, -- :: FilePath -> IO ByteString
writeFile, -- :: FilePath -> ByteString -> IO ()
appendFile, -- :: FilePath -> ByteString -> IO ()
-- ** I\/O with Handles
hGetLine, -- :: Handle -> IO ByteString
hGetContents, -- :: Handle -> IO ByteString
hGet, -- :: Handle -> Int -> IO ByteString
hGetSome, -- :: Handle -> Int -> IO ByteString
hGetNonBlocking, -- :: Handle -> Int -> IO ByteString
hPut, -- :: Handle -> ByteString -> IO ()
hPutStr, -- :: Handle -> ByteString -> IO ()
hPutStrLn, -- :: Handle -> ByteString -> IO ()
breakByte
) where
import qualified Prelude as P
import Prelude hiding (reverse,head,tail,last,init,null
,length,map,lines,foldl,foldr,unlines
,concat,any,take,drop,splitAt,takeWhile
,dropWhile,span,break,elem,filter,maximum
,minimum,all,concatMap,foldl1,foldr1
,scanl,scanl1,scanr,scanr1
,readFile,writeFile,appendFile,replicate
,getContents,getLine,putStr,putStrLn,interact
,zip,zipWith,unzip,notElem)
import Data.ByteString.Internal
import Data.ByteString.Unsafe
import qualified Data.List as List
import Data.Word (Word8)
import Data.Maybe (isJust, listToMaybe)
-- Control.Exception.assert not available in yhc or nhc
#ifndef __NHC__
import Control.Exception (finally, bracket, assert)
#else
import Control.Exception (bracket, finally)
#endif
import Control.Monad (when)
import Foreign.C.String (CString, CStringLen)
import Foreign.C.Types (CSize)
import Foreign.ForeignPtr
import Foreign.Marshal.Alloc (allocaBytes, mallocBytes, reallocBytes, finalizerFree)
import Foreign.Marshal.Array (allocaArray)
import Foreign.Ptr
import Foreign.Storable (Storable(..))
-- hGetBuf and hPutBuf not available in yhc or nhc
import System.IO (stdin,stdout,hClose,hFileSize
,hGetBuf,hPutBuf,openBinaryFile
,IOMode(..))
import System.IO.Error (mkIOError, illegalOperationErrorType)
import Data.Monoid (Monoid, mempty, mappend, mconcat)
#if !defined(__GLASGOW_HASKELL__)
import System.IO.Unsafe
import qualified System.Environment
import qualified System.IO (hGetLine)
#endif
#if defined(__GLASGOW_HASKELL__)
import System.IO (hGetBufNonBlocking)
#if MIN_VERSION_base(4,3,0)
import System.IO (hGetBufSome)
#else
import System.IO (hWaitForInput, hIsEOF)
#endif
#if __GLASGOW_HASKELL__ >= 611
import Data.IORef
import GHC.IO.Handle.Internals
import GHC.IO.Handle.Types
import GHC.IO.Buffer
import GHC.IO.BufferedIO as Buffered
import GHC.IO hiding (finally)
import Data.Char (ord)
import Foreign.Marshal.Utils (copyBytes)
#else
import System.IO.Error (isEOFError)
import GHC.IOBase
import GHC.Handle
#endif
import GHC.Prim (Word#, (+#), writeWord8OffAddr#)
import GHC.Base (build)
import GHC.Word hiding (Word8)
import GHC.Ptr (Ptr(..))
import GHC.ST (ST(..))
#endif
-- An alternative to Control.Exception (assert) for nhc98
#ifdef __NHC__
import System.IO (Handle)
#define assert assertS "__FILE__ : __LINE__"
assertS :: String -> Bool -> a -> a
assertS _ True = id
assertS s False = error ("assertion failed at "++s)
-- An alternative to hWaitForInput
hWaitForInput :: Handle -> Int -> IO ()
hWaitForInput _ _ = return ()
#endif
-- -----------------------------------------------------------------------------
--
-- Useful macros, until we have bang patterns
--
#define STRICT1(f) f a | a `seq` False = undefined
#define STRICT2(f) f a b | a `seq` b `seq` False = undefined
#define STRICT3(f) f a b c | a `seq` b `seq` c `seq` False = undefined
#define STRICT4(f) f a b c d | a `seq` b `seq` c `seq` d `seq` False = undefined
#define STRICT5(f) f a b c d e | a `seq` b `seq` c `seq` d `seq` e `seq` False = undefined
-- -----------------------------------------------------------------------------
instance Eq ByteString where
(==) = eq
instance Ord ByteString where
compare = compareBytes
instance Monoid ByteString where
mempty = empty
mappend = append
mconcat = concat
-- | /O(n)/ Equality on the 'ByteString' type.
eq :: ByteString -> ByteString -> Bool
eq a@(PS p s l) b@(PS p' s' l')
| l /= l' = False -- short cut on length
| p == p' && s == s' = True -- short cut for the same string
| otherwise = compareBytes a b == EQ
{-# INLINE eq #-}
-- ^ still needed
-- | /O(n)/ 'compareBytes' provides an 'Ordering' for 'ByteStrings' supporting slices.
compareBytes :: ByteString -> ByteString -> Ordering
compareBytes (PS x1 s1 l1) (PS x2 s2 l2)
| l1 == 0 && l2 == 0 = EQ -- short cut for empty strings
| otherwise = inlinePerformIO $
withForeignPtr x1 $ \p1 ->
withForeignPtr x2 $ \p2 -> do
i <- memcmp (p1 `plusPtr` s1) (p2 `plusPtr` s2) (fromIntegral $ min l1 l2)
return $! case i `compare` 0 of
EQ -> l1 `compare` l2
x -> x
{-
-- Pure Haskell version
compareBytes (PS fp1 off1 len1) (PS fp2 off2 len2)
-- | len1 == 0 && len2 == 0 = EQ -- short cut for empty strings
-- | fp1 == fp2 && off1 == off2 && len1 == len2 = EQ -- short cut for the same string
| otherwise = inlinePerformIO $
withForeignPtr fp1 $ \p1 ->
withForeignPtr fp2 $ \p2 ->
cmp (p1 `plusPtr` off1)
(p2 `plusPtr` off2) 0 len1 len2
-- XXX todo.
cmp :: Ptr Word8 -> Ptr Word8 -> Int -> Int -> Int-> IO Ordering
cmp p1 p2 n len1 len2
| n == len1 = if n == len2 then return EQ else return LT
| n == len2 = return GT
| otherwise = do
a <- peekByteOff p1 n :: IO Word8
b <- peekByteOff p2 n
case a `compare` b of
EQ -> cmp p1 p2 (n+1) len1 len2
LT -> return LT
GT -> return GT
-}
-- -----------------------------------------------------------------------------
-- Introducing and eliminating 'ByteString's
-- | /O(1)/ The empty 'ByteString'
empty :: ByteString
empty = PS nullForeignPtr 0 0
-- | /O(1)/ Convert a 'Word8' into a 'ByteString'
singleton :: Word8 -> ByteString
singleton c = unsafeCreate 1 $ \p -> poke p c
{-# INLINE [1] singleton #-}
-- Inline [1] for intercalate rule
--
-- XXX The use of unsafePerformIO in allocating functions (unsafeCreate) is critical!
--
-- Otherwise:
--
-- singleton 255 `compare` singleton 127
--
-- is compiled to:
--
-- case mallocByteString 2 of
-- ForeignPtr f internals ->
-- case writeWord8OffAddr# f 0 255 of _ ->
-- case writeWord8OffAddr# f 0 127 of _ ->
-- case eqAddr# f f of
-- False -> case compare (GHC.Prim.plusAddr# f 0)
-- (GHC.Prim.plusAddr# f 0)
--
--
-- | /O(n)/ Convert a '[Word8]' into a 'ByteString'.
--
-- For applications with large numbers of string literals, pack can be a
-- bottleneck. In such cases, consider using packAddress (GHC only).
pack :: [Word8] -> ByteString
#if !defined(__GLASGOW_HASKELL__)
pack str = unsafeCreate (P.length str) $ \p -> go p str
where
go _ [] = return ()
go p (x:xs) = poke p x >> go (p `plusPtr` 1) xs -- less space than pokeElemOff
#else /* hack away */
pack str = unsafeCreate (P.length str) $ \(Ptr p) -> stToIO (go p 0# str)
where
go _ _ [] = return ()
go p i (W8# c:cs) = writeByte p i c >> go p (i +# 1#) cs
writeByte p i c = ST $ \s# ->
case writeWord8OffAddr# p i c s# of s2# -> (# s2#, () #)
#endif
-- | /O(n)/ Converts a 'ByteString' to a '[Word8]'.
unpack :: ByteString -> [Word8]
#if !defined(__GLASGOW_HASKELL__)
unpack (PS _ _ 0) = []
unpack (PS ps s l) = inlinePerformIO $ withForeignPtr ps $ \p ->
go (p `plusPtr` s) (l - 1) []
where
STRICT3(go)
go p 0 acc = peek p >>= \e -> return (e : acc)
go p n acc = peekByteOff p n >>= \e -> go p (n-1) (e : acc)
{-# INLINE unpack #-}
#else
unpack ps = build (unpackFoldr ps)
{-# INLINE unpack #-}
--
-- Have unpack fuse with good list consumers
--
-- critical this isn't strict in the acc
-- as it will break in the presence of list fusion. this is a known
-- issue with seq and build/foldr rewrite rules, which rely on lazy
-- demanding to avoid bottoms in the list.
--
unpackFoldr :: ByteString -> (Word8 -> a -> a) -> a -> a
unpackFoldr (PS fp off len) f ch = withPtr fp $ \p -> do
let loop q n _ | q `seq` n `seq` False = undefined -- n.b.
loop _ (-1) acc = return acc
loop q n acc = do
a <- peekByteOff q n
loop q (n-1) (a `f` acc)
loop (p `plusPtr` off) (len-1) ch
{-# INLINE [0] unpackFoldr #-}
unpackList :: ByteString -> [Word8]
unpackList (PS fp off len) = withPtr fp $ \p -> do
let STRICT3(loop)
loop _ (-1) acc = return acc
loop q n acc = do
a <- peekByteOff q n
loop q (n-1) (a : acc)
loop (p `plusPtr` off) (len-1) []
{-# RULES
"ByteString unpack-list" [1] forall p .
unpackFoldr p (:) [] = unpackList p
#-}
#endif
-- ---------------------------------------------------------------------
-- Basic interface
-- | /O(1)/ Test whether a ByteString is empty.
null :: ByteString -> Bool
null (PS _ _ l) = assert (l >= 0) $ l <= 0
{-# INLINE null #-}
-- ---------------------------------------------------------------------
-- | /O(1)/ 'length' returns the length of a ByteString as an 'Int'.
length :: ByteString -> Int
length (PS _ _ l) = assert (l >= 0) $ l
{-# INLINE length #-}
------------------------------------------------------------------------
-- | /O(n)/ 'cons' is analogous to (:) for lists, but of different
-- complexity, as it requires a memcpy.
cons :: Word8 -> ByteString -> ByteString
cons c (PS x s l) = unsafeCreate (l+1) $ \p -> withForeignPtr x $ \f -> do
poke p c
memcpy (p `plusPtr` 1) (f `plusPtr` s) (fromIntegral l)
{-# INLINE cons #-}
-- | /O(n)/ Append a byte to the end of a 'ByteString'
snoc :: ByteString -> Word8 -> ByteString
snoc (PS x s l) c = unsafeCreate (l+1) $ \p -> withForeignPtr x $ \f -> do
memcpy p (f `plusPtr` s) (fromIntegral l)
poke (p `plusPtr` l) c
{-# INLINE snoc #-}
-- todo fuse
-- | /O(1)/ Extract the first element of a ByteString, which must be non-empty.
-- An exception will be thrown in the case of an empty ByteString.
head :: ByteString -> Word8
head (PS x s l)
| l <= 0 = errorEmptyList "head"
| otherwise = inlinePerformIO $ withForeignPtr x $ \p -> peekByteOff p s
{-# INLINE head #-}
-- | /O(1)/ Extract the elements after the head of a ByteString, which must be non-empty.
-- An exception will be thrown in the case of an empty ByteString.
tail :: ByteString -> ByteString
tail (PS p s l)
| l <= 0 = errorEmptyList "tail"
| otherwise = PS p (s+1) (l-1)
{-# INLINE tail #-}
-- | /O(1)/ Extract the head and tail of a ByteString, returning Nothing
-- if it is empty.
uncons :: ByteString -> Maybe (Word8, ByteString)
uncons (PS x s l)
| l <= 0 = Nothing
| otherwise = Just (inlinePerformIO $ withForeignPtr x
$ \p -> peekByteOff p s,
PS x (s+1) (l-1))
{-# INLINE uncons #-}
-- | /O(1)/ Extract the last element of a ByteString, which must be finite and non-empty.
-- An exception will be thrown in the case of an empty ByteString.
last :: ByteString -> Word8
last ps@(PS x s l)
| null ps = errorEmptyList "last"
| otherwise = inlinePerformIO $ withForeignPtr x $ \p -> peekByteOff p (s+l-1)
{-# INLINE last #-}
-- | /O(1)/ Return all the elements of a 'ByteString' except the last one.
-- An exception will be thrown in the case of an empty ByteString.
init :: ByteString -> ByteString
init ps@(PS p s l)
| null ps = errorEmptyList "init"
| otherwise = PS p s (l-1)
{-# INLINE init #-}
-- | /O(n)/ Append two ByteStrings
append :: ByteString -> ByteString -> ByteString
append xs ys | null xs = ys
| null ys = xs
| otherwise = concat [xs,ys]
{-# INLINE append #-}
-- ---------------------------------------------------------------------
-- Transformations
-- | /O(n)/ 'map' @f xs@ is the ByteString obtained by applying @f@ to each
-- element of @xs@. This function is subject to array fusion.
map :: (Word8 -> Word8) -> ByteString -> ByteString
map f (PS fp s len) = inlinePerformIO $ withForeignPtr fp $ \a ->
create len $ map_ 0 (a `plusPtr` s)
where
map_ :: Int -> Ptr Word8 -> Ptr Word8 -> IO ()
STRICT3(map_)
map_ n p1 p2
| n >= len = return ()
| otherwise = do
x <- peekByteOff p1 n
pokeByteOff p2 n (f x)
map_ (n+1) p1 p2
{-# INLINE map #-}
-- | /O(n)/ 'reverse' @xs@ efficiently returns the elements of @xs@ in reverse order.
reverse :: ByteString -> ByteString
reverse (PS x s l) = unsafeCreate l $ \p -> withForeignPtr x $ \f ->
c_reverse p (f `plusPtr` s) (fromIntegral l)
-- | /O(n)/ The 'intersperse' function takes a 'Word8' and a
-- 'ByteString' and \`intersperses\' that byte between the elements of
-- the 'ByteString'. It is analogous to the intersperse function on
-- Lists.
intersperse :: Word8 -> ByteString -> ByteString
intersperse c ps@(PS x s l)
| length ps < 2 = ps
| otherwise = unsafeCreate (2*l-1) $ \p -> withForeignPtr x $ \f ->
c_intersperse p (f `plusPtr` s) (fromIntegral l) c
-- | The 'transpose' function transposes the rows and columns of its
-- 'ByteString' argument.
transpose :: [ByteString] -> [ByteString]
transpose ps = P.map pack (List.transpose (P.map unpack ps))
-- ---------------------------------------------------------------------
-- Reducing 'ByteString's
-- | 'foldl', applied to a binary operator, a starting value (typically
-- the left-identity of the operator), and a ByteString, reduces the
-- ByteString using the binary operator, from left to right.
--
-- This function is subject to array fusion.
--
foldl :: (a -> Word8 -> a) -> a -> ByteString -> a
foldl f v (PS x s l) = inlinePerformIO $ withForeignPtr x $ \ptr ->
lgo v (ptr `plusPtr` s) (ptr `plusPtr` (s+l))
where
STRICT3(lgo)
lgo z p q | p == q = return z
| otherwise = do c <- peek p
lgo (f z c) (p `plusPtr` 1) q
{-# INLINE foldl #-}
-- | 'foldl\'' is like 'foldl', but strict in the accumulator.
-- However, for ByteStrings, all left folds are strict in the accumulator.
--
foldl' :: (a -> Word8 -> a) -> a -> ByteString -> a
foldl' = foldl
{-# INLINE foldl' #-}
-- | 'foldr', applied to a binary operator, a starting value
-- (typically the right-identity of the operator), and a ByteString,
-- reduces the ByteString using the binary operator, from right to left.
foldr :: (Word8 -> a -> a) -> a -> ByteString -> a
foldr k v (PS x s l) = inlinePerformIO $ withForeignPtr x $ \ptr ->
go v (ptr `plusPtr` (s+l-1)) (ptr `plusPtr` (s-1))
where
STRICT3(go)
go z p q | p == q = return z
| otherwise = do c <- peek p
go (c `k` z) (p `plusPtr` (-1)) q -- tail recursive
{-# INLINE foldr #-}
-- | 'foldr\'' is like 'foldr', but strict in the accumulator.
foldr' :: (Word8 -> a -> a) -> a -> ByteString -> a
foldr' k v (PS x s l) = inlinePerformIO $ withForeignPtr x $ \ptr ->
go v (ptr `plusPtr` (s+l-1)) (ptr `plusPtr` (s-1))
where
STRICT3(go)
go z p q | p == q = return z
| otherwise = do c <- peek p
go (c `k` z) (p `plusPtr` (-1)) q -- tail recursive
{-# INLINE foldr' #-}
-- | 'foldl1' is a variant of 'foldl' that has no starting value
-- argument, and thus must be applied to non-empty 'ByteStrings'.
-- This function is subject to array fusion.
-- An exception will be thrown in the case of an empty ByteString.
foldl1 :: (Word8 -> Word8 -> Word8) -> ByteString -> Word8
foldl1 f ps
| null ps = errorEmptyList "foldl1"
| otherwise = foldl f (unsafeHead ps) (unsafeTail ps)
{-# INLINE foldl1 #-}
-- | 'foldl1\'' is like 'foldl1', but strict in the accumulator.
-- An exception will be thrown in the case of an empty ByteString.
foldl1' :: (Word8 -> Word8 -> Word8) -> ByteString -> Word8
foldl1' f ps
| null ps = errorEmptyList "foldl1'"
| otherwise = foldl' f (unsafeHead ps) (unsafeTail ps)
{-# INLINE foldl1' #-}
-- | 'foldr1' is a variant of 'foldr' that has no starting value argument,
-- and thus must be applied to non-empty 'ByteString's
-- An exception will be thrown in the case of an empty ByteString.
foldr1 :: (Word8 -> Word8 -> Word8) -> ByteString -> Word8
foldr1 f ps
| null ps = errorEmptyList "foldr1"
| otherwise = foldr f (last ps) (init ps)
{-# INLINE foldr1 #-}
-- | 'foldr1\'' is a variant of 'foldr1', but is strict in the
-- accumulator.
foldr1' :: (Word8 -> Word8 -> Word8) -> ByteString -> Word8
foldr1' f ps
| null ps = errorEmptyList "foldr1"
| otherwise = foldr' f (last ps) (init ps)
{-# INLINE foldr1' #-}
-- ---------------------------------------------------------------------
-- Special folds
-- | /O(n)/ Concatenate a list of ByteStrings.
concat :: [ByteString] -> ByteString
concat [] = empty
concat [ps] = ps
concat xs = unsafeCreate len $ \ptr -> go xs ptr
where len = P.sum . P.map length $ xs
STRICT2(go)
go [] _ = return ()
go (PS p s l:ps) ptr = do
withForeignPtr p $ \fp -> memcpy ptr (fp `plusPtr` s) (fromIntegral l)
go ps (ptr `plusPtr` l)
-- | Map a function over a 'ByteString' and concatenate the results
concatMap :: (Word8 -> ByteString) -> ByteString -> ByteString
concatMap f = concat . foldr ((:) . f) []
-- foldr (append . f) empty
-- | /O(n)/ Applied to a predicate and a ByteString, 'any' determines if
-- any element of the 'ByteString' satisfies the predicate.
any :: (Word8 -> Bool) -> ByteString -> Bool
any _ (PS _ _ 0) = False
any f (PS x s l) = inlinePerformIO $ withForeignPtr x $ \ptr ->
go (ptr `plusPtr` s) (ptr `plusPtr` (s+l))
where
STRICT2(go)
go p q | p == q = return False
| otherwise = do c <- peek p
if f c then return True
else go (p `plusPtr` 1) q
{-# INLINE any #-}
-- todo fuse
-- | /O(n)/ Applied to a predicate and a 'ByteString', 'all' determines
-- if all elements of the 'ByteString' satisfy the predicate.
all :: (Word8 -> Bool) -> ByteString -> Bool
all _ (PS _ _ 0) = True
all f (PS x s l) = inlinePerformIO $ withForeignPtr x $ \ptr ->
go (ptr `plusPtr` s) (ptr `plusPtr` (s+l))
where
STRICT2(go)
go p q | p == q = return True -- end of list
| otherwise = do c <- peek p
if f c
then go (p `plusPtr` 1) q
else return False
{-# INLINE all #-}
------------------------------------------------------------------------
-- | /O(n)/ 'maximum' returns the maximum value from a 'ByteString'
-- This function will fuse.
-- An exception will be thrown in the case of an empty ByteString.
maximum :: ByteString -> Word8
maximum xs@(PS x s l)
| null xs = errorEmptyList "maximum"
| otherwise = inlinePerformIO $ withForeignPtr x $ \p ->
c_maximum (p `plusPtr` s) (fromIntegral l)
{-# INLINE maximum #-}
-- | /O(n)/ 'minimum' returns the minimum value from a 'ByteString'
-- This function will fuse.
-- An exception will be thrown in the case of an empty ByteString.
minimum :: ByteString -> Word8
minimum xs@(PS x s l)
| null xs = errorEmptyList "minimum"
| otherwise = inlinePerformIO $ withForeignPtr x $ \p ->
c_minimum (p `plusPtr` s) (fromIntegral l)
{-# INLINE minimum #-}
------------------------------------------------------------------------
-- | The 'mapAccumL' function behaves like a combination of 'map' and
-- 'foldl'; it applies a function to each element of a ByteString,
-- passing an accumulating parameter from left to right, and returning a
-- final value of this accumulator together with the new list.
mapAccumL :: (acc -> Word8 -> (acc, Word8)) -> acc -> ByteString -> (acc, ByteString)
mapAccumL f acc (PS fp o len) = inlinePerformIO $ withForeignPtr fp $ \a -> do
gp <- mallocByteString len
acc' <- withForeignPtr gp $ \p -> mapAccumL_ acc 0 (a `plusPtr` o) p
return $! (acc', PS gp 0 len)
where
STRICT4(mapAccumL_)
mapAccumL_ s n p1 p2
| n >= len = return s
| otherwise = do
x <- peekByteOff p1 n
let (s', y) = f s x
pokeByteOff p2 n y
mapAccumL_ s' (n+1) p1 p2
{-# INLINE mapAccumL #-}
-- | The 'mapAccumR' function behaves like a combination of 'map' and
-- 'foldr'; it applies a function to each element of a ByteString,
-- passing an accumulating parameter from right to left, and returning a
-- final value of this accumulator together with the new ByteString.
mapAccumR :: (acc -> Word8 -> (acc, Word8)) -> acc -> ByteString -> (acc, ByteString)
mapAccumR f acc (PS fp o len) = inlinePerformIO $ withForeignPtr fp $ \a -> do
gp <- mallocByteString len
acc' <- withForeignPtr gp $ \p -> mapAccumR_ acc (len-1) (a `plusPtr` o) p
return $! (acc', PS gp 0 len)
where
STRICT4(mapAccumR_)
mapAccumR_ s n p q
| n < 0 = return s
| otherwise = do
x <- peekByteOff p n
let (s', y) = f s x
pokeByteOff q n y
mapAccumR_ s' (n-1) p q
{-# INLINE mapAccumR #-}
-- ---------------------------------------------------------------------
-- Building ByteStrings
-- | 'scanl' is similar to 'foldl', but returns a list of successive
-- reduced values from the left. This function will fuse.
--
-- > scanl f z [x1, x2, ...] == [z, z `f` x1, (z `f` x1) `f` x2, ...]
--
-- Note that
--
-- > last (scanl f z xs) == foldl f z xs.
--
scanl :: (Word8 -> Word8 -> Word8) -> Word8 -> ByteString -> ByteString
scanl f v (PS fp s len) = inlinePerformIO $ withForeignPtr fp $ \a ->
create (len+1) $ \q -> do
poke q v
scanl_ v 0 (a `plusPtr` s) (q `plusPtr` 1)
where
STRICT4(scanl_)
scanl_ z n p q
| n >= len = return ()
| otherwise = do
x <- peekByteOff p n
let z' = f z x
pokeByteOff q n z'
scanl_ z' (n+1) p q
{-# INLINE scanl #-}
-- n.b. haskell's List scan returns a list one bigger than the
-- input, so we need to snoc here to get some extra space, however,
-- it breaks map/up fusion (i.e. scanl . map no longer fuses)
-- | 'scanl1' is a variant of 'scanl' that has no starting value argument.
-- This function will fuse.
--
-- > scanl1 f [x1, x2, ...] == [x1, x1 `f` x2, ...]
scanl1 :: (Word8 -> Word8 -> Word8) -> ByteString -> ByteString
scanl1 f ps
| null ps = empty
| otherwise = scanl f (unsafeHead ps) (unsafeTail ps)
{-# INLINE scanl1 #-}
-- | scanr is the right-to-left dual of scanl.
scanr :: (Word8 -> Word8 -> Word8) -> Word8 -> ByteString -> ByteString
scanr f v (PS fp s len) = inlinePerformIO $ withForeignPtr fp $ \a ->
create (len+1) $ \q -> do
poke (q `plusPtr` len) v
scanr_ v (len-1) (a `plusPtr` s) q
where
STRICT4(scanr_)
scanr_ z n p q
| n < 0 = return ()
| otherwise = do
x <- peekByteOff p n
let z' = f x z
pokeByteOff q n z'
scanr_ z' (n-1) p q
{-# INLINE scanr #-}
-- | 'scanr1' is a variant of 'scanr' that has no starting value argument.
scanr1 :: (Word8 -> Word8 -> Word8) -> ByteString -> ByteString
scanr1 f ps
| null ps = empty
| otherwise = scanr f (last ps) (init ps) -- todo, unsafe versions
{-# INLINE scanr1 #-}
-- ---------------------------------------------------------------------
-- Unfolds and replicates
-- | /O(n)/ 'replicate' @n x@ is a ByteString of length @n@ with @x@
-- the value of every element. The following holds:
--
-- > replicate w c = unfoldr w (\u -> Just (u,u)) c
--
-- This implemenation uses @memset(3)@
replicate :: Int -> Word8 -> ByteString
replicate w c
| w <= 0 = empty
| otherwise = unsafeCreate w $ \ptr ->
memset ptr c (fromIntegral w) >> return ()
-- | /O(n)/, where /n/ is the length of the result. The 'unfoldr'
-- function is analogous to the List \'unfoldr\'. 'unfoldr' builds a
-- ByteString from a seed value. The function takes the element and
-- returns 'Nothing' if it is done producing the ByteString or returns
-- 'Just' @(a,b)@, in which case, @a@ is the next byte in the string,
-- and @b@ is the seed value for further production.
--
-- Examples:
--
-- > unfoldr (\x -> if x <= 5 then Just (x, x + 1) else Nothing) 0
-- > == pack [0, 1, 2, 3, 4, 5]
--
unfoldr :: (a -> Maybe (Word8, a)) -> a -> ByteString
unfoldr f = concat . unfoldChunk 32 64
where unfoldChunk n n' x =
case unfoldrN n f x of
(s, Nothing) -> s : []
(s, Just x') -> s : unfoldChunk n' (n+n') x'
{-# INLINE unfoldr #-}
-- | /O(n)/ Like 'unfoldr', 'unfoldrN' builds a ByteString from a seed
-- value. However, the length of the result is limited by the first
-- argument to 'unfoldrN'. This function is more efficient than 'unfoldr'
-- when the maximum length of the result is known.
--
-- The following equation relates 'unfoldrN' and 'unfoldr':
--
-- > snd (unfoldrN n f s) == take n (unfoldr f s)
--
unfoldrN :: Int -> (a -> Maybe (Word8, a)) -> a -> (ByteString, Maybe a)
unfoldrN i f x0
| i < 0 = (empty, Just x0)
| otherwise = unsafePerformIO $ createAndTrim' i $ \p -> go p x0 0
where STRICT3(go)
go p x n =
case f x of
Nothing -> return (0, n, Nothing)
Just (w,x')
| n == i -> return (0, n, Just x)
| otherwise -> do poke p w
go (p `plusPtr` 1) x' (n+1)
{-# INLINE unfoldrN #-}
-- ---------------------------------------------------------------------
-- Substrings
-- | /O(1)/ 'take' @n@, applied to a ByteString @xs@, returns the prefix
-- of @xs@ of length @n@, or @xs@ itself if @n > 'length' xs@.
take :: Int -> ByteString -> ByteString
take n ps@(PS x s l)
| n <= 0 = empty
| n >= l = ps
| otherwise = PS x s n
{-# INLINE take #-}
-- | /O(1)/ 'drop' @n xs@ returns the suffix of @xs@ after the first @n@
-- elements, or @[]@ if @n > 'length' xs@.
drop :: Int -> ByteString -> ByteString
drop n ps@(PS x s l)
| n <= 0 = ps
| n >= l = empty
| otherwise = PS x (s+n) (l-n)
{-# INLINE drop #-}
-- | /O(1)/ 'splitAt' @n xs@ is equivalent to @('take' n xs, 'drop' n xs)@.
splitAt :: Int -> ByteString -> (ByteString, ByteString)
splitAt n ps@(PS x s l)
| n <= 0 = (empty, ps)
| n >= l = (ps, empty)
| otherwise = (PS x s n, PS x (s+n) (l-n))
{-# INLINE splitAt #-}
-- | 'takeWhile', applied to a predicate @p@ and a ByteString @xs@,
-- returns the longest prefix (possibly empty) of @xs@ of elements that
-- satisfy @p@.
takeWhile :: (Word8 -> Bool) -> ByteString -> ByteString
takeWhile f ps = unsafeTake (findIndexOrEnd (not . f) ps) ps
{-# INLINE takeWhile #-}
-- | 'dropWhile' @p xs@ returns the suffix remaining after 'takeWhile' @p xs@.
dropWhile :: (Word8 -> Bool) -> ByteString -> ByteString
dropWhile f ps = unsafeDrop (findIndexOrEnd (not . f) ps) ps
{-# INLINE dropWhile #-}
-- instead of findIndexOrEnd, we could use memchr here.
-- | 'break' @p@ is equivalent to @'span' ('not' . p)@.
--
-- Under GHC, a rewrite rule will transform break (==) into a
-- call to the specialised breakByte:
--
-- > break ((==) x) = breakByte x
-- > break (==x) = breakByte x
--
break :: (Word8 -> Bool) -> ByteString -> (ByteString, ByteString)
break p ps = case findIndexOrEnd p ps of n -> (unsafeTake n ps, unsafeDrop n ps)
#if __GLASGOW_HASKELL__
{-# INLINE [1] break #-}
#endif
#if __GLASGOW_HASKELL__ >= 606
-- This RULE LHS is not allowed by ghc-6.4
{-# RULES
"ByteString specialise break (x==)" forall x.
break ((==) x) = breakByte x
"ByteString specialise break (==x)" forall x.
break (==x) = breakByte x
#-}
#endif
-- INTERNAL:
-- | 'breakByte' breaks its ByteString argument at the first occurence
-- of the specified byte. It is more efficient than 'break' as it is
-- implemented with @memchr(3)@. I.e.
--
-- > break (=='c') "abcd" == breakByte 'c' "abcd"
--
breakByte :: Word8 -> ByteString -> (ByteString, ByteString)
breakByte c p = case elemIndex c p of
Nothing -> (p,empty)
Just n -> (unsafeTake n p, unsafeDrop n p)
{-# INLINE breakByte #-}
-- | 'breakEnd' behaves like 'break' but from the end of the 'ByteString'
--
-- breakEnd p == spanEnd (not.p)
breakEnd :: (Word8 -> Bool) -> ByteString -> (ByteString, ByteString)
breakEnd p ps = splitAt (findFromEndUntil p ps) ps
-- | 'span' @p xs@ breaks the ByteString into two segments. It is
-- equivalent to @('takeWhile' p xs, 'dropWhile' p xs)@
span :: (Word8 -> Bool) -> ByteString -> (ByteString, ByteString)
span p ps = break (not . p) ps
#if __GLASGOW_HASKELL__
{-# INLINE [1] span #-}
#endif
-- | 'spanByte' breaks its ByteString argument at the first
-- occurence of a byte other than its argument. It is more efficient
-- than 'span (==)'
--
-- > span (=='c') "abcd" == spanByte 'c' "abcd"
--
spanByte :: Word8 -> ByteString -> (ByteString, ByteString)
spanByte c ps@(PS x s l) = inlinePerformIO $ withForeignPtr x $ \p ->
go (p `plusPtr` s) 0
where
STRICT2(go)
go p i | i >= l = return (ps, empty)
| otherwise = do c' <- peekByteOff p i
if c /= c'
then return (unsafeTake i ps, unsafeDrop i ps)
else go p (i+1)
{-# INLINE spanByte #-}
#if __GLASGOW_HASKELL__ >= 606
-- This RULE LHS is not allowed by ghc-6.4
{-# RULES
"ByteString specialise span (x==)" forall x.
span ((==) x) = spanByte x
"ByteString specialise span (==x)" forall x.
span (==x) = spanByte x
#-}
#endif
-- | 'spanEnd' behaves like 'span' but from the end of the 'ByteString'.
-- We have
--
-- > spanEnd (not.isSpace) "x y z" == ("x y ","z")
--
-- and
--
-- > spanEnd (not . isSpace) ps
-- > ==
-- > let (x,y) = span (not.isSpace) (reverse ps) in (reverse y, reverse x)
--
spanEnd :: (Word8 -> Bool) -> ByteString -> (ByteString, ByteString)
spanEnd p ps = splitAt (findFromEndUntil (not.p) ps) ps
-- | /O(n)/ Splits a 'ByteString' into components delimited by
-- separators, where the predicate returns True for a separator element.
-- The resulting components do not contain the separators. Two adjacent
-- separators result in an empty component in the output. eg.
--
-- > splitWith (=='a') "aabbaca" == ["","","bb","c",""]
-- > splitWith (=='a') [] == []
--
splitWith :: (Word8 -> Bool) -> ByteString -> [ByteString]
#if defined(__GLASGOW_HASKELL__)
splitWith _pred (PS _ _ 0) = []
splitWith pred_ (PS fp off len) = splitWith0 pred# off len fp
where pred# c# = pred_ (W8# c#)
STRICT4(splitWith0)
splitWith0 pred' off' len' fp' = withPtr fp $ \p ->
splitLoop pred' p 0 off' len' fp'
splitLoop :: (Word# -> Bool)
-> Ptr Word8
-> Int -> Int -> Int
-> ForeignPtr Word8
-> IO [ByteString]
splitLoop pred' p idx' off' len' fp'
| idx' >= len' = return [PS fp' off' idx']
| otherwise = do
w <- peekElemOff p (off'+idx')
if pred' (case w of W8# w# -> w#)
then return (PS fp' off' idx' :
splitWith0 pred' (off'+idx'+1) (len'-idx'-1) fp')
else splitLoop pred' p (idx'+1) off' len' fp'
{-# INLINE splitWith #-}
#else
splitWith _ (PS _ _ 0) = []
splitWith p ps = loop p ps
where
STRICT2(loop)
loop q qs = if null rest then [chunk]
else chunk : loop q (unsafeTail rest)
where (chunk,rest) = break q qs
#endif
-- | /O(n)/ Break a 'ByteString' into pieces separated by the byte
-- argument, consuming the delimiter. I.e.
--
-- > split '\n' "a\nb\nd\ne" == ["a","b","d","e"]
-- > split 'a' "aXaXaXa" == ["","X","X","X",""]
-- > split 'x' "x" == ["",""]
--
-- and
--
-- > intercalate [c] . split c == id
-- > split == splitWith . (==)
--
-- As for all splitting functions in this library, this function does
-- not copy the substrings, it just constructs new 'ByteStrings' that
-- are slices of the original.
--
split :: Word8 -> ByteString -> [ByteString]
split _ (PS _ _ 0) = []
split w (PS x s l) = loop 0
where
STRICT1(loop)
loop n =
let q = inlinePerformIO $ withForeignPtr x $ \p ->
memchr (p `plusPtr` (s+n))
w (fromIntegral (l-n))
in if q == nullPtr
then [PS x (s+n) (l-n)]
else let i = inlinePerformIO $ withForeignPtr x $ \p ->
return (q `minusPtr` (p `plusPtr` s))
in PS x (s+n) (i-n) : loop (i+1)
{-# INLINE split #-}
{-
-- slower. but stays inside Haskell.
split _ (PS _ _ 0) = []
split (W8# w#) (PS fp off len) = splitWith' off len fp
where
splitWith' off' len' fp' = withPtr fp $ \p ->
splitLoop p 0 off' len' fp'
splitLoop :: Ptr Word8
-> Int -> Int -> Int
-> ForeignPtr Word8
-> IO [ByteString]
STRICT5(splitLoop)
splitLoop p idx' off' len' fp'
| idx' >= len' = return [PS fp' off' idx']
| otherwise = do
(W8# x#) <- peekElemOff p (off'+idx')
if word2Int# w# ==# word2Int# x#
then return (PS fp' off' idx' :
splitWith' (off'+idx'+1) (len'-idx'-1) fp')
else splitLoop p (idx'+1) off' len' fp'
-}
{-
-- | Like 'splitWith', except that sequences of adjacent separators are
-- treated as a single separator. eg.
--
-- > tokens (=='a') "aabbaca" == ["bb","c"]
--
tokens :: (Word8 -> Bool) -> ByteString -> [ByteString]
tokens f = P.filter (not.null) . splitWith f
{-# INLINE tokens #-}
-}
-- | The 'group' function takes a ByteString and returns a list of
-- ByteStrings such that the concatenation of the result is equal to the
-- argument. Moreover, each sublist in the result contains only equal
-- elements. For example,
--
-- > group "Mississippi" = ["M","i","ss","i","ss","i","pp","i"]
--
-- It is a special case of 'groupBy', which allows the programmer to
-- supply their own equality test. It is about 40% faster than
-- /groupBy (==)/
group :: ByteString -> [ByteString]
group xs
| null xs = []
| otherwise = ys : group zs
where
(ys, zs) = spanByte (unsafeHead xs) xs
-- | The 'groupBy' function is the non-overloaded version of 'group'.
groupBy :: (Word8 -> Word8 -> Bool) -> ByteString -> [ByteString]
groupBy k xs
| null xs = []
| otherwise = unsafeTake n xs : groupBy k (unsafeDrop n xs)
where
n = 1 + findIndexOrEnd (not . k (unsafeHead xs)) (unsafeTail xs)
-- | /O(n)/ The 'intercalate' function takes a 'ByteString' and a list of
-- 'ByteString's and concatenates the list after interspersing the first
-- argument between each element of the list.
intercalate :: ByteString -> [ByteString] -> ByteString
intercalate s = concat . (List.intersperse s)
{-# INLINE [1] intercalate #-}
{-# RULES
"ByteString specialise intercalate c -> intercalateByte" forall c s1 s2 .
intercalate (singleton c) (s1 : s2 : []) = intercalateWithByte c s1 s2
#-}
-- | /O(n)/ intercalateWithByte. An efficient way to join to two ByteStrings
-- with a char. Around 4 times faster than the generalised join.
--
intercalateWithByte :: Word8 -> ByteString -> ByteString -> ByteString
intercalateWithByte c f@(PS ffp s l) g@(PS fgp t m) = unsafeCreate len $ \ptr ->
withForeignPtr ffp $ \fp ->
withForeignPtr fgp $ \gp -> do
memcpy ptr (fp `plusPtr` s) (fromIntegral l)
poke (ptr `plusPtr` l) c
memcpy (ptr `plusPtr` (l + 1)) (gp `plusPtr` t) (fromIntegral m)
where
len = length f + length g + 1
{-# INLINE intercalateWithByte #-}
-- ---------------------------------------------------------------------
-- Indexing ByteStrings
-- | /O(1)/ 'ByteString' index (subscript) operator, starting from 0.
index :: ByteString -> Int -> Word8
index ps n
| n < 0 = moduleError "index" ("negative index: " ++ show n)
| n >= length ps = moduleError "index" ("index too large: " ++ show n
++ ", length = " ++ show (length ps))
| otherwise = ps `unsafeIndex` n
{-# INLINE index #-}
-- | /O(n)/ The 'elemIndex' function returns the index of the first
-- element in the given 'ByteString' which is equal to the query
-- element, or 'Nothing' if there is no such element.
-- This implementation uses memchr(3).
elemIndex :: Word8 -> ByteString -> Maybe Int
elemIndex c (PS x s l) = inlinePerformIO $ withForeignPtr x $ \p -> do
let p' = p `plusPtr` s
q <- memchr p' c (fromIntegral l)
return $! if q == nullPtr then Nothing else Just $! q `minusPtr` p'
{-# INLINE elemIndex #-}
-- | /O(n)/ The 'elemIndexEnd' function returns the last index of the
-- element in the given 'ByteString' which is equal to the query
-- element, or 'Nothing' if there is no such element. The following
-- holds:
--
-- > elemIndexEnd c xs ==
-- > (-) (length xs - 1) `fmap` elemIndex c (reverse xs)
--
elemIndexEnd :: Word8 -> ByteString -> Maybe Int
elemIndexEnd ch (PS x s l) = inlinePerformIO $ withForeignPtr x $ \p ->
go (p `plusPtr` s) (l-1)
where
STRICT2(go)
go p i | i < 0 = return Nothing
| otherwise = do ch' <- peekByteOff p i
if ch == ch'
then return $ Just i
else go p (i-1)
{-# INLINE elemIndexEnd #-}
-- | /O(n)/ The 'elemIndices' function extends 'elemIndex', by returning
-- the indices of all elements equal to the query element, in ascending order.
-- This implementation uses memchr(3).
elemIndices :: Word8 -> ByteString -> [Int]
elemIndices w (PS x s l) = loop 0
where
STRICT1(loop)
loop n = let q = inlinePerformIO $ withForeignPtr x $ \p ->
memchr (p `plusPtr` (n+s))
w (fromIntegral (l - n))
in if q == nullPtr
then []
else let i = inlinePerformIO $ withForeignPtr x $ \p ->
return (q `minusPtr` (p `plusPtr` s))
in i : loop (i+1)
{-# INLINE elemIndices #-}
{-
-- much slower
elemIndices :: Word8 -> ByteString -> [Int]
elemIndices c ps = loop 0 ps
where STRICT2(loop)
loop _ ps' | null ps' = []
loop n ps' | c == unsafeHead ps' = n : loop (n+1) (unsafeTail ps')
| otherwise = loop (n+1) (unsafeTail ps')
-}
-- | count returns the number of times its argument appears in the ByteString
--
-- > count = length . elemIndices
--
-- But more efficiently than using length on the intermediate list.
count :: Word8 -> ByteString -> Int
count w (PS x s m) = inlinePerformIO $ withForeignPtr x $ \p ->
fmap fromIntegral $ c_count (p `plusPtr` s) (fromIntegral m) w
{-# INLINE count #-}
{-
--
-- around 30% slower
--
count w (PS x s m) = inlinePerformIO $ withForeignPtr x $ \p ->
go (p `plusPtr` s) (fromIntegral m) 0
where
go :: Ptr Word8 -> CSize -> Int -> IO Int
STRICT3(go)
go p l i = do
q <- memchr p w l
if q == nullPtr
then return i
else do let k = fromIntegral $ q `minusPtr` p
go (q `plusPtr` 1) (l-k-1) (i+1)
-}
-- | The 'findIndex' function takes a predicate and a 'ByteString' and
-- returns the index of the first element in the ByteString
-- satisfying the predicate.
findIndex :: (Word8 -> Bool) -> ByteString -> Maybe Int
findIndex k (PS x s l) = inlinePerformIO $ withForeignPtr x $ \f -> go (f `plusPtr` s) 0
where
STRICT2(go)
go ptr n | n >= l = return Nothing
| otherwise = do w <- peek ptr
if k w
then return (Just n)
else go (ptr `plusPtr` 1) (n+1)
{-# INLINE findIndex #-}
-- | The 'findIndices' function extends 'findIndex', by returning the
-- indices of all elements satisfying the predicate, in ascending order.
findIndices :: (Word8 -> Bool) -> ByteString -> [Int]
findIndices p ps = loop 0 ps
where
STRICT2(loop)
loop n qs | null qs = []
| p (unsafeHead qs) = n : loop (n+1) (unsafeTail qs)
| otherwise = loop (n+1) (unsafeTail qs)
-- ---------------------------------------------------------------------
-- Searching ByteStrings
-- | /O(n)/ 'elem' is the 'ByteString' membership predicate.
elem :: Word8 -> ByteString -> Bool
elem c ps = case elemIndex c ps of Nothing -> False ; _ -> True
{-# INLINE elem #-}
-- | /O(n)/ 'notElem' is the inverse of 'elem'
notElem :: Word8 -> ByteString -> Bool
notElem c ps = not (elem c ps)
{-# INLINE notElem #-}
-- | /O(n)/ 'filter', applied to a predicate and a ByteString,
-- returns a ByteString containing those characters that satisfy the
-- predicate. This function is subject to array fusion.
filter :: (Word8 -> Bool) -> ByteString -> ByteString
filter k ps@(PS x s l)
| null ps = ps
| otherwise = unsafePerformIO $ createAndTrim l $ \p -> withForeignPtr x $ \f -> do
t <- go (f `plusPtr` s) p (f `plusPtr` (s + l))
return $! t `minusPtr` p -- actual length
where
STRICT3(go)
go f t end | f == end = return t
| otherwise = do
w <- peek f
if k w
then poke t w >> go (f `plusPtr` 1) (t `plusPtr` 1) end
else go (f `plusPtr` 1) t end
{-# INLINE filter #-}
{-
--
-- | /O(n)/ A first order equivalent of /filter . (==)/, for the common
-- case of filtering a single byte. It is more efficient to use
-- /filterByte/ in this case.
--
-- > filterByte == filter . (==)
--
-- filterByte is around 10x faster, and uses much less space, than its
-- filter equivalent
--
filterByte :: Word8 -> ByteString -> ByteString
filterByte w ps = replicate (count w ps) w
{-# INLINE filterByte #-}
{-# RULES
"ByteString specialise filter (== x)" forall x.
filter ((==) x) = filterByte x
"ByteString specialise filter (== x)" forall x.
filter (== x) = filterByte x
#-}
-}
-- | /O(n)/ The 'find' function takes a predicate and a ByteString,
-- and returns the first element in matching the predicate, or 'Nothing'
-- if there is no such element.
--
-- > find f p = case findIndex f p of Just n -> Just (p ! n) ; _ -> Nothing
--
find :: (Word8 -> Bool) -> ByteString -> Maybe Word8
find f p = case findIndex f p of
Just n -> Just (p `unsafeIndex` n)
_ -> Nothing
{-# INLINE find #-}
{-
--
-- fuseable, but we don't want to walk the whole array.
--
find k = foldl findEFL Nothing
where findEFL a@(Just _) _ = a
findEFL _ c | k c = Just c
| otherwise = Nothing
-}
-- | /O(n)/ The 'partition' function takes a predicate a ByteString and returns
-- the pair of ByteStrings with elements which do and do not satisfy the
-- predicate, respectively; i.e.,
--
-- > partition p bs == (filter p xs, filter (not . p) xs)
--
partition :: (Word8 -> Bool) -> ByteString -> (ByteString, ByteString)
partition p bs = (filter p bs, filter (not . p) bs)
--TODO: use a better implementation
-- ---------------------------------------------------------------------
-- Searching for substrings
-- | /O(n)/ The 'isPrefixOf' function takes two ByteStrings and returns 'True'
-- iff the first is a prefix of the second.
isPrefixOf :: ByteString -> ByteString -> Bool
isPrefixOf (PS x1 s1 l1) (PS x2 s2 l2)
| l1 == 0 = True
| l2 < l1 = False
| otherwise = inlinePerformIO $ withForeignPtr x1 $ \p1 ->
withForeignPtr x2 $ \p2 -> do
i <- memcmp (p1 `plusPtr` s1) (p2 `plusPtr` s2) (fromIntegral l1)
return $! i == 0
-- | /O(n)/ The 'isSuffixOf' function takes two ByteStrings and returns 'True'
-- iff the first is a suffix of the second.
--
-- The following holds:
--
-- > isSuffixOf x y == reverse x `isPrefixOf` reverse y
--
-- However, the real implemenation uses memcmp to compare the end of the
-- string only, with no reverse required..
isSuffixOf :: ByteString -> ByteString -> Bool
isSuffixOf (PS x1 s1 l1) (PS x2 s2 l2)
| l1 == 0 = True
| l2 < l1 = False
| otherwise = inlinePerformIO $ withForeignPtr x1 $ \p1 ->
withForeignPtr x2 $ \p2 -> do
i <- memcmp (p1 `plusPtr` s1) (p2 `plusPtr` s2 `plusPtr` (l2 - l1)) (fromIntegral l1)
return $! i == 0
-- | Check whether one string is a substring of another. @isInfixOf
-- p s@ is equivalent to @not (null (findSubstrings p s))@.
isInfixOf :: ByteString -> ByteString -> Bool
isInfixOf p s = isJust (findSubstring p s)
-- | Break a string on a substring, returning a pair of the part of the
-- string prior to the match, and the rest of the string.
--
-- The following relationships hold:
--
-- > break (== c) l == breakSubstring (singleton c) l
--
-- and:
--
-- > findSubstring s l ==
-- > if null s then Just 0
-- > else case breakSubstring s l of
-- > (x,y) | null y -> Nothing
-- > | otherwise -> Just (length x)
--
-- For example, to tokenise a string, dropping delimiters:
--
-- > tokenise x y = h : if null t then [] else tokenise x (drop (length x) t)
-- > where (h,t) = breakSubstring x y
--
-- To skip to the first occurence of a string:
--
-- > snd (breakSubstring x y)
--
-- To take the parts of a string before a delimiter:
--
-- > fst (breakSubstring x y)
--
breakSubstring :: ByteString -- ^ String to search for
-> ByteString -- ^ String to search in
-> (ByteString,ByteString) -- ^ Head and tail of string broken at substring
breakSubstring pat src = search 0 src
where
STRICT2(search)
search n s
| null s = (src,empty) -- not found
| pat `isPrefixOf` s = (take n src,s)
| otherwise = search (n+1) (unsafeTail s)
-- | Get the first index of a substring in another string,
-- or 'Nothing' if the string is not found.
-- @findSubstring p s@ is equivalent to @listToMaybe (findSubstrings p s)@.
findSubstring :: ByteString -- ^ String to search for.
-> ByteString -- ^ String to seach in.
-> Maybe Int
findSubstring f i = listToMaybe (findSubstrings f i)
{-# DEPRECATED findSubstring "findSubstring is deprecated in favour of breakSubstring." #-}
{-
findSubstring pat str = search 0 str
where
STRICT2(search)
search n s
= let x = pat `isPrefixOf` s
in
if null s
then if x then Just n else Nothing
else if x then Just n
else search (n+1) (unsafeTail s)
-}
-- | Find the indexes of all (possibly overlapping) occurances of a
-- substring in a string.
--
findSubstrings :: ByteString -- ^ String to search for.
-> ByteString -- ^ String to seach in.
-> [Int]
findSubstrings pat str
| null pat = [0 .. length str]
| otherwise = search 0 str
where
STRICT2(search)
search n s
| null s = []
| pat `isPrefixOf` s = n : search (n+1) (unsafeTail s)
| otherwise = search (n+1) (unsafeTail s)
{-# DEPRECATED findSubstrings "findSubstrings is deprecated in favour of breakSubstring." #-}
{-
{- This function uses the Knuth-Morris-Pratt string matching algorithm. -}
findSubstrings pat@(PS _ _ m) str@(PS _ _ n) = search 0 0
where
patc x = pat `unsafeIndex` x
strc x = str `unsafeIndex` x
-- maybe we should make kmpNext a UArray before using it in search?
kmpNext = listArray (0,m) (-1:kmpNextL pat (-1))
kmpNextL p _ | null p = []
kmpNextL p j = let j' = next (unsafeHead p) j + 1
ps = unsafeTail p
x = if not (null ps) && unsafeHead ps == patc j'
then kmpNext Array.! j' else j'
in x:kmpNextL ps j'
search i j = match ++ rest -- i: position in string, j: position in pattern
where match = if j == m then [(i - j)] else []
rest = if i == n then [] else search (i+1) (next (strc i) j + 1)
next c j | j >= 0 && (j == m || c /= patc j) = next c (kmpNext Array.! j)
| otherwise = j
-}
-- ---------------------------------------------------------------------
-- Zipping
-- | /O(n)/ 'zip' takes two ByteStrings and returns a list of
-- corresponding pairs of bytes. If one input ByteString is short,
-- excess elements of the longer ByteString are discarded. This is
-- equivalent to a pair of 'unpack' operations.
zip :: ByteString -> ByteString -> [(Word8,Word8)]
zip ps qs
| null ps || null qs = []
| otherwise = (unsafeHead ps, unsafeHead qs) : zip (unsafeTail ps) (unsafeTail qs)
-- | 'zipWith' generalises 'zip' by zipping with the function given as
-- the first argument, instead of a tupling function. For example,
-- @'zipWith' (+)@ is applied to two ByteStrings to produce the list of
-- corresponding sums.
zipWith :: (Word8 -> Word8 -> a) -> ByteString -> ByteString -> [a]
zipWith f ps qs
| null ps || null qs = []
| otherwise = f (unsafeHead ps) (unsafeHead qs) : zipWith f (unsafeTail ps) (unsafeTail qs)
--
-- | A specialised version of zipWith for the common case of a
-- simultaneous map over two bytestrings, to build a 3rd. Rewrite rules
-- are used to automatically covert zipWith into zipWith' when a pack is
-- performed on the result of zipWith.
--
zipWith' :: (Word8 -> Word8 -> Word8) -> ByteString -> ByteString -> ByteString
zipWith' f (PS fp s l) (PS fq t m) = inlinePerformIO $
withForeignPtr fp $ \a ->
withForeignPtr fq $ \b ->
create len $ zipWith_ 0 (a `plusPtr` s) (b `plusPtr` t)
where
zipWith_ :: Int -> Ptr Word8 -> Ptr Word8 -> Ptr Word8 -> IO ()
STRICT4(zipWith_)
zipWith_ n p1 p2 r
| n >= len = return ()
| otherwise = do
x <- peekByteOff p1 n
y <- peekByteOff p2 n
pokeByteOff r n (f x y)
zipWith_ (n+1) p1 p2 r
len = min l m
{-# INLINE zipWith' #-}
{-# RULES
"ByteString specialise zipWith" forall (f :: Word8 -> Word8 -> Word8) p q .
zipWith f p q = unpack (zipWith' f p q)
#-}
-- | /O(n)/ 'unzip' transforms a list of pairs of bytes into a pair of
-- ByteStrings. Note that this performs two 'pack' operations.
unzip :: [(Word8,Word8)] -> (ByteString,ByteString)
unzip ls = (pack (P.map fst ls), pack (P.map snd ls))
{-# INLINE unzip #-}
-- ---------------------------------------------------------------------
-- Special lists
-- | /O(n)/ Return all initial segments of the given 'ByteString', shortest first.
inits :: ByteString -> [ByteString]
inits (PS x s l) = [PS x s n | n <- [0..l]]
-- | /O(n)/ Return all final segments of the given 'ByteString', longest first.
tails :: ByteString -> [ByteString]
tails p | null p = [empty]
| otherwise = p : tails (unsafeTail p)
-- less efficent spacewise: tails (PS x s l) = [PS x (s+n) (l-n) | n <- [0..l]]
-- ---------------------------------------------------------------------
-- ** Ordered 'ByteString's
-- | /O(n)/ Sort a ByteString efficiently, using counting sort.
sort :: ByteString -> ByteString
sort (PS input s l) = unsafeCreate l $ \p -> allocaArray 256 $ \arr -> do
_ <- memset (castPtr arr) 0 (256 * fromIntegral (sizeOf (undefined :: CSize)))
withForeignPtr input (\x -> countOccurrences arr (x `plusPtr` s) l)
let STRICT2(go)
go 256 _ = return ()
go i ptr = do n <- peekElemOff arr i
when (n /= 0) $ memset ptr (fromIntegral i) n >> return ()
go (i + 1) (ptr `plusPtr` (fromIntegral n))
go 0 p
where
-- | Count the number of occurrences of each byte.
-- Used by 'sort'
--
countOccurrences :: Ptr CSize -> Ptr Word8 -> Int -> IO ()
STRICT3(countOccurrences)
countOccurrences counts str len = go 0
where
STRICT1(go)
go i | i == len = return ()
| otherwise = do k <- fromIntegral `fmap` peekElemOff str i
x <- peekElemOff counts k
pokeElemOff counts k (x + 1)
go (i + 1)
{-
sort :: ByteString -> ByteString
sort (PS x s l) = unsafeCreate l $ \p -> withForeignPtr x $ \f -> do
memcpy p (f `plusPtr` s) l
c_qsort p l -- inplace
-}
-- The 'sortBy' function is the non-overloaded version of 'sort'.
--
-- Try some linear sorts: radix, counting
-- Or mergesort.
--
-- sortBy :: (Word8 -> Word8 -> Ordering) -> ByteString -> ByteString
-- sortBy f ps = undefined
-- ---------------------------------------------------------------------
-- Low level constructors
-- | /O(n) construction/ Use a @ByteString@ with a function requiring a
-- null-terminated @CString@. The @CString@ will be freed
-- automatically. This is a memcpy(3).
useAsCString :: ByteString -> (CString -> IO a) -> IO a
useAsCString (PS fp o l) action = do
allocaBytes (l+1) $ \buf ->
withForeignPtr fp $ \p -> do
memcpy buf (p `plusPtr` o) (fromIntegral l)
pokeByteOff buf l (0::Word8)
action (castPtr buf)
-- | /O(n) construction/ Use a @ByteString@ with a function requiring a @CStringLen@.
-- As for @useAsCString@ this function makes a copy of the original @ByteString@.
useAsCStringLen :: ByteString -> (CStringLen -> IO a) -> IO a
useAsCStringLen p@(PS _ _ l) f = useAsCString p $ \cstr -> f (cstr,l)
------------------------------------------------------------------------
-- | /O(n)./ Construct a new @ByteString@ from a @CString@. The
-- resulting @ByteString@ is an immutable copy of the original
-- @CString@, and is managed on the Haskell heap. The original
-- @CString@ must be null terminated.
packCString :: CString -> IO ByteString
packCString cstr = do
len <- c_strlen cstr
packCStringLen (cstr, fromIntegral len)
-- | /O(n)./ Construct a new @ByteString@ from a @CStringLen@. The
-- resulting @ByteString@ is an immutable copy of the original @CStringLen@.
-- The @ByteString@ is a normal Haskell value and will be managed on the
-- Haskell heap.
packCStringLen :: CStringLen -> IO ByteString
packCStringLen (cstr, len) | len >= 0 = create len $ \p ->
memcpy p (castPtr cstr) (fromIntegral len)
packCStringLen (_, len) =
moduleError "packCStringLen" ("negative length: " ++ show len)
------------------------------------------------------------------------
-- | /O(n)/ Make a copy of the 'ByteString' with its own storage.
-- This is mainly useful to allow the rest of the data pointed
-- to by the 'ByteString' to be garbage collected, for example
-- if a large string has been read in, and only a small part of it
-- is needed in the rest of the program.
--
copy :: ByteString -> ByteString
copy (PS x s l) = unsafeCreate l $ \p -> withForeignPtr x $ \f ->
memcpy p (f `plusPtr` s) (fromIntegral l)
-- ---------------------------------------------------------------------
-- Line IO
-- | Read a line from stdin.
getLine :: IO ByteString
getLine = hGetLine stdin
-- | Read a line from a handle
hGetLine :: Handle -> IO ByteString
#if !defined(__GLASGOW_HASKELL__)
hGetLine h = System.IO.hGetLine h >>= return . pack . P.map c2w
#elif __GLASGOW_HASKELL__ >= 611
hGetLine h =
wantReadableHandle_ "Data.ByteString.hGetLine" h $
\ h_@Handle__{haByteBuffer} -> do
flushCharReadBuffer h_
buf <- readIORef haByteBuffer
if isEmptyBuffer buf
then fill h_ buf 0 []
else haveBuf h_ buf 0 []
where
fill h_@Handle__{haByteBuffer,haDevice} buf len xss =
len `seq` do
(r,buf') <- Buffered.fillReadBuffer haDevice buf
if r == 0
then do writeIORef haByteBuffer buf{ bufR=0, bufL=0 }
if len > 0
then mkBigPS len xss
else ioe_EOF
else haveBuf h_ buf' len xss
haveBuf h_@Handle__{haByteBuffer}
buf@Buffer{ bufRaw=raw, bufR=w, bufL=r }
len xss =
do
off <- findEOL r w raw
let new_len = len + off - r
xs <- mkPS raw r off
-- if eol == True, then off is the offset of the '\n'
-- otherwise off == w and the buffer is now empty.
if off /= w
then do if (w == off + 1)
then writeIORef haByteBuffer buf{ bufL=0, bufR=0 }
else writeIORef haByteBuffer buf{ bufL = off + 1 }
mkBigPS new_len (xs:xss)
else do
fill h_ buf{ bufL=0, bufR=0 } new_len (xs:xss)
-- find the end-of-line character, if there is one
findEOL r w raw
| r == w = return w
| otherwise = do
c <- readWord8Buf raw r
if c == fromIntegral (ord '\n')
then return r -- NB. not r+1: don't include the '\n'
else findEOL (r+1) w raw
mkPS :: RawBuffer Word8 -> Int -> Int -> IO ByteString
mkPS buf start end =
create len $ \p ->
withRawBuffer buf $ \pbuf -> do
copyBytes p (pbuf `plusPtr` start) len
where
len = end - start
#else
-- GHC 6.10 and older, pre-Unicode IO library
hGetLine h = wantReadableHandle "Data.ByteString.hGetLine" h $ \ handle_ -> do
case haBufferMode handle_ of
NoBuffering -> error "no buffering"
_other -> hGetLineBuffered handle_
where
hGetLineBuffered handle_ = do
let ref = haBuffer handle_
buf <- readIORef ref
hGetLineBufferedLoop handle_ ref buf 0 []
hGetLineBufferedLoop handle_ ref
buf@Buffer{ bufRPtr=r, bufWPtr=w, bufBuf=raw } len xss =
len `seq` do
off <- findEOL r w raw
let new_len = len + off - r
xs <- mkPS raw r off
-- if eol == True, then off is the offset of the '\n'
-- otherwise off == w and the buffer is now empty.
if off /= w
then do if (w == off + 1)
then writeIORef ref buf{ bufRPtr=0, bufWPtr=0 }
else writeIORef ref buf{ bufRPtr = off + 1 }
mkBigPS new_len (xs:xss)
else do
maybe_buf <- maybeFillReadBuffer (haFD handle_) True (haIsStream handle_)
buf{ bufWPtr=0, bufRPtr=0 }
case maybe_buf of
-- Nothing indicates we caught an EOF, and we may have a
-- partial line to return.
Nothing -> do
writeIORef ref buf{ bufRPtr=0, bufWPtr=0 }
if new_len > 0
then mkBigPS new_len (xs:xss)
else ioe_EOF
Just new_buf ->
hGetLineBufferedLoop handle_ ref new_buf new_len (xs:xss)
-- find the end-of-line character, if there is one
findEOL r w raw
| r == w = return w
| otherwise = do
(c,r') <- readCharFromBuffer raw r
if c == '\n'
then return r -- NB. not r': don't include the '\n'
else findEOL r' w raw
maybeFillReadBuffer fd is_line is_stream buf = catch
(do buf' <- fillReadBuffer fd is_line is_stream buf
return (Just buf'))
(\e -> if isEOFError e then return Nothing else ioError e)
-- TODO, rewrite to use normal memcpy
mkPS :: RawBuffer -> Int -> Int -> IO ByteString
mkPS buf start end =
let len = end - start
in create len $ \p -> do
memcpy_ptr_baoff p buf (fromIntegral start) (fromIntegral len)
return ()
#endif
mkBigPS :: Int -> [ByteString] -> IO ByteString
mkBigPS _ [ps] = return ps
mkBigPS _ pss = return $! concat (P.reverse pss)
-- ---------------------------------------------------------------------
-- Block IO
-- | Outputs a 'ByteString' to the specified 'Handle'.
hPut :: Handle -> ByteString -> IO ()
hPut _ (PS _ _ 0) = return ()
hPut h (PS ps s l) = withForeignPtr ps $ \p-> hPutBuf h (p `plusPtr` s) l
-- | A synonym for @hPut@, for compatibility
hPutStr :: Handle -> ByteString -> IO ()
hPutStr = hPut
-- | Write a ByteString to a handle, appending a newline byte
hPutStrLn :: Handle -> ByteString -> IO ()
hPutStrLn h ps
| length ps < 1024 = hPut h (ps `snoc` 0x0a)
| otherwise = hPut h ps >> hPut h (singleton (0x0a)) -- don't copy
-- | Write a ByteString to stdout
putStr :: ByteString -> IO ()
putStr = hPut stdout
-- | Write a ByteString to stdout, appending a newline byte
putStrLn :: ByteString -> IO ()
putStrLn = hPutStrLn stdout
------------------------------------------------------------------------
-- Low level IO
-- | Read a 'ByteString' directly from the specified 'Handle'. This
-- is far more efficient than reading the characters into a 'String'
-- and then using 'pack'. First argument is the Handle to read from,
-- and the second is the number of bytes to read. It returns the bytes
-- read, up to n, or 'null' if EOF has been reached.
--
-- 'hGet' is implemented in terms of 'hGetBuf'.
--
-- If the handle is a pipe or socket, and the writing end
-- is closed, 'hGet' will behave as if EOF was reached.
--
hGet :: Handle -> Int -> IO ByteString
hGet h i
| i > 0 = createAndTrim i $ \p -> hGetBuf h p i
| i == 0 = return empty
| otherwise = illegalBufferSize h "hGet" i
-- | hGetNonBlocking is identical to 'hGet', except that it will never
-- block waiting for data to become available. If there is no data
-- available to be read, 'hGetNonBlocking' returns 'null'.
--
hGetNonBlocking :: Handle -> Int -> IO ByteString
#if defined(__GLASGOW_HASKELL__)
hGetNonBlocking h i
| i > 0 = createAndTrim i $ \p -> hGetBufNonBlocking h p i
| i == 0 = return empty
| otherwise = illegalBufferSize h "hGetNonBlocking" i
#else
hGetNonBlocking = hGet
#endif
-- | Like 'hGet', except that a shorter 'ByteString' may be returned
-- if there are not enough bytes immediately available to satisfy the
-- whole request. 'hGetSome' only blocks if there is no data
-- available, and EOF has not yet been reached.
--
hGetSome :: Handle -> Int -> IO ByteString
hGetSome hh i
#if MIN_VERSION_base(4,3,0)
| i > 0 = createAndTrim i $ \p -> hGetBufSome hh p i
#else
| i > 0 = let
loop = do
s <- hGetNonBlocking hh i
if not (null s)
then return s
else do eof <- hIsEOF hh
if eof then return s
else hWaitForInput hh (-1) >> loop
-- for this to work correctly, the
-- Handle should be in binary mode
-- (see GHC ticket #3808)
in loop
#endif
| i == 0 = return empty
| otherwise = illegalBufferSize hh "hGetSome" i
illegalBufferSize :: Handle -> String -> Int -> IO a
illegalBufferSize handle fn sz =
ioError (mkIOError illegalOperationErrorType msg (Just handle) Nothing)
--TODO: System.IO uses InvalidArgument here, but it's not exported :-(
where
msg = fn ++ ": illegal ByteString size " ++ showsPrec 9 sz []
-- | Read entire handle contents strictly into a 'ByteString'.
--
-- This function reads chunks at a time, doubling the chunksize on each
-- read. The final buffer is then realloced to the appropriate size. For
-- files > half of available memory, this may lead to memory exhaustion.
-- Consider using 'readFile' in this case.
--
-- As with 'hGet', the string representation in the file is assumed to
-- be ISO-8859-1.
--
-- The Handle is closed once the contents have been read,
-- or if an exception is thrown.
--
hGetContents :: Handle -> IO ByteString
hGetContents h = always (hClose h) $ do -- strict, so hClose
let start_size = 1024
p <- mallocBytes start_size
i <- hGetBuf h p start_size
if i < start_size
then do p' <- reallocBytes p i
fp <- newForeignPtr finalizerFree p'
return $! PS fp 0 i
else f p start_size
where
always = flip finally
f p s = do
let s' = 2 * s
p' <- reallocBytes p s'
i <- hGetBuf h (p' `plusPtr` s) s
if i < s
then do let i' = s + i
p'' <- reallocBytes p' i'
fp <- newForeignPtr finalizerFree p''
return $! PS fp 0 i'
else f p' s'
-- | getContents. Read stdin strictly. Equivalent to hGetContents stdin
-- The 'Handle' is closed after the contents have been read.
--
getContents :: IO ByteString
getContents = hGetContents stdin
-- | The interact function takes a function of type @ByteString -> ByteString@
-- as its argument. The entire input from the standard input device is passed
-- to this function as its argument, and the resulting string is output on the
-- standard output device.
--
interact :: (ByteString -> ByteString) -> IO ()
interact transformer = putStr . transformer =<< getContents
-- | Read an entire file strictly into a 'ByteString'. This is far more
-- efficient than reading the characters into a 'String' and then using
-- 'pack'. It also may be more efficient than opening the file and
-- reading it using hGet. Files are read using 'binary mode' on Windows,
-- for 'text mode' use the Char8 version of this function.
--
readFile :: FilePath -> IO ByteString
readFile f = bracket (openBinaryFile f ReadMode) hClose
(\h -> hFileSize h >>= hGet h . fromIntegral)
-- | Write a 'ByteString' to a file.
writeFile :: FilePath -> ByteString -> IO ()
writeFile f txt = bracket (openBinaryFile f WriteMode) hClose
(\h -> hPut h txt)
-- | Append a 'ByteString' to a file.
appendFile :: FilePath -> ByteString -> IO ()
appendFile f txt = bracket (openBinaryFile f AppendMode) hClose
(\h -> hPut h txt)
-- ---------------------------------------------------------------------
-- Internal utilities
-- | 'findIndexOrEnd' is a variant of findIndex, that returns the length
-- of the string if no element is found, rather than Nothing.
findIndexOrEnd :: (Word8 -> Bool) -> ByteString -> Int
findIndexOrEnd k (PS x s l) = inlinePerformIO $ withForeignPtr x $ \f -> go (f `plusPtr` s) 0
where
STRICT2(go)
go ptr n | n >= l = return l
| otherwise = do w <- peek ptr
if k w
then return n
else go (ptr `plusPtr` 1) (n+1)
{-# INLINE findIndexOrEnd #-}
-- | Perform an operation with a temporary ByteString
withPtr :: ForeignPtr a -> (Ptr a -> IO b) -> b
withPtr fp io = inlinePerformIO (withForeignPtr fp io)
{-# INLINE withPtr #-}
-- Common up near identical calls to `error' to reduce the number
-- constant strings created when compiled:
errorEmptyList :: String -> a
errorEmptyList fun = moduleError fun "empty ByteString"
{-# NOINLINE errorEmptyList #-}
moduleError :: String -> String -> a
moduleError fun msg = error ("Data.ByteString." ++ fun ++ ':':' ':msg)
{-# NOINLINE moduleError #-}
-- Find from the end of the string using predicate
findFromEndUntil :: (Word8 -> Bool) -> ByteString -> Int
STRICT2(findFromEndUntil)
findFromEndUntil f ps@(PS x s l) =
if null ps then 0
else if f (last ps) then l
else findFromEndUntil f (PS x s (l-1))
| markflorisson/hpack | testrepo/bytestring-0.9.1.9/Data/ByteString.hs | bsd-3-clause | 78,702 | 0 | 20 | 23,325 | 13,856 | 7,461 | 6,395 | -1 | -1 |
{-# LANGUAGE MultiParamTypeClasses #-}
-- | A module for documenting Java source files using @javadoc@.
module System.Build.Java.Javadoc
(
Javadoc
-- * @Javadoc@ values
, javadoc
) where
import System.Build.Access.Overview
import System.Build.Access.Public
import System.Build.Access.Protected
import System.Build.Access.Package
import System.Build.Access.Private
import System.Build.Access.Help
import System.Build.Access.Doclet
import System.Build.Access.Docletpath
import System.Build.Access.Sourcepath
import System.Build.Access.Classpath
import System.Build.Access.Exclude
import System.Build.Access.Subpackages
import System.Build.Access.Breakiterator
import System.Build.Access.Bootclasspath
import System.Build.Access.Source
import System.Build.Access.Extdirs
import System.Build.Access.Verbose
import System.Build.Access.Locale
import System.Build.Access.Encoding
import System.Build.Access.Quiet
import System.Build.Access.Flags
import System.Build.Access.Directory
import System.Build.Access.Use
import System.Build.Access.Version
import System.Build.Access.Author
import System.Build.Access.Docfilessubdirs
import System.Build.Access.Splitindex
import System.Build.Access.Windowtitle
import System.Build.Access.Doctitle
import System.Build.Access.Header
import System.Build.Access.Footer
import System.Build.Access.Top
import System.Build.Access.Bottom
import System.Build.Access.Link
import System.Build.Access.Linkoffline
import System.Build.Access.Excludedocfilessubdir
import System.Build.Access.Group
import System.Build.Access.Nocomment
import System.Build.Access.Nodeprecated
import System.Build.Access.Noqualifier
import System.Build.Access.Nosince
import System.Build.Access.Notimestamp
import System.Build.Access.Nodeprecatedlist
import System.Build.Access.Notree
import System.Build.Access.Noindex
import System.Build.Access.Nohelp
import System.Build.Access.Nonavbar
import System.Build.Access.Serialwarn
import System.Build.Access.Tag
import System.Build.Access.Taglet
import System.Build.Access.Tagletpath
import System.Build.Access.Charset
import System.Build.Access.Helpfile
import System.Build.Access.Linksource
import System.Build.Access.Sourcetab
import System.Build.Access.Keywords
import System.Build.Access.Stylesheetfile
import System.Build.Access.Docencoding
import System.Build.Data.SourceRelease
import System.Build.Compile.Options
import System.Build.Compile.Extensions
import System.Build.Compile.ExecCommand
import Control.Monad
import Data.Maybe
import Data.List hiding (group)
import System.FilePath
import System.Environment
-- | Javadoc is the compiler for Java API documentation.
data Javadoc = Javadoc {
overview' :: Maybe FilePath, -- ^ @-overview@
public :: Bool, -- ^ @-public@
protected :: Bool, -- ^ @-protected@
package :: Bool, -- ^ @-package@
private :: Bool, -- ^ @-private@
help :: Bool, -- ^ @-help@
doclet' :: Maybe String, -- ^ @-doclet@
docletpath' :: Maybe FilePath, -- ^ @-docletpath@
sourcepath' :: [FilePath], -- ^ @-sourcepath@
classpath' :: [FilePath], -- ^ @-classpath@
exclude' :: [String], -- ^ @-exclude@
subpackages' :: [String], -- ^ @-subpackages@
breakiterator :: Bool, -- ^ @-breakiterator@
bootclasspath' :: [FilePath], -- ^ @-bootclasspath@
source' :: Maybe SourceRelease, -- ^ @-source@
extdirs' :: [FilePath], -- ^ @-extdirs@
verbose :: Bool, -- ^ @-verbose@
locale' :: Maybe String, -- ^ @-locale@
encoding' :: Maybe String, -- ^ @-encoding@
quiet :: Bool, -- ^ @-quiet@
flags' :: [String], -- ^ @-flags@
directory' :: Maybe FilePath, -- ^ @-d@
use :: Bool, -- ^ @-use@
version :: Bool, -- ^ @-version@
author :: Bool, -- ^ @-author@
docfilessubdirs :: Bool, -- ^ @-docfilessubdirs@
splitindex :: Bool, -- ^ @-splitindex@
windowtitle' :: Maybe String, -- ^ @-windowtitle@
doctitle' :: Maybe String, -- ^ @-doctitle@
header' :: Maybe String, -- ^ @-header@
footer' :: Maybe String, -- ^ @-footer@
top' :: Maybe String, -- ^ @-top@
bottom' :: Maybe String, -- ^ @-bottom@
link' :: [String], -- ^ @-link@
linkoffline' :: [(String, String)], -- ^ @-linkoffline@
excludedocfilessubdir' :: [String], -- ^ @-excludedocfilessubdir@
group' :: [(String, [String])], -- ^ @-group@
nocomment :: Bool, -- ^ @-nocomment@
nodeprecated :: Bool, -- ^ @-nodeprecated@
noqualifier' :: [String], -- ^ @-noqualifier@
nosince :: Bool, -- ^ @-nosince@
notimestamp :: Bool, -- ^ @-notimestamp@
nodeprecatedlist :: Bool, -- ^ @-nodeprecatedlist@
notree :: Bool, -- ^ @-notree@
noindex :: Bool, -- ^ @-noindex@
nohelp :: Bool, -- ^ @-nohelp@
nonavbar :: Bool, -- ^ @-nonavbar@
serialwarn :: Bool, -- ^ @-serialwarn@
tag' :: [(String, String, String)], -- ^ @-tag@
taglet :: Bool, -- ^ @-taglet@
tagletpath :: Bool, -- ^ @-tagletpath@
charset' :: Maybe String, -- ^ @-charset@
helpfile' :: Maybe FilePath, -- ^ @-helpfile@
linksource :: Bool, -- ^ @-linksource@
sourcetab' :: Maybe Int, -- ^ @-sourcetab@
keywords :: Bool, -- ^ @-keywords@
stylesheetfile' :: Maybe FilePath, -- ^ @-stylesheetfile@
docencoding' :: Maybe String -- ^ @-docencoding@
}
-- | A @Javadoc@ with nothing set.
javadoc ::
Javadoc
javadoc =
Javadoc Nothing False False False False False Nothing Nothing [] [] [] [] False [] Nothing [] False Nothing Nothing False [] Nothing False False False False False Nothing Nothing Nothing Nothing Nothing Nothing [] [] [] [] False False [] False False False False False False False False [] False False Nothing Nothing False Nothing False Nothing Nothing
instance Overview Javadoc where
overview x j =
j { overview' = x }
getOverview =
overview'
instance Public Javadoc where
setPublic j =
j { public = True }
unsetPublic j =
j { public = False }
instance Protected Javadoc where
setProtected j =
j { protected = True }
unsetProtected j =
j { protected = False }
instance Package Javadoc where
setPackage j =
j { package = True }
unsetPackage j =
j { package = False }
instance Private Javadoc where
setPrivate j =
j { private = True }
unsetPrivate j =
j { private = False }
instance Help Javadoc where
setHelp j =
j { help = True }
unsetHelp j =
j { help = False }
instance Doclet Javadoc where
doclet x j =
j { doclet' = x }
getDoclet =
doclet'
instance Docletpath Javadoc where
docletpath x j =
j { docletpath' = x }
getDocletpath =
docletpath'
instance Sourcepath Javadoc where
sourcepath x j =
j { sourcepath' = x }
getSourcepath =
sourcepath'
instance Classpath Javadoc where
classpath x j =
j { classpath' = x }
getClasspath =
classpath'
instance Exclude Javadoc where
exclude x j =
j { exclude' = x }
getExclude =
exclude'
instance Subpackages Javadoc where
subpackages x j =
j { subpackages' = x }
getSubpackages =
subpackages'
instance Breakiterator Javadoc where
setBreakiterator j =
j { breakiterator = True }
unsetBreakiterator j =
j { breakiterator = False }
instance Bootclasspath Javadoc where
bootclasspath x j =
j { bootclasspath' = x }
getBootclasspath =
bootclasspath'
instance Source Javadoc where
source x j =
j { source' = x }
getSource =
source'
instance Extdirs Javadoc where
extdirs x j =
j { extdirs' = x }
getExtdirs =
extdirs'
instance Verbose Javadoc where
setVerbose j =
j { verbose = True }
unsetVerbose j =
j { verbose = False }
instance Locale Javadoc where
locale x j =
j { locale' = x }
getLocale =
locale'
instance Encoding Javadoc where
encoding x j =
j { encoding' = x }
getEncoding =
encoding'
instance Quiet Javadoc where
setQuiet j =
j { quiet = True }
unsetQuiet j =
j { quiet = False }
instance Flags Javadoc where
flags x j =
j { flags' = x }
getFlags =
flags'
instance Directory Javadoc where
directory x j =
j { directory' = x }
getDirectory =
directory'
instance Use Javadoc where
setUse j =
j { use = True }
unsetUse j =
j { use = False }
instance Version Javadoc where
setVersion j =
j { version = True }
unsetVersion j =
j { version = False }
instance Author Javadoc where
setAuthor j =
j { author = True }
unsetAuthor j =
j { author = False }
instance Docfilessubdirs Javadoc where
setDocfilessubdirs j =
j { docfilessubdirs = True }
unsetDocfilessubdirs j =
j { docfilessubdirs = False }
instance Splitindex Javadoc where
setSplitindex j =
j { splitindex = True }
unsetSplitindex j =
j { splitindex = False }
instance Windowtitle Javadoc where
windowtitle x j =
j { windowtitle' = x }
getWindowtitle =
windowtitle'
instance Doctitle Javadoc where
doctitle x j =
j { doctitle' = x }
getDoctitle =
doctitle'
instance Header Javadoc where
header x j =
j { header' = x }
getHeader =
header'
instance Footer Javadoc where
footer x j =
j { footer' = x }
getFooter =
footer'
instance Top Javadoc where
top x j =
j { top' = x }
getTop =
top'
instance Bottom Javadoc where
bottom x j =
j { bottom' = x }
getBottom =
bottom'
instance Link Javadoc where
link x j =
j { link' = x }
getLink =
link'
instance Linkoffline Javadoc where
linkoffline x j =
j { linkoffline' = x }
getLinkoffline =
linkoffline'
instance Excludedocfilessubdir Javadoc where
excludedocfilessubdir x j =
j { excludedocfilessubdir' = x }
getExcludedocfilessubdir =
excludedocfilessubdir'
instance Group Javadoc where
group x j =
j { group' = x }
getGroup =
group'
instance Nocomment Javadoc where
setNocomment j =
j { nocomment = True }
unsetNocomment j =
j { nocomment = False }
instance Nodeprecated Javadoc where
setNodeprecated j =
j { nodeprecated = True }
unsetNodeprecated j =
j { nodeprecated = False }
instance Noqualifier Javadoc where
noqualifier x j =
j { noqualifier' = x }
getNoqualifier =
noqualifier'
instance Nosince Javadoc where
setNosince j =
j { nosince = True }
unsetNosince j =
j { nosince = False }
instance Notimestamp Javadoc where
setNotimestamp j =
j { notimestamp = True }
unsetNotimestamp j =
j { notimestamp = False }
instance Nodeprecatedlist Javadoc where
setNodeprecatedlist j =
j { nodeprecatedlist = True }
unsetNodeprecatedlist j =
j { nodeprecatedlist = False }
instance Notree Javadoc where
setNotree j =
j { notree = True }
unsetNotree j =
j { notree = False }
instance Noindex Javadoc where
setNoindex j =
j { noindex = True }
unsetNoindex j =
j { noindex = False }
instance Nohelp Javadoc where
setNohelp j =
j { nohelp = True }
unsetNohelp j =
j { nohelp = False }
instance Nonavbar Javadoc where
setNonavbar j =
j { nonavbar = True }
unsetNonavbar j =
j { nonavbar = False }
instance Serialwarn Javadoc where
setSerialwarn j =
j { serialwarn = True }
unsetSerialwarn j =
j { serialwarn = False }
instance Tag Javadoc where
tag x j =
j { tag' = x }
getTag =
tag'
instance Taglet Javadoc where
setTaglet j =
j { taglet = True }
unsetTaglet j =
j { taglet = False }
instance Tagletpath Javadoc where
setTagletpath j =
j { tagletpath = True }
unsetTagletpath j =
j { tagletpath = False }
instance Charset Javadoc where
charset x j =
j { charset' = x }
getCharset =
charset'
instance Helpfile Javadoc where
helpfile x j =
j { helpfile' = x }
getHelpfile =
helpfile'
instance Linksource Javadoc where
setLinksource j =
j { linksource = True }
unsetLinksource j =
j { linksource = False }
instance Sourcetab Javadoc where
sourcetab x j =
j { sourcetab' = x }
getSourcetab =
sourcetab'
instance Keywords Javadoc where
setKeywords j =
j { keywords = True }
unsetKeywords j =
j { keywords = False }
instance Stylesheetfile Javadoc where
stylesheetfile x j =
j { stylesheetfile' = x }
getStylesheetfile =
stylesheetfile'
instance Docencoding Javadoc where
docencoding x j =
j { docencoding' = x }
getDocencoding =
docencoding'
instance Options Javadoc where
options (Javadoc overview'
public'
protected'
package'
private'
help'
doclet'
docletpath'
sourcepath'
classpath'
exclude'
subpackages'
breakiterator'
bootclasspath'
source'
extdirs'
verbose'
locale'
encoding'
quiet'
flags'
directory'
use'
version'
author'
docfilessubdirs'
splitindex'
windowtitle'
doctitle'
header'
footer'
top'
bottom'
link'
linkoffline'
excludedocfilessubdir'
group'
nocomment'
nodeprecated'
noqualifier'
nosince'
notimestamp'
nodeprecatedlist'
notree'
noindex'
nohelp'
nonavbar'
serialwarn'
tag'
taglet'
tagletpath'
charset'
helpfile'
linksource'
sourcetab'
keywords'
stylesheetfile'
docencoding') =
let g ^^^ t = intercalate t (filter (not . null) g)
param k c s = (~?) (\z -> '-' : k ++ c : quote (s z))
g ~~ k = if k then '-' : g else []
(~?) = maybe []
s ~: z = if null z then [] else '-' : s ++ ' ' : [searchPathSeparator] >===< z
s >===< k = intercalate s (fmap quote k)
quote s = '"' : (s >>= \x -> if x == '"' then "\\\"" else [x]) ++ "\""
(~~>) k = param k ' ' show
(~~~>) = (. Just) . (~~>)
many k v = intercalate " " $ map (k ~~~>) v
manys f k = many k . map f
c = intercalate ":"
in [ "overview" ~~> overview'
, "public" ~~ public'
, "protected" ~~ protected'
, "package" ~~ package'
, "private" ~~ private'
, "help" ~~ help'
, "doclet" ~~> doclet'
, "docletpath" ~~> docletpath'
, "sourcepath" ~: sourcepath'
, "classpath" ~: classpath'
, "exclude" ~: exclude'
, "subpackages" ~: subpackages'
, "breakiterator" ~~ breakiterator'
, "bootclasspath" ~: bootclasspath'
, "source" ~~> source'
, "extdirs" ~: extdirs'
, "verbose" ~~ verbose'
, "locale" ~~> locale'
, "encoding" ~~> encoding'
, "quiet" ~~ quiet'
, intercalate " " $ map ("-J" ++) flags'
, "d" ~~> directory'
, "use" ~~ use'
, "version" ~~ version'
, "author" ~~ author'
, "docfilessubdirs" ~~ docfilessubdirs'
, "splitindex" ~~ splitindex'
, "windowtitle" ~~> windowtitle'
, "doctitle" ~~> doctitle'
, "header" ~~> header'
, "footer" ~~> footer'
, "top" ~~> top'
, "bottom" ~~> bottom'
, "link" `many` link'
, manys (\(x, y) -> x ++ "\" \"" ++ y) "linkoffline" linkoffline'
, intercalate ":" excludedocfilessubdir'
, manys (\(x, y) -> x ++ "\" \"" ++ c y) "group" group'
, "nocomment" ~~ nocomment'
, "nodeprecated" ~~ nodeprecated'
, intercalate ":" noqualifier'
, "nosince" ~~ nosince'
, "notimestamp" ~~ notimestamp'
, "nodeprecatedlist" ~~ nodeprecatedlist'
, "notree" ~~ notree'
, "noindex" ~~ noindex'
, "nohelp" ~~ nohelp'
, "nonavbar" ~~ nonavbar'
, "serialwarn" ~~ serialwarn'
, manys (\(x, y, z) -> c [x, y, z]) "tag" tag'
, "taglet" ~~ taglet'
, "tagletpath" ~~ tagletpath'
, "charset" ~~> charset'
, "helpfile" ~~> helpfile'
, "linksource" ~~ linksource'
, "sourcetab" ~~> sourcetab'
, "keywords" ~~ keywords'
, "stylesheetfile" ~~> stylesheetfile'
, "docencoding" ~~> docencoding'
] ^^^ " "
instance Extensions Javadoc where
isSourceExtension _ =
(== "java")
isTargetExtension _ _ =
True
instance ExecCommand IO Javadoc where
command _ =
let envs = [
("JAVADOC_HOME", (</> "bin" </> "javadoc"))
, ("JDK_HOME", (</> "bin" </> "javadoc"))
, ("JAVADOC", id)
]
tryEnvs es =
do e <- getEnvironment
let k [] = Nothing
k ((a, b):t) = fmap b (a `lookup` e) `mplus` k t
return (k es)
in fromMaybe "javadoc" `fmap` tryEnvs envs
| tonymorris/lastik | System/Build/Java/Javadoc.hs | bsd-3-clause | 18,044 | 0 | 18 | 5,732 | 4,376 | 2,528 | 1,848 | 572 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module Main where
import Control.Applicative
import Control.Arrow
import Control.Exception
import Control.Lens
import Control.Monad
import Control.Monad.Error.Class
import Control.Monad.IO.Class
import Control.Monad.Trans.Except
import Data.Aeson
import Data.Aeson.Lens
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as BC
import qualified Data.ByteString.Lazy as BSL
import Data.Either
import Data.Function
import Data.List
import Data.Maybe
import Data.Monoid
import qualified Data.Text.Encoding as T
import Network.HTTP.Client (HttpException (..),
defaultManagerSettings,
newManager)
import Network.HTTP.Types (Status (..), hLocation)
import qualified Network.OAuth.OAuth2 as HOAuth2
import Network.URI
import Network.Wreq hiding (statusCode)
import System.Environment
import Test.Hspec
import Text.HandsomeSoup
import Text.XML.HXT.Core (IOSArrow, XmlTree, runX)
import qualified URI.ByteString as UB
import Yesod.Core (PathPiece (..))
import Network.OAuth2.Server.Types hiding (refreshToken)
import qualified Network.OAuth2.Server.Types as OAuth2
main :: IO ()
main = do
args <- getArgs
case args of
(uri:rest) | Just x <- parseURI uri -> withArgs rest $ hspec (tests x)
_ -> putStrLn "First argument must be a server URI."
onLeft :: (a -> Bool) -> Either a b -> Bool
onLeft f (Left x) = f x
onLeft _ (Right _) = False
tests :: URI -> Spec
tests base_uri = do
describe "verify endpoint" $ do
it "returns a response when given valid credentials and a matching token" $ do
resp <- verifyToken base_uri client1 (fst tokenVV)
resp `shouldSatisfy` isRight
it "returns an error when given valid credentials and a token from another client" $ do
resp <- verifyToken base_uri client2 (fst tokenVV)
resp `shouldSatisfy` onLeft ("404 Not Found" `isPrefixOf`)
it "returns an error when given invalid client credentials" $ do
resp <- verifyToken base_uri client3 (fst tokenVV)
resp `shouldSatisfy` onLeft ("400 Bad Request" `isPrefixOf`)
it "returns an error when given a token which has been revoked" $ do
resp <- verifyToken base_uri client1 (fst tokenRV)
resp `shouldSatisfy` onLeft ("404 Not Found" `isPrefixOf`)
it "returns an error when given a token which is not valid" $ do
resp <- verifyToken base_uri client1 (fst tokenDERP)
resp `shouldSatisfy` onLeft ("404 Not Found" `isPrefixOf`)
describe "token endpoint" $ do
it "uses the same details when refreshing a token" $ do
-- Verify a good token.
t1' <- verifyToken base_uri client1 (fst tokenVV)
t1 <- either (\_ -> fail "Valid token is invalid, so can't test!")
(return) t1'
-- Refresh it.
t2_id' <- runExceptT $ refreshToken base_uri client1 (snd tokenVV)
t2_id <- either (\e -> fail $ "Couldn't refresh: " <> e)
(return) t2_id'
-- Verify that token.
t2' <- verifyToken base_uri client1 t2_id
t2 <- either (\_ -> fail "Couldn't verify new token.")
(return) t2'
-- If we got a new refresh token, the old one should be revoked.
when (isJust $ OAuth2.refreshToken t2) $ do
r1 <- verifyToken base_uri client1 (snd tokenVV)
r1 `shouldSatisfy` onLeft ("404 Not Found" `isPrefixOf`)
-- The original bearer token should now be revoked.
t1'' <- verifyToken base_uri client1 (fst tokenVV)
t1'' `shouldSatisfy` onLeft ("404 Not Found" `isPrefixOf`)
-- Compare them in all the respects which should be identical.
(shouldBe `on` tokenType) t1 t2
-- (shouldBe `on` accessToken) t1 t2
-- (shouldBe `on` refreshToken) t1 t2
-- (shouldBe `on` tokenExpiresIn) t1 t2
(shouldBe `on` tokenUserID) t1 t2
(shouldBe `on` tokenClientID) t1 t2
(shouldBe `on` tokenScope) t1 t2
it "revokes the existing token when it is refreshed" $ do
let tok = tokenVV2
-- Verify a pair of existing tokens.
t1' <- verifyToken base_uri client1 (fst tok)
t1' `shouldSatisfy` isRight
t1r' <- verifyToken base_uri client1 (snd tok)
t1r' `shouldSatisfy` isRight
-- Refresh to get new bearer and, optionally, refresh tokens.
t2_id' <- runExceptT $ refreshToken base_uri client1 (snd tok)
t2_id <- either (\e -> fail $ "Couldn't refresh: " <> e)
(return) t2_id'
-- Verify new bearer token.
t2' <- verifyToken base_uri client1 t2_id
t2 <- either (\_ -> fail "Couldn't verify new token.")
(return) t2'
-- The old bearer token should now be invalid.
t1_2' <- verifyToken base_uri client1 (fst tok)
t1_2' `shouldSatisfy` onLeft ("404 Not Found" `isPrefixOf`)
-- If we got a new refresh token, the old one should be revoked.
when (isJust $ OAuth2.refreshToken t2) $ do
r1 <- verifyToken base_uri client1 (snd tok)
r1 `shouldSatisfy` onLeft ("404 Not Found" `isPrefixOf`)
it "restricts new tokens to the client which granted them"
pending
it "works with hoauth2" $ do
res <- runExceptT $ do
let Just a_scope = bsToScope "login missiles:launch"
let code_request = a_scope <$ client1
-- 1. Get the page.
pg <- getAuthorizePage base_uri (Just user1) code_request Nothing
-- 2. Extract details from the form.
(uri, fields) <- getAuthorizeFields base_uri pg
-- 3. Submit the approval form.
let fields' = nubBy ((==) `on` fst) fields
x <- sendAuthorization uri (Just user1) fields'
auth_code <- case lookup "code" $ x ^. UB.uriQueryL . UB.queryPairsL of
Nothing -> error "No code in redirect URI"
Just auth_code -> return auth_code
-- 4. Use the code in the redirect to request a token via hoauth2.
man <- liftIO $ newManager defaultManagerSettings
let oauth2 = HOAuth2.OAuth2
{ HOAuth2.oauthClientId = review clientID $ fst client1
, HOAuth2.oauthClientSecret = T.encodeUtf8 $ review password $ snd client1
, HOAuth2.oauthOAuthorizeEndpoint = ""
, HOAuth2.oauthAccessTokenEndpoint = (BC.pack $ show base_uri) <> "/oauth2/token"
, HOAuth2.oauthCallback = Nothing
}
res <- liftIO $ HOAuth2.fetchAccessToken man oauth2 auth_code
case res of
Left e -> throwError $ show e
Right _ -> return ()
case res of
Left e -> error e
Right () -> return ()
describe "authorize endpoint" $ do
let Just a_scope = bsToScope "login missiles:launch"
let code_request = a_scope <$ client1
let client_state = "THISISMYSTATE" ^?! clientState
it "returns an error when Shibboleth authentication headers are missing" $ do
resp <- runExceptT $ getAuthorizePage base_uri Nothing code_request Nothing
resp `shouldSatisfy` onLeft ("500 Internal Server Error" `isPrefixOf`)
it "the POST returns an error when Shibboleth authentication headers are missing" $ do
-- 1. Get the page.
resp <- runExceptT $ getAuthorizePage base_uri (Just user1) code_request Nothing
resp `shouldSatisfy` isRight
-- 2. Extract the code.
let Right pg = resp
resp2 <- runExceptT $ getAuthorizeFields base_uri pg
case resp2 of
Left _ -> error "No fields"
Right (uri, fields) -> do
let fields' = nubBy ((==) `on` fst) fields
resp3 <- runExceptT $ sendAuthorization uri Nothing fields'
resp3 `shouldSatisfy` isLeft
it "the POST returns an error when the request ID is missing" $ do
-- 1. Get the page.
resp <- runExceptT $ getAuthorizePage base_uri (Just user1) code_request Nothing
resp `shouldSatisfy` isRight
-- 2. Extract the code.
let Right pg = resp
resp2 <- runExceptT $ getAuthorizeFields base_uri pg
case resp2 of
Left _ -> error "No fields"
Right (uri, fields) -> do
let f = filter (\(k,_) -> k /= "code") fields
resp3 <- runExceptT $ sendAuthorization uri (Just user1) f
-- TODO(thsutton): FromFormUrlEncoded Code results in this
-- terrible error.
resp3 `shouldSatisfy` onLeft ("400 Bad Request" `isPrefixOf`)
it "the POST returns an error when the Shibboleth authentication headers identify a mismatched user" $ do
-- 1. Get the page.
resp <- runExceptT $ getAuthorizePage base_uri (Just user1) code_request Nothing
resp `shouldSatisfy` isRight
-- 2. Extract the code.
let Right pg = resp
resp2 <- runExceptT $ getAuthorizeFields base_uri pg
case resp2 of
Left _ -> error "No fields"
Right (uri, fields) -> do
resp3 <- runExceptT $ sendAuthorization uri (Just user2) fields
resp3 `shouldSatisfy` onLeft ("403 Forbidden" `isPrefixOf`)
it "the redirect contains a code which can be used to request a token" $ do
res <- runExceptT $ do
-- 1. Get the page.
pg <- getAuthorizePage base_uri (Just user1) code_request (Just client_state)
-- 2. Check that the page describes the requested token.
liftIO $ do
pg `shouldSatisfy` ("App 1" `BC.isInfixOf`)
pg `shouldSatisfy` ("Application One" `BC.isInfixOf`)
pg `shouldSatisfy` ("missiles:launch" `BC.isInfixOf`)
pg `shouldSatisfy` ("login" `BC.isInfixOf`)
-- 3. Extract details from the form.
(uri, fields) <- getAuthorizeFields base_uri pg
-- 4. Submit the approval form.
let fields' = nubBy ((==) `on` fst) fields
x <- sendAuthorization uri (Just user1) fields'
let query_params = x ^. UB.uriQueryL . UB.queryPairsL
auth_code <- case lookup "code" query_params of
Nothing -> error "No code in redirect URI"
Just auth_code -> return auth_code
liftIO $ lookup "state" query_params
`shouldBe` Just (client_state ^.re clientState)
-- 5. Use the code in the redirect to request a token.
t <- requestTokenWithCode base_uri client1 auth_code
-- 6. Verify the token and check that it contaisn the appropriate details.
liftIO $ do
tokenUserID t `shouldBe` (Just $ fst user1)
tokenClientID t `shouldBe` (Just $ fst client1)
tokenScope t `shouldBe` a_scope
case res of
Left e -> error e
Right () -> return ()
it "the redirect contains \"access_denied\" error if declined" $ do
res <- runExceptT $ do
-- 1. Get the page.
pg <- getAuthorizePage base_uri (Just user1) code_request (Just client_state)
-- 2. Check that the page describes the requested token.
liftIO $ do
pg `shouldSatisfy` ("App 1" `BC.isInfixOf`)
pg `shouldSatisfy` ("Application One" `BC.isInfixOf`)
pg `shouldSatisfy` ("missiles:launch" `BC.isInfixOf`)
pg `shouldSatisfy` ("login" `BC.isInfixOf`)
-- 3. Extract details from the form.
(uri, fields) <- getAuthorizeFields base_uri pg
-- 4. Submit the approval form.
let fields' = nubBy ((==) `on` fst) $ deleteBy ((==) `on` fst) ("action","") fields
x <- sendAuthorization uri (Just user1) fields'
let qps = x ^. UB.uriQueryL . UB.queryPairsL
case lookup "code" qps of
Nothing -> return ()
Just _ -> error $ "redirect has an auth_code"
case lookup "error" qps of
Nothing -> error $ "redirect has no error"
Just "access_denied" -> return ()
Just e -> error $ "wrong error: " <> show e
liftIO $ lookup "state" qps
`shouldBe` Just (client_state ^.re clientState)
case res of
Left e -> error e
Right () -> return ()
describe "user interface" $ do
it "returns an error when Shibboleth authentication headers are missing"
pending
it "displays a list of the users tokens"
pending
it "includes a revoke link for each token"
pending
it "allows the user to revoke a token"
pending
-- | Use the verify endpoint of a token server to verify a token.
verifyToken :: URI -> (ClientID, Password) -> Token -> IO (Either String AccessResponse)
verifyToken base_uri (client,secret) tok = do
let opts = defaults & header "Accept" .~ ["application/json"]
& header "Content-Type" .~ ["application/octet-stream"]
& auth ?~ basicAuth user pass
r <- try (postWith opts (show endpoint) body)
case r of
Left (StatusCodeException (Status c m) h _) -> do
let b = BC.unpack <$> lookup "X-Response-Body-Start" h
return (Left $ show c <> " " <> BC.unpack m <> " - " <> fromMaybe "" b)
Left e -> return (Left $ show e)
Right v ->
return $ case v ^? responseBody . _JSON of
Nothing -> Left "Could not decode response."
Just tr -> Right tr
where
user = review clientID client
pass = T.encodeUtf8 $ review password secret
body = review token tok
endpoint = base_uri { uriPath = "/oauth2/verify" }
refreshToken
:: URI
-> (ClientID, Password)
-> Token
-> ExceptT String IO Token
refreshToken base_uri (client, secret) tok = do
let opts = defaults & header "Accept" .~ ["application/json"]
& header "Content-Type" .~ ["application/json"]
& auth ?~ basicAuth user pass
r <- liftIO $ try (postWith opts (show endpoint) body)
grant <- case r of
Left (StatusCodeException (Status c m) h _) -> do
let b = BC.unpack <$> lookup "X-Response-Body-Start" h
throwError $ show c <> " " <> BC.unpack m <> " - " <> fromMaybe "" b
Left e -> throwError (show e)
Right v ->
case v ^? responseBody . _JSON of
Nothing -> throwError $ "Could not decode response." <> show (v ^? responseBody)
Just tr -> return tr
return $ accessToken grant
where
body :: [(ByteString, ByteString)]
body = [ ("grant_type", "refresh_token")
, ("refresh_token", review token tok)
-- , ("", "") -- Scope
] -- RequestRefreshToken token Nothing
endpoint = base_uri { uriPath = "/oauth2/token" }
pass = T.encodeUtf8 $ review password secret
user = review clientID client
getAuthorizePage
:: URI
-> Maybe (UserID, Scope)
-> (ClientID, Scope)
-> Maybe ClientState
-> ExceptT String IO ByteString
getAuthorizePage base_uri user_m (client, req_scope) maybe_state = do
let opts = defaults & header "Accept" .~ ["text/html"]
& param "response_type" .~ ["code"]
& param "client_id" .~ [T.decodeUtf8 $ review clientID client]
& param "scope" .~ [T.decodeUtf8 . scopeToBs $ req_scope]
& param "state" .~ maybeToList (T.decodeUtf8 . review clientState <$> maybe_state)
& addAuthHeaders user_m
r <- liftIO $ try (getWith opts (show endpoint))
handleResponse r
where
endpoint = base_uri { uriPath = "/oauth2/authorize" }
handleResponse
:: (MonadIO m, MonadError String m)
=> Either HttpException (Response BSL.ByteString)
-> m ByteString
handleResponse r =
case r of
Left (StatusCodeException (Status c m) h _) -> do
let b = BC.unpack <$> lookup "X-Response-Body-Start" h
throwError $ show c <> " " <> BC.unpack m <> " - " <> fromMaybe "" b
Left e -> throwError (show e)
Right v -> do
liftIO $ do
(v ^? responseHeader "Cache-Control") `shouldBe` Just "no-store"
(v ^? responseHeader "Pragma") `shouldBe` Just "no-cache"
return $ v ^. responseBody . to BSL.toStrict
addAuthHeaders :: Maybe (UserID, Scope) -> Options -> Options
addAuthHeaders Nothing = id
addAuthHeaders (Just (user, perms)) =
(header "Identity-OAuthUser" .~ [review userID user])
. (header "Identity-OAuthUserScopes" .~ [scopeToBs perms])
-- | Helper for string -> bytestring conversion and lifting IO
runXBS :: MonadIO m => IOSArrow XmlTree String -> m [ByteString]
runXBS a = liftIO $ runX (a >>^ BC.pack)
-- | Extract form fields and submission URI from authorize endpoint HTML.
getAuthorizeFields
:: URI
-> ByteString
-> ExceptT String IO (URI, [(ByteString, ByteString)])
getAuthorizeFields base_uri pg = do
let doc = parseHtml (BC.unpack pg)
form_actions <- liftIO . runX $ doc >>> css "form" ! "action"
dst_uri <- case form_actions of
[tgt] ->
case parseURIReference tgt of
Nothing -> error $ "invalid uri: " <> tgt
Just dst_uri -> return dst_uri
xs -> throwError $ "Expected one form, got " <> show (length xs)
names <- runXBS $ doc >>> css "form input" ! "name"
vals <- runXBS $ doc >>> css "form input" ! "value"
return (dst_uri `relativeTo` base_uri, zip names vals)
-- | Submit authorization form
sendAuthorization
:: URI
-> Maybe (UserID, Scope)
-> [(ByteString, ByteString)]
-> ExceptT String IO UB.URI
sendAuthorization uri user_m fields = do
let opts = defaults & header "Accept" .~ ["text/html"]
& redirects .~ 0
& addAuthHeaders user_m
res <- liftIO . try $ postWith opts (show uri) fields
case res of
Left e -> do
hs <- case e of
TooManyRedirects [r] -> return $ r ^. responseHeaders
StatusCodeException st hs _
| statusCode st `elem` [301,302,303] -> return hs
StatusCodeException (Status c m) h _ -> do
let b = BC.unpack <$> lookup "X-Response-Body-Start" h
throwError $ show c <> " " <> BC.unpack m <> " - " <> fromMaybe "" b
_ -> throwError $ show e
redirect <- case lookup hLocation hs of
Nothing -> throwError "No Location header in redirect"
Just x' -> return x'
case UB.parseURI UB.strictURIParserOptions redirect of
Left e' -> throwError $ "Invalid Location header in redirect: " <> show (redirect, e')
Right x -> return x
Right _ -> throwError "No redirect"
-- | Request a token (Authorization Code Grant) as described in
-- https://tools.ietf.org/html/rfc6749#section-4.1.1
requestTokenWithCode
:: URI
-> (ClientID, Password)
-> ByteString
-> ExceptT String IO AccessResponse
requestTokenWithCode base_uri (client, secret) auth_code = do
let opts = defaults & header "Accept" .~ ["application/json"]
& auth ?~ basicAuth client' secret'
let req = [ ("grant_type", "authorization_code")
, ("code", auth_code)
, ("client_id", client')
] :: [(ByteString, ByteString)]
r <- liftIO $ try $ postWith opts (show base_uri <> "/oauth2/token") req
res <- handleResponse r
case eitherDecode $ BSL.fromStrict res of
Left e -> throwError e
Right x -> return x
where
client' = review clientID client
secret' = T.encodeUtf8 $ review password secret
-- * Fixtures
--
-- $ These values refer to clients and tokens defined in the database fixture.
-- ** Clients
--
-- $ Clients are identified by their client_id and client_secret.
client1 :: (ClientID, Password)
client1 =
let Just i = preview clientID "5641ea27-1111-1111-1111-8fc06b502be0"
Just p = preview password "clientpassword1"
in (i,p)
-- | 'client1' with an incorrect password.
client1bad :: (ClientID, Password)
client1bad =
let Just p = preview password "clientpassword1bad"
in const p <$> client1
client2 :: (ClientID, Password)
client2 =
let Just i = preview clientID "5641ea27-2222-2222-2222-8fc06b502be0"
Just p = preview password "clientpassword2"
in (i,p)
-- | 'client2' with an incorrect password.
client2bad :: (ClientID, Password)
client2bad =
let Just p = preview password "clientpassword2bad"
in const p <$> client2
-- | A non-existant client.
client3 :: (ClientID, Password)
client3 =
let Just i = preview clientID "5641ea27-3333-3333-3333-8fc06b502be0"
Just p = preview password "clientpassword3"
in (i,p)
-- * Users
--
-- $ These details can be anything (within the obvious limits) as far as the
-- OAuth2 Server is concerned, but we'll use these values in the tests.
user1 :: (UserID, Scope)
user1 =
let Just i = fromPathPiece "[email protected]"
Just s = bsToScope "login missiles:launch missiles:selfdestruct"
in (i,s)
user2 :: (UserID, Scope)
user2 =
let Just i = fromPathPiece "[email protected]"
Just s = bsToScope "login football:penalty:bend-it"
in (i,s)
-- ** Tokens
--
-- $ Tokens pre-defined in the fixture database. These pairs contain the bearer
-- and refresh token in that order and are named for the status of these tokens
-- (V, E, and R mean valid, expired, and revoked respectively).
--
-- All of these tokens are valid for 'client1' above.
tokenVV :: (Token, Token)
tokenVV =
let Just b = preview token "Xnl4W3J3ReJYN9qH1YfR4mjxaZs70lVX/Edwbh42KPpmlqhp500c4UKnQ6XKmyjbnqoRW1NFWl7h"
Just r = preview token "hBC86fa6py9nDYMNNZAOfkseAJlN5WvnEmelbCuAUOqOYhYan8N7EgZh6b6k7DpWF6j9DomLlaGZ"
in (b,r)
tokenVV2 :: (Token, Token)
tokenVV2 =
let Just b = preview token "2224W3J3ReJYN9qH1YfR4mjxaZs70lVX/Edwbh42KPpmlqhp500c4UKnQ6XKmyjbnqoRW1NFWl7h"
Just r = preview token "22286fa6py9nDYMNNZAOfkseAJlN5WvnEmelbCuAUOqOYhYan8N7EgZh6b6k7DpWF6j9DomLlaGZ"
in (b,r)
tokenEV :: (Token, Token)
tokenEV =
let Just b = preview token "4Bb+zZV3cizc4kIiWwxxKxj4nRxBdyvB3aWgfqsq8u9h+Y9uqP6NJTtcLWLZaxmjl+oqn+bHObJU"
Just r = preview token "l5lXecbLVcUvE25fPHbMpJnK0IY6wta9nKId60Q06HY4fYkx5b3djFwU2xtA9+NDK3aPdaByNXFC"
in (b,r)
tokenEE :: (Token, Token)
tokenEE =
let Just b = preview token "cRIhk3UyxiABoafo4h100kZcjGQQJ/UDEVjM4qv/Htcn2LNApJkhIc6hzDPvujgCmRV3CRY1Up4a"
Just r = preview token "QVuRV4RxA2lO8B6y8vOIi03pZMSj8S8F/LsMxCyfA3OBtgmB1IFh51aMSeh4qjBid9nNmk3BOYr0"
in (b,r)
tokenRV :: (Token, Token)
tokenRV =
let Just b = preview token "AjMuHxnw5TIrO9C2BQStlXUv6luAWmg7pt1GhVjYctvD8w3eZE9eEjbyGsVjrJT8S11egXsOi7e4"
Just r = preview token "E4VkzDDDm8till5xSYIeOO8GbnSYtBHiIIClwdd46+J9K/dH/l5YVBFXLHmHZno5YAVtIp84GLwH"
in (b,r)
tokenRR :: (Token, Token)
tokenRR =
let Just b = preview token "/D6TJwBSK18sB0cLyVWdt38Pca5keFb/sHeblGNScQI35qhUZwnMZh1Gz9RSIjFfxmBDdHeBWeLM"
Just r = preview token "++1ZuShqJ0BQ7uesZGus2G+IGsETS7jn1ZhfjohBx1SzrJbviQ1MkemmGWtZOxbcbtJS+gANj+Es"
in (b,r)
-- | This isn't even a token, just some made up words.
tokenDERP :: (Token, Token)
tokenDERP =
let Just b = preview token "lemmeinlemmeinlemmeinlemmeinlemmeinlemmeinlemmeinlemmeinlemmeinlemmeinlemmein"
Just r = preview token "pleasepleasepleasepleasepleasepleasepleasepleasepleasepleasepleasepleaseplease"
in (b,r)
| anchor/oauth2-server | test/acceptance.hs | bsd-3-clause | 25,371 | 0 | 25 | 8,169 | 6,125 | 3,077 | 3,048 | -1 | -1 |
module Language.StreamIt.Graph
( StreamItT (..)
, StreamIt
, StatementS (..)
, FileMode (..)
, GraphDecl
, evalStream
, execStream
, findDefs
, add
, add1
, add2
, add3
, pipeline
, pipeline_
, splitjoin
, splitjoin_
, split
, join
, roundrobin
, fileReader
, fileWriter
) where
import Data.Char
import Data.List
import Data.Typeable
import Control.Monad.Trans
import qualified Control.Monad.State as S
import Language.StreamIt.Core
import Language.StreamIt.Filter
-- Type of file filter.
data FileMode = FileReader | FileWriter
data StatementS where
DeclS :: Elt a => Var a -> StatementS
AssignS :: Elt a => Var a -> Exp a -> StatementS
BranchS :: Exp Bool -> StatementS -> StatementS -> StatementS
LoopS :: StatementS -> Exp Bool -> StatementS -> StatementS -> StatementS
AddS :: (AddE a) => a -> String -> String -> (Maybe (Exp b), Maybe (Exp c), Maybe (Exp d)) -> StatementS
Pipeline :: Bool -> StatementS -> StatementS
SplitJoin :: Bool -> StatementS -> StatementS
Split :: Splitter -> StatementS
Join :: Joiner -> StatementS
Chain :: StatementS -> StatementS -> StatementS
File :: FileMode -> Const -> String -> StatementS
Empty :: StatementS
instance Eq (StatementS) where (==) _ _ = True
-- Type of splitters
data Splitter = RoundrobinS [Exp Int]
instance Show Splitter where
show sp = case sp of
RoundrobinS es -> "roundrobin(" ++ intercalate "," (map show es) ++ ")"
-- Type of joiners
data Joiner = RoundrobinJ [Exp Int]
instance Show Joiner where
show jn = case jn of
RoundrobinJ es -> "roundrobin(" ++ intercalate "," (map show es) ++ ")"
-- | The StreamIt monad holds StreamIt statements.
newtype StreamItT i o m a = StreamItT {runStreamItT :: ((Int, StatementS) -> m (a, (Int, StatementS)))}
type StreamIt a b = StreamItT a b IO
instance (Typeable a, Typeable b) => Typeable1 (StreamIt a b) where
typeOf1 s = let
tyCon = mkTyCon3 "Language" "StreamIt" "Graph.StreamIt"
(a, b) = peel s
peel :: StreamIt a b m -> (a, b)
peel = undefined
in mkTyConApp tyCon [typeOf a, typeOf b]
instance (Elt a, Elt b, Monad m) => Monad (StreamItT a b m) where
return a = StreamItT $ \ s -> return (a, s)
(>>=) sf f = StreamItT $ \ s -> do (a1, s1) <- runStreamItT sf s
(a2, s2) <- runStreamItT (f a1) s1
return (a2, s2)
instance (Elt a, Elt b) => MonadTrans (StreamItT a b) where
lift m = StreamItT $ \ s -> do
a <- m
return (a, s)
instance (Elt a, Elt b, MonadIO m) => MonadIO (StreamItT a b m) where
liftIO = lift . liftIO
-- Returns the complete type (int->int) of a pipeline filter
instance (Typeable a, Typeable b, Typeable m) => Show (StreamIt a b m) where
show s = map toLower $ (head $ tail t) ++ "->" ++ (head $ tail $ tail t)
where
t = words $ (show . typeOf) s
addNode :: (Elt a, Elt b, Monad m) => StatementS -> StreamItT a b m ()
addNode n = StreamItT $ \ (id, node) -> return ((), (id, Chain node n))
evalStream :: (Elt a, Elt b, Monad m) => Int -> StreamItT a b m () -> m (Int, StatementS)
evalStream id (StreamItT f) = do
(_, x) <- f (id, Empty)
return x
execStream:: (Elt a, Elt b, Monad m) => StreamItT a b m () -> m StatementS
execStream n = do
(_, x) <- evalStream 0 n
return x
get :: (Elt a, Elt b, Monad m) => StreamItT a b m (Int, StatementS)
get = StreamItT $ \ a -> return (a, a)
put :: (Elt a, Elt b, Monad m) => (Int, StatementS) -> StreamItT a b m ()
put s = StreamItT $ \ _ -> return ((), s)
-- GraphDecl = (Type, Name, Arguments, AST node)
type GraphDecl = (String, String, String, StatementS)
instance (Elt a, Elt b) => CoreE (StreamIt a b) where
var init = do
(id, stmt) <- get
sym <- lift $ gensym init
put (id, Chain stmt $ DeclS sym)
return sym
float = var zero
float' = var
int = var zero
int' = var
bool = var zero
bool' = var
array _ size = var (Array size zero)
a <== b = addNode $ AssignS a b
ifelse cond onTrue onFalse = do
(id0, node) <- get
(id1, node1) <- lift $ evalStream id0 (onTrue >> return ())
(id2, node2) <- lift $ evalStream id1 (onFalse >> return ())
put (id2, node)
addNode $ BranchS cond node1 node2
if_ cond onTrue = do
(id0, node) <- get
(id1, node1) <- lift $ evalStream id0 (onTrue >> return ())
put (id1, node)
addNode $ BranchS cond node1 Empty
for_ (init, cond, inc) body = do
(id0, stmt) <- get
(id1, stmt1) <- lift $ evalStream id0 (body >> return ())
ini <- lift $ execStream init
inc <- lift $ execStream inc
put (id1, stmt)
addNode $ LoopS ini cond inc stmt1
while_ cond body = do
(id0, stmt) <- get
(id1, stmt1) <- lift $ evalStream id0 (body >> return ())
put (id1, stmt)
addNode $ LoopS Empty cond Empty stmt1
----------------------------------------------------------------------------
-- The 'AddE' class represents add expressions in the StreamIt EDSL.
class AddE a where
-- Add a primitive or composite stream to the stream graph.
add :: (Elt b, Elt c) => a -> StreamIt b c ()
-- Add a primitive or composite stream accepting 1 argument.
add1 :: (Elt b, Elt c, Elt d) => (Var d -> a) -> (Exp d) -> StreamIt b c ()
-- Add a primitive or composite stream accepting 2 arguments.
add2 :: (Elt b, Elt c, Elt d, Elt e) => (Var d -> Var e -> a) -> (Exp d, Exp e) -> StreamIt b c ()
-- Add a primitive or composite stream accepting 3 arguments.
add3 :: (Elt b, Elt c, Elt d, Elt e, Elt f) => (Var d -> Var e -> Var f -> a) -> (Exp d, Exp e, Exp f) -> StreamIt b c ()
-- Given an AST node, returns a list of filter and pipeline declarations
-- in the body.
info :: a -> String -> String-> S.StateT ([FilterDecl], [GraphDecl]) IO ()
instance (Elt a, Elt b, Typeable a, Typeable b) => AddE (Filter a b ()) where
add a = do
name <- lift $ newStableName a "filt"
addNode $ AddS a name "" (Nothing, Nothing, Nothing)
add1 a (b) = do
name <- lift $ newStableName a "filt"
x <- lift $ genExpVar b
addNode $ AddS (a x) name (showVarDecl x) (Just b, Nothing, Nothing)
add2 a (b,c) = do
name <- lift $ newStableName a "filt"
x <- lift $ genExpVar b
y <- lift $ genExpVar c
addNode $ AddS (a x y) name (showVarDecl x ++ "," ++ showVarDecl y) (Just b, Just c, Nothing)
add3 a (b,c,d) = do
name <- lift $ newStableName a "filt"
x <- lift $ genExpVar b
y <- lift $ genExpVar c
z <- lift $ genExpVar d
addNode $ AddS (a x y z) name (showVarDecl x ++ "," ++ showVarDecl y ++ "," ++ showVarDecl z) (Just b, Just c, Just d)
info b name args = do
(f, g) <- S.get
bs <- liftIO $ execStmt b
if (elem name $ map getName f)
then return ()
else S.put ((show b, name, args, bs):f, g)
where
getName (_, x, _, _) = x
instance (Elt a, Elt b, Typeable a, Typeable b) => AddE (StreamIt a b ()) where
add a = do
name <- lift $ newStableName a "filt"
addNode $ AddS a name "" (Nothing, Nothing, Nothing)
add1 a (b) = do
name <- lift $ newStableName a "filt"
x <- lift $ genExpVar b
addNode $ AddS (a x) name (showVarDecl x) (Just b, Nothing, Nothing)
add2 a (b,c) = do
name <- lift $ newStableName a "filt"
x <- lift $ genExpVar b
y <- lift $ genExpVar c
addNode $ AddS (a x y) name (showVarDecl x ++ "," ++ showVarDecl y) (Just b, Just c, Nothing)
add3 a (b,c,d) = do
name <- lift $ newStableName a "filt"
x <- lift $ genExpVar b
y <- lift $ genExpVar c
z <- lift $ genExpVar d
addNode $ AddS (a x y z) name (showVarDecl x ++ "," ++ showVarDecl y ++ "," ++ showVarDecl z) (Just b, Just c, Just d)
info b name args = do
(f, g) <- S.get
bs <- liftIO $ execStream b
if (elem name $ map getName g)
then return ()
else do
S.put (f, (show b, name, args, bs):g) >> findDefs bs
where
getName (_, x, _, _) = x
----------------------------------------------------------------------------
addPipeline :: (Elt a, Elt b) => Bool -> StreamIt a b () -> StreamIt a b ()
addPipeline named a = do
(id0, node) <- get
(id1, node1) <- lift $ evalStream id0 a
put (id1, node)
addNode $ Pipeline named node1
-- 'pipeline' declares a composite stream consisting of
-- multiple children streams.
pipeline :: (Elt a, Elt b) => StreamIt a b () -> StreamIt a b ()
pipeline = addPipeline True
-- Anonymous, inline pipeline function.
pipeline_ :: (Elt a, Elt b) => StreamIt a b () -> StreamIt a b ()
pipeline_ = addPipeline False
addSplitjoin :: (Elt a, Elt b) => Bool -> StreamIt a b () -> StreamIt a b ()
addSplitjoin named a = do
(id0, node) <- get
(id1, node1) <- lift $ evalStream id0 a
put (id1, node)
addNode $ SplitJoin named node1
-- Split-join composite streams.
splitjoin :: (Elt a, Elt b) => StreamIt a b () -> StreamIt a b ()
splitjoin = addSplitjoin True
-- An anonymous, inline split-join stream.
splitjoin_ :: (Elt a, Elt b) => StreamIt a b () -> StreamIt a b ()
splitjoin_ = addSplitjoin False
class SplitterJoiner a where
roundrobin :: [Exp Int] -> a
instance SplitterJoiner Splitter where
roundrobin = RoundrobinS
instance SplitterJoiner Joiner where
roundrobin = RoundrobinJ
-- Split and join
split :: (Elt a, Elt b) => Splitter -> StreamIt a b ()
split s = addNode $ Split s
join :: (Elt a, Elt b) => Joiner -> StreamIt a b ()
join j = addNode $ Join j
-- Recurse down the root of the AST and return the filter and pipeline
-- definitions in the program.
findDefs :: StatementS -> S.StateT ([FilterDecl], [GraphDecl]) IO ()
findDefs st = do
case st of
BranchS _ a b -> findDefs a >> findDefs b
LoopS _ _ _ a -> findDefs a
AddS a n args _ -> info a n args
Pipeline _ a -> findDefs a
SplitJoin _ a -> findDefs a
Chain a b -> findDefs a >> findDefs b
_ -> return ()
fileReader :: (Elt a, Elt b, Elt c) => (c -> Const) -> String -> StreamIt a b ()
fileReader ty fname = addNode $ File FileReader (ty zero) fname
fileWriter :: (Elt a, Elt b, Elt c) => (c -> Const) -> String -> StreamIt a b ()
fileWriter ty fname = addNode $ File FileWriter (ty zero) fname
| adk9/haskell-streamit | Language/StreamIt/Graph.hs | bsd-3-clause | 10,218 | 0 | 16 | 2,618 | 4,450 | 2,270 | 2,180 | -1 | -1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.