code
stringlengths 2
1.05M
| repo_name
stringlengths 5
101
| path
stringlengths 4
991
| language
stringclasses 3
values | license
stringclasses 5
values | size
int64 2
1.05M
|
|---|---|---|---|---|---|
-- TODO this parser is wonky
module Parse where
data Parser a = P {runParser :: String -> [(a, String)]}
first f (a, b) = (f a , b)
instance Functor Parser where
fmap f p = P $ map (first f) . runParser p
instance Applicative Parser where
pure = return
f <*> x = do
f <- f
x <- x
return $ f x
instance Monad Parser where
return x = P $ \s -> [(x, s)]
x >>= f = P $ \s ->
let ms = runParser x s
step (a, str) = runParser (f a) str
in concatMap step ms
char :: Char -> Parser Char
char x = P char'
where
char' (c : rest) | c == x = [(c, rest)]
char' _ = []
string :: String -> Parser String
string str = mapM char str
parseAny :: [Parser a] -> Parser a
parseAny ps = P $ \s ->
concatMap (\f -> runParser f s) ps
(<|>) a b = parseAny [a, b]
many, many1 :: Parser a -> Parser [a]
many p = parseAny [(:) <$> p <*> many p, return []]
many1 p = (:) <$> p <*> many p
many_ x = many x *> return ()
charSet = parseAny . map char
ws :: Parser Char
ws = charSet $ " \n\t"
ws' = charSet $ " \t"
whitespace = many_ ws
whitespace' = many_ ws'
newline = charSet "\n"
lowerAlpha = charSet $ ['a'..'z']
upperAlpha = charSet $ ['A'..'Z']
digit = charSet ['0'..'9']
idSym = charSet "-'"
idChar = lowerAlpha <|> upperAlpha <|> digit <|> idSym
identifier' first = (:) <$> first <*> many idChar
identifier = identifier' lowerAlpha
predIdentifier = identifier' upperAlpha
token x = (x <* many ws)
indent = many1 ws
sepBy :: Parser a -> Parser b -> Parser [b]
sepBy a b = ((:) <$> b <*> (a *> sepBy a b)) <|> (return <$> b)
type Symbol = String
data Value
= Num Int
| Ref Symbol
| Member Symbol Symbol
deriving (Show, Eq, Ord)
data Expr
= App Symbol [Value]
| EVal Value
deriving (Show, Eq, Ord)
data Binder = Binder Expr Symbol
deriving (Show, Eq, Ord)
data Predicate = Predicate Symbol [Value]
deriving (Show, Eq, Ord)
data Pattern
= PExpr Expr
| PBind Binder
| PPred Predicate
deriving (Show, Eq, Ord)
data Action
= Mutate Symbol Symbol Expr
| AExpr Expr
| ABind Binder
| APred Predicate
deriving (Show, Eq, Ord)
data LHS = LHS [Pattern]
deriving (Show, Eq, Ord)
data ERHS = ERHS Expr
deriving (Show, Eq, Ord)
data MRHS = MRHS [Action]
deriving (Show, Eq, Ord)
data Arrow = FnArrow | MutArrow
deriving (Eq, Ord)
instance Show Arrow where
show FnArrow = "->"
show MutArrow = "~>"
data Rule = ERule LHS ERHS | MRule LHS MRHS
deriving (Show, Eq, Ord)
data Def = Def String [Rule]
deriving (Eq, Ord)
instance Show Def where
show (Def name rules) =
unlines $ name : map ((" " ++) . show) rules
finish :: Parser a -> Parser a
finish p = p <* (P finish')
where
finish' "" = [((), "")]
finish' _ = []
symbol = token identifier
readInt :: String -> [(Int, String)]
readInt = reads
value :: Parser Value
value = num <|> ref <|> member
where
num = Num <$> P readInt
ref = Ref <$> identifier
member = Member <$> identifier <*> (char '.' *> identifier)
spaces = sepBy (many1 ws)
args = spaces value
expr :: Parser Expr
expr = (EVal <$> value) <|> appParser
where
appParser = App <$> identifier <*> (many1 ws *> args)
binder :: Parser Binder
binder = bindR <|> bindL
where
bindR = Binder <$> token expr <*> (token (char ')') *> identifier)
bindL = flip Binder <$> token identifier <*> (token (char '(') *> expr)
predicate :: Parser Predicate
predicate = Predicate <$> predIdentifier <*> (many1 ws *> args)
pattern :: Parser Pattern
pattern = (PExpr <$> expr) <|> (PBind <$> binder) <|> (PPred <$> predicate)
-- TODO
action :: Parser Action
action = (ABind <$> binder) <|> (AExpr <$> expr) <|> (APred <$> predicate)
<|> mutate
where
mutate = Mutate <$> identifier <*> (char '.' *> token identifier)
<*> (token (string "<-") *> expr)
commas x = sepBy (whitespace >> token (char ',')) x
lhs = LHS <$> commas (pattern)
erhs = ERHS <$> expr
mrhs = MRHS <$> commas (action)
earrow = (string "->" >> return FnArrow)
marrow = (string "~>" >> return MutArrow)
nlws = whitespace' >> many1 newline >> whitespace'
wslr x = whitespace *> x <* whitespace
endDef = string "\n.\n"
def = Def <$> identifier <*> (nlws *> sepBy nlws rule <* endDef)
rule = erule <|> mrule
where
erule = ERule <$> token lhs <*> (token earrow *> erhs)
mrule = MRule <$> token lhs <*> (token marrow *> mrhs)
prog :: Parser [Def]
prog = wslr $ many def
chk' p = head . runParser p
chk p = runParser (finish p)
chn n p = take n . runParser (finish p)
|
kovach/cards
|
src/Parse.hs
|
Haskell
|
mit
| 4,510
|
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as BC
import Data.Time
import Data.Word
import Test.Tasty
import Test.Tasty.HUnit
-- IUT
import Data.OTP
hotpSecret :: ByteString
hotpSecret = "12345678901234567890"
testHotp :: Word64 -> Word32 -> TestTree
testHotp key result = testCase (show result) $ do
let h = hotp SHA1 hotpSecret key 6
result @=? h
hotpResults :: [Word32]
hotpResults =
[ 755224, 287082, 359152
, 969429, 338314, 254676
, 287922, 162583, 399871
, 520489
]
testTotp :: (ByteString, UTCTime, HashAlgorithm, Word32) -> TestTree
testTotp (secr, key, alg, result) =
testCase (show alg ++ " => " ++ show result) $ do
let t = totp alg secr key 30 8
result @=? t
sha1Secr :: ByteString
sha1Secr = BC.pack $ take 20 $ cycle "12345678901234567890"
sha256Secr :: ByteString
sha256Secr = BC.pack $ take 32 $ cycle "12345678901234567890"
sha512Secr :: ByteString
sha512Secr = BC.pack $ take 64 $ cycle "12345678901234567890"
totpData :: [(ByteString, UTCTime, HashAlgorithm, Word32)]
totpData =
[ (sha1Secr, read "1970-01-01 00:00:59 UTC", SHA1, 94287082)
, (sha256Secr, read "1970-01-01 00:00:59 UTC", SHA256, 46119246)
, (sha512Secr, read "1970-01-01 00:00:59 UTC", SHA512, 90693936)
, (sha1Secr, read "2005-03-18 01:58:29 UTC", SHA1, 07081804)
, (sha256Secr, read "2005-03-18 01:58:29 UTC", SHA256, 68084774)
, (sha512Secr, read "2005-03-18 01:58:29 UTC", SHA512, 25091201)
, (sha1Secr, read "2005-03-18 01:58:31 UTC", SHA1, 14050471)
, (sha256Secr, read "2005-03-18 01:58:31 UTC", SHA256, 67062674)
, (sha512Secr, read "2005-03-18 01:58:31 UTC", SHA512, 99943326)
, (sha1Secr, read "2009-02-13 23:31:30 UTC", SHA1, 89005924)
, (sha256Secr, read "2009-02-13 23:31:30 UTC", SHA256, 91819424)
, (sha512Secr, read "2009-02-13 23:31:30 UTC", SHA512, 93441116)
, (sha1Secr, read "2033-05-18 03:33:20 UTC", SHA1, 69279037)
, (sha256Secr, read "2033-05-18 03:33:20 UTC", SHA256, 90698825)
, (sha512Secr, read "2033-05-18 03:33:20 UTC", SHA512, 38618901)
, (sha1Secr, read "2603-10-11 11:33:20 UTC", SHA1, 65353130)
, (sha256Secr, read "2603-10-11 11:33:20 UTC", SHA256, 77737706)
, (sha512Secr, read "2603-10-11 11:33:20 UTC", SHA512, 47863826)
]
main :: IO ()
main = defaultMain $ testGroup "test vectors"
[ testGroup "hotp" $ map (uncurry testHotp) $ zip [0..] hotpResults
, testGroup "totp" $ map testTotp totpData
]
|
matshch/OTP
|
test/Test.hs
|
Haskell
|
mit
| 2,655
|
module Data.FacetedSpec where
import Control.Applicative
import Data.Faceted
import Test.Hspec
-- Simple Faceted Value
simple = (\x -> x > 0) ? 1 .: 0
nested = (\x -> x <= 2) ?? ((\x -> x < 2) ? 1 .: 2) .: ((\x -> x < 4 ) ? 3 .: 4)
-- do syntax test cases
ap_do = do a <- ((\x -> 0 < x && x < 3) ? 1 .: 2)
b <- ((\x -> 1 < x && x < 4) ? 4 .: 8)
return (a + b)
monad_do = do a <- ((\x -> 0 < x && x < 3) ? 1 .: 2)
b <- ((\x -> 1 < x && x < 4) ? (a+4) .: (a+8))
(\y -> y < 3) ? (10*b) .: (100*b)
spec :: Spec
spec = do
describe "facete value can be declared in intuitive manner \"(\\x -> x > 0) ? 1 .: 0)\"" $ do
it "its observation with context 0 should be 0." $
observe simple 0 `shouldBe` 0
it "its observation with context 1 should be 1." $
observe simple 1 `shouldBe` 1
describe "use (??) for nested facete value \"(\\x -> x <= 2) ?? ((\\x -> x < 2) ? 1 .: 2) .: ((\\x -> x < 4 ) ? 3 .: 4)\"" $ do
it "its observation with context 1 should be 1." $
observe nested 1 `shouldBe` 1
it "its observation with context 2 should be 2." $
observe nested 2 `shouldBe` 2
it "its observation with context 3 should be 3." $
observe nested 3 `shouldBe` 3
it "its observation with context 4 should be 4." $
observe nested 4 `shouldBe` 4
describe "Functor: ((*3) `fmap` (\\x -> x > 0) ? 1 .: 0)) should be equivalent with < (x > 0) ? 1*3 : 0*3>." $ do
it "observation with context 0 should be 0." $
observe ((*3) `fmap` simple) 0 `shouldBe` 0
it "observation with context 1 should be 3." $
observe ((*3) `fmap` simple) 1 `shouldBe` 3
describe ("Applicative: ((+) <$> ((\\x -> 0 < x && x < 3) ? 1 .: 2) <*> ((\\x -> 1 < x && x < 4) ? 4 .: 8))\n"
++"\tThis computation adds two faceted values. So in this case, 4 patterns of results can be observed.\n"
++"\tThe result should be equivalent with\n"
++"\t < (0 < x < 3) ? < (1 < x < 4) ? 1+4 : 1+8 >\n"
++"\t : < (1 < x < 4) ? 2+4 : 2+8 >>") $ do
it "observation with context 1 should be 9 (= 1 + 8)." $
observe ( (+) <$> ((\x -> 0 < x && x < 3) ? 1 .: 2) <*> ((\x -> 1 < x && x < 4) ? 4 .: 8)) 1 `shouldBe` 9
it "observation with context 2 should be 5 (= 1 + 4)." $
observe ( (+) <$> ((\x -> 0 < x && x < 3) ? 1 .: 2) <*> ((\x -> 1 < x && x < 4) ? 4 .: 8)) 2 `shouldBe` 5
it "observation with context 3 should be 6 (= 2 + 4)." $
observe ( (+) <$> ((\x -> 0 < x && x < 3) ? 1 .: 2) <*> ((\x -> 1 < x && x < 4) ? 4 .: 8)) 3 `shouldBe` 6
it "observation with context 4 should be 10 (= 2 + 8)." $
observe ( (+) <$> ((\x -> 0 < x && x < 3) ? 1 .: 2) <*> ((\x -> 1 < x && x < 4) ? 4 .: 8)) 4 `shouldBe` 10
describe ("Applicative Do: \n"
++"\t do a <- ((\\x -> 0 < x && x < 3) ? 1 .: 2)\n"
++"\t b <- ((\\x -> 1 < x && x < 4) ? 4 .: 8)\n"
++"\t return a + b\n"
++"\tshould be equivalent with above.\n") $ do
it "observation with context 1 should be 9 (= 1 + 8)." $
observe ap_do 1 `shouldBe` 9
it "observation with context 2 should be 5 (= 1 + 4)." $
observe ap_do 2 `shouldBe` 5
it "observation with context 3 should be 6 (= 2 + 4)." $
observe ap_do 3 `shouldBe` 6
it "observation with context 4 should be 10 (= 2 + 8)." $
observe ap_do 4 `shouldBe` 10
describe ("Bind: ((\\x -> 0 < x && x < 3) ? 1 .: 2) >>= (\\v -> ((\\x -> 1 < x && x < 4) ? (v+4) .: (v+8))\n"
++"\tshoule be equivalent with\n"
++"\t < (0 < x < 3) ? < (1 < x < 4) ? 1+4 : 1+8 >\n"
++"\t : < (1 < x < 4) ? 2+4 : 2+8 >>") $ do
it "observation with context 1 should be 9 (= 1 + 8)." $
observe (((\x -> 0 < x && x < 3) ? 1 .: 2) >>= \v -> ((\x -> 1 < x && x < 4) ? (v+4) .: (v+8))) 1 `shouldBe` 9
it "observation with context 2 should be 5 (= 1 + 4)." $
observe (((\x -> 0 < x && x < 3) ? 1 .: 2) >>= \v -> ((\x -> 1 < x && x < 4) ? (v+4) .: (v+8))) 2 `shouldBe` 5
it "observation with context 3 should be 6 (= 2 + 4)." $
observe (((\x -> 0 < x && x < 3) ? 1 .: 2) >>= \v -> ((\x -> 1 < x && x < 4) ? (v+4) .: (v+8))) 3 `shouldBe` 6
it "observation with context 4 should be 10 (= 2 + 8)." $
observe (((\x -> 0 < x && x < 3) ? 1 .: 2) >>= \v -> ((\x -> 1 < x && x < 4) ? (v+4) .: (v+8))) 4 `shouldBe` 10
describe ("Do Syntax:\n"
++"\tdo a <- ((\\x -> 0 < x && x < 3) ? 1 .: 2)\n"
++"\t b <- ((\\x -> 1 < x && x < 4) ? (a+4) .: (a+8))\n"
++"\t (\\y -> y < 3) ? (10*b) .: (100*b)\n"
++"\tshoule be equivalent with\n"
++"\t < (0 < x < 3) ? < (1 < x < 4) ? <(y < 3)? 10*(1+4) : 100*(1+4)>\n"
++"\t : <(y < 3)? 10*(2+8) : 100*(2+8)>>\n"
++"\t : < (1 < x < 4) ? <(y < 3)? 10*(2+4) : 100*(2+4)>\n"
++"\t : <(y < 3)? 10*(2+8) : 100*(2+8)>>") $ do
it "observation with context 1 should be 90 (= 10 * (1 + 8))." $
observe monad_do 1 `shouldBe` 90
it "observation with context 2 should be 50 (= 10 * (1 + 4))." $
observe monad_do 2 `shouldBe` 50
it "observation with context 3 should be 600 (= 100 * (2 + 4))." $
observe monad_do 3 `shouldBe` 600
it "observation with context 4 should be 1000 (= 100 * (2 + 8))." $
observe monad_do 4 `shouldBe` 1000
|
everpeace/faceted-values
|
test/Data/FacetedSpec.hs
|
Haskell
|
mit
| 5,471
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
-- | This is a Haskell port of the Hashids library by Ivan Akimov.
-- This is /not/ a cryptographic hashing algorithm. Hashids is typically
-- used to encode numbers to a format suitable for appearance in places
-- like urls.
--
-- See the official Hashids home page: <http://hashids.org>
--
-- Hashids is a small open-source library that generates short, unique,
-- non-sequential ids from numbers. It converts numbers like 347 into
-- strings like @yr8@, or a list of numbers like [27, 986] into @3kTMd@.
-- You can also decode those ids back. This is useful in bundling several
-- parameters into one or simply using them as short UIDs.
module Web.Hashids
( HashidsContext
-- * How to use
-- $howto
-- ** Encoding
-- $encoding
-- ** Decoding
-- $decoding
-- ** Randomness
-- $randomness
-- *** Repeating numbers
-- $repeating
-- *** Incrementing number sequence
-- $incrementing
-- ** Curses\! \#\$\%\@
-- $curses
-- * API
, version
-- ** Context object constructors
, createHashidsContext
, hashidsSimple
, hashidsMinimum
-- ** Encoding and decoding
, encodeHex
, decodeHex
, encode
, encodeList
, decode
-- ** Convenience wrappers
, encodeUsingSalt
, encodeListUsingSalt
, decodeUsingSalt
, encodeHexUsingSalt
, decodeHexUsingSalt
) where
import Data.ByteString ( ByteString )
import Data.Foldable ( toList )
import Data.List ( (\\), nub, intersect, foldl' )
import Data.List.Split ( chunksOf )
import Data.Sequence ( Seq )
import Numeric ( showHex, readHex )
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as C8
import qualified Data.Sequence as Seq
-- $howto
--
-- Note that most of the examples on this page require the OverloadedStrings extension.
-- $encoding
--
-- Unless you require a minimum length for the generated hash, create a
-- context using 'hashidsSimple' and then call 'encode' and 'decode' with
-- this object.
--
-- > {-# LANGUAGE OverloadedStrings #-}
-- >
-- > import Web.Hashids
-- >
-- > main :: IO ()
-- > main = do
-- > let context = hashidsSimple "oldsaltyswedishseadog"
-- > print $ encode context 42
--
-- This program will output
--
-- > "kg"
--
-- To specify a minimum hash length, use 'hashidsMinimum' instead.
--
-- > main = do
-- > let context = hashidsMinimum "oldsaltyswedishseadog" 12
-- > print $ encode context 42
--
-- The output will now be
--
-- > "W3xbdkgdy42v"
--
-- If you only need the context once, you can use one of the provided wrappers
-- to simplify things.
--
-- > main :: IO ()
-- > main = print $ encodeUsingSalt "oldsaltyswedishseadog" 42
--
-- On the other hand, if your implementation invokes the hashing algorithm
-- frequently without changing the configuration, it is probably better to
-- define partially applied versions of 'encode', 'encodeList', and 'decode'.
--
-- > import Web.Hashids
-- >
-- > context :: HashidsContext
-- > context = createHashidsContext "oldsaltyswedishseadog" 12 "abcdefghijklmnopqrstuvwxyz"
-- >
-- > encode' = encode context
-- > encodeList' = encodeList context
-- > decode' = decode context
-- >
-- > main :: IO ()
-- > main = print $ encode' 12345
--
-- Use a custom alphabet and 'createHashidsContext' if you want to make your
-- hashes \"unique\".
--
-- > main = do
-- > let context = createHashidsContext "oldsaltyswedishseadog" 0 "XbrNfdylm5qtnP19R"
-- > print $ encode context 1
--
-- The output is now
--
-- > "Rd"
--
-- To encode a list of numbers, use `encodeList`.
--
-- > let context = hashidsSimple "this is my salt" in encodeList context [0, 1, 2]
--
-- > "yJUWHx"
-- $decoding
--
-- Decoding a hash returns a list of numbers,
--
-- > let context = hashidsSimple "this is my salt"
-- > hash = decode context "rD" -- == [5]
--
-- Decoding will not work if the salt is changed:
--
-- > main = do
-- > let context = hashidsSimple "this is my salt"
-- > hash = encode context 5
-- >
-- > print $ decodeUsingSalt "this is my pepper" hash
--
-- When decoding fails, the empty list is returned.
--
-- > []
--
-- $randomness
--
-- Hashids is based on a modified version of the Fisher-Yates shuffle. The
-- primary purpose is to obfuscate ids, and it is not meant for security
-- purposes or compression. Having said that, the algorithm does try to make
-- hashes unguessable and unpredictable. See the official Hashids home page
-- for details: <http://hashids.org>
-- $repeating
--
-- > let context = hashidsSimple "this is my salt" in encodeList context $ replicate 4 5
--
-- There are no repeating patterns in the hash to suggest that four identical
-- numbers are used:
--
-- > "1Wc8cwcE"
--
-- The same is true for increasing numbers:
--
-- > let context = hashidsSimple "this is my salt" in encodeList context [1..10]
--
-- > "kRHnurhptKcjIDTWC3sx"
-- $incrementing
--
-- > let context = hashidsSimple "this is my salt" in map (encode context) [1..5]
--
-- > ["NV","6m","yD","2l","rD"]
-- $curses
--
-- The algorithm tries to avoid generating common curse words in English by
-- never placing the following letters next to each other:
--
-- > c, C, s, S, f, F, h, H, u, U, i, I, t, T
{-# INLINE (|>) #-}
(|>) :: a -> (a -> b) -> b
(|>) a f = f a
{-# INLINE splitOn #-}
splitOn :: ByteString -> ByteString -> [ByteString]
splitOn = BS.splitWith . flip BS.elem
-- | Opaque data type with various internals required for encoding and decoding.
data HashidsContext = Context
{ guards :: !ByteString
, seps :: !ByteString
, salt :: !ByteString
, minHashLength :: !Int
, alphabet :: !ByteString }
-- | Hashids version number.
version :: String
version = "1.0.2"
-- | Create a context object using the given salt, a minimum hash length, and
-- a custom alphabet. If you only need to supply the salt, or the first two
-- arguments, use 'hashidsSimple' or 'hashidsMinimum' instead.
--
-- Changing the alphabet is useful if you want to make your hashes unique,
-- i.e., create hashes different from those generated by other applications
-- relying on the same algorithm.
createHashidsContext :: ByteString -- ^ Salt
-> Int -- ^ Minimum required hash length
-> String -- ^ Alphabet
-> HashidsContext
createHashidsContext salt minHashLen alphabet
| length uniqueAlphabet < minAlphabetLength
= error $ "alphabet must contain at least " ++ show minAlphabetLength ++ " unique characters"
| ' ' `elem` uniqueAlphabet
= error "alphabet cannot contain spaces"
| BS.null seps'' || fromIntegral (BS.length alphabet') / fromIntegral (BS.length seps'') > sepDiv
= case sepsLength - BS.length seps'' of
diff | diff > 0
-> res (BS.drop diff alphabet') (seps'' `BS.append` BS.take diff alphabet')
_ -> res alphabet' (BS.take sepsLength seps'')
| otherwise = res alphabet' seps''
where
res ab _seps =
let shuffled = consistentShuffle ab salt
guardCount = ceiling (fromIntegral (BS.length shuffled) / guardDiv)
context = Context
{ guards = BS.take guardCount _seps
, seps = BS.drop guardCount _seps
, salt = salt
, minHashLength = minHashLen
, alphabet = shuffled }
in if BS.length shuffled < 3
then context
else context{ guards = BS.take guardCount shuffled
, seps = _seps
, alphabet = BS.drop guardCount shuffled }
seps' = C8.pack $ uniqueAlphabet `intersect` seps
seps'' = consistentShuffle seps' salt
sepsLength =
case ceiling (fromIntegral (BS.length alphabet') / sepDiv) of
1 -> 2
n -> n
uniqueAlphabet = nub alphabet
alphabet' = C8.pack $ uniqueAlphabet \\ seps
minAlphabetLength = 16
sepDiv = 3.5
guardDiv = 12
seps = "cfhistuCFHISTU"
defaultAlphabet :: String
defaultAlphabet = ['a'..'z'] ++ ['A'..'Z'] ++ "1234567890"
-- | Create a context object using the default alphabet and the provided salt,
-- without any minimum required length.
hashidsSimple :: ByteString -- ^ Salt
-> HashidsContext
hashidsSimple salt = createHashidsContext salt 0 defaultAlphabet
-- | Create a context object using the default alphabet and the provided salt.
-- The generated hashes will have a minimum length as specified by the second
-- argument.
hashidsMinimum :: ByteString -- ^ Salt
-> Int -- ^ Minimum required hash length
-> HashidsContext
hashidsMinimum salt minimum = createHashidsContext salt minimum defaultAlphabet
-- | Decode a hash generated with 'encodeHex'.
--
-- /Example use:/
--
-- > decodeHex context "yzgwD"
--
decodeHex :: HashidsContext -- ^ A Hashids context object
-> ByteString -- ^ Hash
-> String
decodeHex context hash = concatMap (drop 1 . flip showHex "") numbers
where
numbers = decode context hash
-- | Encode a hexadecimal number.
--
-- /Example use:/
--
-- > encodeHex context "ff83"
--
encodeHex :: HashidsContext -- ^ A Hashids context object
-> String -- ^ Hexadecimal number represented as a string
-> ByteString
encodeHex context str
| not (all hexChar str) = ""
| otherwise = encodeList context $ map go $ chunksOf 12 str
where
go str = let [(a,_)] = readHex ('1':str) in a
hexChar c = c `elem` ("0123456789abcdefABCDEF" :: String)
-- | Decode a hash.
--
-- /Example use:/
--
-- > let context = hashidsSimple "this is my salt"
-- > hash = decode context "rD" -- == [5]
--
decode :: HashidsContext -- ^ A Hashids context object
-> ByteString -- ^ Hash
-> [Int]
decode ctx@Context{..} hash
| BS.null hash = []
| encodeList ctx res /= hash = []
| otherwise = res
where
res = splitOn seps tail
|> foldl' go ([], alphabet)
|> fst
|> reverse
hashArray = splitOn guards hash
alphabetLength = BS.length alphabet
Just str@(lottery, tail) =
BS.uncons $ hashArray !! case length hashArray of
0 -> error "Internal error."
2 -> 1
3 -> 1
_ -> 0
prefix = BS.cons lottery salt
go (xs, ab) ssh =
let buffer = prefix `BS.append` ab
ab' = consistentShuffle ab buffer
in (unhash ssh ab':xs, ab')
numbersHashInt :: [Int] -> Int
numbersHashInt xs = foldr ((+) . uncurry mod) 0 $ zip xs [100 .. ]
-- | Encode a single number.
--
-- /Example use:/
--
-- > let context = hashidsSimple "this is my salt"
-- > hash = encode context 5 -- == "rD"
--
encode :: HashidsContext -- ^ A Hashids context object
-> Int -- ^ Number to encode
-> ByteString
encode context n = encodeList context [n]
-- | Encode a list of numbers.
--
-- /Example use:/
--
-- > let context = hashidsSimple "this is my salt"
-- > hash = encodeList context [2, 3, 5, 7, 11] -- == "EOurh6cbTD"
--
encodeList :: HashidsContext -- ^ A Hashids context object
-> [Int] -- ^ List of numbers
-> ByteString
encodeList _ [] = error "encodeList: empty list"
encodeList Context{..} numbers =
res |> expand False |> BS.reverse
|> expand True |> BS.reverse
|> expand' alphabet'
where
(res, alphabet') = foldl' go (BS.singleton lottery, alphabet) (zip [0 .. ] numbers)
expand rep str
| BS.length str < minHashLength
= let ix = if rep then BS.length str - 3 else 0
jx = fromIntegral (BS.index str ix) + hashInt
in BS.index guards (jx `mod` guardsLength) `BS.cons` str
| otherwise = str
expand' ab str
| BS.length str < minHashLength
= let ab' = consistentShuffle ab ab
str' = BS.concat [BS.drop halfLength ab', str, BS.take halfLength ab']
in expand' ab' $ case BS.length str' - minHashLength of
n | n > 0
-> BS.take minHashLength $ BS.drop (div n 2) str'
_ -> str'
| otherwise = str
hashInt = numbersHashInt numbers
lottery = alphabet `BS.index` (hashInt `mod` alphabetLength)
prefix = BS.cons lottery salt
numLast = length numbers - 1
guardsLength = BS.length guards
alphabetLength = BS.length alphabet
halfLength = div alphabetLength 2
go (r, ab) (i, number)
| number < 0 = error "all numbers must be non-negative"
| otherwise =
let shuffled = consistentShuffle ab (BS.append prefix ab)
last = hash number shuffled
n = number `mod` (fromIntegral (BS.head last) + i) `mod` BS.length seps
suffix = if i < numLast
then BS.singleton (seps `BS.index` n)
else BS.empty
in (BS.concat [r,last,suffix], shuffled)
-- Exchange elements at positions i and j in a sequence.
exchange :: Int -> Int -> Seq a -> Seq a
exchange i j seq = i <--> j $ j <--> i $ seq
where
a <--> b = Seq.update a $ Seq.index seq b
consistentShuffle :: ByteString -> ByteString -> ByteString
consistentShuffle alphabet salt
| 0 == saltLength = alphabet
| otherwise = BS.pack $ toList x
where
(_,x) = zip3 [len, pred len .. 1] xs ys |> foldl' go (0, toSeq alphabet)
xs = cycle [0 .. saltLength - 1]
ys = map (fromIntegral . saltLookup) xs
saltLookup ix = BS.index salt (ix `mod` saltLength)
saltLength = BS.length salt
toSeq = BS.foldl' (Seq.|>) Seq.empty
len = BS.length alphabet - 1
go (p, ab) (i, v, ch) =
let shuffled = exchange i j ab
p' = p + ch
j = mod (ch + v + p') i
in (p', shuffled)
unhash :: ByteString -> ByteString -> Int
unhash input alphabet = fst $ BS.foldl' go (0, pred $ BS.length input) input
where
go (num, i) w8 =
let Just index = BS.elemIndex w8 alphabet
in (num + index * alphabetLength ^ i, pred i)
alphabetLength = BS.length alphabet
hash :: Int -> ByteString -> ByteString
hash input alphabet
| 0 == input = BS.take 1 alphabet
| otherwise = BS.reverse $ BS.unfoldr go input
where
len = BS.length alphabet
go 0 = Nothing
go i = Just (alphabet `BS.index` (i `mod` len), div i len)
-- | Encode a number using the provided salt.
--
-- This convenience function creates a context with the default alphabet.
-- If the same context is used repeatedly, use 'encode' with one of the
-- constructors instead.
encodeUsingSalt :: ByteString -- ^ Salt
-> Int -- ^ Number
-> ByteString
encodeUsingSalt = encode . hashidsSimple
-- | Encode a list of numbers using the provided salt.
--
-- This function wrapper creates a context with the default alphabet.
-- If the same context is used repeatedly, use 'encodeList' with one of the
-- constructors instead.
encodeListUsingSalt :: ByteString -- ^ Salt
-> [Int] -- ^ Numbers
-> ByteString
encodeListUsingSalt = encodeList . hashidsSimple
-- | Decode a hash using the provided salt.
--
-- This convenience function creates a context with the default alphabet.
-- If the same context is used repeatedly, use 'decode' with one of the
-- constructors instead.
decodeUsingSalt :: ByteString -- ^ Salt
-> ByteString -- ^ Hash
-> [Int]
decodeUsingSalt = decode . hashidsSimple
-- | Shortcut for 'encodeHex'.
encodeHexUsingSalt :: ByteString -- ^ Salt
-> String -- ^ Hexadecimal number represented as a string
-> ByteString
encodeHexUsingSalt = encodeHex . hashidsSimple
-- | Shortcut for 'decodeHex'.
decodeHexUsingSalt :: ByteString -- ^ Salt
-> ByteString -- ^ Hash
-> String
decodeHexUsingSalt = decodeHex . hashidsSimple
|
tmcgilchrist/hashids-haskell
|
Web/Hashids.hs
|
Haskell
|
mit
| 16,507
|
module Graphics.UI.FLTK.LowLevel.FLTKHS
(
-- * Motivation
--
-- $Motivation
-- * Goals
--
-- $Goals
-- * Look And Feel
--
-- $LookAndFeel
-- * Obstacles
--
-- $Obstacles
-- * Installation #Installation#
--
-- $InstallationSummary
-- ** Build With Bundled FLTK #BundledBuild#
-- *** Linux & *BSD
--
-- $InstallationLinuxBundled
-- *** Mac (Yosemite, El Capitan, Sierra)
--
-- $InstallationMacBundled
-- *** Windows(7,8,10)(64-bit)
--
-- $InstallationWindowsBundled
-- ** Compile FLTK Yourself #SelfCompilation#
-- *** Linux & *BSD
--
-- $InstallationLinux
-- *** Mac (Yosemite & El Capitan)
--
-- $InstallationMac
-- *** Windows(7,8,10)(64-bit)
--
-- $InstallationWindows10
-- * Demos
--
-- $Demos
-- * Getting Started
--
-- $GettingStarted
-- * Fluid Support #FluidSupport#
--
-- $FluidSupport
-- * Stack Traces
--
-- $StackTrace
-- * API Guide
--
-- ** Guide to the Haddock Docs
--
-- $guidetothehaddockdocs
-- ** Widget Construction
--
-- $widgetconstruction
-- ** Widget Methods
--
-- $widgetmethods
-- ** Widget Hierachy
--
-- $widgethierarchyguide
-- ** Overriding C++ Methods (Creating Custom Widgets)
--
-- $overriding
-- ** Explicitly Calling Base Class Methods
--
-- $explicitbaseclasscalling
-- ** Overriding the Widget Destructor
--
-- $destructors
-- * Slow Compilation Issues
--
-- $Compilation
-- * Running in the REPL #RunningInTheREPL#
--
-- $REPL
-- * Core Types
module Graphics.UI.FLTK.LowLevel.Fl_Types,
-- * Widgets
module Graphics.UI.FLTK.LowLevel.Base.Adjuster,
module Graphics.UI.FLTK.LowLevel.Adjuster,
module Graphics.UI.FLTK.LowLevel.Ask,
module Graphics.UI.FLTK.LowLevel.BMPImage,
module Graphics.UI.FLTK.LowLevel.Bitmap,
module Graphics.UI.FLTK.LowLevel.Box,
module Graphics.UI.FLTK.LowLevel.Base.Browser,
module Graphics.UI.FLTK.LowLevel.Browser,
module Graphics.UI.FLTK.LowLevel.Base.Button,
module Graphics.UI.FLTK.LowLevel.Button,
module Graphics.UI.FLTK.LowLevel.Base.CheckButton,
module Graphics.UI.FLTK.LowLevel.CheckButton,
module Graphics.UI.FLTK.LowLevel.Base.Choice,
module Graphics.UI.FLTK.LowLevel.Choice,
module Graphics.UI.FLTK.LowLevel.Base.Clock,
module Graphics.UI.FLTK.LowLevel.Clock,
module Graphics.UI.FLTK.LowLevel.Base.ColorChooser,
module Graphics.UI.FLTK.LowLevel.ColorChooser,
module Graphics.UI.FLTK.LowLevel.CopySurface,
module Graphics.UI.FLTK.LowLevel.Base.Counter,
module Graphics.UI.FLTK.LowLevel.Counter,
module Graphics.UI.FLTK.LowLevel.Base.Dial,
module Graphics.UI.FLTK.LowLevel.Dial,
module Graphics.UI.FLTK.LowLevel.DoubleWindow,
module Graphics.UI.FLTK.LowLevel.Base.DoubleWindow,
module Graphics.UI.FLTK.LowLevel.Draw,
module Graphics.UI.FLTK.LowLevel.Base.FileBrowser,
module Graphics.UI.FLTK.LowLevel.FileBrowser,
module Graphics.UI.FLTK.LowLevel.Base.FileInput,
module Graphics.UI.FLTK.LowLevel.FileInput,
module Graphics.UI.FLTK.LowLevel.FillDial,
module Graphics.UI.FLTK.LowLevel.Base.FillSlider,
module Graphics.UI.FLTK.LowLevel.FillSlider,
module Graphics.UI.FLTK.LowLevel.GIFImage,
module Graphics.UI.FLTK.LowLevel.Base.Group,
module Graphics.UI.FLTK.LowLevel.Group,
module Graphics.UI.FLTK.LowLevel.Base.HorFillSlider,
module Graphics.UI.FLTK.LowLevel.HorFillSlider,
module Graphics.UI.FLTK.LowLevel.Base.HorNiceSlider,
module Graphics.UI.FLTK.LowLevel.HorNiceSlider,
module Graphics.UI.FLTK.LowLevel.Base.HorSlider,
module Graphics.UI.FLTK.LowLevel.HorSlider,
module Graphics.UI.FLTK.LowLevel.HorValueSlider,
module Graphics.UI.FLTK.LowLevel.Image,
module Graphics.UI.FLTK.LowLevel.ImageSurface,
module Graphics.UI.FLTK.LowLevel.Base.Input,
module Graphics.UI.FLTK.LowLevel.Input,
module Graphics.UI.FLTK.LowLevel.JPEGImage,
module Graphics.UI.FLTK.LowLevel.Base.LightButton,
module Graphics.UI.FLTK.LowLevel.LightButton,
module Graphics.UI.FLTK.LowLevel.LineDial,
module Graphics.UI.FLTK.LowLevel.Base.MenuBar,
module Graphics.UI.FLTK.LowLevel.MenuBar,
module Graphics.UI.FLTK.LowLevel.Base.MenuButton,
module Graphics.UI.FLTK.LowLevel.MenuButton,
module Graphics.UI.FLTK.LowLevel.Base.MenuItem,
module Graphics.UI.FLTK.LowLevel.MenuItem,
module Graphics.UI.FLTK.LowLevel.Base.MenuPrim,
module Graphics.UI.FLTK.LowLevel.MenuPrim,
module Graphics.UI.FLTK.LowLevel.MultiLabel,
module Graphics.UI.FLTK.LowLevel.NativeFileChooser,
module Graphics.UI.FLTK.LowLevel.Base.NiceSlider,
module Graphics.UI.FLTK.LowLevel.NiceSlider,
module Graphics.UI.FLTK.LowLevel.Base.Output,
module Graphics.UI.FLTK.LowLevel.Output,
module Graphics.UI.FLTK.LowLevel.OverlayWindow,
module Graphics.UI.FLTK.LowLevel.Base.OverlayWindow,
module Graphics.UI.FLTK.LowLevel.PNGImage,
module Graphics.UI.FLTK.LowLevel.PNMImage,
module Graphics.UI.FLTK.LowLevel.Base.Pack,
module Graphics.UI.FLTK.LowLevel.Pack,
module Graphics.UI.FLTK.LowLevel.Pixmap,
module Graphics.UI.FLTK.LowLevel.Base.Positioner,
module Graphics.UI.FLTK.LowLevel.Positioner,
module Graphics.UI.FLTK.LowLevel.Base.Progress,
module Graphics.UI.FLTK.LowLevel.Progress,
module Graphics.UI.FLTK.LowLevel.RGBImage,
module Graphics.UI.FLTK.LowLevel.Base.RadioLightButton,
module Graphics.UI.FLTK.LowLevel.RadioLightButton,
module Graphics.UI.FLTK.LowLevel.Base.RepeatButton,
module Graphics.UI.FLTK.LowLevel.RepeatButton,
module Graphics.UI.FLTK.LowLevel.Base.ReturnButton,
module Graphics.UI.FLTK.LowLevel.ReturnButton,
module Graphics.UI.FLTK.LowLevel.Base.Roller,
module Graphics.UI.FLTK.LowLevel.Roller,
module Graphics.UI.FLTK.LowLevel.Base.RoundButton,
module Graphics.UI.FLTK.LowLevel.RoundButton,
module Graphics.UI.FLTK.LowLevel.SVGImage,
module Graphics.UI.FLTK.LowLevel.Base.Scrollbar,
module Graphics.UI.FLTK.LowLevel.Scrollbar,
module Graphics.UI.FLTK.LowLevel.Base.Scrolled,
module Graphics.UI.FLTK.LowLevel.Scrolled,
module Graphics.UI.FLTK.LowLevel.SelectBrowser,
module Graphics.UI.FLTK.LowLevel.Base.SimpleTerminal,
module Graphics.UI.FLTK.LowLevel.SimpleTerminal,
module Graphics.UI.FLTK.LowLevel.Base.SingleWindow,
module Graphics.UI.FLTK.LowLevel.SingleWindow,
module Graphics.UI.FLTK.LowLevel.Base.Slider,
module Graphics.UI.FLTK.LowLevel.Slider,
module Graphics.UI.FLTK.LowLevel.Base.Spinner,
module Graphics.UI.FLTK.LowLevel.Spinner,
module Graphics.UI.FLTK.LowLevel.Base.SysMenuBar,
module Graphics.UI.FLTK.LowLevel.SysMenuBar,
module Graphics.UI.FLTK.LowLevel.Base.Table,
module Graphics.UI.FLTK.LowLevel.Table,
module Graphics.UI.FLTK.LowLevel.Base.TableRow,
module Graphics.UI.FLTK.LowLevel.TableRow,
module Graphics.UI.FLTK.LowLevel.Base.Tabs,
module Graphics.UI.FLTK.LowLevel.Tabs,
module Graphics.UI.FLTK.LowLevel.TextBuffer,
module Graphics.UI.FLTK.LowLevel.Base.TextDisplay,
module Graphics.UI.FLTK.LowLevel.TextDisplay,
module Graphics.UI.FLTK.LowLevel.Base.TextEditor,
module Graphics.UI.FLTK.LowLevel.TextEditor,
module Graphics.UI.FLTK.LowLevel.TextSelection,
module Graphics.UI.FLTK.LowLevel.Base.Tile,
module Graphics.UI.FLTK.LowLevel.Tile,
module Graphics.UI.FLTK.LowLevel.Base.ToggleButton,
module Graphics.UI.FLTK.LowLevel.ToggleButton,
module Graphics.UI.FLTK.LowLevel.Tooltip,
module Graphics.UI.FLTK.LowLevel.Base.Tree,
module Graphics.UI.FLTK.LowLevel.Tree,
module Graphics.UI.FLTK.LowLevel.TreeItem,
module Graphics.UI.FLTK.LowLevel.TreePrefs,
module Graphics.UI.FLTK.LowLevel.Base.Valuator,
module Graphics.UI.FLTK.LowLevel.Valuator,
module Graphics.UI.FLTK.LowLevel.Base.ValueInput,
module Graphics.UI.FLTK.LowLevel.ValueInput,
module Graphics.UI.FLTK.LowLevel.Base.ValueOutput,
module Graphics.UI.FLTK.LowLevel.ValueOutput,
module Graphics.UI.FLTK.LowLevel.Base.ValueSlider,
module Graphics.UI.FLTK.LowLevel.ValueSlider,
module Graphics.UI.FLTK.LowLevel.Widget,
module Graphics.UI.FLTK.LowLevel.Base.Widget,
module Graphics.UI.FLTK.LowLevel.Base.Window,
module Graphics.UI.FLTK.LowLevel.Window,
module Graphics.UI.FLTK.LowLevel.Base.Wizard,
module Graphics.UI.FLTK.LowLevel.Wizard,
module Graphics.UI.FLTK.LowLevel.XBMImage,
module Graphics.UI.FLTK.LowLevel.XPMImage,
-- * Machinery for static dispatch
module Graphics.UI.FLTK.LowLevel.Dispatch,
-- * Association of widgets and functions
module Graphics.UI.FLTK.LowLevel.Hierarchy
)
where
import Graphics.UI.FLTK.LowLevel.Base.Adjuster
import Graphics.UI.FLTK.LowLevel.Adjuster()
import Graphics.UI.FLTK.LowLevel.Ask
import Graphics.UI.FLTK.LowLevel.BMPImage
import Graphics.UI.FLTK.LowLevel.Bitmap
import Graphics.UI.FLTK.LowLevel.Box
import Graphics.UI.FLTK.LowLevel.Base.Browser
import Graphics.UI.FLTK.LowLevel.Browser()
import Graphics.UI.FLTK.LowLevel.Base.Button
import Graphics.UI.FLTK.LowLevel.Button()
import Graphics.UI.FLTK.LowLevel.Base.CheckButton
import Graphics.UI.FLTK.LowLevel.CheckButton()
import Graphics.UI.FLTK.LowLevel.Base.Choice
import Graphics.UI.FLTK.LowLevel.Choice()
import Graphics.UI.FLTK.LowLevel.Base.Clock
import Graphics.UI.FLTK.LowLevel.Clock()
import Graphics.UI.FLTK.LowLevel.Base.ColorChooser
import Graphics.UI.FLTK.LowLevel.ColorChooser()
import Graphics.UI.FLTK.LowLevel.CopySurface
import Graphics.UI.FLTK.LowLevel.Base.Counter
import Graphics.UI.FLTK.LowLevel.Counter()
import Graphics.UI.FLTK.LowLevel.Base.Dial
import Graphics.UI.FLTK.LowLevel.Dial()
import Graphics.UI.FLTK.LowLevel.Dispatch
import Graphics.UI.FLTK.LowLevel.DoubleWindow()
import Graphics.UI.FLTK.LowLevel.Base.DoubleWindow
import Graphics.UI.FLTK.LowLevel.Draw
import Graphics.UI.FLTK.LowLevel.Base.FileBrowser
import Graphics.UI.FLTK.LowLevel.FileBrowser()
import Graphics.UI.FLTK.LowLevel.Base.FileInput
import Graphics.UI.FLTK.LowLevel.FileInput()
import Graphics.UI.FLTK.LowLevel.FillDial
import Graphics.UI.FLTK.LowLevel.Base.FillSlider
import Graphics.UI.FLTK.LowLevel.FillSlider()
import Graphics.UI.FLTK.LowLevel.Fl_Types
import Graphics.UI.FLTK.LowLevel.GIFImage
import Graphics.UI.FLTK.LowLevel.Base.Group
import Graphics.UI.FLTK.LowLevel.Group()
import Graphics.UI.FLTK.LowLevel.Hierarchy
import Graphics.UI.FLTK.LowLevel.Base.HorFillSlider
import Graphics.UI.FLTK.LowLevel.HorFillSlider()
import Graphics.UI.FLTK.LowLevel.Base.HorNiceSlider
import Graphics.UI.FLTK.LowLevel.HorNiceSlider()
import Graphics.UI.FLTK.LowLevel.Base.HorSlider
import Graphics.UI.FLTK.LowLevel.HorSlider()
import Graphics.UI.FLTK.LowLevel.HorValueSlider
import Graphics.UI.FLTK.LowLevel.Image
import Graphics.UI.FLTK.LowLevel.ImageSurface
import Graphics.UI.FLTK.LowLevel.Base.Input
import Graphics.UI.FLTK.LowLevel.Input()
import Graphics.UI.FLTK.LowLevel.JPEGImage
import Graphics.UI.FLTK.LowLevel.Base.LightButton
import Graphics.UI.FLTK.LowLevel.LightButton()
import Graphics.UI.FLTK.LowLevel.LineDial
import Graphics.UI.FLTK.LowLevel.Base.MenuBar
import Graphics.UI.FLTK.LowLevel.MenuBar()
import Graphics.UI.FLTK.LowLevel.Base.MenuButton
import Graphics.UI.FLTK.LowLevel.MenuButton()
import Graphics.UI.FLTK.LowLevel.Base.MenuItem
import Graphics.UI.FLTK.LowLevel.MenuItem()
import Graphics.UI.FLTK.LowLevel.Base.MenuPrim
import Graphics.UI.FLTK.LowLevel.MenuPrim()
import Graphics.UI.FLTK.LowLevel.MultiLabel
import Graphics.UI.FLTK.LowLevel.NativeFileChooser
import Graphics.UI.FLTK.LowLevel.Base.NiceSlider
import Graphics.UI.FLTK.LowLevel.NiceSlider()
import Graphics.UI.FLTK.LowLevel.Base.Output
import Graphics.UI.FLTK.LowLevel.Output()
import Graphics.UI.FLTK.LowLevel.Base.OverlayWindow
import Graphics.UI.FLTK.LowLevel.OverlayWindow()
import Graphics.UI.FLTK.LowLevel.PNGImage
import Graphics.UI.FLTK.LowLevel.PNMImage
import Graphics.UI.FLTK.LowLevel.Base.Pack
import Graphics.UI.FLTK.LowLevel.Pack()
import Graphics.UI.FLTK.LowLevel.Pixmap
import Graphics.UI.FLTK.LowLevel.Base.Positioner
import Graphics.UI.FLTK.LowLevel.Positioner()
import Graphics.UI.FLTK.LowLevel.Base.Progress
import Graphics.UI.FLTK.LowLevel.Progress()
import Graphics.UI.FLTK.LowLevel.RGBImage
import Graphics.UI.FLTK.LowLevel.Base.RadioLightButton
import Graphics.UI.FLTK.LowLevel.RadioLightButton()
import Graphics.UI.FLTK.LowLevel.Base.RepeatButton
import Graphics.UI.FLTK.LowLevel.RepeatButton()
import Graphics.UI.FLTK.LowLevel.Base.ReturnButton
import Graphics.UI.FLTK.LowLevel.ReturnButton()
import Graphics.UI.FLTK.LowLevel.Base.Roller
import Graphics.UI.FLTK.LowLevel.Roller()
import Graphics.UI.FLTK.LowLevel.Base.RoundButton
import Graphics.UI.FLTK.LowLevel.RoundButton()
import Graphics.UI.FLTK.LowLevel.SVGImage
import Graphics.UI.FLTK.LowLevel.Base.Scrollbar
import Graphics.UI.FLTK.LowLevel.Scrollbar()
import Graphics.UI.FLTK.LowLevel.Base.Scrolled
import Graphics.UI.FLTK.LowLevel.Scrolled()
import Graphics.UI.FLTK.LowLevel.SelectBrowser
import Graphics.UI.FLTK.LowLevel.Base.SimpleTerminal
import Graphics.UI.FLTK.LowLevel.SimpleTerminal()
import Graphics.UI.FLTK.LowLevel.Base.SingleWindow
import Graphics.UI.FLTK.LowLevel.SingleWindow()
import Graphics.UI.FLTK.LowLevel.Base.Slider
import Graphics.UI.FLTK.LowLevel.Slider()
import Graphics.UI.FLTK.LowLevel.Base.Spinner
import Graphics.UI.FLTK.LowLevel.Spinner()
import Graphics.UI.FLTK.LowLevel.Base.SysMenuBar
import Graphics.UI.FLTK.LowLevel.SysMenuBar()
import Graphics.UI.FLTK.LowLevel.Base.Table
import Graphics.UI.FLTK.LowLevel.Table()
import Graphics.UI.FLTK.LowLevel.Base.TableRow
import Graphics.UI.FLTK.LowLevel.TableRow()
import Graphics.UI.FLTK.LowLevel.Base.Tabs
import Graphics.UI.FLTK.LowLevel.Tabs()
import Graphics.UI.FLTK.LowLevel.TextBuffer
import Graphics.UI.FLTK.LowLevel.Base.TextDisplay
import Graphics.UI.FLTK.LowLevel.TextDisplay()
import Graphics.UI.FLTK.LowLevel.Base.TextEditor
import Graphics.UI.FLTK.LowLevel.TextEditor()
import Graphics.UI.FLTK.LowLevel.TextSelection()
import Graphics.UI.FLTK.LowLevel.Base.Tile
import Graphics.UI.FLTK.LowLevel.Tile()
import Graphics.UI.FLTK.LowLevel.Base.ToggleButton
import Graphics.UI.FLTK.LowLevel.ToggleButton()
import Graphics.UI.FLTK.LowLevel.Tooltip
import Graphics.UI.FLTK.LowLevel.Base.Tree
import Graphics.UI.FLTK.LowLevel.Tree()
import Graphics.UI.FLTK.LowLevel.TreeItem
import Graphics.UI.FLTK.LowLevel.TreePrefs
import Graphics.UI.FLTK.LowLevel.Base.Valuator
import Graphics.UI.FLTK.LowLevel.Valuator()
import Graphics.UI.FLTK.LowLevel.Base.ValueInput
import Graphics.UI.FLTK.LowLevel.ValueInput()
import Graphics.UI.FLTK.LowLevel.Base.ValueOutput
import Graphics.UI.FLTK.LowLevel.ValueOutput()
import Graphics.UI.FLTK.LowLevel.Base.ValueSlider
import Graphics.UI.FLTK.LowLevel.ValueSlider()
import Graphics.UI.FLTK.LowLevel.Base.Widget
import Graphics.UI.FLTK.LowLevel.Widget()
import Graphics.UI.FLTK.LowLevel.Base.Window
import Graphics.UI.FLTK.LowLevel.Window()
import Graphics.UI.FLTK.LowLevel.Base.Wizard
import Graphics.UI.FLTK.LowLevel.Wizard()
import Graphics.UI.FLTK.LowLevel.XBMImage
import Graphics.UI.FLTK.LowLevel.XPMImage
-- $Module Documentation
-- This module re-exports all the available widgets and
-- their core types. The types and list of widgets is listed under the __Core
-- Types__ and __Widgets__ section below.
--
-- A general introduction to the library follows.
--
-- $Motivation
-- This library aims to make it easy for users to build native apps that work portably across platforms.
--
-- I'm also very interested in the user interface renaissance in the programming community,
-- whether the various kinds of functional reactive programming, meta-object protocol UIs,
-- or something like React.js.
--
-- The hope is that a low-cost, hassle-free way of getting a UI up and running
-- without having to deal with browser, authentication, and compilation issues
-- will make it more fun to play around with these great ideas using Haskell.
--
-- == Why a native toolkit?
-- Even in this era of web interfaces, it is still
-- useful to be able to make native apps. They are usually faster and have fewer
-- security issues.
--
-- == Why FLTK?
-- - I chose FLTK because it was small enough that one person could bind the whole thing in an initial
-- pass. Larger toolkits like QT, although much slicker, would require many man-years of effort.
-- - FLTK is quite featureful.
-- - FLTK is mature and maintained. The project is about 20 years old, and I have had good experiences with the community.
-- - FLTK comes with a simple but quite useful GUI builder, <https://en.wikipedia.org/wiki/FLUID Fluid> which is now able to
-- generate Haskell code. See the `Fluid Support` section for more details.
--
-- == What about HsQML\/WxHaskell/Gtk2Hs?
-- These are all great projects and produce really nice UIs, but they all fail
-- at least one of criterion listed under the __Goals__ section below.
--
-- To my knowledge, as of the first quarter of 2019, no other package
-- in the Haskell ecosystem meets all those constraints.
--
-- $Goals
-- The goals of this library are to provide a low-level API to the <http://fltk.org FLTK> that:
--
-- (1) provides full coverage of the toolkit allowing the user to write GUIs in pure Haskell.
-- (2) feels like it has polymorphic dispatch, meaning a single function dispatches to the right implementation based on the type of widget it is given.
-- (3) is /not/ monolithic, meaning new widgets can be incorporated the user's application without needing to recompile this library.
-- (4) is easy to install. This library has a minimum of dependencies and <http://fltk.org FLTK> itself compiles cleanly on most architectures.
-- And now there is a <https://hackage.haskell.org/package/fltkhs/docs/Graphics-UI-FLTK-LowLevel-FLTKHS.html#g:4 bundled option> where Cabal/Stack build FLTK for you behind the scenes.
-- (5) allows the user to produce statically linked binaries with a minimum of external dependencies.
-- (6) includes a lot of <https://github.com/deech/fltkhs-demos complete> <https://github.com/deech/fltkhs-fluid-demos working> demos so that you can get up and running faster.
-- (7) comes with <https://hackage.haskell.org/package/fltkhs/docs/Graphics-UI-FLTK-LowLevel-FLTKHS.html#g:15 GUI builder support> to alleviate the tedium of laying out widgets by hand.
--
-- $FluidSupport
--
-- This package also comes with a utility (fltkhs-fluidtohs) that takes a user
-- interface generated using the <https://en.wikipedia.org/wiki/FLUID Fluid GUI builder>
-- that ships with FLTK and generates Haskell code.
--
-- Now the user can drag and drop widgets into place instead of having to
-- calculate coordinates and sizes by hand. Additionally, arbitrary Haskell code
-- can be inserted into Fluid interfaces, allowing the user to do most of the callback
-- wiring directly from Fluid.
--
-- The quickest way to get started is to download the
-- <https://github.com/deech/fltkhs-fluid-hello-world Fluid/Haskell project template>.
-- The @Setup.hs@ that comes with the skeleton is configured to use
-- the 'fltkhs-fluidtohs' utility to automatically convert any Fluid in 'src'
-- directory into a Haskell module of the same name during the preprocess step.
-- This means using Fluid in a FLTKHS project is as simple as creating a Fluid
-- interface and running 'stack build --flag fltkhs:bundled' or 'stack install --flag fltkhs:bundled'.
--
-- Additionally, the <https://github.com/deech/fltkhs-fluid-demos fltkhs-fluid-demos> package
-- comes with a number of demos that show how Fluid integrates with FLTKS.
--
-- $LookAndFeel
-- Now FLTKHS has a [themes
-- package](https://hackage.haskell.org/package/fltkhs-themes/docs/Graphics-UI-FLTK-Theme-Light.html)
-- which considerably improves look and feel. The documentation for this package
-- still applies because the theme mostly just re-draws widgets to look a little
-- nicer so the fundamentals of the API are not touched.
-- $Obstacles
-- This section attempts to briefly highlight some possible dealbreakers users
-- might want to know about before proceeding. To be clear, building and deploying
-- portable static application binaries works well on all platforms which is why the
-- library is considered usable. And most of these issues are being aggressively
-- addressed but in the interests of full disclosure ...
--
-- == Compile Times
-- Currently a dense app with ~ 160-180 widgets crammed into the same window takes
-- 9-12 seconds to compile with GHC 7.10.3 on a 32GB quad-core machine.
-- The good news is that this is a <https://ghc.haskell.org/trac/ghc/ticket/12506 known issue>.
--
-- $StackTrace
--
-- In a traditional callback-heavy API such as FLTKHS, null pointers happen, which
-- is why FLTKHS supports partial stack traces. All FLTK functions throw an
-- error along with a stack trace when given a null 'Ref'.
--
-- For pre-7.10 GHCs, stack traces will only be shown if the
-- <https://wiki.haskell.org/Debugging#General_usage 'xc'> flag is used when
-- compiling FLTKHS.
--
-- If compiled with GHC > 7.10, a partial stack trace is transparently available
-- to the user. The recently minted
-- <https://hackage.haskell.org/package/base-4.8.1.0/docs/GHC-Stack.html#g:3 'CallStack'>
-- implicit parameter is used to get a trace of the function that
-- made the offending call along with a file name and line number. For
-- example, in the following code:
--
-- @
-- buttonCb :: Ref Button -> IO ()
-- buttonCb b' = do
-- FL.deleteWidget b'
-- l' <- getLabel b'
-- ...
--
-- main :: IO ()
-- main = do
-- window <- windowNew ...
-- begin window
-- b' <- buttonNew ...
-- setCallback b' buttonCb
-- ...
-- @
--
-- a button is placed inside a window in the main method, but the first time it is clicked, the callback will delete it and then try
-- to extract the label from the null 'Ref'.
-- The resulting stack trace will look something like:
--
-- @
-- Ref does not exist. ?loc, called at src\/Graphics\/UI\/FLTK\/LowLevel\/Fl_Types.chs:395:58 in fltkh_Cx8029B5VOwKjdT0OwMERC:Graphics.UI.FLTK.LowLevel.Fl_Types
-- toRefPtr, called at src\/Graphics\/UI\/FLTK\/LowLevel\/Fl_Types.chs:403:22 in fltkh_Cx8029B5VOwKjdT0OwMERC:Graphics.UI.FLTK.LowLevel.Fl_Types
-- withRef, called at src\/Graphics\/UI\/FLTK\/LowLevel\/Hierarchy.hs:1652:166 in fltkh_Cx8029B5VOwKjdT0OwMERC:Graphics.UI.FLTK.LowLevel.Hierarchy
-- getLabel, called at src\/Main.hs:11:10 in main:Main
-- @
--
-- It says that the null pointer was originally detected in the library function 'toRefPtr' function, which was called by the library function 'withRef', which
-- was called by 'getLabel' on line 11 of 'src/Main.hs'. Notice, however, that the trace stops there. It does not tell you 'getLabel' was invoked from 'buttonCb'.
-- For a more detailed trace, the 'CallStack' implicit parameter needs to be passed to each function in the chain like:
--
-- @
-- buttonCb :: (?loc :: CallStack) => Ref Button ...
-- ...
-- main :: IO ()
-- ...
-- @
--
-- $InstallationSummary
-- There are two ways to install FLTKHS, building with the bundled build
-- ("Graphics.UI.FLTK.LowLevel.FLTKHS#BundledBuild"), or compiling and
-- installing FLTK from scratch yourself
-- ("Graphics.UI.FLTK.LowLevel.FLTKHS#SelfCompilation"). The bundled way is by
-- far the easiest on all platforms. It is completely self-contained, you don't
-- need any sudo access to your system.
--
-- For now FLTKHS tracks the [1.4 version Github repo](https://github.com/fltk/fltk) instead
-- of the stable releases. The reason is that it's been quite a while the FLTK
-- project cut an official release but the development branch is actually quite
-- stable and has acquired a lot of useful features including HiDPI and SVG
-- support which are exposed via these bindings.
--
-- NOTE: Since we are temporarily using stable releases please don't install FLTK with your package manager.
--
-- $InstallationLinuxBundled
-- The steps are:
--
-- - Make sure to have OpenGL installed if you need it.
-- - Ensure that 'make', 'autoconf' and 'autoheader' are available on your system.
-- - Download & install <http://docs.haskellstack.org/en/stable/README/#how-to-install Stack>.
-- - Download & install the <https://github.com/deech/fltkhs-hello-world/archive/master.tar.gz FLTKHS hello world skeleton>.
-- - Verify the install by running `fltkhs-hello-world`.
--
-- == Download & Install Stack
-- Pick the <http://docs.haskellstack.org/en/stable/README/#how-to-install Stack installer> that matches your distribution and install according to the instructions.
--
-- == Download & Install the FLTKHS Hello World Skeleton
-- === Downloading Without Git
-- If 'git' is not installed, download the latest version of the fltkhs-hello-world application skeleton from <https://github.com/deech/fltkhs-hello-world/archive/master.tar.gz here>.
--
--
-- Extract and rename the archive:
--
-- @
-- > tar -zxvf fltkhs-hello-world-master.tar.gz
-- > mv fltkhs-hello-world-master fltkhs-hello-world
-- @
--
-- === Downloading With Git
-- If 'git' is available:
--
-- @
-- > git clone http://github.com/deech/fltkhs-hello-world
-- @
--
-- === Building
-- Build it with Stack:
--
-- @
-- > cd fltkhs-hello-world
-- > stack setup
-- > stack install --flag fltkhs:bundled
-- or if you need OpenGL support
-- > stack install --flag fltkhs:bundled --flag fltkhs:opengl
-- @
--
-- == Verify The Install
-- Test that the build completed successfully by invoking:
--
-- @
-- > stack exec fltkhs-hello-world
-- @
--
-- You will be greeted by an incredibly boring little window with a button that says "Hello world".
-- If you click it, it will change to "Goodbye world".
--
--
-- $InstallationLinux
-- The steps are:
--
-- - Make sure you have OpenGL installed.
-- - Download & install <http://docs.haskellstack.org/en/stable/README/#how-to-install Stack>.
-- - Download & install <https://github.com/fltk/fltk/archive/master.tar.gz FLTK 1.4>.
-- - Download & install the <https://github.com/deech/fltkhs-hello-world/archive/master.tar.gz FLTKHS hello world skeleton>.
-- - Verify the install by running `fltkhs-hello-world`.
--
-- == Download & Install Stack
-- Pick the <http://docs.haskellstack.org/en/stable/README/#how-to-install Stack installer> that matches your distribution and install according the instructions.
--
-- == Download & Install FLTK-1.4
-- Please make sure to only download version <https://github.com/fltk/fltk/archive/master.tar.gz FLTK 1.4>.
-- It should build and install smoothly with the standard:
--
-- @
-- > ./configure --enable-shared --enable-localjpeg --enable-localzlib --enable-localpng --enable-xft
-- or if you need OpenGL support
-- > ./configure --enable-gl --enable-shared --enable-localjpeg --enable-localzlib --enable-localpng --enable-xft
-- > make
-- > sudo make install
-- @
--
--
-- If you didn't install FLTK from source, you can use the 'fltk-config' tool to ensure that version 1.4 is installed:
--
-- @
-- > fltk-config --version
-- 1.4
-- @
--
-- The FLTK headers should be in the include path, along with
-- the standard FLTK libraries, `fltk_images`, and `fltk_gl`. You will also need
-- the `make`, `autoconf`, and `autoheader` tools to build the Haskell bindings.
--
--
-- The reason we install from source is that some package managers seem to be
-- behind on versions (as of this writing Ubuntu 14.04 is still on 1.3.2) and
-- others put the headers and libraries in nonstandard locations, which will
-- cause the Haskell bindings to throw compilation errors.
--
--
-- == Download & Install the FLTKHS Hello World Skeleton
-- === Downloading Without Git
-- If 'git' is not installed, download the latest version of the `fltkhs-hello-world` application skeleton from <https://github.com/deech/fltkhs-hello-world/archive/master.tar.gz here>.
--
-- Extract and enter the archive:
--
-- @
-- > tar -zxvf fltkhs-hello-world-master.tar.gz
-- > mv fltkhs-hello-world-master fltkhs-hello-world
-- @
--
-- === Downloading With Git
-- If 'git' is available:
--
-- @
-- > git clone http://github.com/deech/fltkhs-hello-world
-- @
--
-- === Building
-- Build it with Stack:
--
-- @
-- > cd fltkhs-hello-world
-- > stack setup
-- > stack install
-- or if you need OpenGL support
-- > stack install --flag fltkhs:opengl
-- @
--
-- __Note:__ If the `install` step produces a flood of `undefined reference` errors,
-- please ensure that you have the right version of FLTK (1.4) installed and
-- that the headers are in the expected locations. Some package
-- managers put the libraries and headers in nonstandard places, so it
-- is best to build from source.
--
-- == Verify The Install
-- Test that the build completed successfully by invoking:
--
-- @
-- > stack exec fltkhs-hello-world
-- @
--
-- You will be greeted by an incredibly boring little window with a button that says "Hello world".
-- If you click it, it will change to "Goodbye world."
-- $InstallationMacBundled
-- Mac versions older than El Capitan and Yosemite are not supported.
--
-- The general steps are:
--
-- - Brew Install Stack.
-- - Download & install the <https://github.com/deech/fltkhs-hello-world/archive/master.tar.gz FLTKHS hello world skeleton>.
-- - Verify the install by running `fltkhs-hello-world`.
--
-- == Brew Install Stack
-- This should be as simple as:
--
-- @
-- > brew install haskell-stack
-- @
--
-- == Brew Install Autoconf
-- @
-- > brew install autoconf
-- @
--
--
-- == Download & Install the FLTKHS Hello World Skeleton
-- === Downloading Without Git
-- If 'git' is not installed, download the latest version of the fltkhs-hello-world application skeleton from <https://github.com/deech/fltkhs-hello-world/archive/master.tar.gz here>.
--
-- Extract the archive:
--
-- @
-- > cd \/Users\/\<username\>/Downloads\/
-- > tar -zxvf fltkhs-hello-world-master.tar.gz
-- > mv fltkhs-hello-world-master fltkhs-hello-world
-- @
--
-- === Downloading With Git
-- If 'git' is available:
--
-- @
-- > git clone http://github.com/deech/fltkhs-hello-world
-- @
--
-- === Building
-- Build it with Stack:
--
-- @
-- > cd fltkhs-hello-world
-- > stack setup
-- > stack install --flag fltkhs:bundled
-- or if you need OpenGL support
-- > stack install --flag fltkhs:bundled --flag fltkhs:opengl
-- @
--
-- == Verify The Install
-- Test that the build completed successfully by invoking:
--
-- @
-- > stack exec fltkhs-hello-world
-- @
--
-- You will be greeted by an incredibly boring little window with a button that says "Hello world",
-- if you click it, it will change to "Goodbye world."
-- $InstallationMac
-- Unfortunately Mac versions older than El Capitan and Yosemite are not supported.
--
-- The general steps are:
--
-- - Brew Install Stack.
-- - Download & install the <https://github.com/deech/fltkhs-hello-world/archive/master.tar.gz FLTKHS hello world skeleton>.
-- - Verify the install by running `fltkhs-hello-world`.
--
-- == Brew Install Stack
-- This should be as simple as:
--
-- @
-- > brew install haskell-stack
-- @
--
-- == Brew Install Autoconf
-- @
-- > brew install autoconf
-- @
--
-- == Compile & Install FLTK from Source.
-- The `brew` package for the current stable release of FLTK is broken. Fortunately installing from source is pretty
-- quick and painless.
--
--
-- @
-- > wget https://github.com/fltk/fltk/archive/master.tar.gz
-- > tar -zxf fltk-1.3.4-1-source.tar.gz
-- > cd fltk-master
-- > ./configure --enable-shared --enable-localjpeg --enable-localzlib --enable-localpng --enable-xft
-- or if you need OpenGL support
-- > ./configure --enable-gl --enable-shared --enable-localjpeg --enable-localzlib --enable-localpng --enable-xft
-- > make
-- > sudo make install
-- > fltk-config --version
-- 1.4
-- @
--
-- == Download & Install the FLTKHS Hello World Skeleton
-- === Downloading Without Git
-- If 'git' is not installed, download the latest version of the fltkhs-hello-world application skeleton from <https://github.com/deech/fltkhs-hello-world/archive/master.tar.gz here>.
--
--
-- Extract the archive:
--
-- @
-- > cd \/Users\/\<username\>/Downloads\/
-- > tar -zxvf fltkhs-hello-world-master.tar.gz
-- > mv fltkhs-hello-world-master fltkhs-hello-world
-- @
--
-- === Downloading With Git
-- If 'git' is available:
--
-- @
-- > git clone http://github.com/deech/fltkhs-hello-world
-- @
--
-- === Building
-- Build it with Stack:
--
-- @
-- > cd fltkhs-hello-world
-- > stack setup
-- > stack install
-- or if you need OpenGL support
-- > stack install --flag fltkhs:opengl
-- @
--
-- == Verify The Install
-- Test that the build completed successfully by invoking:
--
-- @
-- > stack exec fltkhs-hello-world
-- @
--
-- You will be greeted by an incredibly boring little window with a button that says "Hello world".
-- If you click it, it will change to "Goodbye world".
-- $InstallationWindowsBundled
--
-- This install guide has been tested on a Windows 7, 8 and 10.
--
-- == Install Stack
-- Downloading and following the default instructions for the standard <https://www.stackage.org/stack/windows-x86_64-installer Windows installer> should be enough.
-- If the install succeeded 'stack' should on the PATH. To test run 'cmd.exe' and do:
--
-- @
-- > stack --version
-- @
--
-- Now downloading and setup the latest GHC via 'stack':
--
-- @
-- > stack setup
-- @
--
-- From this point on we can live in the MSYS2 shell that comes with Stack. It is a far superior environment to the command prompt. To open the MSYS2 shell do:
--
-- @
-- > stack exec mintty
-- @
--
-- == Install Necessary Utilities via Pacman
-- In the MSYS2 shell prompt update and upgrade the MSYS2 installation:
--
-- @
-- > pacman -Syy
-- > pacman -Syu
-- @
--
-- ... install packages for download and extracting packages:
--
-- @
-- > pacman -S wget
-- > pacman -S tar
-- > pacman -S unzip
-- > pacman -S zip
-- > pacman -S man
-- @
--
-- ... and building C/C++ programs:
--
-- @
-- > pacman -S autoconf
-- > pacman -S make
-- > pacman -S automake
-- @
--
--
-- == Download And Install The FLTKHS Hello World Skeleton
-- The <https://github.com/deech/fltkhs-hello-world fltkhs-hello-world> skeleton is a simple Hello World GUI which provides the base structure for FLTKHS applications. Please see the 'Demos' section of this document for examples of apps that show off more complex uses of the API.
--
-- @
-- > wget --no-check-certificate https://github.com/deech/fltkhs-hello-world/archive/master.zip
-- > unzip master.zip
-- > mv fltkhs-hello-world-master fltkhs-hello-world
-- > cd fltkhs-hello-world
-- @
--
-- And install with:
--
-- @
-- > stack install --flag fltkhs:bundled
-- or if you need OpenGL support
-- > stack install --flag fltkhs:bundled --flag fltkhs:opengl
-- @
--
-- To test the installation:
--
-- @
-- > stack exec fltkhs-hello-world
-- @
--
-- You will be greeted by an incredibly boring little window with a button that says "Hello world",
-- if you click it, it will change to "Goodbye world."
--
-- == Packaging A Windows Executable
--
-- While the 'fltkhs-hello-world' application is mostly stand-alone the MSYS2 environment bundled with 'stack' seems to require 3 runtime DLLs. The DLLs are bundled with 'stack' so it's easy to zip them up with the executable and deploy. The required DLLs are: 'libstdc++-6.dll', 'libgcc_s_seh-1.dll' and 'libwinpthread-1.dll'.
--
--
--
-- First create the directory that will contain the executable and DLLs:
--
-- @
-- > mkdir \/tmp\/fltkhs-hello-world
-- @
--
-- Copy the executable over to that directory:
--
-- @
-- > cp `which fltkhs-hello-world` \/tmp\/fltkhs-hello-world
-- @
--
-- Copy over the DLLs. They are usually located in '../<ghc-version>/mingw/bin' but to make the process slightly less fragile we specify the directory relative to whatever 'ghc' is currently in 'stack' 's context:
--
-- @
-- > cp `dirname $(which ghc)`..\/mingw\/bin\/libstdc++-6.dll \/tmp\/fltkhs-hello-world
-- > cp `dirname $(which ghc)`..\/mingw\/bin\/libgcc_s_seh-1.dll \/tmp\/fltkhs-hello-world
-- > cp `dirname $(which ghc)`..\/mingw\/bin\/libwinpthread-1.dll \/tmp\/fltkhs-hello-world
-- @
--
-- Zip up archive:
--
-- @
-- > cd /tmp
-- > zip fltkhs-hello-world.zip fltkhs-hello-world/*
-- @
--
-- And that's it! Any Windows 10 user should now be able to extract 'fltkhs-hello-world.zip' and run 'fltkhs-hello-world.exe'.
--
-- $InstallationWindows10
--
-- This install guide has been tested on a Windows 7, 8 and 10.
--
-- == Install Stack
-- Downloading and following the default instructions for the standard <https://www.stackage.org/stack/windows-x86_64-installer Windows installer> should be enough.
-- If the install succeeded 'stack' should on the PATH. To test run 'cmd.exe' and do:
--
-- @
-- > stack --version
-- @
--
-- Now downloading and setup the latest GHC via 'stack':
--
-- @
-- > stack setup
-- @
--
-- From this point on we can live in the MSYS2 shell that comes with Stack. It is a far superior environment to the command prompt. To open the MSYS2 shell do:
--
-- @
-- > stack exec mintty
-- @
--
-- == Install Necessary Utilities via Pacman
-- In the MSYS2 shell prompt update and upgrade the MSYS2 installation:
--
-- @
-- > pacman -Syy
-- > pacmay -Syu
-- @
--
-- ... install packages for download and extracting packages:
--
-- @
-- > pacman -S wget
-- > pacman -S tar
-- > pacman -S unzip
-- > pacman -S zip
-- > pacman -S man
-- @
--
-- ... and building C/C++ programs:
--
-- @
-- > pacman -S autoconf
-- > pacman -S make
-- > pacman -S automake
-- @
--
-- == Download and Install FLTK
--
-- Download the latest stable build of FLTK:
--
-- @
-- > wget --no-check-certificate https://github.com/fltk/fltk/archive/master.tar.gz
-- @
--
-- Untar the FLTK archive and enter the directory:
--
-- @
-- > tar -zxf master.tar.gz
-- > cd fltk-master
-- @
--
-- Configure, make and install:
--
-- @
-- > ./configure --enable-shared --enable-localjpeg --enable-localzlib --enable-localpng --enable-xft
-- or if you need OpenGL support
-- > ./configure --enable-gl --enable-shared --enable-localjpeg --enable-localzlib --enable-localpng --enable-xft
-- > make
-- > make install
-- @
--
-- You can test your installation by running:
--
-- @
-- > fltk-config
-- 1.4
-- @
--
-- == Download And Install The FLTKHS Hello World Skeleton
-- The <https://github.com/deech/fltkhs-hello-world fltkhs-hello-world> skeleton is a simple Hello World GUI which provides the base structure for FLTKHS applications. Please see the 'Demos' section of this document for examples of apps that show off more complex uses of the API.
--
-- @
-- > wget --no-check-certificate https://github.com/deech/fltkhs-hello-world/archive/master.zip
-- > unzip master.zip
-- > mv fltkhs-hello-world-master fltkhs-hello-world
-- > cd fltkhs-hello-world
-- @
--
-- And install with:
--
-- @
-- > stack install
-- or if you need OpenGL support
-- > stack install --flag fltkhs:opengl
-- @
--
-- To test the installation:
--
-- @
-- > stack exec fltkhs-hello-world
-- @
--
-- You will be greeted by an incredibly boring little window with a button that says "Hello world".
-- If you click it, it will change to "Goodbye world".
--
-- == Packaging A Windows Executable #PackagingAWindowsExecutable#
--
-- While the 'fltkhs-hello-world' application can mostly stand alone, the MSYS2 environment bundled with 'stack' seems to require 3 runtime DLLs. The DLLs are bundled with 'stack', so you can zip them up with the executable and deploy. The required DLLs are: 'libstdc++-6.dll', 'libgcc_s_seh-1.dll' and 'libwinpthread-1.dll'.
--
--
--
-- First create the directory that will contain the executable and DLLs:
--
-- @
-- > mkdir \/tmp\/fltkhs-hello-world
-- @
--
-- Copy the executable over to that directory:
--
-- @
-- > cp `which fltkhs-hello-world` \/tmp\/fltkhs-hello-world
-- @
--
-- Copy over the DLLs. They are usually located in '../<ghc-version>/mingw/bin', but to make the process slightly less fragile we specify the directory relative to whatever 'ghc' is currently in Stack's context:
--
-- @
-- > cp `dirname $(which ghc)`..\/mingw\/bin\/libstdc++-6.dll \/tmp\/fltkhs-hello-world
-- > cp `dirname $(which ghc)`..\/mingw\/bin\/libgcc_s_seh-1.dll \/tmp\/fltkhs-hello-world
-- > cp `dirname $(which ghc)`..\/mingw\/bin\/libwinpthread-1.dll \/tmp\/fltkhs-hello-world
-- @
--
-- Zip up the archive:
--
-- @
-- > cd /tmp
-- > zip fltkhs-hello-world.zip fltkhs-hello-world/*
-- @
--
-- And that's it! Any Windows 10 user should now be able to extract 'fltkhs-hello-world.zip' and run 'fltkhs-hello-world.exe'.
--
-- $Demos
--
-- FLTKHS has almost 25 end-to-end demo applications to help you get started. They are
-- split into two sets: those <http://github.com/deech/fltkhs-demos written manually> and those
-- that <http://github.com/deech/fltkhs-fluid-demos show how to use FLUID>.
--
-- The READMEs in the repos have installation instructions, but they assume that you have
-- successfully installed FLTK and the 'fltkhs-hello-world' app (see platform specific instructions above).
--
-- $GettingStarted
--
-- By this point, I assume that you have successfully installed <https://github.com/deech/fltkhs-hello-world hello world>
-- (see above) or one of the <https://github.com/deech/fltkhs-demos demo> <https://github.com/deech/fltkhs-fluid-demos packages>.
--
--
-- = Quick Start
-- The quickest way to get started is to look at the source for the
-- <http://github.com/deech/fltkhs-hello-world FLTKHS project skeleton>. Though it is a
-- simple app, it shows the basics of widget creation and
-- callbacks.
--
-- Other <https://github.com/deech/fltkhs-demos demo> <https://github.com/deech/fltkhs-fluid-demos packages> show more complicated usage of the API.
--
-- Since the API is a low-level binding, code using it takes on the imperative
-- style of the underlying toolkit. Fortunately, it should look pretty familiar
-- to those who have used object-oriented GUI toolkits before.
--
--
-- $guidetothehaddockdocs
--
-- Convenient access to the underlying C++ is achieved using typeclasses and
-- type-level programming to emulate OO classes and multiple dispatch. This approach makes
-- Haddock very unhappy and the generated documentation is frequently unhelpful.
-- For instance, I urge newcomers to this library not to look at
-- "Graphics.UI.FLTK.LowLevel.Dispatch" or
-- "Graphics.UI.FLTK.LowLevel.Hierarchy". The purpose of this guide is to point
-- you in a more useful direction.
--
--
-- The documentation provided with this API is not yet self-contained and is
-- meant to be used in tandem with the <http://www.fltk.org/doc-1.4/classes.html C++ documentation>.
-- The rest of this section is about how the Haskell
-- functions and datatypes map to the C++ ones and how to, in some limited cases, override a C++ function
-- with a Haskell implementations.
-- $widgetconstruction
-- Each widget has its own module, all of which are listed
-- below under the __Widgets__ heading. Most modules include a function named
-- `<widgetName>New` that returns a reference to that widget. Although you
-- do not have to deal with raw pointers directly, it might help to understand
-- that this reference is a pointer to a void pointer to a C++ object.
--
-- For instance, 'windowNew' creates a 'Ref' 'Window', which is a pointer to a
-- C++ object of type <http://www.fltk.org/doc-1.4/classFl__Window.html `Fl_Window`>, the FLTK class that knows how to draw,
-- display, and handle window events.
--
-- This value of type 'Ref' 'Window' is then passed along to various functions
-- which transparently extract the pointer and pass it to the
-- appropriate <http://www.fltk.org/doc-1.4/classFl__Window.html `Fl_Window`> instance method.
--
-- $widgetmethods
--
-- The Haskell functions that bind to the instance methods of an FLTK class are
-- listed under the __Functions__ heading in that widget's module. It's worth
-- remembering that these type signatures associated with the functions listed
-- under the __Functions__ heading are not the real ones but are artifically
-- generated because they are much more helpful to users. For instance, the
-- actual type of 'activate' exposes all the type level arithmetic required so
-- it can be used by subclasses of 'Widget' but is unhelpful as a
-- reference compared to the artificial type under __Functions__ heading of
-- "Graphics.UI.FLTK.LowLevel.Widget".
--
-- Unfortunately to see this more helpful type signature the poor reader has to
-- navigate to the corresponding widget's module, find the __Functions__ header
-- and scroll down to the desired function. Haddock, unfortunately, does not
-- support anchors that link to a named point in the page. I'm /very/
-- open to ideas on how to make this easier.
--
-- Carrying on the previous example from the __Widget Creation__ section, the
-- methods on a 'Ref' 'Window' widget are documented in
-- "Graphics.UI.FLTK.LowLevel.Window" under __Functions__. Each function takes
-- the 'Ref' 'Window' reference as its first argument followed by whatever else
-- it needs and delegates it appropriately.
--
-- As this is a low-level binding, the Haskell functions are kept as close as
-- possible in name and argument list to the underlying C++. This allows users
-- familiar with the FLTK API to use this library with less learning overhead
-- and it lets newcomers to FLTK take advantage of the already extensive
-- <http://www.fltk.org/doc-1.4/classes.html C++ documentation>.
--
-- Functions are named to make it as easy as possible to find the corresponding
-- C++ function, however there are some naming conventions to keep in mind:
--
-- (1) Setters and getters are prefixed with /set/ and /get/ respectively. In
-- C++ both have the same name; the setter takes an argument while the getter
-- does not. Since Haskell does not support overloading, this convention is used.
--
-- (2) In many cases C++ uses overloading to provide default values to
-- arguments. Since Haskell does not support overloading, these arguments are
-- 'Maybe' types, e.g., the `hotspot` function in
-- "Graphics.UI.FLTK.LowLevel.Window". In other cases, where the common use case
-- leaves the default arguments unspecified, the binding provides two functions:
-- a longer less-convenient-to-type one that takes the default argument, and a
-- short one that does not, e.g., `drawBox` and `drawBoxWithBoxtype`, also in
-- "Graphics.UI.FLTK.LowLevel.Window".
--
-- (3) Error codes are 'Either' types.
--
-- (4) Function arguments that are pointers to be filled are not exposed to the
-- API user. For instance, a common C++ idiom is to return a string by taking a
-- pointer to some initialized but empty chunk of memory and filling it up. The
-- corresponding Haskell function just returns a 'Data.Text'.
--
-- (5) Widget destructors can be called explicitly with 'destroy'. The reason it
-- is called 'destroy' instead of 'delete' to match C++ is that it is a mistake
-- and it's too late to change it now.
--
--
-- It is hoped that until the documentation becomes more self-sustaining the
-- user can use these heuristics (and the type signatures) along with the
-- official FLTK documentation to "guess" what the binding functions do.
--
-- $widgethierarchyguide
-- Every widget module in the API has a __Hierarchy__ heading that shows all its parents.
--
-- The design of the API makes all the parent functions transparently available
-- to that widget. This is also the reason why the actual type signatures are so
-- complicated requiring the manual generation of artificial type signatures.
--
-- For instance, the __Functions__ section under
-- "Graphics.UI.FLTK.LowLevel.Window" shows that a 'Ref' 'Window' can be passed
-- to @getModal@ to check if the window is modal, but it can also be passed to
-- @children@ in "Graphics.UI.FLTK.LowLevel.Group" which counts up the number of
-- widgets inside the 'Window' and @getX@ in "Graphics.UI.FLTK.LowLevel.Widget"
-- which returns the X coordinate of the 'Window''s top-left hand corner.
--
-- The hierarchy corresponds almost exactly to the underlying C++ class
-- hierarchy so, again, you should be able to take advantage of the
-- <http://www.fltk.org/doc-1.4/classes.html C++ documentation> to use the
-- binding API.
--
-- $overriding
--
-- The binding API allows a limited but powerful form of "inheritance" allowing
-- users to override certain key FLTK methods with Haskell functions. All GUI
-- elements that derive from the C++ base class
-- <http://www.fltk.org/doc-1.4/classFl__Widget.html Fl_Widget> and the Haskell
-- analog
-- <https://hackage.haskell.org/package/fltkhs/docs/Graphics-UI-FLTK-LowLevel-Base-Widget.html WidgetBase> now allow Haskell
-- <https://hackage.haskell.org/package/fltkhs/docs/Graphics-UI-FLTK-LowLevel-Base-Widget.html#g:2 functions> to be passed at widget construction time that give Haskell
-- complete control over
-- <https://hackage.haskell.org/package/fltkhs/docs/Graphics-UI-FLTK-LowLevel-Base-Widget.html#v:widgetCustom drawing>,
-- <https://hackage.haskell.org/package/fltkhs/docs/Graphics-UI-FLTK-LowLevel-Base-Widget.html#t:CustomWidgetFuncs handling, resizing and other key functions>. This means that the Haskell user
-- can control the look and feel as well as the event loop. The
-- <https://github.com/deech/fltkhs-demos/blob/master/src/Examples/table-as-container.hs#L105 table> demos are an example of drawing in Haskell. An example of taking over
-- the event loop is an FLTKHS <https://github.com/deech/fltkhs-reflex-host proof-of-concept> that
-- <https://github.com/deech/fltkhs-reflex-host/blob/master/src/reflex-host.hs#L33 overrides> the FLTKHS event loop with the
-- <https://hackage.haskell.org/package/reflex Reflex FRP> allowing native
-- functional reactive programming. The sky is the limit!
--
-- When providing custom methods, the object constructor is no longer
-- `<widgetName>New` but `<widgetName>Custom`, which, in addition to the parameters
-- taken by `<widgetName>New` also takes records of Haskell functions which are
-- then passed to the C++ side.
--
-- Much like a callback, the Haskell functions are passed as function pointers
-- to the C++ side and called whenever the event loop deems appropriate. Unlike
-- callbacks, they can be set only on object instantiation.
--
-- An example of this is "Graphics.UI.FLTK.LowLevel.Base.Widget" which, since it is a
-- base class for most widgets and doesn't have much functionality of its own,
-- only allows custom construction using 'widgetCustom'. This constructor takes
-- a 'CustomWidgetFuncs' datatype which is a record of functions which tells a
-- "Graphics.UI.FLTK.LowLevel.Base.Widget" how to handle events and draw, resize and
-- display itself.
--
-- Again "Graphics.UI.FLTK.LowLevel.Base.Window" can be used a motivating example.
-- Its custom constructor 'windowCustom', in fact, takes two records: a
-- 'CustomWidgetFuncs' which allows you to override methods in its
-- "Graphics.UI.FLTK.LowLevel.Base.Widget" parent class, and also a
-- 'CustomWindowFuncs' record which allows you to override @flush@, a
-- method on the Window class which tells the window how to force a redraw. For
-- example, the demo /src\/Examples\/doublebuffer.hs/ (which corresponds to the
-- executable 'ftlkhs-doublebuffer') tells both windows how to draw themselves
-- in a Haskell function that uses low-level FLTK drawing routines by overriding
-- the draw function of their "Graphics.UI.FLTK.LowLevel.Base.Widget" parent.
--
-- Every widget that supports customizing also provides a default function
-- record that can be passed to the constructor. For example,
-- "Graphics.UI.FLTK.LowLevel.Base.Widget" provides 'defaultCustomWidgetFuncs' and
-- "Graphics.UI.FLTK.LowLevel.Base.Window" has 'defaultCustomWindowFuncs'. In the
-- demo mentioned above, the 'singleWindowCustom' function is given
-- 'defaultCustom.WidgetFuncs' but with an overridden 'drawCustom'.
--
-- Another case where customization comes up a lot is when using
-- "Graphics.UI.FLTK.LowLevel.Base.Table" which is a low-level table widget that
-- needs to be told, for example, how to draw its cells. The demo
-- /src\/Examples\/table-simple.hs/ (corresponding to the executable
-- 'fltkhs-table-simple') shows this in action.
--
-- Hopefully the demos just mentioned and others included with this library show
-- that, even though customizing is limited, it is possible to do a lot.
-- $explicitbaseclasscalling
-- A common pattern when overring parent class methods is augment them,
-- some logic followed by an explicit call to the parent method. In C++
-- this is done by explicitly by annotating the call with the parent's class name:
--
-- @
-- void Child::f() {
-- ... some code
-- Parent::f();
-- }
-- @
--
-- In this binding the widget methods that can be overridden have a corresponding
-- explict call to the parent class method in that widget's module. For example,
-- the <https://www.fltk.org/doc-1.4/classFl__Widget.html#a9cb17cc092697dfd05a3fab55856d218 handle> method
-- can be overridden by <https://hackage.haskell.org/package/fltkhs/docs/Graphics-UI-FLTK-LowLevel-Base-Widget.html#t:CustomWidgetFuncs handleCustom>
-- but you can still call the base class 'handle' with <https://hackage.haskell.org/package/fltkhs/Graphics-UI-FLTK-LowLevel-Base-Widget.html#v:handleWidgetBase handleWidgetBase> so
-- a custom handler that just prints console when a widget is minimized but delegates to the parent for all other events could look something like:
--
-- @
-- myHandle :: Ref Widget -> Event -> IO (Either UnknownEvent ())
-- myHandle w e = do
-- case e of
-- Hide -> print "widget has been hidden"
-- _ -> return ()
-- handleWidgetBase (safeCast w) e
-- @
--
-- The 'safeCast' is needed to explicitly cast a widget to it's parent, in this case casting 'Widget' to 'WidgetBase'.
-- The cast is safe because it is statically restricted to only classes in the hierarchy.
--
-- $destructors
-- Most of the <https://hackage.haskell.org/package/fltkhs/docs/Graphics-UI-FLTK-LowLevel-Base-Widget.html#t:CustomWidgetFuncs overrideable methods> correspond to
-- some method in FLTK. <https://hackage.haskell.org/package/fltkhs/docs/Graphics-UI-FLTK-LowLevel-Base-Widget.html#t:CustomWidgetFuncs resizeCustom>, for instance
-- overrides <https://www.fltk.org/doc-1.4/classFl__Widget.html#aca98267e7a9b94f699ebd27d9f59e8bb resize>, but 'destroyCallbacksCustom' does not. This function is called
-- in the widget's C++ destructor and can be used for any Haskell side clean up but exists specifically to release function pointers given to the C++ side by the GHC runtime.
-- This is necessary because any resources closed over by the Haskell function to which we generate a pointer are ignored by the garbage collector until that pointer is
-- explicitly freed. Over time this could cause significant memory bloat. Normally the binding does this for you freeing callbacks set with 'setCallback' and the overriding functions
-- themselves but occasionally there are function pointers the binding does not know about.
--
-- For example <https://hackage.haskell.org/package/fltkhs/Graphics-UI-FLTK-LowLevel-FL.html#v:addTimeout adding a timer>
-- entails passing in a function pointer to a closure that will be invoked at at some specified frequency but the binding has no idea when that needs to be cleaned up
-- so that becomes your responsibility. A custom 'destroyCallbacksCustom' might look something like:
--
-- @
-- myDestroyCallbacks :: FunPtr (IO ()) -> Ref Widget -> [Maybe (FunPtr (IO ())] -> IO ()
-- myDestroyCallbacks myFunptr w cbs = do
-- freeHaskellFunPtr myFunPtr
-- defaultDestroyWidgetCallbacks w cbs
-- @
--
-- The function takes 'myFunPtr', a pointer to the timer's closure, and a widget 'w' and that widget's associated callbacks, 'myFunPtr' is then freed with 'freeHaskellFunPtr'
-- and control passes to 'defaultDestroyWidgetCallbacks' which frees the rest of them. Passing control to 'defaultDestroyWidgetCallbacks' is critical otherwise those callbacks
-- will never be freed.
--
-- $Compilation
--
-- As described above, the API emulates multiple dispatch using type-level
-- programming, closed type families, and typeclasses. While this makes for a
-- nice API, it has also
-- slowed down compilation of executables much more than expected.
--
-- To clarify, the time taken to compile the library itself has not changed, but
-- applications that use the library to create executables are taking a lot
-- longer to compile. To further emphasize, there do not appear to be any
-- runtime performance issues. This is only a compile time problem.
--
-- To preserve your and my sanity, a flag `fastCompile` has been
-- introduced to the <https://github.com/deech/fltkhs-hello-world skeleton>, the <https://github.com/deech/fltkhs-fluid-hello-world projects>, the <https://github.com/deech/fltkhs-demos fltkhs-demos>, and
-- the <https://github.com/deech/fltkhs-fluid-demos fltkhs-fluid-demos>.
-- This flag, which tells the compiler to skip some steps when
-- compiling executables, dramatically decreases compile time but also bloats
-- the resulting executable size and probably makes runtime performance much
-- slower. In this package and <https://github.com/deech/fltkhs-fluid-demos fltkhs-fluid-demos>
-- it is enabled by default since the executables are
-- demos that are not meant to show off performance. To disable this flag, tell
-- Stack to ignore it during the `build` step:
--
-- @
-- > stack build --flag fltkhs:bundled --flag fltkhs-demos:-fastCompile
-- @
--
-- In the <https://github.com/deech/fltkhs-hello-world fltkhs> and the
-- <https://github.com/deech/fltkhs-fluid-hello-world fltkhs-fluid> project
-- skeletons, this flag is /disabled/ by default to provide the best runtime
-- performance. To enable the flag for a smoother development workflow, tell
-- Stack to enable it during the `configure` step:
--
-- @
-- > stack build --flag fltkhs:bundled --flag fltkhs-hello-world:fastCompile
-- @
--
-- =File Layout
-- @
-- Root
-- - c-src -- The C bindings
-- - c-examples -- demos written using the C bindings (not installed)
-- - fltk-\<version\>.tar.gz -- The bundled FLTK library
-- - src
-- - TestPrograms -- Haskell test programs
-- - Fluid -- The Fluid file to Haskell conversion utility
-- - Graphics
-- - UI
-- - FLTK
-- - LowLevel -- Haskell bindings
-- - scripts -- various helper scripts (probably not interesting to anyone but myself)
-- @
-- $REPL
-- Running GUIs in GHCi is fully supported. Using the <https://github.com/deech/fltkhs-hello-world hello world skeleton> as
-- an example the following steps will run it in the REPL:
--
-- @
-- > git clone http://github.com/deech/fltkhs-hello-world
-- > cd fltkhs-hello-world
-- > stack build --flag fltkhs:bundled
-- > stack ghci --flag fltkhs:bundled fltkhs-hello-world:exe:fltkhs-hello-world
-- [1 of 1] Compiling Main ...
-- Ok, modules loaded: Main ...
-- Loaded GHCi configuration ...
-- Prelude Main> replMain
-- @
--
-- Unfortunately since FLTKHS is hybrid Haskell/C++ there are limitations compared to
-- running a normal Haskell library on the REPL:
--
-- 1. The 'stack build ...' is an essential first step before running 'stack
-- ghci ...'. The reason is the REPL uses '-fobject-code' to link in all the C++
-- libraries which must be built first.
-- 2. The use of 'replMain' instead of just ':main' as you might expect. This
-- is because
--
-- (1) it allows closing the GUI to correctly return control to
-- the REPL prompt and
-- (2) typing 'Ctrl-C' also correctly hands control back to the REPL.
--
-- With just ':main' (1) works but (2) results in a "ghosted" UI where the
-- GUI window is still visible but unable to accept any keyboard/mouse
-- input. The reason for the ghosted GUI is that ':main' delegates to the
-- FLTK C++ event loop which is unable to listen for user interrupts on
-- the Haskell side and so has no way of knowing that it should destroy
-- itself.'replMain' emulates the event loop on the Haskell side allowing
-- it to stop, clean up and return control when it 'catch'es a
-- 'UserInterrupt'. Thus the 'replMain' is slower than the optimized C++
-- event loop but hopefully that's not too big an impediment for REPL
-- work.
|
deech/fltkhs
|
src/Graphics/UI/FLTK/LowLevel/FLTKHS.hs
|
Haskell
|
mit
| 61,697
|
{-# LANGUAGE DeriveGeneric, TypeSynonymInstances, TypeOperators,
FlexibleInstances, FlexibleContexts, OverlappingInstances #-}
module Network.Google.ApiIO.GenericParams where
import Control.Applicative ((<*>), (<$>), (<|>), pure)
import GHC.Generics
import Data.DList (DList, toList, empty)
import Data.Monoid (mappend)
import Network.Google.ApiIO.Common
import qualified Data.Text as T
class ToString a where
toString :: a -> String
instance ToString String where
toString = id
instance ToString Int where
toString = show
instance ToString Bool where
toString = show
instance ToString T.Text where
toString = T.unpack
instance (ToString s) => ToString (Maybe s) where
toString (Just v) = toString v
toString Nothing = ""
type Pair = (String, String)
genericParams :: (Generic a, GEntity (Rep a)) => Options -> a -> [(String, String)]
genericParams opts = extractParams opts . from
class GEntity f where
extractParams :: Options -> f a -> [(String, String)]
instance (GEntity f) => GEntity (M1 i c f) where
extractParams opts = extractParams opts . unM1
instance (ToString a) => ToString (K1 i a p) where
toString = toString . unK1
instance GEntity U1 where
extractParams _ _ = []
data Options = Options { fieldLabelModifier :: String -> String
, omitNothingFields :: Bool
}
defaultOptions = Options id True
removePrefixLCFirstOpts prefix = defaultOptions { fieldLabelModifier = removePrefixLCFirst prefix }
instance (RecordToPairs f) => GEntity (C1 c f) where
extractParams opts = toList . recordToPairs opts. unM1
class RecordToPairs f where
recordToPairs :: Options -> f a -> DList Pair
instance (RecordToPairs a, RecordToPairs b) => RecordToPairs (a :*: b) where
recordToPairs opts (a :*: b) = recordToPairs opts a `mappend`
recordToPairs opts b
instance (Selector s, ToString c) => RecordToPairs (S1 s (K1 i c)) where
recordToPairs = fieldToPair
instance (Selector s, ToString c) => RecordToPairs (S1 s (K1 i (Maybe c))) where
recordToPairs opts (M1 (K1 Nothing)) | omitNothingFields opts = empty
recordToPairs opts m1 = fieldToPair opts m1
fieldToPair opts m1 = pure ( fieldLabelModifier opts $ selName m1
, toString ( unM1 m1 )
)
|
georgeee/haskell-google-apiIO
|
Network/Google/ApiIO/GenericParams.hs
|
Haskell
|
mit
| 2,402
|
-- Web API part of the code
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeOperators #-}
module StarServer where
import Prelude ()
import Prelude.Compat
import Control.Monad.Trans.Except
import Control.Monad.Trans.Either
import Control.Monad.Except
import Control.Monad.Reader
import Data.Aeson.Compat
import Data.Aeson.Types
import Data.Attoparsec.ByteString
import Data.ByteString (ByteString)
import Data.List
import Data.Maybe
import Data.String.Conversions
import Data.Time.Calendar
import Data.Vector.V3
import GHC.Generics
import Lucid
import Network.HTTP.Media ((//), (/:))
import Network.Wai
import Network.Wai.Handler.Warp
import Servant
import Servant.API
import Servant.API.ContentTypes
import Servant.JS
import System.Directory
import System.FilePath
import Text.Blaze
import Text.Blaze.Html.Renderer.Utf8
import qualified Data.Aeson.Parser
import qualified Text.Blaze.Html
-- StarData imports
import StarData
import StarTree
-- File to output javascript interface to
ifaceFile :: FilePath
ifaceFile = "StarMap.js"
type StarsAPI =
"starsInRadius"
:> QueryParam "radius" Double
:> QueryParam "pointX" Double
:> QueryParam "pointY" Double
:> QueryParam "pointZ" Double
:> Get '[JSON] [StarDataRec]
:<|>
"visibleStars"
:> QueryParam "minLum" Double
:> QueryParam "pointX" Double
:> QueryParam "pointY" Double
:> QueryParam "pointZ" Double
:> Get '[JSON] [StarDataRec]
:<|>
"visibleStarsMagic"
:> QueryParam "minLum" Double
:> QueryParam "blurRad" Double
:> QueryParam "pointX" Double
:> QueryParam "pointY" Double
:> QueryParam "pointZ" Double
:> Get '[JSON] [StarDataRec]
type FilesAPI =
Raw
type StarMapAPI =
StarsAPI :<|> FilesAPI
starsAPI :: Proxy StarsAPI
starsAPI = Proxy
starMapAPI :: Proxy StarMapAPI
starMapAPI = Proxy
genStarServer :: StarTree StarDataAbbrev -> String -> Server StarMapAPI
genStarServer tree scriptDir = ((starsInRadius tree) :<|>
(visStars tree) :<|>
(visStarsM tree)) :<|>
(serveDirectory scriptDir)
starsInRadius :: StarTree StarDataAbbrev ->
Maybe Double ->
Maybe Double -> Maybe Double -> Maybe Double ->
ExceptT ServantErr IO [StarDataRec]
starsInRadius tree (Just radius) (Just px) (Just py) (Just pz) =
let starList = inRadius (Vector3 px py pz) radius tree
in
return $ map starDataRecFromStarData starList
visStars :: StarTree StarDataAbbrev ->
Maybe Double ->
Maybe Double -> Maybe Double -> Maybe Double ->
ExceptT ServantErr IO [StarDataRec]
visStars tree (Just minLum) (Just px) (Just py) (Just pz) =
let starList = visibleStars tree (Vector3 px py pz) minLum
in
return $ map starDataRecFromStarData starList
visStarsM :: StarTree StarDataAbbrev ->
Maybe Double ->
Maybe Double ->
Maybe Double -> Maybe Double -> Maybe Double ->
ExceptT ServantErr IO [StarDataRec]
visStarsM
tree (Just minLum) (Just blurRad) (Just px) (Just py) (Just pz) =
let starList = visibleStarsMagic tree (Vector3 px py pz) minLum blurRad
in
return $ map starDataRecFromStarData starList
writeJSInterface :: FilePath -> IO ()
writeJSInterface scriptDir =
writeJSForAPI starsAPI vanillaJS (scriptDir </> ifaceFile)
starServerApp :: StarTree StarDataAbbrev -> String -> Application
starServerApp tree staticDir =
serve starMapAPI (genStarServer tree staticDir)
|
j3camero/galaxyatlas
|
OldCrap/haskell/server/src/StarServer.hs
|
Haskell
|
mit
| 3,731
|
module Doppler.Tag.Syntax (
parseTag
) where
import Doppler.Tag.Types
import Text.Parsec
import Text.Parsec.String (Parser)
import Control.Monad (void)
-- Generic tag structure parser.
parseTag :: Monoid v =>
Parser TagName ->
-- ^ Parser for tag names.
Parser k ->
-- ^ Parse for attribute keys.
(Quote -> k -> Parser v) ->
-- ^ Parser for attribute values.
(TagName -> Parser c) ->
-- ^ Parser for tag contents.
Parser Char ->
-- ^ Parser for whitespace characters.
Parser [Tag (k, v) c]
-- ^ Tag structure parser.
parseTag tagName attrName attrValue content whitespace =
many whitespace *> tag
where
tag = do
_ <- char '<'
name <- tagName <* many whitespace
attributes <- parseAttribute whitespace attrName attrValue `sepEndBy` many1 whitespace
closing <- string "/>" <|> string ">"
-- Make a short tag if it is explicitly closed.
if closing == "/>" then
return [ShortTag name attributes]
-- Parse full or dangling tag structures.
else do
rest <- manyTill (tagOrContent name) $ try (void (lookAhead endTagName) <|> eof)
endName <- optionMaybe $ lookAhead endTagName
-- Make a full tag if it is closed properly. Consume end tag
-- name because this tag is closed.
if maybe False (== name) endName then
endTagName *> return [FullTag name attributes $ concat rest]
-- Make a dangling tag if it is implicitly short. Leave end tag
-- because parent tag closes it.
else
return $ DanglingTag name attributes : concat rest
tagOrContent name =
tag <|> many (parseContent content name)
endTagName =
between (string "</") (char '>') (tagName <* many whitespace)
parseAttribute :: Monoid v => Parser Char -> Parser k -> (Quote -> k -> Parser v) -> Parser (k, v)
parseAttribute whitespace key value = do
k <- key <* many whitespace
equal <- optionMaybe $ char '=' <* many whitespace
v <- maybe (return mempty)
(const $ between doubleQuote doubleQuote (many $ value DoubleQuotes k)
<|> between singleQuote singleQuote (many $ value SingleQuotes k)
<|> many (value Unquoted k))
equal
return (k, mconcat v)
where
singleQuote = char '\''
doubleQuote = char '"'
parseContent :: (TagName -> Parser b) -> TagName -> Parser (Tag a b)
parseContent content name =
Content <$> content name
|
oinuar/doppler-html
|
src/Doppler/Tag/Syntax.hs
|
Haskell
|
mit
| 2,690
|
import Data.Digest.SHA2
import qualified Data.ByteString as B
import System.IO
doManyHashes :: Int -> IO Bool
doManyHashes 0 = do
return True
doManyHashes counter = do
contents <- B.readFile "/tmp/data.0512"
-- let contentsWord8 = B.unpack contents
let hash = sha256 $ B.unpack contents
-- let oct = toOctets hash
-- putStr "."
-- hFlush stdout
-- putStrLn (show oct)
doManyHashes $ counter-1
main = do
doManyHashes 500000
-- putStrLn ""
|
adizere/nifty-tree
|
playground/sha2-dd.hs
|
Haskell
|
mit
| 486
|
module Syntax_Test where
-- see: https://leiffrenzel.de/papers/getting-started-with-hunit.html
import Test.HUnit
import Syntax
-- The structure of a test case is always this:
-- 1. create some input,
-- 2. run the tested code on that input,
-- 3. make some assertions over the results.
-- 4. group them by test lists, and label them
-- TestCase :: Assertion -> Test
-- assertEqual :: (Eq a, Show a) => String -> a -> a -> Assertion
-- TestList :: [Test] -> Test
testSeven :: Test
testSeven = TestCase $ assertEqual
"Should get seven" "LUCKY NUMBER SEVEN!" $ lucky 7
simpleCases :: Test
simpleCases = TestLabel "Simple cases: " $ TestList [testSeven]
testEdge :: (Integral a) => a -> Test
testEdge a = TestCase $ assertEqual
"Should say sorry" "Sorry, you're out of luck, pal!" $ lucky a
borderCases :: Test
borderCases = TestLabel "Border cases: " $ TestList [testEdge 6, testEdge 8]
-- runTestTT :: Test -> IO Counts
-- TestList :: [Test] -> Test
main :: IO Counts
main = runTestTT $ TestList [simpleCases, borderCases]
|
dnvriend/study-category-theory
|
haskell/learn_a_haskell/ch4/Syntax_Test.hs
|
Haskell
|
apache-2.0
| 1,040
|
module Poset.A334231Spec (main, spec) where
import Test.Hspec
import Poset.A334231 (a334231)
main :: IO ()
main = hspec spec
spec :: Spec
spec = describe "A334231" $
it "correctly computes the first 20 elements" $
map a334231 [1..20] `shouldBe` expectedValue where
expectedValue = [1,2,2,3,3,3,4,4,6,4,5,5,15,5,5,6,6,6,6,15]
|
peterokagey/haskellOEIS
|
test/Poset/A334231Spec.hs
|
Haskell
|
apache-2.0
| 339
|
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QStyleOptionTab.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:36
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Enums.Gui.QStyleOptionTab (
QStyleOptionTabStyleOptionType
, QStyleOptionTabStyleOptionVersion
, QStyleOptionTabTabPosition
, QStyleOptionTabSelectedPosition
, CornerWidget, CornerWidgets, eNoCornerWidgets, fNoCornerWidgets, eLeftCornerWidget, fLeftCornerWidget, eRightCornerWidget, fRightCornerWidget
)
where
import Qtc.Classes.Base
import Qtc.ClassTypes.Core (QObject, TQObject, qObjectFromPtr)
import Qtc.Core.Base (Qcs, connectSlot, qtc_connectSlot_int, wrapSlotHandler_int)
import Qtc.Enums.Base
import Qtc.Enums.Classes.Core
data CQStyleOptionTabStyleOptionType a = CQStyleOptionTabStyleOptionType a
type QStyleOptionTabStyleOptionType = QEnum(CQStyleOptionTabStyleOptionType Int)
ieQStyleOptionTabStyleOptionType :: Int -> QStyleOptionTabStyleOptionType
ieQStyleOptionTabStyleOptionType x = QEnum (CQStyleOptionTabStyleOptionType x)
instance QEnumC (CQStyleOptionTabStyleOptionType Int) where
qEnum_toInt (QEnum (CQStyleOptionTabStyleOptionType x)) = x
qEnum_fromInt x = QEnum (CQStyleOptionTabStyleOptionType x)
withQEnumResult x
= do
ti <- x
return $ qEnum_fromInt $ fromIntegral ti
withQEnumListResult x
= do
til <- x
return $ map qEnum_fromInt til
instance Qcs (QObject c -> QStyleOptionTabStyleOptionType -> IO ()) where
connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler
= do
funptr <- wrapSlotHandler_int slotHandlerWrapper_int
stptr <- newStablePtr (Wrap _handler)
withObjectPtr _qsig_obj $ \cobj_sig ->
withCWString _qsig_nam $ \cstr_sig ->
withObjectPtr _qslt_obj $ \cobj_slt ->
withCWString _qslt_nam $ \cstr_slt ->
qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr)
return ()
where
slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO ()
slotHandlerWrapper_int funptr stptr qobjptr cint
= do qobj <- qObjectFromPtr qobjptr
let hint = fromCInt cint
if (objectIsNull qobj)
then do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
else _handler qobj (qEnum_fromInt hint)
return ()
instance QeType QStyleOptionTabStyleOptionType where
eType
= ieQStyleOptionTabStyleOptionType $ 3
data CQStyleOptionTabStyleOptionVersion a = CQStyleOptionTabStyleOptionVersion a
type QStyleOptionTabStyleOptionVersion = QEnum(CQStyleOptionTabStyleOptionVersion Int)
ieQStyleOptionTabStyleOptionVersion :: Int -> QStyleOptionTabStyleOptionVersion
ieQStyleOptionTabStyleOptionVersion x = QEnum (CQStyleOptionTabStyleOptionVersion x)
instance QEnumC (CQStyleOptionTabStyleOptionVersion Int) where
qEnum_toInt (QEnum (CQStyleOptionTabStyleOptionVersion x)) = x
qEnum_fromInt x = QEnum (CQStyleOptionTabStyleOptionVersion x)
withQEnumResult x
= do
ti <- x
return $ qEnum_fromInt $ fromIntegral ti
withQEnumListResult x
= do
til <- x
return $ map qEnum_fromInt til
instance Qcs (QObject c -> QStyleOptionTabStyleOptionVersion -> IO ()) where
connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler
= do
funptr <- wrapSlotHandler_int slotHandlerWrapper_int
stptr <- newStablePtr (Wrap _handler)
withObjectPtr _qsig_obj $ \cobj_sig ->
withCWString _qsig_nam $ \cstr_sig ->
withObjectPtr _qslt_obj $ \cobj_slt ->
withCWString _qslt_nam $ \cstr_slt ->
qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr)
return ()
where
slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO ()
slotHandlerWrapper_int funptr stptr qobjptr cint
= do qobj <- qObjectFromPtr qobjptr
let hint = fromCInt cint
if (objectIsNull qobj)
then do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
else _handler qobj (qEnum_fromInt hint)
return ()
instance QeVersion QStyleOptionTabStyleOptionVersion where
eVersion
= ieQStyleOptionTabStyleOptionVersion $ 1
data CQStyleOptionTabTabPosition a = CQStyleOptionTabTabPosition a
type QStyleOptionTabTabPosition = QEnum(CQStyleOptionTabTabPosition Int)
ieQStyleOptionTabTabPosition :: Int -> QStyleOptionTabTabPosition
ieQStyleOptionTabTabPosition x = QEnum (CQStyleOptionTabTabPosition x)
instance QEnumC (CQStyleOptionTabTabPosition Int) where
qEnum_toInt (QEnum (CQStyleOptionTabTabPosition x)) = x
qEnum_fromInt x = QEnum (CQStyleOptionTabTabPosition x)
withQEnumResult x
= do
ti <- x
return $ qEnum_fromInt $ fromIntegral ti
withQEnumListResult x
= do
til <- x
return $ map qEnum_fromInt til
instance Qcs (QObject c -> QStyleOptionTabTabPosition -> IO ()) where
connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler
= do
funptr <- wrapSlotHandler_int slotHandlerWrapper_int
stptr <- newStablePtr (Wrap _handler)
withObjectPtr _qsig_obj $ \cobj_sig ->
withCWString _qsig_nam $ \cstr_sig ->
withObjectPtr _qslt_obj $ \cobj_slt ->
withCWString _qslt_nam $ \cstr_slt ->
qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr)
return ()
where
slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO ()
slotHandlerWrapper_int funptr stptr qobjptr cint
= do qobj <- qObjectFromPtr qobjptr
let hint = fromCInt cint
if (objectIsNull qobj)
then do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
else _handler qobj (qEnum_fromInt hint)
return ()
instance QeBeginning QStyleOptionTabTabPosition where
eBeginning
= ieQStyleOptionTabTabPosition $ 0
instance QeMiddle QStyleOptionTabTabPosition where
eMiddle
= ieQStyleOptionTabTabPosition $ 1
instance QeEnd QStyleOptionTabTabPosition where
eEnd
= ieQStyleOptionTabTabPosition $ 2
instance QeOnlyOneTab QStyleOptionTabTabPosition where
eOnlyOneTab
= ieQStyleOptionTabTabPosition $ 3
data CQStyleOptionTabSelectedPosition a = CQStyleOptionTabSelectedPosition a
type QStyleOptionTabSelectedPosition = QEnum(CQStyleOptionTabSelectedPosition Int)
ieQStyleOptionTabSelectedPosition :: Int -> QStyleOptionTabSelectedPosition
ieQStyleOptionTabSelectedPosition x = QEnum (CQStyleOptionTabSelectedPosition x)
instance QEnumC (CQStyleOptionTabSelectedPosition Int) where
qEnum_toInt (QEnum (CQStyleOptionTabSelectedPosition x)) = x
qEnum_fromInt x = QEnum (CQStyleOptionTabSelectedPosition x)
withQEnumResult x
= do
ti <- x
return $ qEnum_fromInt $ fromIntegral ti
withQEnumListResult x
= do
til <- x
return $ map qEnum_fromInt til
instance Qcs (QObject c -> QStyleOptionTabSelectedPosition -> IO ()) where
connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler
= do
funptr <- wrapSlotHandler_int slotHandlerWrapper_int
stptr <- newStablePtr (Wrap _handler)
withObjectPtr _qsig_obj $ \cobj_sig ->
withCWString _qsig_nam $ \cstr_sig ->
withObjectPtr _qslt_obj $ \cobj_slt ->
withCWString _qslt_nam $ \cstr_slt ->
qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr)
return ()
where
slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO ()
slotHandlerWrapper_int funptr stptr qobjptr cint
= do qobj <- qObjectFromPtr qobjptr
let hint = fromCInt cint
if (objectIsNull qobj)
then do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
else _handler qobj (qEnum_fromInt hint)
return ()
instance QeNotAdjacent QStyleOptionTabSelectedPosition where
eNotAdjacent
= ieQStyleOptionTabSelectedPosition $ 0
instance QeNextIsSelected QStyleOptionTabSelectedPosition where
eNextIsSelected
= ieQStyleOptionTabSelectedPosition $ 1
instance QePreviousIsSelected QStyleOptionTabSelectedPosition where
ePreviousIsSelected
= ieQStyleOptionTabSelectedPosition $ 2
data CCornerWidget a = CCornerWidget a
type CornerWidget = QEnum(CCornerWidget Int)
ieCornerWidget :: Int -> CornerWidget
ieCornerWidget x = QEnum (CCornerWidget x)
instance QEnumC (CCornerWidget Int) where
qEnum_toInt (QEnum (CCornerWidget x)) = x
qEnum_fromInt x = QEnum (CCornerWidget x)
withQEnumResult x
= do
ti <- x
return $ qEnum_fromInt $ fromIntegral ti
withQEnumListResult x
= do
til <- x
return $ map qEnum_fromInt til
instance Qcs (QObject c -> CornerWidget -> IO ()) where
connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler
= do
funptr <- wrapSlotHandler_int slotHandlerWrapper_int
stptr <- newStablePtr (Wrap _handler)
withObjectPtr _qsig_obj $ \cobj_sig ->
withCWString _qsig_nam $ \cstr_sig ->
withObjectPtr _qslt_obj $ \cobj_slt ->
withCWString _qslt_nam $ \cstr_slt ->
qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr)
return ()
where
slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO ()
slotHandlerWrapper_int funptr stptr qobjptr cint
= do qobj <- qObjectFromPtr qobjptr
let hint = fromCInt cint
if (objectIsNull qobj)
then do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
else _handler qobj (qEnum_fromInt hint)
return ()
data CCornerWidgets a = CCornerWidgets a
type CornerWidgets = QFlags(CCornerWidgets Int)
ifCornerWidgets :: Int -> CornerWidgets
ifCornerWidgets x = QFlags (CCornerWidgets x)
instance QFlagsC (CCornerWidgets Int) where
qFlags_toInt (QFlags (CCornerWidgets x)) = x
qFlags_fromInt x = QFlags (CCornerWidgets x)
withQFlagsResult x
= do
ti <- x
return $ qFlags_fromInt $ fromIntegral ti
withQFlagsListResult x
= do
til <- x
return $ map qFlags_fromInt til
instance Qcs (QObject c -> CornerWidgets -> IO ()) where
connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler
= do
funptr <- wrapSlotHandler_int slotHandlerWrapper_int
stptr <- newStablePtr (Wrap _handler)
withObjectPtr _qsig_obj $ \cobj_sig ->
withCWString _qsig_nam $ \cstr_sig ->
withObjectPtr _qslt_obj $ \cobj_slt ->
withCWString _qslt_nam $ \cstr_slt ->
qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr)
return ()
where
slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO ()
slotHandlerWrapper_int funptr stptr qobjptr cint
= do qobj <- qObjectFromPtr qobjptr
let hint = fromCInt cint
if (objectIsNull qobj)
then do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
else _handler qobj (qFlags_fromInt hint)
return ()
eNoCornerWidgets :: CornerWidget
eNoCornerWidgets
= ieCornerWidget $ 0
eLeftCornerWidget :: CornerWidget
eLeftCornerWidget
= ieCornerWidget $ 1
eRightCornerWidget :: CornerWidget
eRightCornerWidget
= ieCornerWidget $ 2
fNoCornerWidgets :: CornerWidgets
fNoCornerWidgets
= ifCornerWidgets $ 0
fLeftCornerWidget :: CornerWidgets
fLeftCornerWidget
= ifCornerWidgets $ 1
fRightCornerWidget :: CornerWidgets
fRightCornerWidget
= ifCornerWidgets $ 2
|
uduki/hsQt
|
Qtc/Enums/Gui/QStyleOptionTab.hs
|
Haskell
|
bsd-2-clause
| 12,522
|
-- | Settings are centralized, as much as possible, into this file. This
-- includes database connection settings, static file locations, etc.
-- In addition, you can configure a number of different aspects of Yesod
-- by overriding methods in the Yesod typeclass. That instance is
-- declared in the Foundation.hs file.
module Settings
( widgetFile
, PersistConfig
, staticRoot
, staticDir
, Extra (..)
, parseExtra
) where
import Text.Hamlet
import Data.Default (def)
import Prelude
import Text.Shakespeare.Text (st)
import Language.Haskell.TH.Syntax
import Database.Persist.MongoDB (MongoConf)
import Yesod.Default.Config
import Yesod.Default.Util
import Data.Text (Text)
import Data.Yaml
import Control.Applicative
import Settings.Development
-- | Which Persistent backend this site is using.
type PersistConfig = MongoConf
-- Static setting below. Changing these requires a recompile
-- | The location of static files on your system. This is a file system
-- path. The default value works properly with your scaffolded site.
staticDir :: FilePath
staticDir = "static"
-- | The base URL for your static files. As you can see by the default
-- value, this can simply be "static" appended to your application root.
-- A powerful optimization can be serving static files from a separate
-- domain name. This allows you to use a web server optimized for static
-- files, more easily set expires and cache values, and avoid possibly
-- costly transference of cookies on static files. For more information,
-- please see:
-- http://code.google.com/speed/page-speed/docs/request.html#ServeFromCookielessDomain
--
-- If you change the resource pattern for StaticR in Foundation.hs, you will
-- have to make a corresponding change here.
--
-- To see how this value is used, see urlRenderOverride in Foundation.hs
staticRoot :: AppConfig DefaultEnv x -> Text
staticRoot conf = [st|#{appRoot conf}/static|]
-- | Settings for 'widgetFile', such as which template languages to support and
-- default Hamlet settings.
widgetFileSettings :: WidgetFileSettings
widgetFileSettings = def
{ wfsHamletSettings = defaultHamletSettings
{ hamletNewlines = AlwaysNewlines
}
}
-- The rest of this file contains settings which rarely need changing by a
-- user.
widgetFile :: String -> Q Exp
widgetFile = (if development then widgetFileReload
else widgetFileNoReload)
widgetFileSettings
data Extra = Extra
{ extraCopyright :: Text
, extraAnalytics :: Maybe Text -- ^ Google Analytics
, extraHatenaStar :: Maybe Text -- ^ Google Analytics
, extraAdmins :: [Text]
, extraTitle :: Text
, extraDescription :: Text
, extraMarkup :: Maybe String
, extraMailAddress :: Maybe Text
, extraGoogleCSE :: Maybe Text
, extraReCAPTCHA :: Maybe (Text, Text)
} deriving Show
parseExtra :: DefaultEnv -> Object -> Parser Extra
parseExtra _ o = Extra
<$> o .: "copyright"
<*> o .:? "analytics"
<*> o .:? "hatenastar"
<*> o .: "admins"
<*> o .: "title"
<*> o .: "description"
<*> o .:? "markup"
<*> o .:? "admin-mail"
<*> o .:? "google-cse"
<*> (liftA2 (,) <$> o .:? "recaptcha-public-key"
<*> o .:? "recaptcha-private-key")
|
konn/Yablog
|
Settings.hs
|
Haskell
|
bsd-2-clause
| 3,325
|
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE EmptyDataDecls #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE ImpredicativeTypes #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
-- | A simple API for /routing/, using a custom exchange type.
module Control.Distributed.Process.Platform.Execution.Exchange.Router
( -- * Types
HeaderName
, Binding(..)
, Bindable
, BindingSelector
, RelayType(..)
-- * Starting a Router
, router
, supervisedRouter
, supervisedRouterRef
-- * Client (Publishing) API
, route
, routeMessage
-- * Routing via message/binding keys
, messageKeyRouter
, bindKey
-- * Routing via message headers
, headerContentRouter
, bindHeader
) where
import Control.DeepSeq (NFData)
import Control.Distributed.Process
( Process
, ProcessMonitorNotification(..)
, ProcessId
, monitor
, handleMessage
, unsafeWrapMessage
)
import qualified Control.Distributed.Process as P
import Control.Distributed.Process.Serializable (Serializable)
import Control.Distributed.Process.Platform.Execution.Exchange.Internal
( startExchange
, startSupervised
, configureExchange
, Message(..)
, Exchange
, ExchangeType(..)
, post
, postMessage
, applyHandlers
)
import Control.Distributed.Process.Platform.Internal.Primitives
( deliver
, Resolvable(..)
)
import Control.Distributed.Process.Platform.Supervisor (SupervisorPid)
import Data.Binary
import Data.Foldable (forM_)
import Data.Hashable
import Data.HashMap.Strict (HashMap)
import qualified Data.HashMap.Strict as Map
import Data.HashSet (HashSet)
import qualified Data.HashSet as Set
import Data.Typeable (Typeable)
import GHC.Generics
type HeaderName = String
-- | The binding key used by the built-in key and header based
-- routers.
data Binding =
BindKey { bindingKey :: !String }
| BindHeader { bindingKey :: !String
, headerName :: !HeaderName
}
| BindNone
deriving (Typeable, Generic, Eq, Show)
instance Binary Binding where
instance NFData Binding where
instance Hashable Binding where
-- | Things that can be used as binding keys in a router.
class (Hashable k, Eq k, Serializable k) => Bindable k
instance (Hashable k, Eq k, Serializable k) => Bindable k
-- | Used to convert a 'Message' into a 'Bindable' routing key.
type BindingSelector k = (Message -> Process k)
-- | Given to a /router/ to indicate whether clients should
-- receive 'Message' payloads only, or the whole 'Message' object
-- itself.
data RelayType = PayloadOnly | WholeMessage
data State k = State { bindings :: !(HashMap k (HashSet ProcessId))
, selector :: !(BindingSelector k)
, relayType :: !RelayType
}
type Router k = ExchangeType (State k)
--------------------------------------------------------------------------------
-- Starting/Running the Exchange --
--------------------------------------------------------------------------------
-- | A router that matches on a 'Message' 'key'. To bind a client @Process@ to
-- such an exchange, use the 'bindKey' function.
messageKeyRouter :: RelayType -> Process Exchange
messageKeyRouter t = router t matchOnKey -- (return . BindKey . key)
where
matchOnKey :: Message -> Process Binding
matchOnKey m = return $ BindKey (key m)
-- | A router that matches on a specific (named) header. To bind a client
-- @Process@ to such an exchange, use the 'bindHeader' function.
headerContentRouter :: RelayType -> HeaderName -> Process Exchange
headerContentRouter t n = router t (checkHeaders n)
where
checkHeaders hn Message{..} = do
case Map.lookup hn (Map.fromList headers) of
Nothing -> return BindNone
Just hv -> return $ BindHeader hn hv
-- | Defines a /router/ exchange. The 'BindingSelector' is used to construct
-- a binding (i.e., an instance of the 'Bindable' type @k@) for each incoming
-- 'Message'. Such bindings are matched against bindings stored in the exchange.
-- Clients of a /router/ exchange are identified by a binding, mapped to
-- one or more 'ProcessId's.
--
-- The format of the bindings, nature of their storage and mechanism for
-- submitting new bindings is implementation dependent (i.e., will vary by
-- exchange type). For example, the 'messageKeyRouter' and 'headerContentRouter'
-- implementations both use the 'Binding' data type, which can represent a
-- 'Message' key or a 'HeaderName' and content. As with all custom exchange
-- types, bindings should be submitted by evaluating 'configureExchange' with
-- a suitable data type.
--
router :: (Bindable k) => RelayType -> BindingSelector k -> Process Exchange
router t s = routerT t s >>= startExchange
supervisedRouterRef :: Bindable k
=> RelayType
-> BindingSelector k
-> SupervisorPid
-> Process (ProcessId, P.Message)
supervisedRouterRef t sel spid = do
ex <- supervisedRouter t sel spid
Just pid <- resolve ex
return (pid, unsafeWrapMessage ex)
-- | Defines a /router/ that can be used in a supervision tree.
supervisedRouter :: Bindable k
=> RelayType
-> BindingSelector k
-> SupervisorPid
-> Process Exchange
supervisedRouter t sel spid =
routerT t sel >>= \t' -> startSupervised t' spid
routerT :: Bindable k
=> RelayType
-> BindingSelector k
-> Process (Router k)
routerT t s = do
return $ ExchangeType { name = "Router"
, state = State Map.empty s t
, configureEx = apiConfigure
, routeEx = apiRoute
}
--------------------------------------------------------------------------------
-- Client Facing API --
--------------------------------------------------------------------------------
-- | Add a binding (for the calling process) to a 'messageKeyRouter' exchange.
bindKey :: String -> Exchange -> Process ()
bindKey k ex = do
self <- P.getSelfPid
configureExchange ex (self, BindKey k)
-- | Add a binding (for the calling process) to a 'headerContentRouter' exchange.
bindHeader :: HeaderName -> String -> Exchange -> Process ()
bindHeader n v ex = do
self <- P.getSelfPid
configureExchange ex (self, BindHeader v n)
-- | Send a 'Serializable' message to the supplied 'Exchange'. The given datum
-- will be converted to a 'Message', with the 'key' set to @""@ and the
-- 'headers' to @[]@.
--
-- The routing behaviour will be dependent on the choice of 'BindingSelector'
-- given when initialising the /router/.
route :: Serializable m => Exchange -> m -> Process ()
route = post
-- | Send a 'Message' to the supplied 'Exchange'.
-- The routing behaviour will be dependent on the choice of 'BindingSelector'
-- given when initialising the /router/.
routeMessage :: Exchange -> Message -> Process ()
routeMessage = postMessage
--------------------------------------------------------------------------------
-- Exchage Definition/State & API Handlers --
--------------------------------------------------------------------------------
apiRoute :: forall k. Bindable k
=> State k
-> Message
-> Process (State k)
apiRoute st@State{..} msg = do
binding <- selector msg
case Map.lookup binding bindings of
Nothing -> return st
Just bs -> forM_ bs (fwd relayType msg) >> return st
where
fwd WholeMessage m = deliver m
fwd PayloadOnly m = P.forward (payload m)
-- TODO: implement 'unbind' ???
-- TODO: apiConfigure currently leaks memory if clients die (we don't cleanup)
apiConfigure :: forall k. Bindable k
=> State k
-> P.Message
-> Process (State k)
apiConfigure st msg = do
applyHandlers st msg $ [ \m -> handleMessage m (createBinding st)
, \m -> handleMessage m (handleMonitorSignal st)
]
where
createBinding s@State{..} (pid, bind) = do
case Map.lookup bind bindings of
Nothing -> do _ <- monitor pid
return $ s { bindings = newBind bind pid bindings }
Just ps -> return $ s { bindings = addBind bind pid bindings ps }
newBind b p bs = Map.insert b (Set.singleton p) bs
addBind b' p' bs' ps = Map.insert b' (Set.insert p' ps) bs'
handleMonitorSignal s@State{..} (ProcessMonitorNotification _ p _) =
let bs = bindings
bs' = Map.foldlWithKey' (\a k v -> Map.insert k (Set.delete p v) a) bs bs
in return $ s { bindings = bs' }
|
haskell-distributed/distributed-process-platform
|
src/Control/Distributed/Process/Platform/Execution/Exchange/Router.hs
|
Haskell
|
bsd-3-clause
| 9,019
|
{-------------------------------------------------------------------------------
DSem.VectorSpace
Vector space model interface
(c) 2013 Jan Snajder <jan.snajder@fer.hr>
-------------------------------------------------------------------------------}
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}
module DSem.VectorSpace
( existsTarget
, module DSem.Vector
, getTargetVector
, Model (..)
, ModelIO
, ModelPure
, runModelIO
, runModelIO2
, runModelPure
, Targetable (..) ) where
import Control.Applicative
import Control.Monad
import Control.Monad.Reader
import Control.Monad.State.Strict
import Data.Maybe
import qualified DSem.Vector
import DSem.Vector (Vector)
class (Monad m, Vector v) =>
Model m t c v | m -> v, m -> t, m -> c where
getVector :: t -> m (Maybe v)
getDim :: m (Int,Int)
getTargets :: m [t]
getContexts :: m [c]
class Targetable a t where
toTarget :: a -> t
fromTarget :: t -> a
getTargetVector :: (Model m t c v, Targetable a t) => a -> m (Maybe v)
getTargetVector = getVector . toTarget
type ModelIO a = StateT a IO
type ModelPure a = Reader a
runModelPure :: a -> ModelPure a b -> b
runModelPure = flip runReader
runModelIO :: a -> ModelIO a b -> IO b
runModelIO = flip evalStateT
runModelIO2 :: a -> ReaderT a IO b -> IO b
runModelIO2 = flip runReaderT
existsTarget :: Model m t c v => t -> m Bool
existsTarget t = isJust `liftM` getVector t
{-
targetMarginals :: (VectModel m t v, Ord t) => m -> M.Map t Double
targetMarginals m =
M.fromList [ (t, sum $ V.toList v) | (t,v) <- toList m]
contextMarginals :: VectModel m t v => m -> v
contextMarginals = V.sum . map snd . toList
-- todo: conflate into a single function, with LMI | PMI ...
{-
lmiWeighting :: (Ord t, DModel m t v) => m -> m
lmiWeighting m = fromList . map f $ toList m
where tm = targetMarginals m
cm = contextMarginals m
n = sum $ V.toList cm
f (t,v) = (t,vzip (\fx fxy ->
lmi n fx (M.findWithDefault 0 t tm) fxy) cm v)
-}
lmi :: Double -> Double -> Double -> Double -> Double
lmi n fx fy fxy
| n * fx * fy * fxy == 0 = 0
| otherwise = fxy * (log fxy + log n - log fx - log fy)
-}
|
jsnajder/dsem
|
src/DSem/VectorSpace.hs
|
Haskell
|
bsd-3-clause
| 2,231
|
module Main where
import Multiarg.Examples.Grover
import System.Environment
main :: IO ()
main = do
as <- getArgs
putStrLn . show $ parseGrover as
|
massysett/multiarg
|
tests/grover-main.hs
|
Haskell
|
bsd-3-clause
| 153
|
{-
(c) The University of Glasgow, 2004-2006
Module
~~~~~~~~~~
Simply the name of a module, represented as a FastString.
These are Uniquable, hence we can build Maps with Modules as
the keys.
-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE RecordWildCards #-}
module Module
(
-- * The ModuleName type
ModuleName,
pprModuleName,
moduleNameFS,
moduleNameString,
moduleNameSlashes, moduleNameColons,
moduleStableString,
mkModuleName,
mkModuleNameFS,
stableModuleNameCmp,
-- * The UnitId type
UnitId,
fsToUnitId,
unitIdFS,
stringToUnitId,
unitIdString,
stableUnitIdCmp,
-- * Wired-in UnitIds
-- $wired_in_packages
primUnitId,
integerUnitId,
baseUnitId,
rtsUnitId,
thUnitId,
dphSeqUnitId,
dphParUnitId,
mainUnitId,
thisGhcUnitId,
holeUnitId, isHoleModule,
interactiveUnitId, isInteractiveModule,
wiredInUnitIds,
-- * The Module type
Module(Module),
moduleUnitId, moduleName,
pprModule,
mkModule,
stableModuleCmp,
HasModule(..),
ContainsModule(..),
-- * The ModuleLocation type
ModLocation(..),
addBootSuffix, addBootSuffix_maybe, addBootSuffixLocn,
-- * Module mappings
ModuleEnv,
elemModuleEnv, extendModuleEnv, extendModuleEnvList,
extendModuleEnvList_C, plusModuleEnv_C,
delModuleEnvList, delModuleEnv, plusModuleEnv, lookupModuleEnv,
lookupWithDefaultModuleEnv, mapModuleEnv, mkModuleEnv, emptyModuleEnv,
moduleEnvKeys, moduleEnvElts, moduleEnvToList,
unitModuleEnv, isEmptyModuleEnv,
foldModuleEnv, extendModuleEnvWith, filterModuleEnv,
-- * ModuleName mappings
ModuleNameEnv,
-- * Sets of Modules
ModuleSet,
emptyModuleSet, mkModuleSet, moduleSetElts, extendModuleSet, elemModuleSet
) where
import Config
import Outputable
import Unique
import UniqFM
import FastString
import Binary
import Util
import Data.List
import Data.Ord
import {-# SOURCE #-} Packages
import GHC.PackageDb (BinaryStringRep(..))
import Control.DeepSeq
import Data.Coerce
import Data.Data
import Data.Map (Map)
import qualified Data.Map as Map
import qualified FiniteMap as Map
import Data.Set (Set)
import qualified Data.Set as Set
import System.FilePath
-- Note [The identifier lexicon]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Package keys, installed package IDs, ABI hashes, package names,
-- versions, there are a *lot* of different identifiers for closely
-- related things. What do they all mean? Here's what. (See also
-- https://ghc.haskell.org/trac/ghc/wiki/Commentary/Packages/Concepts )
--
-- THE IMPORTANT ONES
--
-- ComponentId: An opaque identifier provided by Cabal, which should
-- uniquely identify such things as the package name, the package
-- version, the name of the component, the hash of the source code
-- tarball, the selected Cabal flags, GHC flags, direct dependencies of
-- the component. These are very similar to InstalledPackageId, but
-- an 'InstalledPackageId' implies that it identifies a package, while
-- a package may install multiple components with different
-- 'ComponentId's.
-- - Same as Distribution.Package.ComponentId
--
-- UnitId: A ComponentId + a mapping from hole names (ModuleName) to
-- Modules. This is how the compiler identifies instantatiated
-- components, and also is the main identifier by which GHC identifies
-- things.
-- - When Backpack is not being used, UnitId = ComponentId.
-- this means a useful fiction for end-users is that there are
-- only ever ComponentIds, and some ComponentIds happen to have
-- more information (UnitIds).
-- - Same as Language.Haskell.TH.Syntax:PkgName, see
-- https://ghc.haskell.org/trac/ghc/ticket/10279
-- - The same as PackageKey in GHC 7.10 (we renamed it because
-- they don't necessarily identify packages anymore.)
-- - Same as -this-package-key/-package-name flags
--
-- Module: A UnitId + ModuleName. This is how the compiler identifies
-- modules (e.g. a Name is a Module + OccName)
-- - Same as Language.Haskell.TH.Syntax:Module
--
-- THE LESS IMPORTANT ONES
--
-- PackageName: The "name" field in a Cabal file, something like "lens".
-- - Same as Distribution.Package.PackageName
-- - DIFFERENT FROM Language.Haskell.TH.Syntax:PkgName, see
-- https://ghc.haskell.org/trac/ghc/ticket/10279
-- - DIFFERENT FROM -package-name flag
-- - DIFFERENT FROM the 'name' field in an installed package
-- information. This field could more accurately be described
-- as a munged package name: when it's for the main library
-- it is the same as the package name, but if it's an internal
-- library it's a munged combination of the package name and
-- the component name.
--
-- LEGACY ONES
--
-- InstalledPackageId: This is what we used to call ComponentId.
-- It's a still pretty useful concept for packages that have only
-- one library; in that case the logical InstalledPackageId =
-- ComponentId. Also, the Cabal nix-local-build continues to
-- compute an InstalledPackageId which is then forcibly used
-- for all components in a package. This means that if a dependency
-- from one component in a package changes, the InstalledPackageId
-- changes: you don't get as fine-grained dependency tracking,
-- but it means your builds are hermetic. Eventually, Cabal will
-- deal completely in components and we can get rid of this.
--
-- PackageKey: This is what we used to call UnitId. We ditched
-- "Package" from the name when we realized that you might want to
-- assign different "PackageKeys" to components from the same package.
-- (For a brief, non-released period of time, we also called these
-- UnitKeys).
{-
************************************************************************
* *
\subsection{Module locations}
* *
************************************************************************
-}
-- | Where a module lives on the file system: the actual locations
-- of the .hs, .hi and .o files, if we have them
data ModLocation
= ModLocation {
ml_hs_file :: Maybe FilePath,
-- The source file, if we have one. Package modules
-- probably don't have source files.
ml_hi_file :: FilePath,
-- Where the .hi file is, whether or not it exists
-- yet. Always of form foo.hi, even if there is an
-- hi-boot file (we add the -boot suffix later)
ml_obj_file :: FilePath
-- Where the .o file is, whether or not it exists yet.
-- (might not exist either because the module hasn't
-- been compiled yet, or because it is part of a
-- package with a .a file)
} deriving Show
instance Outputable ModLocation where
ppr = text . show
{-
For a module in another package, the hs_file and obj_file
components of ModLocation are undefined.
The locations specified by a ModLocation may or may not
correspond to actual files yet: for example, even if the object
file doesn't exist, the ModLocation still contains the path to
where the object file will reside if/when it is created.
-}
addBootSuffix :: FilePath -> FilePath
-- ^ Add the @-boot@ suffix to .hs, .hi and .o files
addBootSuffix path = path ++ "-boot"
addBootSuffix_maybe :: Bool -> FilePath -> FilePath
-- ^ Add the @-boot@ suffix if the @Bool@ argument is @True@
addBootSuffix_maybe is_boot path
| is_boot = addBootSuffix path
| otherwise = path
addBootSuffixLocn :: ModLocation -> ModLocation
-- ^ Add the @-boot@ suffix to all file paths associated with the module
addBootSuffixLocn locn
= locn { ml_hs_file = fmap addBootSuffix (ml_hs_file locn)
, ml_hi_file = addBootSuffix (ml_hi_file locn)
, ml_obj_file = addBootSuffix (ml_obj_file locn) }
{-
************************************************************************
* *
\subsection{The name of a module}
* *
************************************************************************
-}
-- | A ModuleName is essentially a simple string, e.g. @Data.List@.
newtype ModuleName = ModuleName FastString
deriving Typeable
instance Uniquable ModuleName where
getUnique (ModuleName nm) = getUnique nm
instance Eq ModuleName where
nm1 == nm2 = getUnique nm1 == getUnique nm2
instance Ord ModuleName where
nm1 `compare` nm2 = stableModuleNameCmp nm1 nm2
instance Outputable ModuleName where
ppr = pprModuleName
instance Binary ModuleName where
put_ bh (ModuleName fs) = put_ bh fs
get bh = do fs <- get bh; return (ModuleName fs)
instance BinaryStringRep ModuleName where
fromStringRep = mkModuleNameFS . mkFastStringByteString
toStringRep = fastStringToByteString . moduleNameFS
instance Data ModuleName where
-- don't traverse?
toConstr _ = abstractConstr "ModuleName"
gunfold _ _ = error "gunfold"
dataTypeOf _ = mkNoRepType "ModuleName"
instance NFData ModuleName where
rnf x = x `seq` ()
stableModuleNameCmp :: ModuleName -> ModuleName -> Ordering
-- ^ Compares module names lexically, rather than by their 'Unique's
stableModuleNameCmp n1 n2 = moduleNameFS n1 `compare` moduleNameFS n2
pprModuleName :: ModuleName -> SDoc
pprModuleName (ModuleName nm) =
getPprStyle $ \ sty ->
if codeStyle sty
then ztext (zEncodeFS nm)
else ftext nm
moduleNameFS :: ModuleName -> FastString
moduleNameFS (ModuleName mod) = mod
moduleNameString :: ModuleName -> String
moduleNameString (ModuleName mod) = unpackFS mod
-- | Get a string representation of a 'Module' that's unique and stable
-- across recompilations.
-- eg. "$aeson_70dylHtv1FFGeai1IoxcQr$Data.Aeson.Types.Internal"
moduleStableString :: Module -> String
moduleStableString Module{..} =
"$" ++ unitIdString moduleUnitId ++ "$" ++ moduleNameString moduleName
mkModuleName :: String -> ModuleName
mkModuleName s = ModuleName (mkFastString s)
mkModuleNameFS :: FastString -> ModuleName
mkModuleNameFS s = ModuleName s
-- |Returns the string version of the module name, with dots replaced by slashes.
--
moduleNameSlashes :: ModuleName -> String
moduleNameSlashes = dots_to_slashes . moduleNameString
where dots_to_slashes = map (\c -> if c == '.' then pathSeparator else c)
-- |Returns the string version of the module name, with dots replaced by underscores.
--
moduleNameColons :: ModuleName -> String
moduleNameColons = dots_to_colons . moduleNameString
where dots_to_colons = map (\c -> if c == '.' then ':' else c)
{-
************************************************************************
* *
\subsection{A fully qualified module}
* *
************************************************************************
-}
-- | A Module is a pair of a 'UnitId' and a 'ModuleName'.
data Module = Module {
moduleUnitId :: !UnitId, -- pkg-1.0
moduleName :: !ModuleName -- A.B.C
}
deriving (Eq, Ord, Typeable)
instance Uniquable Module where
getUnique (Module p n) = getUnique (unitIdFS p `appendFS` moduleNameFS n)
instance Outputable Module where
ppr = pprModule
instance Binary Module where
put_ bh (Module p n) = put_ bh p >> put_ bh n
get bh = do p <- get bh; n <- get bh; return (Module p n)
instance Data Module where
-- don't traverse?
toConstr _ = abstractConstr "Module"
gunfold _ _ = error "gunfold"
dataTypeOf _ = mkNoRepType "Module"
instance NFData Module where
rnf x = x `seq` ()
-- | This gives a stable ordering, as opposed to the Ord instance which
-- gives an ordering based on the 'Unique's of the components, which may
-- not be stable from run to run of the compiler.
stableModuleCmp :: Module -> Module -> Ordering
stableModuleCmp (Module p1 n1) (Module p2 n2)
= (p1 `stableUnitIdCmp` p2) `thenCmp`
(n1 `stableModuleNameCmp` n2)
mkModule :: UnitId -> ModuleName -> Module
mkModule = Module
pprModule :: Module -> SDoc
pprModule mod@(Module p n) =
pprPackagePrefix p mod <> pprModuleName n
pprPackagePrefix :: UnitId -> Module -> SDoc
pprPackagePrefix p mod = getPprStyle doc
where
doc sty
| codeStyle sty =
if p == mainUnitId
then empty -- never qualify the main package in code
else ztext (zEncodeFS (unitIdFS p)) <> char '_'
| qualModule sty mod = ppr (moduleUnitId mod) <> char ':'
-- the PrintUnqualified tells us which modules have to
-- be qualified with package names
| otherwise = empty
class ContainsModule t where
extractModule :: t -> Module
class HasModule m where
getModule :: m Module
{-
************************************************************************
* *
\subsection{UnitId}
* *
************************************************************************
-}
-- | A string which uniquely identifies a package. For wired-in packages,
-- it is just the package name, but for user compiled packages, it is a hash.
-- ToDo: when the key is a hash, we can do more clever things than store
-- the hex representation and hash-cons those strings.
newtype UnitId = PId FastString deriving( Eq, Typeable )
-- here to avoid module loops with PackageConfig
instance Uniquable UnitId where
getUnique pid = getUnique (unitIdFS pid)
instance Ord UnitId where
nm1 `compare` nm2 = stableUnitIdCmp nm1 nm2
instance Data UnitId where
-- don't traverse?
toConstr _ = abstractConstr "UnitId"
gunfold _ _ = error "gunfold"
dataTypeOf _ = mkNoRepType "UnitId"
instance NFData UnitId where
rnf x = x `seq` ()
stableUnitIdCmp :: UnitId -> UnitId -> Ordering
-- ^ Compares package ids lexically, rather than by their 'Unique's
stableUnitIdCmp p1 p2 = unitIdFS p1 `compare` unitIdFS p2
instance Outputable UnitId where
ppr pk = getPprStyle $ \sty -> sdocWithDynFlags $ \dflags ->
case unitIdPackageIdString dflags pk of
Nothing -> ftext (unitIdFS pk)
Just pkg -> text pkg
-- Don't bother qualifying if it's wired in!
<> (if qualPackage sty pk && not (pk `elem` wiredInUnitIds)
then char '@' <> ftext (unitIdFS pk)
else empty)
instance Binary UnitId where
put_ bh pid = put_ bh (unitIdFS pid)
get bh = do { fs <- get bh; return (fsToUnitId fs) }
instance BinaryStringRep UnitId where
fromStringRep = fsToUnitId . mkFastStringByteString
toStringRep = fastStringToByteString . unitIdFS
fsToUnitId :: FastString -> UnitId
fsToUnitId = PId
unitIdFS :: UnitId -> FastString
unitIdFS (PId fs) = fs
stringToUnitId :: String -> UnitId
stringToUnitId = fsToUnitId . mkFastString
unitIdString :: UnitId -> String
unitIdString = unpackFS . unitIdFS
-- -----------------------------------------------------------------------------
-- $wired_in_packages
-- Certain packages are known to the compiler, in that we know about certain
-- entities that reside in these packages, and the compiler needs to
-- declare static Modules and Names that refer to these packages. Hence
-- the wired-in packages can't include version numbers, since we don't want
-- to bake the version numbers of these packages into GHC.
--
-- So here's the plan. Wired-in packages are still versioned as
-- normal in the packages database, and you can still have multiple
-- versions of them installed. However, for each invocation of GHC,
-- only a single instance of each wired-in package will be recognised
-- (the desired one is selected via @-package@\/@-hide-package@), and GHC
-- will use the unversioned 'UnitId' below when referring to it,
-- including in .hi files and object file symbols. Unselected
-- versions of wired-in packages will be ignored, as will any other
-- package that depends directly or indirectly on it (much as if you
-- had used @-ignore-package@).
-- Make sure you change 'Packages.findWiredInPackages' if you add an entry here
integerUnitId, primUnitId,
baseUnitId, rtsUnitId,
thUnitId, dphSeqUnitId, dphParUnitId,
mainUnitId, thisGhcUnitId, interactiveUnitId :: UnitId
primUnitId = fsToUnitId (fsLit "ghc-prim")
integerUnitId = fsToUnitId (fsLit n)
where
n = case cIntegerLibraryType of
IntegerGMP -> "integer-gmp"
IntegerSimple -> "integer-simple"
baseUnitId = fsToUnitId (fsLit "base")
rtsUnitId = fsToUnitId (fsLit "rts")
thUnitId = fsToUnitId (fsLit "template-haskell")
dphSeqUnitId = fsToUnitId (fsLit "dph-seq")
dphParUnitId = fsToUnitId (fsLit "dph-par")
thisGhcUnitId = fsToUnitId (fsLit "ghc")
interactiveUnitId = fsToUnitId (fsLit "interactive")
-- | This is the package Id for the current program. It is the default
-- package Id if you don't specify a package name. We don't add this prefix
-- to symbol names, since there can be only one main package per program.
mainUnitId = fsToUnitId (fsLit "main")
-- | This is a fake package id used to provide identities to any un-implemented
-- signatures. The set of hole identities is global over an entire compilation.
holeUnitId :: UnitId
holeUnitId = fsToUnitId (fsLit "hole")
isInteractiveModule :: Module -> Bool
isInteractiveModule mod = moduleUnitId mod == interactiveUnitId
isHoleModule :: Module -> Bool
isHoleModule mod = moduleUnitId mod == holeUnitId
wiredInUnitIds :: [UnitId]
wiredInUnitIds = [ primUnitId,
integerUnitId,
baseUnitId,
rtsUnitId,
thUnitId,
thisGhcUnitId,
dphSeqUnitId,
dphParUnitId ]
{-
************************************************************************
* *
\subsection{@ModuleEnv@s}
* *
************************************************************************
-}
-- | A map keyed off of 'Module's
newtype ModuleEnv elt = ModuleEnv (Map NDModule elt)
{-
Note [ModuleEnv performance and determinism]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
To prevent accidental reintroduction of nondeterminism the Ord instance
for Module was changed to not depend on Unique ordering and to use the
lexicographic order. This is potentially expensive, but when measured
there was no difference in performance.
To be on the safe side and not pessimize ModuleEnv uses nondeterministic
ordering on Module and normalizes by doing the lexicographic sort when
turning the env to a list.
See Note [Unique Determinism] for more information about the source of
nondeterminismand and Note [Deterministic UniqFM] for explanation of why
it matters for maps.
-}
newtype NDModule = NDModule { unNDModule :: Module }
deriving Eq
-- A wrapper for Module with faster nondeterministic Ord.
-- Don't export, See [ModuleEnv performance and determinism]
instance Ord NDModule where
compare (NDModule (Module p1 n1)) (NDModule (Module p2 n2)) =
(getUnique p1 `compare` getUnique p2) `thenCmp`
(getUnique n1 `compare` getUnique n2)
filterModuleEnv :: (Module -> a -> Bool) -> ModuleEnv a -> ModuleEnv a
filterModuleEnv f (ModuleEnv e) =
ModuleEnv (Map.filterWithKey (f . unNDModule) e)
elemModuleEnv :: Module -> ModuleEnv a -> Bool
elemModuleEnv m (ModuleEnv e) = Map.member (NDModule m) e
extendModuleEnv :: ModuleEnv a -> Module -> a -> ModuleEnv a
extendModuleEnv (ModuleEnv e) m x = ModuleEnv (Map.insert (NDModule m) x e)
extendModuleEnvWith :: (a -> a -> a) -> ModuleEnv a -> Module -> a
-> ModuleEnv a
extendModuleEnvWith f (ModuleEnv e) m x =
ModuleEnv (Map.insertWith f (NDModule m) x e)
extendModuleEnvList :: ModuleEnv a -> [(Module, a)] -> ModuleEnv a
extendModuleEnvList (ModuleEnv e) xs =
ModuleEnv (Map.insertList [(NDModule k, v) | (k,v) <- xs] e)
extendModuleEnvList_C :: (a -> a -> a) -> ModuleEnv a -> [(Module, a)]
-> ModuleEnv a
extendModuleEnvList_C f (ModuleEnv e) xs =
ModuleEnv (Map.insertListWith f [(NDModule k, v) | (k,v) <- xs] e)
plusModuleEnv_C :: (a -> a -> a) -> ModuleEnv a -> ModuleEnv a -> ModuleEnv a
plusModuleEnv_C f (ModuleEnv e1) (ModuleEnv e2) =
ModuleEnv (Map.unionWith f e1 e2)
delModuleEnvList :: ModuleEnv a -> [Module] -> ModuleEnv a
delModuleEnvList (ModuleEnv e) ms =
ModuleEnv (Map.deleteList (map NDModule ms) e)
delModuleEnv :: ModuleEnv a -> Module -> ModuleEnv a
delModuleEnv (ModuleEnv e) m = ModuleEnv (Map.delete (NDModule m) e)
plusModuleEnv :: ModuleEnv a -> ModuleEnv a -> ModuleEnv a
plusModuleEnv (ModuleEnv e1) (ModuleEnv e2) = ModuleEnv (Map.union e1 e2)
lookupModuleEnv :: ModuleEnv a -> Module -> Maybe a
lookupModuleEnv (ModuleEnv e) m = Map.lookup (NDModule m) e
lookupWithDefaultModuleEnv :: ModuleEnv a -> a -> Module -> a
lookupWithDefaultModuleEnv (ModuleEnv e) x m =
Map.findWithDefault x (NDModule m) e
mapModuleEnv :: (a -> b) -> ModuleEnv a -> ModuleEnv b
mapModuleEnv f (ModuleEnv e) = ModuleEnv (Map.mapWithKey (\_ v -> f v) e)
mkModuleEnv :: [(Module, a)] -> ModuleEnv a
mkModuleEnv xs = ModuleEnv (Map.fromList [(NDModule k, v) | (k,v) <- xs])
emptyModuleEnv :: ModuleEnv a
emptyModuleEnv = ModuleEnv Map.empty
moduleEnvKeys :: ModuleEnv a -> [Module]
moduleEnvKeys (ModuleEnv e) = sort $ map unNDModule $ Map.keys e
-- See Note [ModuleEnv performance and determinism]
moduleEnvElts :: ModuleEnv a -> [a]
moduleEnvElts e = map snd $ moduleEnvToList e
-- See Note [ModuleEnv performance and determinism]
moduleEnvToList :: ModuleEnv a -> [(Module, a)]
moduleEnvToList (ModuleEnv e) =
sortBy (comparing fst) [(m, v) | (NDModule m, v) <- Map.toList e]
-- See Note [ModuleEnv performance and determinism]
unitModuleEnv :: Module -> a -> ModuleEnv a
unitModuleEnv m x = ModuleEnv (Map.singleton (NDModule m) x)
isEmptyModuleEnv :: ModuleEnv a -> Bool
isEmptyModuleEnv (ModuleEnv e) = Map.null e
foldModuleEnv :: (a -> b -> b) -> b -> ModuleEnv a -> b
foldModuleEnv f x (ModuleEnv e) = Map.foldRightWithKey (\_ v -> f v) x e
-- | A set of 'Module's
type ModuleSet = Set NDModule
mkModuleSet :: [Module] -> ModuleSet
extendModuleSet :: ModuleSet -> Module -> ModuleSet
emptyModuleSet :: ModuleSet
moduleSetElts :: ModuleSet -> [Module]
elemModuleSet :: Module -> ModuleSet -> Bool
emptyModuleSet = Set.empty
mkModuleSet = Set.fromList . coerce
extendModuleSet s m = Set.insert (NDModule m) s
moduleSetElts = sort . coerce . Set.toList
elemModuleSet = Set.member . coerce
{-
A ModuleName has a Unique, so we can build mappings of these using
UniqFM.
-}
-- | A map keyed off of 'ModuleName's (actually, their 'Unique's)
type ModuleNameEnv elt = UniqFM elt
|
GaloisInc/halvm-ghc
|
compiler/basicTypes/Module.hs
|
Haskell
|
bsd-3-clause
| 23,424
|
module Graphics.Renderer where
import Graphics.Types
import Graphics.QuadRenderer
import Graphics.TextRenderer
import Graphics.Rendering.OpenGL
import Data.List (intercalate)
printGraphicStats :: IO ()
printGraphicStats = do
-- Display some info about opengl
vendorStr <- get vendor
rendererStr <- get renderer
versionStr <- get glVersion
exts <- get glExtensions
glslV <- get shadingLanguageVersion
putStrLn $ intercalate "\n" [ "Vendor:" ++ vendorStr
, "Renderer:" ++ rendererStr
, "OpenGL Version:" ++ versionStr
, "GLSL Version:" ++ glslV
, "Extensions:\n [ " ++ intercalate "\n , " exts ++ "\n ]"
]
setGraphicDefaults :: IO ()
setGraphicDefaults = do
blend $= Enabled
blendFunc $= (SrcAlpha, OneMinusSrcAlpha)
depthFunc $= Nothing
initRenderer :: FilePath -> IO Renderer
initRenderer fp = do
printGraphicStats
setGraphicDefaults
quadRndr <- initQuadRenderer
textRndr <- initTextRenderer fp
return $ Renderer { _screenSize = (0,0)
, _quadRndr = quadRndr
, _textRndr = textRndr
}
|
schell/blocks
|
src/Graphics/Renderer.hs
|
Haskell
|
bsd-3-clause
| 1,351
|
-- Copyright (c) 2012, Christoph Pohl
-- BSD License (see http://www.opensource.org/licenses/BSD-3-Clause)
-------------------------------------------------------------------------------
--
-- Project Euler Problem 6
--
-- The sum of the squares of the first ten natural numbers is,
-- 1² + 2² + ... + 10² = 385
--
-- The square of the sum of the first ten natural numbers is,
-- (1 + 2 + ... + 10)² = 55² = 3025
--
-- Hence the difference between the sum of the squares of the first ten natural
-- numbers and the square of the sum is 3025 − 385 = 2640.
--
-- Find the difference between the sum of the squares of the first one hundred
-- natural numbers and the square of the sum.
module Main where
main :: IO ()
main = print result
result = squareOfSum - sumOfSquares
squareOfSum = (sum [1..100])^2
sumOfSquares = sum (map (^2) [1..100])
|
Psirus/euler
|
src/euler006.hs
|
Haskell
|
bsd-3-clause
| 856
|
{-# LANGUAGE DeriveGeneric #-}
module Package (Package(..)) where
import GHC.Generics
import qualified Data.Yaml as Yaml
import Description
data Package = Package
{ version :: String
-- , description :: Description
}
deriving (Show, Generic)
instance Yaml.FromJSON Package
|
angerman/stackage2nix
|
src/Package.hs
|
Haskell
|
bsd-3-clause
| 284
|
module Data.Shapefile.Types where
|
tolysz/shapefile2json
|
src/Data/Shapefile/Types.hs
|
Haskell
|
bsd-3-clause
| 35
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
module Test.Golden where
import Prelude ()
import Prelude.Compat
import Control.Exception (try)
import Control.Lens ((&), (.~))
import Control.Monad.IO.Class (MonadIO)
import Data.ByteString (ByteString)
import Data.ByteString.Lazy (fromStrict)
import qualified Data.ByteString.Lazy as LByteString
import Data.Foldable (fold)
import Data.Monoid ((<>))
import Pipes (Pipe, Producer, (>->))
import Pipes.Prelude (mapFoldable, toListM)
import System.Directory
(Permissions, emptyPermissions, removeFile, setOwnerReadable,
setOwnerSearchable, setOwnerWritable, setPermissions)
import System.IO (IOMode(WriteMode), hClose, openBinaryFile)
import System.IO.Error (isPermissionError)
import Test.Tasty (TestTree, testGroup, withResource)
import Test.Tasty.Golden (goldenVsString)
import Highlight.Common.Monad (Output(OutputStderr, OutputStdout))
import Highlight.Common.Options
(CommonOptions, IgnoreCase(IgnoreCase), Recursive(Recursive),
defaultCommonOptions, ignoreCaseLens, inputFilenamesLens,
rawRegexLens, recursiveLens)
import Highlight.Highlight.Monad (HighlightM, runHighlightM)
import Highlight.Highlight.Options
(ColorGrepFilenames(ColorGrepFilenames), Options,
colorGrepFilenamesLens, defaultOptions)
import Highlight.Highlight.Run (highlightOutputProducer)
import Highlight.Hrep.Monad (HrepM, runHrepM)
import Highlight.Hrep.Run (hrepOutputProducer)
import Highlight.Pipes (fromFileLines, stdinLines)
runHighlightTestWithStdin
:: Options
-> Producer ByteString HighlightM ()
-> (forall m. Monad m => Pipe Output ByteString m ())
-> IO LByteString.ByteString
runHighlightTestWithStdin opts stdinPipe filterPipe = do
eitherByteStrings <- runHighlightM opts $ do
outputProducer <- highlightOutputProducer stdinPipe
toListM $ outputProducer >-> filterPipe
case eitherByteStrings of
Left err -> error $ "unexpected error: " <> show err
Right byteStrings -> return . fromStrict $ fold byteStrings
runHighlightTest
:: Options
-> (forall m. Monad m => Pipe Output ByteString m ())
-> IO LByteString.ByteString
runHighlightTest opts =
runHighlightTestWithStdin opts stdinLines
runHrepTestWithStdin
:: CommonOptions
-> (Producer ByteString HrepM ())
-> (forall m. Monad m => Pipe Output ByteString m ())
-> IO LByteString.ByteString
runHrepTestWithStdin opts stdinPipe filterPipe = do
eitherByteStrings <- runHrepM opts $ do
outputProducer <- hrepOutputProducer stdinPipe
toListM $ outputProducer >-> filterPipe
case eitherByteStrings of
Left err -> error $ "unexpected error: " <> show err
Right byteStrings -> return . fromStrict $ fold byteStrings
runHrepTest
:: CommonOptions
-> (forall m. Monad m => Pipe Output ByteString m ())
-> IO LByteString.ByteString
runHrepTest opts =
runHrepTestWithStdin opts stdinLines
filterStdout :: Monad m => Pipe Output ByteString m ()
filterStdout = mapFoldable f
where
f :: Output -> Maybe ByteString
f (OutputStderr _) = Nothing
f (OutputStdout byteString) = Just byteString
filterStderr :: Monad m => Pipe Output ByteString m ()
filterStderr = mapFoldable f
where
f :: Output -> Maybe ByteString
f (OutputStderr byteString) = Just byteString
f (OutputStdout _) = Nothing
getFileOutputProducer
:: MonadIO m
=> FilePath -> IO (Producer ByteString m ())
getFileOutputProducer filePath = do
eitherProducer <- fromFileLines filePath
case eitherProducer of
Left ioerr ->
error $
"ERROR: following error occured when trying to read \"" <>
filePath <> "\": " <> show ioerr
Right producer -> return producer
testStderrAndStdout
:: String
-> FilePath
-> ( ( forall m. Monad m => Pipe Output ByteString m ())
-> IO LByteString.ByteString
)
-> TestTree
testStderrAndStdout msg path runner =
testGroup
msg
[ goldenVsString "stderr" (path <> ".stderr") (runner filterStderr)
, goldenVsString "stdout" (path <> ".stdout") (runner filterStdout)
]
goldenTests :: TestTree
goldenTests =
withResource createUnreadableFile (const deleteUnreadableFile) $
const (testGroup "golden tests" [highlightGoldenTests, hrepGoldenTests])
createUnreadableFile :: IO ()
createUnreadableFile = do
eitherHandle <- try $ openBinaryFile unreadableFilePath WriteMode
case eitherHandle of
Right handle -> do
hClose handle
makeFileUnreadable unreadableFilePath
Left ioerr
| isPermissionError ioerr ->
-- assume that the file already exists, and just try to make sure that
-- the permissions are null
makeFileUnreadable unreadableFilePath
| otherwise ->
-- we shouldn't have gotten an error here, so just rethrow it
ioError ioerr
makeFileUnreadable :: FilePath -> IO ()
makeFileUnreadable filePath = setPermissions filePath emptyPermissions
makeFileReadable :: FilePath -> IO ()
makeFileReadable filePath =
setPermissions filePath fullPermissions
where
fullPermissions :: Permissions
fullPermissions =
setOwnerWritable True .
setOwnerSearchable True .
setOwnerReadable True $
emptyPermissions
deleteUnreadableFile :: IO ()
deleteUnreadableFile = do
makeFileReadable unreadableFilePath
eitherRes <- try $ removeFile unreadableFilePath
either ioError return eitherRes
unreadableFilePath :: FilePath
unreadableFilePath = "test/golden/test-files/dir2/unreadable-file"
---------------------
-- Highlight Tests --
---------------------
highlightGoldenTests :: TestTree
highlightGoldenTests =
testGroup
"highlight"
[ testHighlightSingleFile
, testHighlightMultiFile
, testHighlightFromGrep
]
testHighlightSingleFile :: TestTree
testHighlightSingleFile =
let opts =
defaultOptions
& rawRegexLens .~ "or"
& inputFilenamesLens .~ ["test/golden/test-files/file1"]
in testStderrAndStdout
"`highlight or 'test/golden/test-files/file1'`"
"test/golden/golden-files/highlight/single-file"
(runHighlightTest opts)
testHighlightMultiFile :: TestTree
testHighlightMultiFile =
let opts =
defaultOptions
& rawRegexLens .~ "and"
& ignoreCaseLens .~ IgnoreCase
& recursiveLens .~ Recursive
& inputFilenamesLens .~
[ "test/golden/test-files/dir1"
, "test/golden/test-files/empty-file"
, "test/golden/test-files/dir2"
]
testName =
"`touch 'test/golden/test-files/dir2/unreadable-file' ; " <>
"chmod 0 'test/golden/test-files/dir2/unreadable-file' ; " <>
"highlight --ignore-case --recursive and " <>
"'test/golden/test-files/dir1' " <>
"'test/golden/test-files/empty-file' " <>
"'test/golden/test-files/dir2' ; " <>
"rm -rf 'test/golden/test-files/dir2/unreadable-file'`"
in testStderrAndStdout
testName
"test/golden/golden-files/highlight/multi-file"
(runHighlightTest opts)
testHighlightFromGrep :: TestTree
testHighlightFromGrep =
let opts =
defaultOptions
& rawRegexLens .~ "and"
& colorGrepFilenamesLens .~ ColorGrepFilenames
testName =
"`cat test/golden/test-files/from-grep | " <>
"highlight --from-grep and`"
in testStderrAndStdout
testName
"test/golden/golden-files/highlight/from-grep"
(go opts)
where
go
:: Options
-> (forall m. Monad m => Pipe Output ByteString m ())
-> IO LByteString.ByteString
go opts outputPipe = do
-- This is the output file from @grep@ to use for the test
-- 'testHighlightFromGrep'.
--
-- This file was created with the following command:
-- > $ grep --recursive and 'test/golden/test-files/dir1'
let grepOutputTestFile = "test/golden/test-files/from-grep"
grepOutputProducer <- getFileOutputProducer grepOutputTestFile
runHighlightTestWithStdin opts grepOutputProducer outputPipe
----------------
-- Hrep Tests --
----------------
hrepGoldenTests :: TestTree
hrepGoldenTests =
testGroup
"hrep"
[ testHrepSingleFile
, testHrepMultiFile
, testHrepFromStdin
]
testHrepSingleFile :: TestTree
testHrepSingleFile =
let opts =
defaultCommonOptions
& rawRegexLens .~ "another"
& inputFilenamesLens .~ ["test/golden/test-files/file1"]
in testStderrAndStdout
"`hrep another 'test/golden/test-files/file1'`"
"test/golden/golden-files/hrep/single-file"
(runHrepTest opts)
testHrepMultiFile :: TestTree
testHrepMultiFile =
let opts =
defaultCommonOptions
& rawRegexLens .~ "as"
& ignoreCaseLens .~ IgnoreCase
& recursiveLens .~ Recursive
& inputFilenamesLens .~
[ "test/golden/test-files/dir1"
, "test/golden/test-files/empty-file"
, "test/golden/test-files/dir2"
]
testName =
"`touch 'test/golden/test-files/dir2/unreadable-file' ; " <>
"chmod 0 'test/golden/test-files/dir2/unreadable-file' ; " <>
"hrep --ignore-case --recursive as " <>
"'test/golden/test-files/dir1' " <>
"'test/golden/test-files/empty-file' " <>
"'test/golden/test-files/dir2' ; " <>
"rm -rf 'test/golden/test-files/dir2/unreadable-file'`"
in testStderrAndStdout
testName
"test/golden/golden-files/hrep/multi-file"
(runHrepTest opts)
testHrepFromStdin :: TestTree
testHrepFromStdin =
let opts =
defaultCommonOptions & rawRegexLens .~ "co."
stdinInputFile = "test/golden/test-files/file2"
testName =
"`cat '" <> stdinInputFile <> "' | hrep 'co.'`"
in testStderrAndStdout
testName
"test/golden/golden-files/hrep/from-stdin"
(go opts stdinInputFile)
where
go
:: CommonOptions
-> FilePath
-> (forall m. Monad m => Pipe Output ByteString m ())
-> IO LByteString.ByteString
go opts stdinInputFile outputPipe = do
stdinProducer <- getFileOutputProducer stdinInputFile
runHrepTestWithStdin opts stdinProducer outputPipe
|
cdepillabout/highlight
|
test/Test/Golden.hs
|
Haskell
|
bsd-3-clause
| 10,201
|
{-# LANGUAGE OverloadedStrings #-}
import TPG.WebAPI
import TPG.Structured
import System.Directory
import System.Environment
import System.IO
import qualified Data.ByteString.Lazy as BS
import Cfg
import Control.Monad
import Control.Monad.Loops
import Data.Either
getDepartureList :: String -> [([String],[Thermometer])] -> IO [(Departure,[String],[Thermometer])]
getDepartureList key stopCodesPaired = do
thisNextDepartures <- mapM (\p -> do
nd <- getNextDepartures key ((head . fst) p)
return (nd, fst p, snd p)) stopCodesPaired
let successfulNexts = thisNextDepartures
let ndList nd = case nd of
(Nothing,_,_) -> []
(Just dpts,sts,ts) -> map (\d -> (d,sts,ts)) (departures dpts)
let mapped = map ndList successfulNexts
return (join mapped)
nonEmptyPair :: ([a],[b]) -> Bool
nonEmptyPair ([],[]) = False
nonEmptyPair _ = True
wrapGetThermometer :: String -> (Departure,[String],[Thermometer]) -> IO ([String],[Thermometer])
wrapGetThermometer key (d,sts,prevThermometers) = do
tres <- getThermometer key (show $ departureCode d)
case tres of
Nothing -> return ([],[])
Just tres -> return (sts,tres:prevThermometers)
getThermometerList :: String -> [(Departure,[String],[Thermometer])] -> IO [([String],[Thermometer])]
getThermometerList key departures = do
thisFullResultThermometers <- mapM (wrapGetThermometer key) departures
return (filter nonEmptyPair $ thisFullResultThermometers)
-- Prepends a next possible stop to the current route
-- the stop is only possible if it leads to another line
performStopStep :: [([String],[Thermometer])] -> [([String],[Thermometer])]
performStopStep routes = performStep routes isChangeStop
-- Given the current routes, filter out those that end in one of the given
-- destinations
intersectWithDestinationCodes :: [([String],[Thermometer])] -> [String] -> [([String],[Thermometer])]
intersectWithDestinationCodes routes destinationCodes =
performStep routes (\_ -> stopMatchesDestinations destinationCodes)
stopMatchesDestinations :: [String] -> Stop -> Bool
stopMatchesDestinations destinations stop = any (\c -> stopCode stop == c) destinations
performStep :: [([String],[Thermometer])] -> (String -> Stop -> Bool) -> [([String],[Thermometer])]
performStep pairs filterGen =
join $ map (\q ->
case q of
(sts,ts) ->
let t = head ts in
let currentLineCode = lineCodeThermometer t in
map (\st -> ((stopCode st):sts,ts)) $ filter (filterGen currentLineCode) $ map stopStep $ steps $ t) pairs
calculate_route :: String -> [([String],[Thermometer])] -> [String] -> Int -> IO [([String],[Thermometer])]
calculate_route key fromStopCodeList toStopCodeList maxIter = do
dList <- getDepartureList key fromStopCodeList
let extractedDestinations = map (\t -> case t of
(ds,_,_) -> ds) dList
let departureCodes = map (show . departureCode) extractedDestinations
thermometers <- getThermometerList key dList
let nextStep = performStopStep thermometers
let currentStepResults = (intersectWithDestinationCodes thermometers toStopCodeList)
if maxIter <= 0 then
return currentStepResults
else do
furtherResults <- calculate_route key nextStep toStopCodeList (maxIter - 1)
return (currentStepResults ++ furtherResults)
calculate_route_with_names :: String -> String -> String -> IO ()
calculate_route_with_names key fromStopName toStopName = do
mFromStop <- getStops key fromStopName
mToStop <- getStops key toStopName
case (mFromStop,mToStop) of
(Just fromStop,Just toStop) -> do
let fromStopCodeList = stopCodeList fromStop
let fromStopCodesPaired = map (\sc -> ([sc],[])) fromStopCodeList
let toStopCodeList = stopCodeList toStop
routes <- calculate_route key fromStopCodesPaired toStopCodeList 2 -- max 5 changes
putStrLn (show (map fst routes))
putStrLn (show toStopCodeList)
_ -> putStrLn "Could not match from/to"
main = do
args <- getArgs
if length args < 2 then
do
putStrLn "Usage: from_to fromStationName toStationName"
else
do
home_directory <- getHomeDirectory
config_handle <- openFile (home_directory ++ "/.tpg_tests") ReadMode
contents <- BS.hGetContents config_handle
let key = getApiKeyFromConfigString contents
case key of
Nothing -> error "Did not find API key"
Just key -> calculate_route_with_names key (head args) (head (tail args))
hClose config_handle
|
sebug/tpg_sandbox
|
from_to.hs
|
Haskell
|
bsd-3-clause
| 4,601
|
module Market.Board
( module Market.Board.Types
) where
import Market.Board.Types
|
s9gf4ult/market
|
Market/Board.hs
|
Haskell
|
bsd-3-clause
| 97
|
{-# LANGUAGE DeriveFunctor, DeriveFoldable, DeriveTraversable #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Language.Angler.ScopedTable
( ScopedTable, Scope
, tab_stack
-- basic
, emptyScope, emptyWithIndefinable, empty
, lookup , elem, elemInCurrentScope
, insertWith, safeInsert
, adjust, replace
-- scope handling
, enterScopeWith, enterScope
, topScope, exitScope
, toList
, fromFoldable, safeFromFoldable
-- on keys
, mapKeys
, filterByKey
) where
import Language.Angler.Error
import PrettyShow
import Control.Lens hiding (op)
import Data.Foldable (msum)
import qualified Data.Map.Strict as Map
import Prelude hiding (elem, lookup)
import qualified Prelude as P (elem)
type Scope sym = Map.Map String sym
-- interface for a scoped symbol table
data ScopedTable sym
= ScopedTable
{ _tab_stack :: [ Scope sym ]
, _indefinable :: [ String ]
}
deriving (Show, Functor, Foldable, Traversable)
makeLenses ''ScopedTable
emptyScope :: Scope sym
emptyScope = Map.empty
emptyWithIndefinable :: [String] -> ScopedTable sym
emptyWithIndefinable = ScopedTable [emptyScope]
empty :: ScopedTable sym
empty = emptyWithIndefinable []
enterScopeWith :: Scope sym -> ScopedTable sym -> ScopedTable sym
enterScopeWith up = over tab_stack (cons up)
enterScope :: ScopedTable sym -> ScopedTable sym
enterScope = enterScopeWith emptyScope
topScope :: ScopedTable sym -> Scope sym
topScope = views tab_stack head
exitScope :: ScopedTable sym -> ScopedTable sym
exitScope = over tab_stack tail
lookup :: String -> ScopedTable sym -> Maybe sym
lookup str = views tab_stack (msum . fmap (Map.lookup str))
scopeElem :: String -> Scope sym -> Bool
scopeElem str = P.elem str . Map.keys
elem :: String -> ScopedTable sym -> Bool
elem str = views tab_stack (any (scopeElem str))
elemInCurrentScope :: String -> ScopedTable sym -> Bool
elemInCurrentScope str = views tab_stack (scopeElem str . head)
insertWith :: (sym -> sym -> sym) -> String -> sym -> ScopedTable sym -> ScopedTable sym
insertWith join str sym = over (tab_stack._head) (Map.insertWith join str sym)
safeInsert :: String -> sym -> ScopedTable sym -> Either Error (ScopedTable sym)
safeInsert str sym tab = if P.elem str (view indefinable tab) || elemInCurrentScope str tab
then (Left . CheckError . CErrAlreadyInSymbolTable) str
else Right (insert str sym tab)
-- overwrites the symbol in the top scope
insert :: String -> sym -> ScopedTable sym -> ScopedTable sym
insert = insertWith const
-- looks for the symbol and adjusts it in the appropiate scope
adjust :: forall sym . (sym -> sym) -> String -> ScopedTable sym -> ScopedTable sym
adjust f str = over tab_stack adjust'
where
adjust' :: [Scope sym] -> [Scope sym]
adjust' scopes = case scopes of
sc : scs -> if scopeElem str sc
then Map.adjust f str sc : scs
else sc : adjust' scs
[] -> []
replace :: String -> sym -> ScopedTable sym -> ScopedTable sym
replace str sym = adjust (const sym) str
toList :: ScopedTable sym -> [(String, sym)]
toList = views tab_stack (proccess . concatMap Map.toList)
where
proccess :: [(String, sym)] -> [(String, sym)]
proccess = Map.toList . foldr (uncurry Map.insert) emptyScope
fromFoldable :: Foldable f => f (String, sym) -> ScopedTable sym
fromFoldable = foldl (flip (uncurry insert)) empty
safeFromFoldable :: Foldable f => f (String, sym) -> Either Error (ScopedTable sym)
safeFromFoldable = foldl (\act (str,sym) -> act >>= safeInsert str sym) (Right empty)
mapKeys :: (String -> String) -> ScopedTable sym -> ScopedTable sym
mapKeys f = over (tab_stack.traverse) (Map.mapKeys f)
filterByKey :: (String -> Bool) -> ScopedTable sym -> ScopedTable sym
filterByKey f = over (tab_stack.traverse) (Map.filterWithKey (\s _ -> f s))
instance PrettyShow sym => PrettyShow (ScopedTable sym) where
pshow = pshows line . (map snd . toList)
|
angler-lang/angler-lang
|
src/Language/Angler/ScopedTable.hs
|
Haskell
|
bsd-3-clause
| 4,239
|
-----------------------------------------------------------------------------
-- |
-- Module : HJScript.DOM
-- Copyright : (c) Joel Bjornson 2008
-- License : BSD-style
-- Maintainer : Joel Bjornson joel.bjornson@gmail.com
-- Niklas Broberg nibro@cs.chalmers.se
-- Stability : experimental
-----------------------------------------------------------------------------
module HJScript.DOM
(
module HJScript.DOM.NodeTypes,
module HJScript.DOM.Node,
module HJScript.DOM.Document,
module HJScript.DOM.ElementNode,
module HJScript.DOM.AttributeNode,
module HJScript.DOM.TextNode,
module HJScript.DOM.Window,
module HJScript.DOM.XHTML
) where
import HJScript.DOM.NodeTypes (NodeType(..), nodeTypeVal)
import HJScript.DOM.Node
import HJScript.DOM.Document
import HJScript.DOM.ElementNode
import HJScript.DOM.AttributeNode
import HJScript.DOM.TextNode
import HJScript.DOM.Window
import HJScript.DOM.XHTML
|
seereason/HJScript
|
src/HJScript/DOM.hs
|
Haskell
|
bsd-3-clause
| 968
|
module Main where
import Control.Exception (bracket)
import Data.Time.Clock.POSIX (POSIXTime, getPOSIXTime)
import qualified Data.Map as Map
import qualified Data.Vector as Vector
import Minecraft.Anvil (ChunkX, ChunkZ, ChunkData, ChunkMap, compressChunkData, writeChunkMap)
import Minecraft.Core (BlockId(..), toNBT)
import Minecraft.Chunk (Chunk(..), Section(..), emptyChunk, emptySection)
import System.IO (IOMode(WriteMode), withFile)
section0 :: Section
section0 =
emptySection { _Blocks = Vector.replicate 4096 (BlockId 20)
}
chunk0 :: Chunk
chunk0 = emptyChunk { _Sections = [section0] }
chunkData0 :: ChunkData
chunkData0 = compressChunkData (toNBT chunk0)
chunkMap :: POSIXTime -> ChunkMap
chunkMap now = Map.fromList
[ ((0,0), (chunkData0, now)) ]
main :: IO ()
main =
withFile "test-r.0.0.mca" WriteMode $ \h ->
do now <- getPOSIXTime
writeChunkMap h (chunkMap now)
|
stepcut/minecraft-data
|
utils/GenWorld.hs
|
Haskell
|
bsd-3-clause
| 915
|
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
--
-- Copyright © 2013-2015 Anchor Systems, Pty Ltd and Others
--
-- The code in this file, and the program it is a part of, is
-- made available to you by its authors as open source software:
-- you can redistribute it and/or modify it under the terms of
-- the 3-clause BSD licence.
--
--
-- This module defines a convienient interface for clients
-- of Ceilometer.
--
-- For flexibility use the Collector and Fold modules.
--
module Ceilometer.Client
( -- * Interface
decodeFold
, decodeFold_
-- * Re-exports
, module X
) where
import Control.Applicative
import Control.Foldl
import Control.Lens
import Control.Monad
import Data.Monoid ((<>))
import qualified Data.Traversable as T
import Pipes
import qualified Pipes.Prelude as P
import System.IO (hPutStrLn, stderr)
import System.IO.Unsafe (unsafePerformIO)
import Ceilometer.Fold as X
import Ceilometer.Tags as X
import Ceilometer.Types as X
import Vaultaire.Types as X
decodeFold
:: (Monad m, Applicative m)
=> Env -- ^ @SourceDict@ to infer the resource type.
-> Producer SimplePoint m () -- ^ The raw data points to parse and aggregate.
-> m (Maybe FoldResult) -- ^ Result
decodeFold env@(Env _ sd _ _ _) raw = do
let x = do
name <- lookupMetricName sd
if | name == valCPU
-> return (decodeFold_ (undefined :: proxy PDCPU) env raw)
| name == valDiskReads
-> return (decodeFold_ (undefined :: proxy PDDiskRead) env raw)
| name == valDiskWrites
-> return (decodeFold_ (undefined :: proxy PDDiskWrite) env raw)
| name == valNeutronIn
-> return (decodeFold_ (undefined :: proxy PDNeutronRx) env raw)
| name == valNeutronOut
-> return (decodeFold_ (undefined :: proxy PDNeutronTx) env raw)
| name == valVolume -> do
voltype <- lookupVolumeType sd
if | voltype == valVolumeBlock
-> return (decodeFold_ (undefined :: proxy PDVolume) env raw)
| voltype == valVolumeFast
-> return (decodeFold_ (undefined :: proxy PDSSD) env raw)
| otherwise -> mzero
| name == valInstanceFlavor -> do
compound <- lookupCompound sd
event <- lookupEvent sd
if | compound == valTrue && event == valFalse
-> return (decodeFold_ (undefined :: proxy PDInstanceFlavor) env raw)
| otherwise -> mzero
| name == valInstanceVCPU
-> return (decodeFold_ (undefined :: proxy PDInstanceVCPU) env raw)
| name == valInstanceRAM
-> return (decodeFold_ (undefined :: proxy PDInstanceRAM) env raw)
| name == valImage ->
if | isEvent sd
-> return (decodeFold_ (undefined :: proxy PDImage) env raw)
| otherwise
-> return (decodeFold_ (undefined :: proxy PDImagePollster) env raw)
| name == valSnapshot
-> return (decodeFold_ (undefined :: proxy PDSnapshot) env raw)
| name == valIP
-> return (decodeFold_ (undefined :: proxy PDIP) env raw)
| otherwise -> mzero
T.sequence x
decodeFold_
:: forall proxy a m . (Known a, Applicative m, Monad m)
=> proxy a
-> Env
-> Producer SimplePoint m ()
-> m FoldResult
decodeFold_ _ env raw
= foldDecoded env (raw >-> (decode env :: Pipe SimplePoint (Timed a) m ()))
decode
:: (Known a, Monad m)
=> Env
-> Pipe SimplePoint (Timed a) m ()
decode env = forever $ do
p@(SimplePoint _ (TimeStamp t) v) <- await
let x = T.sequence $ Timed t $ v ^? clonePrism (mkPrism env)
case x of
Nothing -> do
-- Originally this would call error on Nothing, instead we print an angry
-- message and try to keep going. This *really* shoudn't happen for any
-- billing runs after August 2015, but due to a terrible recovery of data
-- we have some invalid points that are hard to get rid of.
let msg = "This shouldn't happen after August 2015, could not decode point:\n\t"
<> show p
return $! unsafePerformIO $ hPutStrLn stderr msg
Just x' -> yield x'
foldDecoded
:: (Known a, Monad m)
=> Env
-> Producer (Timed a) m ()
-> m FoldResult
foldDecoded env = impurely P.foldM (generalize $ mkFold env)
|
anchor/ceilometer-common
|
lib/Ceilometer/Client.hs
|
Haskell
|
bsd-3-clause
| 4,830
|
{-# LANGUAGE PatternSynonyms #-}
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.GL.ARB.DrawBuffers
-- Copyright : (c) Sven Panne 2019
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
--------------------------------------------------------------------------------
module Graphics.GL.ARB.DrawBuffers (
-- * Extension Support
glGetARBDrawBuffers,
gl_ARB_draw_buffers,
-- * Enums
pattern GL_DRAW_BUFFER0_ARB,
pattern GL_DRAW_BUFFER10_ARB,
pattern GL_DRAW_BUFFER11_ARB,
pattern GL_DRAW_BUFFER12_ARB,
pattern GL_DRAW_BUFFER13_ARB,
pattern GL_DRAW_BUFFER14_ARB,
pattern GL_DRAW_BUFFER15_ARB,
pattern GL_DRAW_BUFFER1_ARB,
pattern GL_DRAW_BUFFER2_ARB,
pattern GL_DRAW_BUFFER3_ARB,
pattern GL_DRAW_BUFFER4_ARB,
pattern GL_DRAW_BUFFER5_ARB,
pattern GL_DRAW_BUFFER6_ARB,
pattern GL_DRAW_BUFFER7_ARB,
pattern GL_DRAW_BUFFER8_ARB,
pattern GL_DRAW_BUFFER9_ARB,
pattern GL_MAX_DRAW_BUFFERS_ARB,
-- * Functions
glDrawBuffersARB
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Tokens
import Graphics.GL.Functions
|
haskell-opengl/OpenGLRaw
|
src/Graphics/GL/ARB/DrawBuffers.hs
|
Haskell
|
bsd-3-clause
| 1,214
|
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
-- |
-- Module : Pact.Types.Runtime
-- Copyright : (C) 2019 Stuart Popejoy
-- License : BSD-style (see the file LICENSE)
-- Maintainer : Stuart Popejoy <stuart@kadena.io>
--
-- Meta data and its types
--
module Pact.Types.ChainMeta
( -- * types
Address(..)
, PrivateMeta(..)
, PublicMeta(..)
, HasPlafMeta(..)
, PublicData(..)
, EntityName(..)
, TTLSeconds(..)
, TxCreationTime(..)
-- * optics
, aFrom, aTo
, pmAddress, pmChainId, pmSender, pmGasLimit, pmGasPrice, pmTTL, pmCreationTime
, pdPublicMeta, pdBlockHeight, pdBlockTime, pdPrevBlockHash
, getCurrentCreationTime
) where
import GHC.Generics
import Control.DeepSeq (NFData)
import Control.Lens (makeLenses)
import Data.Aeson
import Data.Default (Default, def)
import Data.Hashable (Hashable)
import Data.Int (Int64)
import Data.Serialize (Serialize)
import Data.Set (Set)
import Data.String (IsString)
import Data.Text
import Pact.Time (getCurrentTime, toPosixTimestampMicros)
import Data.Word (Word64)
-- internal pact modules
import Pact.Parse
import Pact.Types.ChainId (ChainId)
import Pact.Types.Gas
import Pact.Types.Util (AsString, lensyToJSON, lensyParseJSON)
-- | Name of "entity", ie confidential counterparty in an encrypted exchange, in privacy-supporting platforms.
newtype EntityName = EntityName Text
deriving stock (Eq, Ord, Generic)
deriving newtype (Show, NFData, Hashable, Serialize, Default, ToJSON, FromJSON, IsString, AsString)
-- | Wrapper for 'PublicMeta' ttl field in seconds since offset
--
newtype TTLSeconds = TTLSeconds ParsedInteger
deriving stock (Eq, Ord, Generic)
deriving newtype (Show, Num, NFData, ToJSON, FromJSON, Serialize)
-- | Wrapper for 'PublicMeta' creation time field in seconds since POSIX epoch
--
newtype TxCreationTime = TxCreationTime ParsedInteger
deriving stock (Eq, Ord, Generic)
deriving newtype (Show, Num, NFData, ToJSON, FromJSON, Serialize)
-- | Get current time as TxCreationTime
getCurrentCreationTime :: IO TxCreationTime
getCurrentCreationTime = TxCreationTime
. fromIntegral
. (`div` 1000000)
. toPosixTimestampMicros
<$> getCurrentTime
-- | Confidential/Encrypted addressing info, for use in metadata on privacy-supporting platforms.
data Address = Address
{ _aFrom :: EntityName
, _aTo :: Set EntityName
} deriving (Eq,Show,Ord,Generic)
instance NFData Address
instance Serialize Address
instance ToJSON Address where toJSON = lensyToJSON 2
instance FromJSON Address where parseJSON = lensyParseJSON 2
makeLenses ''Address
-- | Private-blockchain specific metadata.
newtype PrivateMeta = PrivateMeta { _pmAddress :: Maybe Address }
deriving (Eq,Show,Generic)
makeLenses ''PrivateMeta
instance Default PrivateMeta where def = PrivateMeta def
instance ToJSON PrivateMeta where toJSON = lensyToJSON 3
instance FromJSON PrivateMeta where parseJSON = lensyParseJSON 3
instance NFData PrivateMeta
instance Serialize PrivateMeta
-- | Allows user to specify execution parameters specific to public-chain
-- execution, namely gas parameters, TTL, creation time, chain identifier.
data PublicMeta = PublicMeta
{ _pmChainId :: !ChainId
-- ^ platform-specific chain identifier, e.g. "0"
, _pmSender :: !Text
-- ^ sender gas account key
, _pmGasLimit :: !GasLimit
-- ^ gas limit (maximum acceptable gas units for tx)
, _pmGasPrice :: !GasPrice
-- ^ per-unit gas price
, _pmTTL :: !TTLSeconds
-- ^ TTL in seconds
, _pmCreationTime :: !TxCreationTime
-- ^ Creation time in seconds since UNIX epoch
} deriving (Eq, Show, Generic)
makeLenses ''PublicMeta
instance Default PublicMeta where def = PublicMeta "" "" 0 0 0 0
instance ToJSON PublicMeta where
toJSON (PublicMeta cid s gl gp ttl ct) = object
[ "chainId" .= cid
, "sender" .= s
, "gasLimit" .= gl
, "gasPrice" .= gp
, "ttl" .= ttl
, "creationTime" .= ct
]
instance FromJSON PublicMeta where
parseJSON = withObject "PublicMeta" $ \o -> PublicMeta
<$> o .: "chainId"
<*> o .: "sender"
<*> o .: "gasLimit"
<*> o .: "gasPrice"
<*> o .: "ttl"
<*> o .: "creationTime"
instance NFData PublicMeta
instance Serialize PublicMeta
class HasPlafMeta a where
getPrivateMeta :: a -> PrivateMeta
getPublicMeta :: a -> PublicMeta
instance HasPlafMeta PrivateMeta where
getPrivateMeta = id
getPublicMeta = const def
instance HasPlafMeta PublicMeta where
getPrivateMeta = const def
getPublicMeta = id
instance HasPlafMeta () where
getPrivateMeta = const def
getPublicMeta = const def
-- | "Public chain" data with immutable block data
-- height, hash, creation time
data PublicData = PublicData
{ _pdPublicMeta :: !PublicMeta
-- ^ 'PublicMeta' data from request
, _pdBlockHeight :: !Word64
-- ^ block height as specified by platform.
, _pdBlockTime :: !Int64
-- ^ block creation time, micros since UNIX epoch
, _pdPrevBlockHash :: !Text
-- ^ block hash of preceding block
}
deriving (Show, Eq, Generic)
makeLenses ''PublicData
instance ToJSON PublicData where toJSON = lensyToJSON 3
instance FromJSON PublicData where parseJSON = lensyParseJSON 3
instance Default PublicData where def = PublicData def def def def
|
kadena-io/pact
|
src/Pact/Types/ChainMeta.hs
|
Haskell
|
bsd-3-clause
| 5,386
|
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeFamilies #-}
module Cardano.Faucet.Types.Recaptcha
( CaptchaSecret(..)
, CaptchaRequest(..), secret, response
, CaptchaResponse(..), success, challengeTS, hostname, errorCodes
, ReadRecaptchaSecretError(..)
, readCaptchaSecret
, captchaRequest
) where
import Control.Exception.Safe (Exception, throwIO)
import Control.Lens (makeLenses, makeWrapped, _Wrapped)
import Data.String (IsString)
import Network.Wreq (FormParam (..))
import qualified Network.Wreq as Wreq
-- import Data.Proxy
import Data.Aeson
import qualified Data.Text as Text
import qualified Data.Text.IO as Text
import Data.Time.Clock (UTCTime)
import Data.Typeable (Typeable)
import GHC.Generics (Generic)
import Universum
import Cardano.Faucet.Types.API
--------------------------------------------------------------------------------
newtype CaptchaSecret = CaptchaSecret Text deriving (Show, Eq, IsString)
makeWrapped ''CaptchaSecret
--------------------------------------------------------------------------------
-- | Request for sending to google to validate recaptcha
data CaptchaRequest = CaptchaRequest {
-- | The secret given by google
_secret :: CaptchaSecret
-- | The "g-recaptcha-response" field sent by the form
, _response :: GCaptchaResponse
} deriving (Generic)
makeLenses ''CaptchaRequest
--------------------------------------------------------------------------------
-- | Error thrown if recaptcha secret isn't a single line in a file
data ReadRecaptchaSecretError =
MoreThanOneLine FilePath
deriving (Eq, Show, Typeable)
instance Exception ReadRecaptchaSecretError
--------------------------------------------------------------------------------
-- | Response from google to being sent a 'CaptchaRequest'
data CaptchaResponse = CaptchaResponse {
-- | Was the recatcha validated as not coming from a bot
_success :: Bool
-- | The time of the challenge
--
-- (Maybe because this isn't present if there are errors)
, _challengeTS :: Maybe UTCTime
-- | The hostname serving the form
--
-- (Maybe because this isn't present if there are errors)
, _hostname :: Maybe Text
-- | Any errors present
, _errorCodes :: [Text]
} deriving (Eq, Show)
makeLenses ''CaptchaResponse
instance FromJSON CaptchaResponse where
parseJSON = withObject "CaptchaResponse" $ \v -> CaptchaResponse
<$> v .: "success"
<*> v .:? "challenge_ts"
<*> v .:? "hostname"
<*> (fromMaybe [] <$> v .:? "error-codes")
-- | Reads a CaptchaSecret out of a file
readCaptchaSecret :: FilePath -> IO CaptchaSecret
readCaptchaSecret fp = do
file <- Text.readFile fp
case Text.lines file of
[rSecret] -> return $ CaptchaSecret rSecret
_ -> throwIO $ MoreThanOneLine fp
-- | Makes the 'CaptchaRequest' to google
captchaRequest :: CaptchaRequest -> IO CaptchaResponse
captchaRequest cr = do
resp <- Wreq.asJSON =<< (Wreq.post "https://www.google.com/recaptcha/api/siteverify"
[ "secret" := cr ^. secret . _Wrapped
, "response" := cr ^. response . _Wrapped])
return $ resp ^. Wreq.responseBody
|
input-output-hk/pos-haskell-prototype
|
faucet/src/Cardano/Faucet/Types/Recaptcha.hs
|
Haskell
|
mit
| 3,617
|
f x = y 0
where y z | z > 10 = 10
| otherwise = (10 + 20)
q = 20
p = 10
|
itchyny/vim-haskell-indent
|
test/where/where_paren.in.hs
|
Haskell
|
mit
| 73
|
{-| Definition of the data collectors used by MonD.
-}
{-
Copyright (C) 2014 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.DataCollectors( collectors ) where
import Data.Map (findWithDefault)
import Data.Monoid (mempty)
import qualified Ganeti.DataCollectors.CPUload as CPUload
import qualified Ganeti.DataCollectors.Diskstats as Diskstats
import qualified Ganeti.DataCollectors.Drbd as Drbd
import qualified Ganeti.DataCollectors.InstStatus as InstStatus
import qualified Ganeti.DataCollectors.Lv as Lv
import qualified Ganeti.DataCollectors.XenCpuLoad as XenCpuLoad
import Ganeti.DataCollectors.Types (DataCollector(..),ReportBuilder(..))
import Ganeti.JSON (GenericContainer(..))
import Ganeti.Objects
import Ganeti.Types
-- | The list of available builtin data collectors.
collectors :: [DataCollector]
collectors =
[ cpuLoadCollector
, xenCpuLoadCollector
, diskStatsCollector
, drdbCollector
, instStatusCollector
, lvCollector
]
where
f .&&. g = \x y -> f x y && g x y
xenHypervisor = flip elem [XenPvm, XenHvm]
xenCluster _ cfg =
any xenHypervisor . clusterEnabledHypervisors $ configCluster cfg
collectorConfig name cfg =
let config = fromContainer . clusterDataCollectors $ configCluster cfg
in findWithDefault mempty name config
updateInterval name cfg = dataCollectorInterval $ collectorConfig name cfg
activeConfig name cfg = dataCollectorActive $ collectorConfig name cfg
diskStatsCollector =
DataCollector Diskstats.dcName Diskstats.dcCategory
Diskstats.dcKind (StatelessR Diskstats.dcReport) Nothing activeConfig
updateInterval
drdbCollector =
DataCollector Drbd.dcName Drbd.dcCategory Drbd.dcKind
(StatelessR Drbd.dcReport) Nothing activeConfig updateInterval
instStatusCollector =
DataCollector InstStatus.dcName InstStatus.dcCategory
InstStatus.dcKind (StatelessR InstStatus.dcReport) Nothing
(xenCluster .&&. activeConfig) updateInterval
lvCollector =
DataCollector Lv.dcName Lv.dcCategory Lv.dcKind
(StatelessR Lv.dcReport) Nothing activeConfig updateInterval
cpuLoadCollector =
DataCollector CPUload.dcName CPUload.dcCategory CPUload.dcKind
(StatefulR CPUload.dcReport) (Just CPUload.dcUpdate) activeConfig
updateInterval
xenCpuLoadCollector =
DataCollector XenCpuLoad.dcName XenCpuLoad.dcCategory XenCpuLoad.dcKind
(StatefulR XenCpuLoad.dcReport) (Just XenCpuLoad.dcUpdate) activeConfig
updateInterval
|
dimara/ganeti
|
src/Ganeti/DataCollectors.hs
|
Haskell
|
bsd-2-clause
| 3,774
|
{-# LANGUAGE BangPatterns #-}
-- | In-place quicksort.
module QuickSort (quickSort) where
import Control.Monad
import Control.Monad.Primitive
import Control.Monad.ST
import Data.List (sort)
import Data.Vector (Vector)
import qualified Data.Vector as V (toList)
import qualified Data.Vector.Generic as V(freeze)
import Data.Vector.Mutable (MVector)
import qualified Data.Vector.Mutable as V
import Prelude hiding (read)
import Test.QuickCheck
--------------------------------------------------------------------------------
-- Implementation
-- | In-place quicksort the given vector in some mutation-permitting
-- monad.
quickSort :: (PrimMonad m,Ord a) => MVector (PrimState m) a -> m ()
quickSort vec =
qsort vec 0 (V.length vec)
where qsort array begin end =
when (end > begin)
(do let startP = begin + ((end - begin) `div` 2)
-- ^ I chose to simply choose the pivot as the
-- median, no cleverness or randomness here. AIUI
-- Sedgewick recommends this.
pivot <- partition array begin end startP
-- The condition below is recommended by Sedgewick:
--
-- To make sure at most O(log n) space is used,
-- recurse first into the smaller side of the
-- partition, then use a tail call to recurse into
-- the other.
if pivot - begin > end - pivot + 1
then do qsort array (pivot + 1) end
qsort array begin pivot
else do qsort array begin pivot
qsort array (pivot + 1) end)
-- | Swap elements in the array until all elements <pivot are to the
-- left of pivot.
partition :: (PrimMonad m,Ord a) => V.MVector (PrimState m) a -> Int -> Int -> Int -> m Int
partition array begin end pivot =
do piv <- V.read array pivot
V.swap array pivot (end - 1)
store <- for begin (end - 1) begin
(\ix !store ->
do v <- V.read array ix
if v <= piv
then do V.swap array store ix
return (store + 1)
else return store)
V.swap array (end - 1) store
return store
where for from to state m = go from state
where go i state =
if i < to
then do state' <- m i state
go (i + 1) state'
else return state
--------------------------------------------------------------------------------
-- Tests
-- | Test that sorting some list of ints is equivalent to @sort xs@.
quickSortProp :: [Int] -> Bool
quickSortProp xs =
sort xs ==
V.toList (runST (do arr <- thaw xs
quickSort arr
freeze arr))
--------------------------------------------------------------------------------
-- Example
-- | Works in either the IO or ST monad!
main :: IO ()
main =
do quickCheck quickSortProp
ioVector <- do arr <- thaw [1,7,2,4,1,8,5,2]
quickSort arr
freeze arr
print ioVector
print (runST (do arr <- thaw [1,7,2,4,1,8,5,2]
quickSort arr
freeze arr))
-- | Handy function to construct a mutable vector from a list.
thaw :: (PrimMonad m)
=> [Int] -> m (MVector (PrimState m) Int)
thaw is =
do array <- V.new (length is)
forM_ (zip [0 ..] is)
(\(i,v) -> V.write array i (v :: Int))
return array
-- | More specific type for freezing.
freeze :: (PrimMonad m)
=> MVector (PrimState m) a -> m (Vector a)
freeze = V.freeze
|
QuinnSurkamer/sorting
|
src/Quicksort.hs
|
Haskell
|
bsd-3-clause
| 3,850
|
module Distribution.Solver.Modular.Explore
( backjump
, backjumpAndExplore
) where
import Data.Foldable as F
import Data.List as L (foldl')
import Data.Map as M
import Distribution.Solver.Modular.Assignment
import Distribution.Solver.Modular.Dependency
import Distribution.Solver.Modular.Log
import Distribution.Solver.Modular.Message
import qualified Distribution.Solver.Modular.PSQ as P
import qualified Distribution.Solver.Modular.ConflictSet as CS
import Distribution.Solver.Modular.Tree
import Distribution.Solver.Types.PackagePath
import Distribution.Solver.Types.Settings (EnableBackjumping(..), CountConflicts(..))
import qualified Distribution.Solver.Types.Progress as P
-- | This function takes the variable we're currently considering, an
-- initial conflict set and a
-- list of children's logs. Each log yields either a solution or a
-- conflict set. The result is a combined log for the parent node that
-- has explored a prefix of the children.
--
-- We can stop traversing the children's logs if we find an individual
-- conflict set that does not contain the current variable. In this
-- case, we can just lift the conflict set to the current level,
-- because the current level cannot possibly have contributed to this
-- conflict, so no other choice at the current level would avoid the
-- conflict.
--
-- If any of the children might contain a successful solution, we can
-- return it immediately. If all children contain conflict sets, we can
-- take the union as the combined conflict set.
--
-- The initial conflict set corresponds to the justification that we
-- have to choose this goal at all. There is a reason why we have
-- introduced the goal in the first place, and this reason is in conflict
-- with the (virtual) option not to choose anything for the current
-- variable. See also the comments for 'avoidSet'.
--
backjump :: EnableBackjumping -> Var QPN
-> ConflictSet QPN -> P.PSQ k (ConflictMap -> ConflictSetLog a)
-> ConflictMap -> ConflictSetLog a
backjump (EnableBackjumping enableBj) var initial xs =
F.foldr combine logBackjump xs initial
where
combine :: (ConflictMap -> ConflictSetLog a)
-> (ConflictSet QPN -> ConflictMap -> ConflictSetLog a)
-> ConflictSet QPN -> ConflictMap -> ConflictSetLog a
combine x f csAcc cm =
let l = x cm
in case l of
P.Done d -> P.Done d
P.Fail (cs, cm')
| enableBj && not (var `CS.member` cs) -> logBackjump cs cm'
| otherwise -> f (csAcc `CS.union` cs) cm'
P.Step m ms ->
let l' = combine (\ _ -> ms) f csAcc cm
in P.Step m l'
logBackjump :: ConflictSet QPN -> ConflictMap -> ConflictSetLog a
logBackjump cs cm = failWith (Failure cs Backjump) (cs, cm)
type ConflictSetLog = P.Progress Message (ConflictSet QPN, ConflictMap)
type ConflictMap = Map (Var QPN) Int
getBestGoal :: ConflictMap -> P.PSQ (Goal QPN) a -> (Goal QPN, a)
getBestGoal cm =
P.maximumBy
( flip (M.findWithDefault 0) cm
. (\ (Goal v _) -> v)
)
getFirstGoal :: P.PSQ (Goal QPN) a -> (Goal QPN, a)
getFirstGoal ts =
P.casePSQ ts
(error "getFirstGoal: empty goal choice") -- empty goal choice is an internal error
(\ k v _xs -> (k, v)) -- commit to the first goal choice
updateCM :: ConflictSet QPN -> ConflictMap -> ConflictMap
updateCM cs cm =
L.foldl' (\ cmc k -> M.alter inc k cmc) cm (CS.toList cs)
where
inc Nothing = Just 1
inc (Just n) = Just $! n + 1
-- | A tree traversal that simultaneously propagates conflict sets up
-- the tree from the leaves and creates a log.
exploreLog :: EnableBackjumping -> CountConflicts -> Tree QGoalReason
-> (Assignment -> ConflictMap -> ConflictSetLog (Assignment, RevDepMap))
exploreLog enableBj (CountConflicts countConflicts) = cata go
where
getBestGoal' :: P.PSQ (Goal QPN) a -> ConflictMap -> (Goal QPN, a)
getBestGoal'
| countConflicts = \ ts cm -> getBestGoal cm ts
| otherwise = \ ts _ -> getFirstGoal ts
go :: TreeF QGoalReason (Assignment -> ConflictMap -> ConflictSetLog (Assignment, RevDepMap))
-> (Assignment -> ConflictMap -> ConflictSetLog (Assignment, RevDepMap))
go (FailF c fr) _ = \ cm -> let failure = failWith (Failure c fr)
in if countConflicts
then failure (c, updateCM c cm)
else failure (c, cm)
go (DoneF rdm) a = \ _ -> succeedWith Success (a, rdm)
go (PChoiceF qpn gr ts) (A pa fa sa) =
backjump enableBj (P qpn) (avoidSet (P qpn) gr) $ -- try children in order,
P.mapWithKey -- when descending ...
(\ i@(POption k _) r cm ->
let l = r (A (M.insert qpn k pa) fa sa) cm
in tryWith (TryP qpn i) l
)
ts
go (FChoiceF qfn gr _ _ ts) (A pa fa sa) =
backjump enableBj (F qfn) (avoidSet (F qfn) gr) $ -- try children in order,
P.mapWithKey -- when descending ...
(\ k r cm ->
let l = r (A pa (M.insert qfn k fa) sa) cm
in tryWith (TryF qfn k) l
)
ts
go (SChoiceF qsn gr _ ts) (A pa fa sa) =
backjump enableBj (S qsn) (avoidSet (S qsn) gr) $ -- try children in order,
P.mapWithKey -- when descending ...
(\ k r cm ->
let l = r (A pa fa (M.insert qsn k sa)) cm
in tryWith (TryS qsn k) l
)
ts
go (GoalChoiceF ts) a = \ cm ->
let (k, v) = getBestGoal' ts cm
l = v a cm
in continueWith (Next k) l
-- | Build a conflict set corresponding to the (virtual) option not to
-- choose a solution for a goal at all.
--
-- In the solver, the set of goals is not statically determined, but depends
-- on the choices we make. Therefore, when dealing with conflict sets, we
-- always have to consider that we could perhaps make choices that would
-- avoid the existence of the goal completely.
--
-- Whenever we actual introduce a choice in the tree, we have already established
-- that the goal cannot be avoided. This is tracked in the "goal reason".
-- The choice to avoid the goal therefore is a conflict between the goal itself
-- and its goal reason. We build this set here, and pass it to the 'backjump'
-- function as the initial conflict set.
--
-- This has two effects:
--
-- - In a situation where there are no choices available at all (this happens
-- if an unknown package is requested), the initial conflict set becomes the
-- actual conflict set.
--
-- - In a situation where we backjump past the current node, the goal reason
-- of the current node will be added to the conflict set.
--
avoidSet :: Var QPN -> QGoalReason -> ConflictSet QPN
avoidSet var gr =
CS.fromList (var : goalReasonToVars gr)
-- | Interface.
backjumpAndExplore :: EnableBackjumping
-> CountConflicts
-> Tree QGoalReason -> Log Message (Assignment, RevDepMap)
backjumpAndExplore enableBj countConflicts t =
toLog $ (exploreLog enableBj countConflicts t (A M.empty M.empty M.empty)) M.empty
where
toLog :: P.Progress step fail done -> Log step done
toLog = P.foldProgress P.Step (const (P.Fail ())) P.Done
|
kolmodin/cabal
|
cabal-install/Distribution/Solver/Modular/Explore.hs
|
Haskell
|
bsd-3-clause
| 7,516
|
{- | Client inner-loop
This function is generally only needed if you are adding a new communication channel.
-}
processRemoteState :: IsAcidic st =>
IO CommChannel -- ^ (re-)connect function
-> IO (AcidState st)
processRemoteState reconnect
= do cmdQueue <- atomically newTQueue
ccTMV <- atomically newEmptyTMVar
isClosed <- newIORef False
let actor :: Command -> IO (MVar Response)
actor command =
do debugStrLn "actor: begin."
readIORef isClosed >>= flip when (throwIO AcidStateClosed)
ref <- newEmptyMVar
atomically $ writeTQueue cmdQueue (command, ref)
debugStrLn "actor: end."
return ref
expireQueue listenQueue =
do mCallback <- atomically $ tryReadTQueue listenQueue
case mCallback of
Nothing -> return ()
(Just callback) ->
do callback ConnectionError
expireQueue listenQueue
handleReconnect :: SomeException -> IO ()
handleReconnect e
= case fromException e of
(Just ThreadKilled) ->
do debugStrLn "handleReconnect: ThreadKilled. Not attempting to reconnect."
return ()
_ ->
do debugStrLn $ "handleReconnect begin."
tmv <- atomically $ tryTakeTMVar ccTMV
case tmv of
Nothing ->
do debugStrLn $ "handleReconnect: error handling already in progress."
debugStrLn $ "handleReconnect end."
return ()
(Just (oldCC, oldListenQueue, oldListenerTID)) ->
do thisTID <- myThreadId
when (thisTID /= oldListenerTID) (killThread oldListenerTID)
ccClose oldCC
expireQueue oldListenQueue
cc <- reconnect
listenQueue <- atomically $ newTQueue
listenerTID <- forkIO $ listener cc listenQueue
atomically $ putTMVar ccTMV (cc, listenQueue, listenerTID)
debugStrLn $ "handleReconnect end."
return ()
listener :: CommChannel -> TQueue (Response -> IO ()) -> IO ()
listener cc listenQueue
= getResponse Strict.empty `catch` handleReconnect
where
getResponse leftover =
do debugStrLn $ "listener: listening for Response."
let go inp = case inp of
Fail msg _ -> error msg
Partial cont -> do debugStrLn $ "listener: ccGetSome"
bs <- ccGetSome cc 1024
go (cont bs)
Done resp rest -> do debugStrLn $ "listener: getting callback"
callback <- atomically $ readTQueue listenQueue
debugStrLn $ "listener: passing Response to callback"
callback (resp :: Response)
return rest
rest <- go (runGetPartial get leftover) -- `catch` (\e -> do handleReconnect e
-- throwIO e
-- )
getResponse rest
actorThread :: IO ()
actorThread = forever $
do debugStrLn "actorThread: waiting for something to do."
(cc, cmd) <- atomically $
do (cmd, ref) <- readTQueue cmdQueue
(cc, listenQueue, _) <- readTMVar ccTMV
writeTQueue listenQueue (putMVar ref)
return (cc, cmd)
debugStrLn "actorThread: sending command."
ccPut cc (encode cmd) `catch` handleReconnect
debugStrLn "actorThread: sent."
return ()
shutdown :: ThreadId -> IO ()
shutdown actorTID =
do debugStrLn "shutdown: update isClosed IORef to True."
writeIORef isClosed True
debugStrLn "shutdown: killing actor thread."
killThread actorTID
debugStrLn "shutdown: taking ccTMV."
(cc, listenQueue, listenerTID) <- atomically $ takeTMVar ccTMV -- FIXME: or should this by tryTakeTMVar
debugStrLn "shutdown: killing listener thread."
killThread listenerTID
debugStrLn "shutdown: expiring listen queue."
expireQueue listenQueue
debugStrLn "shutdown: closing connection."
ccClose cc
return ()
cc <- reconnect
listenQueue <- atomically $ newTQueue
actorTID <- forkIO $ actorThread
listenerTID <- forkIO $ listener cc listenQueue
atomically $ putTMVar ccTMV (cc, listenQueue, listenerTID)
return (toAcidState $ RemoteState actor (shutdown actorTID))
|
bitemyapp/apply-refact
|
tests/examples/Remote.hs
|
Haskell
|
bsd-3-clause
| 5,693
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE BangPatterns #-}
module Network.Wai.Handler.Warp.ResponseHeader (composeHeader) where
import Control.Monad
import Data.ByteString (ByteString)
import qualified Data.ByteString as S
import Data.ByteString.Internal (create)
import qualified Data.CaseInsensitive as CI
import Data.List (foldl')
import Data.Word (Word8)
import Foreign.Ptr
import GHC.Storable
import qualified Network.HTTP.Types as H
import Network.Wai.Handler.Warp.Buffer (copy)
----------------------------------------------------------------
composeHeader :: H.HttpVersion -> H.Status -> H.ResponseHeaders -> IO ByteString
composeHeader !httpversion !status !responseHeaders = create len $ \ptr -> do
ptr1 <- copyStatus ptr httpversion status
ptr2 <- copyHeaders ptr1 responseHeaders
void $ copyCRLF ptr2
where
!len = 17 + slen + foldl' fieldLength 0 responseHeaders
fieldLength !l !(k,v) = l + S.length (CI.original k) + S.length v + 4
!slen = S.length $ H.statusMessage status
httpVer11 :: ByteString
httpVer11 = "HTTP/1.1 "
httpVer10 :: ByteString
httpVer10 = "HTTP/1.0 "
{-# INLINE copyStatus #-}
copyStatus :: Ptr Word8 -> H.HttpVersion -> H.Status -> IO (Ptr Word8)
copyStatus !ptr !httpversion !status = do
ptr1 <- copy ptr httpVer
writeWord8OffPtr ptr1 0 (zero + fromIntegral r2)
writeWord8OffPtr ptr1 1 (zero + fromIntegral r1)
writeWord8OffPtr ptr1 2 (zero + fromIntegral r0)
writeWord8OffPtr ptr1 3 spc
ptr2 <- copy (ptr1 `plusPtr` 4) (H.statusMessage status)
copyCRLF ptr2
where
httpVer
| httpversion == H.HttpVersion 1 1 = httpVer11
| otherwise = httpVer10
(q0,r0) = H.statusCode status `divMod` 10
(q1,r1) = q0 `divMod` 10
r2 = q1 `mod` 10
{-# INLINE copyHeaders #-}
copyHeaders :: Ptr Word8 -> [H.Header] -> IO (Ptr Word8)
copyHeaders !ptr [] = return ptr
copyHeaders !ptr (h:hs) = do
ptr1 <- copyHeader ptr h
copyHeaders ptr1 hs
{-# INLINE copyHeader #-}
copyHeader :: Ptr Word8 -> H.Header -> IO (Ptr Word8)
copyHeader !ptr (k,v) = do
ptr1 <- copy ptr (CI.original k)
writeWord8OffPtr ptr1 0 colon
writeWord8OffPtr ptr1 1 spc
ptr2 <- copy (ptr1 `plusPtr` 2) v
copyCRLF ptr2
{-# INLINE copyCRLF #-}
copyCRLF :: Ptr Word8 -> IO (Ptr Word8)
copyCRLF !ptr = do
writeWord8OffPtr ptr 0 cr
writeWord8OffPtr ptr 1 lf
return $! ptr `plusPtr` 2
zero :: Word8
zero = 48
spc :: Word8
spc = 32
colon :: Word8
colon = 58
cr :: Word8
cr = 13
lf :: Word8
lf = 10
|
frontrowed/wai
|
warp/Network/Wai/Handler/Warp/ResponseHeader.hs
|
Haskell
|
mit
| 2,513
|
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE CPP, NoImplicitPrelude, MagicHash, UnboxedTuples #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.IORef
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : experimental
-- Portability : portable
--
-- Mutable references in the IO monad.
--
-----------------------------------------------------------------------------
module Data.IORef
(
-- * IORefs
IORef, -- abstract, instance of: Eq, Typeable
newIORef,
readIORef,
writeIORef,
modifyIORef,
modifyIORef',
atomicModifyIORef,
atomicModifyIORef',
atomicWriteIORef,
#if !defined(__PARALLEL_HASKELL__)
mkWeakIORef,
#endif
-- ** Memory Model
-- $memmodel
) where
import GHC.Base
import GHC.STRef
import GHC.IORef hiding (atomicModifyIORef)
import qualified GHC.IORef
#if !defined(__PARALLEL_HASKELL__)
import GHC.Weak
#endif
#if !defined(__PARALLEL_HASKELL__)
-- |Make a 'Weak' pointer to an 'IORef', using the second argument as a finalizer
-- to run when 'IORef' is garbage-collected
mkWeakIORef :: IORef a -> IO () -> IO (Weak (IORef a))
mkWeakIORef r@(IORef (STRef r#)) f = IO $ \s ->
case mkWeak# r# r f s of (# s1, w #) -> (# s1, Weak w #)
#endif
-- |Mutate the contents of an 'IORef'.
--
-- Be warned that 'modifyIORef' does not apply the function strictly. This
-- means if the program calls 'modifyIORef' many times, but seldomly uses the
-- value, thunks will pile up in memory resulting in a space leak. This is a
-- common mistake made when using an IORef as a counter. For example, the
-- following will likely produce a stack overflow:
--
-- >ref <- newIORef 0
-- >replicateM_ 1000000 $ modifyIORef ref (+1)
-- >readIORef ref >>= print
--
-- To avoid this problem, use 'modifyIORef'' instead.
modifyIORef :: IORef a -> (a -> a) -> IO ()
modifyIORef ref f = readIORef ref >>= writeIORef ref . f
-- |Strict version of 'modifyIORef'
--
-- @since 4.6.0.0
modifyIORef' :: IORef a -> (a -> a) -> IO ()
modifyIORef' ref f = do
x <- readIORef ref
let x' = f x
x' `seq` writeIORef ref x'
-- |Atomically modifies the contents of an 'IORef'.
--
-- This function is useful for using 'IORef' in a safe way in a multithreaded
-- program. If you only have one 'IORef', then using 'atomicModifyIORef' to
-- access and modify it will prevent race conditions.
--
-- Extending the atomicity to multiple 'IORef's is problematic, so it
-- is recommended that if you need to do anything more complicated
-- then using 'Control.Concurrent.MVar.MVar' instead is a good idea.
--
-- 'atomicModifyIORef' does not apply the function strictly. This is important
-- to know even if all you are doing is replacing the value. For example, this
-- will leak memory:
--
-- >ref <- newIORef '1'
-- >forever $ atomicModifyIORef ref (\_ -> ('2', ()))
--
-- Use 'atomicModifyIORef'' or 'atomicWriteIORef' to avoid this problem.
--
atomicModifyIORef :: IORef a -> (a -> (a,b)) -> IO b
atomicModifyIORef = GHC.IORef.atomicModifyIORef
-- | Strict version of 'atomicModifyIORef'. This forces both the value stored
-- in the 'IORef' as well as the value returned.
--
-- @since 4.6.0.0
atomicModifyIORef' :: IORef a -> (a -> (a,b)) -> IO b
atomicModifyIORef' ref f = do
b <- atomicModifyIORef ref $ \a ->
case f a of
v@(a',_) -> a' `seq` v
b `seq` return b
-- | Variant of 'writeIORef' with the \"barrier to reordering\" property that
-- 'atomicModifyIORef' has.
--
-- @since 4.6.0.0
atomicWriteIORef :: IORef a -> a -> IO ()
atomicWriteIORef ref a = do
x <- atomicModifyIORef ref (\_ -> (a, ()))
x `seq` return ()
{- $memmodel
In a concurrent program, 'IORef' operations may appear out-of-order
to another thread, depending on the memory model of the underlying
processor architecture. For example, on x86, loads can move ahead
of stores, so in the following example:
> maybePrint :: IORef Bool -> IORef Bool -> IO ()
> maybePrint myRef yourRef = do
> writeIORef myRef True
> yourVal <- readIORef yourRef
> unless yourVal $ putStrLn "critical section"
>
> main :: IO ()
> main = do
> r1 <- newIORef False
> r2 <- newIORef False
> forkIO $ maybePrint r1 r2
> forkIO $ maybePrint r2 r1
> threadDelay 1000000
it is possible that the string @"critical section"@ is printed
twice, even though there is no interleaving of the operations of the
two threads that allows that outcome. The memory model of x86
allows 'readIORef' to happen before the earlier 'writeIORef'.
The implementation is required to ensure that reordering of memory
operations cannot cause type-correct code to go wrong. In
particular, when inspecting the value read from an 'IORef', the
memory writes that created that value must have occurred from the
point of view of the current thread.
'atomicModifyIORef' acts as a barrier to reordering. Multiple
'atomicModifyIORef' operations occur in strict program order. An
'atomicModifyIORef' is never observed to take place ahead of any
earlier (in program order) 'IORef' operations, or after any later
'IORef' operations.
-}
|
jtojnar/haste-compiler
|
libraries/ghc-7.10/base/Data/IORef.hs
|
Haskell
|
bsd-3-clause
| 5,368
|
module Q2 where
import Q
instance Show (IO a) where
show = undefined
|
olsner/ghc
|
testsuite/tests/cabal/T12733/q/Q2.hs
|
Haskell
|
bsd-3-clause
| 73
|
-----------------------------------------------------------------------------
-- |
-- Module : Data.AFSM.Auto
-- Copyright : (c) Hanzhong Xu, Meng Meng 2016,
-- License : MIT License
--
-- Maintainer : hanzh.xu@gmail.com
-- Stability : experimental
-- Portability : portable
-----------------------------------------------------------------------------
-- {-# LANGUAGE ExistentialQuantification #-}
-- {-# LANGUAGE FlexibleInstances, UndecidableInstances #-}
{-# LANGUAGE RankNTypes, ImpredicativeTypes, ExistentialQuantification #-}
module Data.AFSM.Auto where
import Control.Category
import Control.Arrow
import Control.Monad
-- | Control.Arrow.Transformer.Automaton
-- data Auto f a b = forall f. (Arrow f) => Auto (f a (Auto f a b, b))
-- data Auto f a b = Auto (f a (Auto f a b, b))
-- | Control.Auto
-- data Auto m a b = Auto (a -> m (Auto m a b, b))
{-
class Auto z where
build :: (a -> (z a b, b)) -> z a b
step :: (z a b) -> a -> (z a b, b)
-}
data AUTO a b = forall z. (Auto z) => AUTO (a -> (z a b, b))
class Auto z where
step :: (z a b) -> a -> (z a b, b)
{-
instance Auto (->) where
step f a = (f, f a)
-}
instance Auto AUTO where
step (AUTO t) a = (AUTO (step z), b)
where
(z, b) = t a
{-
instance Auto z => Category z where
id = idAuto
(.) = composeAuto
idAuto :: Auto z => z a a
idAuto = build (\a -> (idAuto, a))
composeAuto :: Auto z => z b c -> z a b -> z a c
composeAuto zbc zab = build f
where
f :: a -> (z a c, c)
f a = (composeAuto zbc' zab', c)
where
(zab', b) = step zab a
(zbc', c) = step zbc b
-}
|
PseudoPower/AFSM
|
src/Data/AFSM/Auto.hs
|
Haskell
|
mit
| 1,629
|
module ReplacementExperiment where
replaceWithP :: b -> Char
replaceWithP = const 'p'
lms :: [Maybe [Char]]
lms = [Just "Ave", Nothing, Just "woohoo"]
-- Just making the argument more specific
replaceWithP' :: [Maybe [Char]] -> Char
replaceWithP' = replaceWithP
liftedReplace :: Functor f => f a -> f Char
liftedReplace = fmap replaceWithP
liftedReplace' :: [Maybe [Char]] -> [Char]
liftedReplace' = liftedReplace
twiceLifted :: (Functor f1, Functor f) => f (f1 a) -> f (f1 Char)
twiceLifted = (fmap . fmap) replaceWithP
twiceLifted' :: [Maybe [Char]] -> [Maybe Char]
twiceLifted' = twiceLifted
thriceLifted :: (Functor f2, Functor f1, Functor f) => f (f1 (f2 a)) -> f (f1 (f2 Char))
thriceLifted = (fmap . fmap . fmap) replaceWithP
thriceLifted' :: [Maybe [Char]] -> [Maybe [Char]]
thriceLifted' = thriceLifted
main :: IO ()
main = do
putStr "replaceWithP lms: "
print (replaceWithP lms)
putStr "replaceWithP' lms: "
print (replaceWithP' lms)
putStr "liftedReplace lms: "
print (liftedReplace lms)
putStr "liftedReplace' lms: "
print (liftedReplace' lms)
putStr "twiceLifted lms: "
print (twiceLifted lms)
putStr "twiceLifted' lms: "
print (twiceLifted' lms)
putStr "thriceLifted lms: "
print (thriceLifted lms)
putStr "thriceLifted' lms: "
print (thriceLifted' lms)
|
NickAger/LearningHaskell
|
HaskellProgrammingFromFirstPrinciples/Chapter16.hsproj/ReplacementExperiment.hs
|
Haskell
|
mit
| 1,333
|
{-# LANGUAGE ConstraintKinds, DataKinds, DefaultSignatures, FlexibleContexts,
FlexibleInstances, MultiParamTypeClasses, OverlappingInstances,
RankNTypes, ScopedTypeVariables, TupleSections, TypeFamilies,
TypeOperators, UndecidableInstances #-}
{- |
Module : Control.Monad.Levels.Definitions
Description : Specific levls of monad transformers
Copyright : (c) Ivan Lazar Miljenovic
License : MIT
Maintainer : Ivan.Miljenovic@gmail.com
-}
module Control.Monad.Levels.Definitions where
import Control.Applicative (Applicative, WrappedMonad)
import Data.Coerce (Coercible, coerce)
import Data.Constraint ((:-) (..), Class (..), Constraint, Dict (..),
trans, weaken1, weaken2, (\\))
import Data.Constraint.Forall (Forall, inst)
import Data.Proxy (Proxy (..))
import Control.Monad.Trans.Cont (ContT (..))
import Control.Monad.Trans.Except (ExceptT (..), runExceptT)
import Control.Monad.Trans.Identity (IdentityT (..))
import Control.Monad.Trans.List (ListT (..))
import Control.Monad.Trans.Maybe (MaybeT (..))
import Control.Monad.Trans.Reader (ReaderT (..))
import qualified Control.Monad.Trans.RWS.Lazy as LRWS
import qualified Control.Monad.Trans.RWS.Strict as SRWS
import qualified Control.Monad.Trans.State.Lazy as LSt
import qualified Control.Monad.Trans.State.Strict as SSt
import qualified Control.Monad.Trans.Writer.Lazy as LW
import qualified Control.Monad.Trans.Writer.Strict as SW
import Data.Functor.Identity (Identity (..))
import Control.Arrow (first)
import Data.Monoid (Monoid, mempty)
-- -----------------------------------------------------------------------------
-- | Monads in a monadic stack.
--
-- For monads that are /not/ instances of 'MonadicLevel_' then it
-- suffices to say @instance MonadTower_ MyMonad@; for levels it is
-- required to define 'BaseMonad' (typically recursively).
--
-- You should use 'MonadTower' in any constraints rather than this
-- class. This includes when writing instances of 'MonadTower_' for
-- monadic transformers.
class (Applicative m, Monad m) => MonadTower_ m where
type BaseMonad m :: * -> *
type BaseMonad m = m
-- | This is 'MonadTower_' with additional sanity constraints to
-- ensure that applying 'BaseMonad' is idempotent.
type MonadTower m = (MonadTower_ m, IsBaseMonad (BaseMonad m))
-- -----------------------------------------------------------------------------
instance MonadTower_ []
instance MonadTower_ Maybe
instance MonadTower_ IO
instance MonadTower_ (Either e)
instance MonadTower_ ((->) r)
instance (Monad m) => MonadTower_ (WrappedMonad m)
instance MonadTower_ Identity
instance (MonadTower m) => MonadTower_ (ContT r m) where
type BaseMonad (ContT r m) = BaseMonad m
instance (MonadTower m) => MonadTower_ (ExceptT e m) where
type BaseMonad (ExceptT e m) = BaseMonad m
instance (MonadTower m) => MonadTower_ (IdentityT m) where
type BaseMonad (IdentityT m) = BaseMonad m
instance (MonadTower m) => MonadTower_ (ListT m) where
type BaseMonad (ListT m) = BaseMonad m
instance (MonadTower m) => MonadTower_ (MaybeT m) where
type BaseMonad (MaybeT m) = BaseMonad m
instance (MonadTower m) => MonadTower_ (ReaderT r m) where
type BaseMonad (ReaderT r m) = BaseMonad m
instance (Monoid w, MonadTower m) => MonadTower_ (LRWS.RWST r w s m) where
type BaseMonad (LRWS.RWST r w s m) = BaseMonad m
instance (Monoid w, MonadTower m) => MonadTower_ (SRWS.RWST r w s m) where
type BaseMonad (SRWS.RWST r w s m) = BaseMonad m
instance (MonadTower m) => MonadTower_ (LSt.StateT s m) where
type BaseMonad (LSt.StateT s m) = BaseMonad m
instance (MonadTower m) => MonadTower_ (SSt.StateT s m) where
type BaseMonad (SSt.StateT s m) = BaseMonad m
instance (Monoid w, MonadTower m) => MonadTower_ (LW.WriterT w m) where
type BaseMonad (LW.WriterT w m) = BaseMonad m
instance (Monoid w, MonadTower m) => MonadTower_ (SW.WriterT w m) where
type BaseMonad (SW.WriterT w m) = BaseMonad m
-- -----------------------------------------------------------------------------
-- | How to handle wrappers around existing 'MonadTower' instances.
--
-- For newtype wrappers (e.g. 'IdentityT'), it is sufficient to only
-- define 'LowerMonad'.
--
-- You should use 'MonadLevel' rather than this class in
-- constraints.
class (IsSubTowerOf (LowerMonad m) m, CanAddInternalM m) => MonadLevel_ m where
type LowerMonad m :: * -> *
-- | How the value is represented internally; defaults to @a@.
type InnerValue m a :: *
type InnerValue m a = a
-- | An instance of 'AddInternalM'; this is defined so as to be able
-- to make it easier to add constraints rather than solely relying
-- upon its value within 'Unwrapper'.
type WithLower_ m :: (* -> *) -> * -> *
type WithLower_ m = AddIdent
-- | Within the continuation for 'wrap' for @m a@, we can unwrap any
-- @m b@ if @AllowOtherValues m ~ True@; otherwise, we can only
-- unwrap @m a@. Defaults to @True@.
type AllowOtherValues m :: Bool
type AllowOtherValues m = True
-- | By default, should all constraints be allowed through this
-- level? Defaults to @True@.
type DefaultAllowConstraints m :: Bool
type DefaultAllowConstraints m = True
-- | A continuation-based approach to create a value of this level.
--
-- A default is provided for newtype wrappers around existing
-- 'MonadTower' instances, provided that - with the exception of
-- 'LowerMonad' - all associated types are left as their defaults.
wrap :: (CanUnwrap m a b) => Proxy a
-> (Unwrapper m a (LowerMonadValue m b)) -> m b
default wrap :: (Forall (IsCoercible m), Forall (InnerSame m)
, WithLower_ m ~ AddIdent, AllowOtherValues m ~ True, DefaultAllowConstraints m ~ True)
=> Proxy a -> (Unwrapper m a (LowerMonadValue m b)) -> m b
wrap = coerceWrap
coerceWrap :: forall m a b. (MonadLevel_ m, Forall (IsCoercible m), Forall (InnerSame m)
, WithLower_ m ~ AddIdent, AllowOtherValues m ~ True, DefaultAllowConstraints m ~ True)
=> Proxy a -> (Unwrapper m a (LowerMonadValue m b)) -> m b
coerceWrap _ f = pack (f unpack AddIdent)
where
pack :: LowerMonadValue m b -> m b
pack = coerce \\ (inst :: Forall (InnerSame m) :- InnerSame m b)
\\ (inst :: Forall (IsCoercible m) :- IsCoercible m b)
unpack :: m c -> LowerMonadValue m c
unpack = coerceUnwrap
{-# INLINE coerceWrap #-}
coerceUnwrap :: forall m c. (MonadLevel_ m, Forall (IsCoercible m), Forall (InnerSame m))
=> m c -> LowerMonadValue m c
coerceUnwrap = coerce \\ (inst :: Forall (InnerSame m) :- InnerSame m c)
\\ (inst :: Forall (IsCoercible m) :- IsCoercible m c)
{-# INLINE coerceUnwrap #-}
class (MonadLevel_ m, Coercible (m a) (LowerMonadValue m a), Coercible (LowerMonadValue m a) (m a))
=> IsCoercible m a
instance (MonadLevel_ m, Coercible (m a) (LowerMonadValue m a), Coercible (LowerMonadValue m a) (m a))
=> IsCoercible m a
type CanUnwrap_ m a b = CheckOtherAllowed (AllowOtherValues m) a b
type family CheckOtherAllowed (allowed::Bool) a b :: Constraint where
CheckOtherAllowed True a b = ()
CheckOtherAllowed False a b = (a ~ b)
-- | If we're dealing overall with @m a@, then this allows us to
-- specify those @b@ values for which we can also manipulate @m b@.
--
-- If @'AllowOtherValues' m ~ False@ then we require that @a ~ b@;
-- otherwise, any @b@ is accepted.
class (MonadLevel_ m, CanUnwrap_ m a b) => CanUnwrap m a b
instance (MonadLevel_ m, CanUnwrap_ m a b) => CanUnwrap m a b
-- | Used to ensure that for all monad levels, @CanUnwrap m a a@ is
-- satisfied.
class (MonadLevel_ m, CanUnwrap m a a) => CanUnwrapSelf m a
instance (MonadLevel_ m, CanUnwrap m a a) => CanUnwrapSelf m a
instance (MonadLevel_ m) => Class (MonadLevel_ m, CanUnwrap m a a) (CanUnwrapSelf m a) where
cls = Sub Dict
getUnwrapSelfProof :: (MonadLevel m) => MonadLevel m :- CanUnwrap m a a
getUnwrapSelfProof = trans weaken2 -- CanUnwrap
( trans cls -- Undo CanUnwrapSelf
(trans inst -- Undo Forall
(trans weaken1 -- Get Forall
weaken2 -- Remove MonadLevel_
)
)
)
-- | This is 'MonadLevel_' with some additional sanity constraints.
type MonadLevel m = (MonadLevel_ m, (Forall (CanUnwrapSelf m), WithLowerC m))
-- | The value contained within the actual level (e.g. for
-- @'LSt.StateT' s m a@, this is equivalent to @m (a,s)@).
type LowerMonadValue m a = LowerMonad m (InnerValue m a)
-- | A continuation function to produce a value of type @t@.
type Unwrapper m a t = (forall b. (CanUnwrap m a b) => m b -> LowerMonadValue m b)
-> (WithLower m a)
-> t
type WithLower m = WithLower_ m m
type WithLowerC m = AddConstraint (WithLower_ m) m
type CanAddInternalM m = AddInternalM (WithLower_ m)
type CanAddInternal m = AddInternal (WithLower_ m)
type CanGetInternal m = GetInternal (WithLower_ m)
class AddInternalM (ai :: (* -> *) -> * -> *) where
type AddConstraint ai (m :: * -> *) :: Constraint
type AddConstraint ai m = ()
addInternalM :: (MonadLevel m, WithLower_ m ~ ai, CanUnwrap m a b)
=> ai m a -> LowerMonad m b
-> LowerMonadValue m b
class (AddInternalM ai) => AddInternal ai where
addInternal :: (MonadLevel m, WithLower_ m ~ ai, CanUnwrap m a b)
=> ai m a -> b -> InnerValue m b
mapInternal :: (MonadLevel m, WithLower_ m ~ ai, CanUnwrap m a b, CanUnwrap m a c)
=> ai m a -> (b -> c) -> InnerValue m b -> InnerValue m c
class (AddInternal ai) => GetInternal ai where
-- | This is like a lifted 'maybe' function that applies to
-- 'InnerValue' values rather than just 'Maybe's.
getInternal :: (MonadLevel m, WithLower_ m ~ ai, CanUnwrap m a b)
=> ai m a -> c -> (b -> c) -> InnerValue m b -> c
-- | Used for monad transformers like 'ContT' where it is not possible
-- to manipulate the internal value without considering the monad
-- that it is within.
newtype AddIM m a = AddIM { addIMFunc :: forall b. (CanUnwrap m a b)
=> LowerMonad m b -> LowerMonadValue m b }
instance AddInternalM AddIM where
addInternalM = addIMFunc
-- | In most cases you will want to use 'AddIG' instead of this; this
-- is defined for cases like 'ListT' where it may not be possible to
-- obtain either zero or one value for use with 'getInternal'.
data AddI m a = AddI { setIFunc :: forall b. (CanUnwrap m a b) => b -> InnerValue m b
, mapIFunc :: forall b c. (CanUnwrap m a b, CanUnwrap m a c)
=> (b -> c) -> InnerValue m b -> InnerValue m c
}
instance AddInternalM AddI where
addInternalM ai = fmap (setIFunc ai)
addIntProof :: (MonadLevel m, AddInternalM ai) => ai m a -> MonadLevel m :- CanUnwrap m a a
addIntProof _ = getUnwrapSelfProof
instance AddInternal AddI where
addInternal = setIFunc
mapInternal = mapIFunc
-- | Used for monad transformers where it is possible to consider the
-- 'InnerValue' in isolation. If @InnerValue m a ~ a@ then use
-- 'AddIdent' instead.
data AddIG m a = AddIG { setIUFunc :: forall b. (CanUnwrap m a b) => b -> InnerValue m b
, mapIUFunc :: forall b c. (CanUnwrap m a b, CanUnwrap m a c)
=> (b -> c) -> InnerValue m b -> InnerValue m c
, getIUFunc :: forall b c. (CanUnwrap m a b)
=> c -> (b -> c) -> InnerValue m b -> c
}
instance AddInternalM AddIG where
addInternalM ai = fmap (setIUFunc ai)
instance AddInternal AddIG where
addInternal = setIUFunc
mapInternal = mapIUFunc
instance GetInternal AddIG where
getInternal = getIUFunc
-- | Used for monad transformers where @'InnerValue' m a ~ a@.
data AddIdent (m :: * -> *) a = AddIdent
instance AddInternalM AddIdent where
type AddConstraint AddIdent m = Forall (InnerSame m)
addInternalM ai m = m \\ addIdentProof ai (proxyFromM m)
class (MonadLevel_ m, InnerValue m a ~ a) => InnerSame m a
instance (MonadLevel_ m, InnerValue m a ~ a) => InnerSame m a
addIdentProof :: AddIdent m a -> Proxy b -> Forall (InnerSame m) :- InnerSame m b
addIdentProof _ _ = inst
proxyFrom :: a -> Proxy a
proxyFrom _ = Proxy
proxyFromM :: m a -> Proxy a
proxyFromM _ = Proxy
proxyFromF1 :: (a -> b) -> Proxy a
proxyFromF1 _ = Proxy
proxyFromF2 :: (a -> b) -> Proxy b
proxyFromF2 _ = Proxy
instance AddInternal AddIdent where
addInternal ai b = b \\ addIdentProof ai (proxyFrom b)
mapInternal ai f = f \\ addIdentProof ai (proxyFromF2 f)
\\ addIdentProof ai (proxyFromF1 f)
instance GetInternal AddIdent where
getInternal ai _ f lb = f lb \\ addIdentProof ai (proxyFromF1 f)
-- -----------------------------------------------------------------------------
instance (MonadTower m) => MonadLevel_ (ContT r m) where
type LowerMonad (ContT r m) = m
type InnerValue (ContT r m) a = r
type WithLower_ (ContT r m) = AddIM
type AllowOtherValues (ContT r m) = False
type DefaultAllowConstraints (ContT r m) = False
wrap _ f = ContT $ \ cont -> f (`runContT` cont) (AddIM (>>= cont))
instance (MonadTower m) => MonadLevel_ (ExceptT e m) where
type LowerMonad (ExceptT e m) = m
type InnerValue (ExceptT e m) a = Either e a
type WithLower_ (ExceptT e m) = AddIG
wrap _ f = ExceptT $ f runExceptT (AddIG Right fmap (either . const))
instance (MonadTower m) => MonadLevel_ (IdentityT m) where
type LowerMonad (IdentityT m) = m
-- Using default coerce-based implementation as a test.
-- wrap _ f = IdentityT $ f runIdentityT AddIdent
instance (MonadTower m) => MonadLevel_ (ListT m) where
type LowerMonad (ListT m) = m
type InnerValue (ListT m) a = [a]
type WithLower_ (ListT m) = AddI
type DefaultAllowConstraints (ListT m) = False
wrap _ f = ListT $ f runListT (AddI (:[]) map)
-- Can't define getInternal as that would require length <= 1
instance (MonadTower m) => MonadLevel_ (MaybeT m) where
type LowerMonad (MaybeT m) = m
type InnerValue (MaybeT m) a = Maybe a
type WithLower_ (MaybeT m) = AddIG
wrap _ f = MaybeT $ f runMaybeT (AddIG Just fmap maybe)
instance (MonadTower m) => MonadLevel_ (ReaderT r m) where
type LowerMonad (ReaderT r m) = m
wrap _ f = ReaderT $ \ r -> f (`runReaderT` r) AddIdent
map1 :: (a -> a') -> (a,b,c) -> (a',b,c)
map1 f (a,b,c) = (f a,b,c)
{-# INLINE map1 #-}
get1 :: (a,b,c) -> a
get1 (a,_,_) = a
{-# INLINE get1 #-}
instance (Monoid w, MonadTower m) => MonadLevel_ (LRWS.RWST r w s m) where
type LowerMonad (LRWS.RWST r w s m) = m
type InnerValue (LRWS.RWST r w s m) a = (a,s,w)
type WithLower_ (LRWS.RWST r w s m) = AddIG
wrap _ f = LRWS.RWST $ \ r s -> f (\m -> LRWS.runRWST m r s) (AddIG (,s,mempty) map1 (const (. get1)))
instance (Monoid w, MonadTower m) => MonadLevel_ (SRWS.RWST r w s m) where
type LowerMonad (SRWS.RWST r w s m) = m
type InnerValue (SRWS.RWST r w s m) a = (a,s,w)
type WithLower_ (SRWS.RWST r w s m) = AddIG
wrap _ f = SRWS.RWST $ \ r s -> f (\m -> SRWS.runRWST m r s) (AddIG (,s,mempty) map1 (const (. get1)))
instance (MonadTower m) => MonadLevel_ (LSt.StateT s m) where
type LowerMonad (LSt.StateT s m) = m
type InnerValue (LSt.StateT s m) a = (a,s)
type WithLower_ (LSt.StateT s m) = AddIG
wrap _ f = LSt.StateT $ \ s -> f (`LSt.runStateT` s) (AddIG (,s) first (const (. fst)))
instance (MonadTower m) => MonadLevel_ (SSt.StateT s m) where
type LowerMonad (SSt.StateT s m) = m
type InnerValue (SSt.StateT s m) a = (a,s)
type WithLower_ (SSt.StateT s m) = AddIG
wrap _ f = SSt.StateT $ \ s -> f (`SSt.runStateT` s) (AddIG (,s) first (const (. fst)))
instance (Monoid w, MonadTower m) => MonadLevel_ (LW.WriterT w m) where
type LowerMonad (LW.WriterT w m) = m
type InnerValue (LW.WriterT w m) a = (a,w)
type WithLower_ (LW.WriterT w m) = AddIG
wrap _ f = LW.WriterT $ f LW.runWriterT (AddIG (,mempty) first (const (. fst)))
instance (Monoid w, MonadTower m) => MonadLevel_ (SW.WriterT w m) where
type LowerMonad (SW.WriterT w m) = m
type InnerValue (SW.WriterT w m) a = (a,w)
type WithLower_ (SW.WriterT w m) = AddIG
wrap _ f = SW.WriterT $ f SW.runWriterT (AddIG (,mempty) first (const (. fst)))
-- -----------------------------------------------------------------------------
class (MonadTower_ m, m ~ BaseMonad m, BaseMonad m ~ m) => IsBaseMonad m
instance (MonadTower_ m, m ~ BaseMonad m, BaseMonad m ~ m) => IsBaseMonad m
type family SameMonad (m :: * -> *) (n :: * -> *) where
SameMonad m m = True
SameMonad m n = False
-- -----------------------------------------------------------------------------
-- | When considering whether a particular monad within a 'MonadTower'
-- stack satisfies a constraint, we need to be able to determine
-- this at the type level.
--
-- This is achieved with the 'ConstraintSatisfied' associated type:
-- it should be equated to a closed type family with the result
-- being 'True' for all monads for which the constraint is satisfied
-- and 'False' for all others.
--
-- (This is defined as a type class rather than just a type family
-- so that we can explicitly state that this needs to be defined.)
class ValidConstraint (c :: (* -> *) -> Constraint) where
type ConstraintSatisfied c (m :: * -> *) :: Bool
instance ValidConstraint IsBaseMonad where
type ConstraintSatisfied IsBaseMonad m = SameMonad (BaseMonad m) m
-- -----------------------------------------------------------------------------
-- | @IsSubTowerOf s m@ denotes that @s@ is a part of the @m@
-- @MonadTower@.
class (MonadTower_ s, MonadTower_ m, BaseMonad s ~ BaseMonad m) => IsSubTowerOf s m
instance (MonadTower m) => IsSubTowerOf m m
instance (MonadTower s, MonadLevel_ m, IsSubTowerOf s (LowerMonad m)) => IsSubTowerOf s m
instance (MonadTower s) => ValidConstraint (IsSubTowerOf s) where
type ConstraintSatisfied (IsSubTowerOf s) m = SameMonad s m
|
ivan-m/monad-levels
|
Control/Monad/Levels/Definitions.hs
|
Haskell
|
mit
| 18,679
|
{-|
Description : Parse string into parse tree
Parsec applicative style.
-}
module Uroboro.Parser
(
-- * Parsing Uroboro
parseFile
, parseExpression
, parse
-- * Individual parsers
, parseDef
, parseExp
, Parser
, pq
) where
import Control.Applicative ((<*>), (*>))
import Control.Monad (liftM)
import Text.Parsec hiding (parse)
import Text.Parsec.Error (errorMessages, showErrorMessages)
import Uroboro.Error
import Uroboro.Token
import Uroboro.Tree
(
PExp(..)
, PP(..)
, PQ(..)
, PT(..)
, PTCon(..)
, PTDes(..)
, PTRule(..)
, Type(..)
)
-- | Parse whole file.
parseFile :: FilePath -> String -> Either Error [PT]
parseFile = parse parseDef
-- | Parse expression.
parseExpression :: FilePath -> String -> Either Error PExp
parseExpression = parse parseExp
-- |Parse "(p, ...)".
args :: Parser a -> Parser [a]
args p = parens (commaSep p)
-- |Recursively apply a list of functions to a start value, from left to right.
fold :: a -> [a -> a] -> a
fold x [] = x
fold x (f:fs) = f (fold x fs)
-- |Variant of liftM that also stores the current location
liftLoc :: (Location -> a -> b) -> Parser a -> Parser b
liftLoc make parser = do
loc <- getLocation
arg <- parser
return (make loc arg)
-- |Parse "a.name(b, ...)...".
dotNotation :: (Location -> String -> [b] -> a -> a) -> Parser a -> Parser b -> Parser a
dotNotation make a b = liftM fold_ a <*> (dot *> sepBy1 name dot)
where name = liftLoc make identifier <*> args b
fold_ x l = fold x (reverse l) -- TODO make fold into foldr.
-- |Parse expression.
pexp :: Parser PExp
pexp = choice [des, app, var] <?> "expression"
where
des = try $ dotNotation PDes (app <|> var <?> "function or variable") pexp
app = try $ liftLoc PApp identifier <*> args pexp
var = liftLoc PVar identifier
-- |Parse exactly one expression.
parseExp :: Parser PExp
parseExp = exactly pexp
-- |Parse pattern.
pp :: Parser PP
pp = choice [con, var] <?> "pattern"
where
con = try $ liftLoc PPCon identifier <*> args pp
var = liftLoc PPVar identifier
-- |Parse copattern.
pq :: Parser PQ
pq = choice [des, app] <?> "copattern"
where
des = try $ dotNotation PQDes (app <?> "function") pp
app = liftLoc PQApp identifier <*> args pp
-- |Parse whole file.
parseDef :: Parser [PT]
parseDef = exactly $ many (choice [pos, neg, fun])
where
pos = definition "data" PTPos <*> where1 con
neg = definition "codata" PTNeg <*> where1 des
fun = liftLoc PTFun (reserved "function" *> identifier) <*>
args typ <*> (colon *> typ) <*> where1 rul
con = liftLoc (flip3 PTCon) identifier <*> args typ <*> (colon *> typ)
des = liftLoc (flip4 PTDes) typ <*>
(dot *> identifier) <*> args typ <*> (colon *> typ)
rul = liftLoc PTRule pq <*> (symbol "=" *> pexp)
typ :: Parser Type
typ = liftM Type identifier
flip3 f loc a b c = f loc c a b
flip4 f loc a b c d = f loc d b c a
definition :: String -> (Location -> Type -> a) -> Parser a
definition kind make = liftLoc make (reserved kind *> typ)
where1 :: Parser a -> Parser [a]
where1 a = reserved "where" *> many a
-- | Convert location to custom location type
convertLocation :: SourcePos -> Location
convertLocation pos = MakeLocation name line column where
name = sourceName pos
line = sourceLine pos
column = sourceColumn pos
-- | Convert error to custom error type
convertError :: ParseError -> Error
convertError err = MakeError location messages where
pos = errorPos err
location = convertLocation pos
messages = showErrorMessages
"or" "unknown parse error" "expecting"
"unexpected" "end of input"
(errorMessages err)
|
lordxist/uroboro
|
src/Uroboro/Parser.hs
|
Haskell
|
mit
| 3,798
|
-- N-Point Crossover
-- http://www.codewars.com/kata/57339a5226196a7f90001bcf
module Kata.NPointCrossover where
import Data.List (nub, sort)
import Data.Tuple (swap)
import Control.Arrow ((***))
crossover :: [Int] -> [a] -> [a] -> ([a],[a])
crossover ns xs = unzip . f (nub . sort $ ns) 0 . zip xs
where f [] i ps = map (ff !! (i `mod` 2)) ps
f (n:ns) i ps = uncurry (++) . (map (ff !! (i `mod` 2)) *** f (map ( + (-n)) ns) (succ i)) . splitAt n $ ps
ff = [id, swap]
|
gafiatulin/codewars
|
src/6 kyu/NPointCrossover.hs
|
Haskell
|
mit
| 494
|
module Thirty where
import Control.Exception
data NotDivThree =
NotDivThree Int
deriving (Eq, Show)
instance Exception NotDivThree
data NotEven =
NotEven Int
deriving (Eq, Show)
instance Exception NotEven
evenAndThreeDiv :: Int -> IO Int
evenAndThreeDiv i
| rem i 3 /= 0 = throwIO (NotDivThree i)
| odd i = throwIO (NotEven i)
| otherwise = return i
catchNotDivThree :: IO Int
-> (NotDivThree -> IO Int)
-> IO Int
catchNotDivThree = catch
catchNotEven :: IO Int
-> (NotEven -> IO Int)
-> IO Int
catchNotEven = catch
|
mudphone/HaskellBook
|
src/Thirty.hs
|
Haskell
|
mit
| 598
|
{-# LANGUAGE OverloadedStrings #-}
module Moz.Linkscape.URLMetrics
( URLMetrics(..)
, URLMetricCol(..)
, sumUrlMetricCols
) where
import Data.Aeson (FromJSON(..), Value(..), (.:?))
import Control.Monad (mzero)
data URLMetricCol = Title
| CanoncialURL
| Subdomain
| RootDomain
| ExternalEquityLinks
| SubdomainExternalLinks
| RootDomainExternalLinks
| EquityLinks
| SubdomainsLinking
| RootDomainsLinking
| Links
| SubdomainSubdomainsLinking
| RootDomainRootDomainsLinking
| MozRankURL
| MozRankSubdomain
| MozRankRootDomain
| MozTrust
| MozTrustSubdomain
| MozTrustRootDomain
| MozRankExternalEquity
| MozRankSubdomainExternalEquity
| MozRankRootDomainExternalEquity
| MozRankSubdomainCombined
| MozRankRootDomainCombined
| SubdomainSpamScore
| Social
| HTTPStatusCode
| LinksToSubdomain
| LinksToRootDomain
| RootDomainsLinkingToSubdomain
| PageAuthority
| DomainAuthority
| ExternalLinks
| ExternalLinksToSubdomain
| ExternalLinksToRootDomain
| LinkingCBlocks
| TimeLastCrawled
deriving (Enum, Eq, Show)
-- | Convert a list of URL metrics into a bit mask representing their sum.
sumUrlMetricCols :: [URLMetricCol] -> Int
sumUrlMetricCols = foldr (+) 0 . map toBitFlag
-- This looks like it should be able to be simplified by bitshifting using the
-- position of the value in the enum, but the bit flags have gaps which would
-- comprimise the data type, and the first one ('Title') doesn't fit the
-- pattern.
toBitFlag :: URLMetricCol -> Int
toBitFlag Title = 1
toBitFlag CanoncialURL = 4
toBitFlag Subdomain = 8
toBitFlag RootDomain = 16
toBitFlag ExternalEquityLinks = 32
toBitFlag SubdomainExternalLinks = 64
toBitFlag RootDomainExternalLinks = 128
toBitFlag EquityLinks = 256
toBitFlag SubdomainsLinking = 512
toBitFlag RootDomainsLinking = 1024
toBitFlag Links = 2048
toBitFlag SubdomainSubdomainsLinking = 4096
toBitFlag RootDomainRootDomainsLinking = 8192
toBitFlag MozRankURL = 16384
toBitFlag MozRankSubdomain = 32768
toBitFlag MozRankRootDomain = 65536
toBitFlag MozTrust = 131072
toBitFlag MozTrustSubdomain = 262144
toBitFlag MozTrustRootDomain = 524288
toBitFlag MozRankExternalEquity = 1048576
toBitFlag MozRankSubdomainExternalEquity = 2097152
toBitFlag MozRankRootDomainExternalEquity = 4194304
toBitFlag MozRankSubdomainCombined = 8388608
toBitFlag MozRankRootDomainCombined = 16777216
toBitFlag SubdomainSpamScore = 67108864
toBitFlag Social = 134217728
toBitFlag HTTPStatusCode = 536870912
toBitFlag LinksToSubdomain = 4294967296
toBitFlag LinksToRootDomain = 8589934592
toBitFlag RootDomainsLinkingToSubdomain = 17179869184
toBitFlag PageAuthority = 34359738368
toBitFlag DomainAuthority = 68719476736
toBitFlag ExternalLinks = 549755813888
toBitFlag ExternalLinksToSubdomain = 140737488355328
toBitFlag ExternalLinksToRootDomain = 2251799813685248
toBitFlag LinkingCBlocks = 36028797018963968
toBitFlag TimeLastCrawled = 144115188075855872
data URLMetrics = URLMetrics { title :: Maybe String -- ut
, canonicalURL :: Maybe String -- uu
, subdomain :: Maybe String -- ufq
, rootDomain :: Maybe String -- upl
, externalEquityLinks :: Maybe Int -- ueid
, subdomainExternalLinks :: Maybe Int -- feid
, rootDomainExternalLinks :: Maybe Int -- peid
, equityLinks :: Maybe Int -- ujid
, subdomainsLinking :: Maybe Int -- uifq
, rootDomainsLinking :: Maybe Int -- uipl
, links :: Maybe Int -- uid
, subdomainSubdomainsLinking :: Maybe Int -- fid
, rootDomainRootDomainsLinking :: Maybe Int -- pid
, mozRankURLNormalized :: Maybe Double -- umrp
, mozRankURLRaw :: Maybe Double -- umrr
, mozRankSubdomainNormalized :: Maybe Double -- fmrp
, mozRankSubdomainRaw :: Maybe Double -- fmrr
, mozRankRootDomainNormalized :: Maybe Double -- pmrp
, mozRankRootDomainRaw :: Maybe Double -- pmrr
, mozTrustNormalized :: Maybe Double -- utrp
, mozTrustRaw :: Maybe Double -- utrr
, mozTrustSubdomainNormalized :: Maybe Double -- ftrp
, mozTrustRootDomainNormalized :: Maybe Double -- ptrp
, mozTrustRootDomainRaw :: Maybe Double -- ptrr
, mozRankExternalEquityNormalized :: Maybe Double -- uemrp
, mozRankExternalEquityRaw :: Maybe Double -- uemrr
, mozRankSubdomainExternalEquityNormalized :: Maybe Double -- fejp
, mozRankSubdomainExternalEquityRaw :: Maybe Double -- fejr
, mozRankRootDomainExternalEquityNormalized :: Maybe Double -- pejp
, mozRankRootDomainExternalEquityRaw :: Maybe Double -- pejr
, mozRankSubdomainCombinedNormalized :: Maybe Double -- pjp
, mozRankSubdomainCombinedRaw :: Maybe Double -- pjr
, mozRankRootDomainCombinedNormalized :: Maybe Double -- fjp
, mozRankRootDomainCombinedRaw :: Maybe Double -- fjr
, subdomainSpamScoreSubdomain :: Maybe Int -- fspsc
, subdomainSpamScoreFlags :: Maybe Int -- fspf
, subdomainSpamScoreLanguage :: Maybe String -- flan
, subdomainSpamScoreCrawlStatusCode :: Maybe Int -- fsps
, subdomainSpamScoreLastCrawled :: Maybe Int -- fsplc
, subdomainSpamScorePagesCrawled :: Maybe [String] -- fspp
, socialFacebookAccount :: Maybe String -- ffb
, socialTwitterHandle :: Maybe String -- ftw
, socialGooglePlusAccount :: Maybe String -- fg+
, socialEmailAddress :: Maybe String -- fem
, httpStatusCode :: Maybe String -- us
, linksToSubdomain :: Maybe Int -- fuid
, linksToRootDomain :: Maybe Int -- puid
, rootDomainsLinkingToSubdomain :: Maybe Int -- fipl
, pageAuthority :: Maybe Double -- upa
, domainAuthority :: Maybe Double -- pda
, externalLinks :: Maybe Int -- ued
, externalLinksToSubdomain :: Maybe Int -- fed
, externalLinksToRootDoamin :: Maybe Int -- ped
, linkingCBlocks :: Maybe Int -- pib
, timeLastCrawed :: Maybe Int -- ulc
} deriving (Show)
instance FromJSON URLMetrics where
parseJSON (Object v) =
URLMetrics <$> v .:? "ut"
<*> v .:? "uu"
<*> v .:? "ufq"
<*> v .:? "upl"
<*> v .:? "ueid"
<*> v .:? "feid"
<*> v .:? "peid"
<*> v .:? "ujid"
<*> v .:? "uifq"
<*> v .:? "uipl"
<*> v .:? "uid"
<*> v .:? "fid"
<*> v .:? "pid"
<*> v .:? "umrp"
<*> v .:? "umrr"
<*> v .:? "fmrp"
<*> v .:? "fmrr"
<*> v .:? "pmrp"
<*> v .:? "pmrr"
<*> v .:? "utrp"
<*> v .:? "utrr"
<*> v .:? "ftrp"
<*> v .:? "ptrp"
<*> v .:? "ptrr"
<*> v .:? "uemrp"
<*> v .:? "uemrr"
<*> v .:? "fejp"
<*> v .:? "fejr"
<*> v .:? "pejp"
<*> v .:? "pejr"
<*> v .:? "pjp"
<*> v .:? "pjr"
<*> v .:? "fjp"
<*> v .:? "fjr"
<*> v .:? "fspsc"
<*> v .:? "fspf"
<*> v .:? "flan"
<*> v .:? "fsps"
<*> v .:? "fsplc"
<*> v .:? "fspp"
<*> v .:? "ffb"
<*> v .:? "ftw"
<*> v .:? "fg+"
<*> v .:? "fem"
<*> v .:? "us"
<*> v .:? "fuid"
<*> v .:? "puid"
<*> v .:? "fipl"
<*> v .:? "upa"
<*> v .:? "pda"
<*> v .:? "ued"
<*> v .:? "fed"
<*> v .:? "ped"
<*> v .:? "pib"
<*> v .:? "ulc"
parseJSON _ = mzero
|
ags/hs-moz
|
src/Moz/Linkscape/URLMetrics.hs
|
Haskell
|
mit
| 10,120
|
module BuiltInFunctions where
myOr :: [Bool] -> Bool
myOr = foldr (||) False
myAny :: (a -> Bool) -> [a] -> Bool
myAny f list = myOr $ map f list
myElem :: Eq a => a -> [a] -> Bool
-- myElem item = myAny (== item)
myElem item list = foldr (||) False $ map (== item) list
myReverse :: [a] -> [a]
myReverse list = foldl (flip (:)) [] list
myMap :: (a -> b) -> [a] -> [b]
myMap f list = foldr ((:) . f) [] list
myFilter :: (a -> Bool) -> [a] -> [a]
myFilter f list = foldr (\item acc -> if (f item) then item : acc else acc) [] list
|
mikegehard/haskellBookExercises
|
chapter10/BuiltInFunctions.hs
|
Haskell
|
mit
| 588
|
module Handler.GamesJsonSpec (spec) where
import TestImport
spec :: Spec
spec = withApp $ do
describe "getGamesJsonR" $ do
error "Spec not implemented: getGamesJsonR"
|
jabaraster/minibas-web
|
test/Handler/GamesJsonSpec.hs
|
Haskell
|
mit
| 183
|
import Prelude hiding (lookup)
import Control.Monad.ST
import Data.HashTable.ST.Basic
-- Hashtable parameterized by ST "thread"
type HT s = HashTable s String String
example1 :: ST s (HT s)
example1 = do
ht <- new
insert ht "key" "value1"
return ht
example2 :: HT s -> ST s (Maybe String)
example2 ht = do
val <- lookup ht "key"
return val
example3 :: Maybe String
example3 = runST (example1 >>= example2)
|
riwsky/wiwinwlh
|
src/hashtables.hs
|
Haskell
|
mit
| 421
|
module Maskell.Stats where
import Control.Monad
import Data.List
import Data.Maybe
test_mcmath = do
putStrLn "hello from Mcmath"
{-|
The `prank' function calculates percentile ranks of a list of floats.
prank [23.0, 20.0, 20.0, 57.0, 46.0]
-}
prank :: [Float] -> [Float]
prank arr =
map score arr
where
len p v = fromIntegral $ length $ filter (p v) arr
n = fromIntegral $ length arr
score v = ((len (>) v) + 0.5 * (len (==) v))/n
data1 = [23.0, 20.0, 20.0, 57.0, 46.0]
testPrank = prank data1
prankM :: [Maybe Float] -> [Maybe Float]
prankM arrM =
rebuild [] pranks arrM
where
pranks = prank $ catMaybes arrM
rebuild acc _ [] = acc
rebuild acc (p:ps) (m:ms) =
if isJust m
then rebuild (acc ++ [Just p]) ps ms
else rebuild (acc ++ [Nothing]) (p:ps) ms
testPrankM = prankM [Just 23.0, Just 20.0, Just 20.0, Nothing, Just 57.0, Just 46.0]
-- | on a sorted list
median' xs | null xs = Nothing
| odd len = Just $ xs !! mid
| even len = Just $ meanMedian
where len = length xs
mid = len `div` 2
meanMedian = (xs !! mid + xs !! (mid-1)) / 2
median' :: Fractional a => [a] -> Maybe a
-- | on an unsorted list
median xs = median' $ sort xs
mmedian xs = median $ catMaybes xs
mean :: (Fractional a) => [a] -> a
mean [] = 0
mean xs = sum xs / Data.List.genericLength xs
mmean xs = mean $ catMaybes xs
|
blippy/maskell
|
src/Maskell/Stats.hs
|
Haskell
|
mit
| 1,454
|
module Nameless.Conversion where
import Named.Data
import Nameless.Data
import Data.List
type NamingContext = [Name] -- Naming context for DeBrujin, head = 0
getFree :: Expression -> NamingContext
getFree (Func b ex) = filter (b /=) (getFree ex)
getFree (Call e1 e2) = union (getFree e1) (getFree e2)
getFree (Var x) = [x]
toNameless :: NamingContext -> Expression -> NamelessExp
toNameless ctx (Var x) = case elemIndex x ctx of
Just i -> NlVar i
Nothing -> NlVar (-1) -- Dodgyyyyy!
toNameless ctx (Call e1 e2) = NlCall (toNameless ctx e1) (toNameless ctx e2)
toNameless ctx (Func n e) = NlFunc (toNameless (n : ctx) e)
|
mcapodici/haskelllearn
|
firstlang/simple/src/Nameless/Conversion.hs
|
Haskell
|
mit
| 632
|
{-# LANGUAGE TemplateHaskell #-}
{-# OPTIONS_HADDOCK prune #-}
module System.Console.Docopt.QQ
(
-- * QuasiQuoter usage parsers
docopt
, docoptFile
) where
import qualified Data.Map as M
import System.Console.Docopt.Types
import System.Console.Docopt.QQ.Instances ()
import System.Console.Docopt.ApplicativeParsec
import System.Console.Docopt.UsageParse
import Language.Haskell.TH
import Language.Haskell.TH.Quote
parseFmt :: FilePath -> String -> Either ParseError OptFormat
parseFmt = runParser pDocopt M.empty
docoptExp :: String -> Q Exp
docoptExp rawUsg = do
let usg = trimEmptyLines rawUsg
let mkDocopt fmt = Docopt { usage = usg, optFormat = fmt }
loc <- loc_filename <$> location
case mkDocopt <$> parseFmt loc usg of
Left err -> fail $ show err
Right parser -> [| parser |]
-- | A 'QuasiQuoter' which parses a usage string and returns a
-- 'Docopt'.
--
-- Example usage:
--
-- @
-- patterns :: Docopt
-- patterns = [docopt|
-- docopt-sample version 0.1.0
--
-- Usage:
-- docopt-sample cat \<file\>
-- docopt-sample echo [--caps] \<string\>
--
-- Options:
-- -c, --caps Caps-lock the echoed argument
-- |]
-- @
--
-- For help with the docopt usage format, see
-- <https://github.com/docopt/docopt.hs/blob/master/README.md#help-text-format the readme on github>.
docopt :: QuasiQuoter
docopt = QuasiQuoter { quoteExp = docoptExp
, quoteDec = unsupported "Declaration"
, quotePat = unsupported "Pattern"
, quoteType = unsupported "Type"
}
where unsupported :: String -> String -> Q a
unsupported qqType _ = do
fail $ (qqType ++ " context unsupported")
-- | Same as 'docopt', but parses the given file instead of a literal
-- string.
--
-- Example:
--
-- @
-- patterns :: Docopt
-- patterns = [docoptFile|USAGE|]
-- @
--
-- where @USAGE@ is the name of a file which contains the usage
-- string (relative to the directory from which ghc is invoked).
docoptFile :: QuasiQuoter
docoptFile = quoteFile docopt
|
docopt/docopt.hs
|
System/Console/Docopt/QQ.hs
|
Haskell
|
mit
| 2,082
|
{-# LANGUAGE RankNTypes, OverloadedStrings, DeriveDataTypeable,
ForeignFunctionInterface, JavaScriptFFI, EmptyDataDecls,
TypeFamilies, DataKinds, ScopedTypeVariables,
FlexibleContexts, FlexibleInstances, TypeSynonymInstances,
LambdaCase, MultiParamTypeClasses, DeriveGeneric #-}
module JavaScript.Web.XMLHttpRequest ( xhr
, xhrByteString
, xhrText
, xhrString
, Method(..)
, Request(..)
, RequestData(..)
, Response(..)
, ResponseType(..)
, FormDataVal(..)
, XHRError(..)
) where
import Control.Applicative
import Control.Exception
import Control.Monad
import GHCJS.Types
import GHCJS.Prim
import GHCJS.Marshal
import GHCJS.Marshal.Pure
import GHCJS.Internal.Types
import qualified GHCJS.Buffer as Buffer
import GHC.Generics
import Data.ByteString
import Data.Data
import Data.JSString
import Data.JSString.Internal.Type ( JSString(..) )
import Data.Typeable
import Data.Proxy
import Data.Text (Text)
import Data.JSString.Text (textFromJSString)
import qualified Data.JSString as JSS
import JavaScript.JSON.Types.Internal ( SomeValue(..) )
import JavaScript.TypedArray.Internal.Types ( SomeTypedArray(..) )
import JavaScript.TypedArray.ArrayBuffer ( ArrayBuffer(..) )
import JavaScript.TypedArray.ArrayBuffer.Internal ( SomeArrayBuffer(..) )
import JavaScript.Web.Blob
import JavaScript.Web.Blob.Internal
import JavaScript.Web.File
data Method = GET | POST | PUT | DELETE
deriving (Show, Eq, Ord, Enum)
data XHRError = XHRError String
| XHRAborted
deriving (Generic, Data, Typeable, Show, Eq)
instance Exception XHRError
methodJSString :: Method -> JSString
methodJSString GET = "GET"
methodJSString POST = "POST"
methodJSString PUT = "PUT"
methodJSString DELETE = "DELETE"
type Header = (JSString, JSString)
data FormDataVal = StringVal JSString
| BlobVal Blob (Maybe JSString)
| FileVal File (Maybe JSString)
deriving (Typeable)
data Request = Request { reqMethod :: Method
, reqURI :: JSString
, reqLogin :: Maybe (JSString, JSString)
, reqHeaders :: [Header]
, reqWithCredentials :: Bool
, reqData :: RequestData
}
deriving (Typeable)
data RequestData = NoData
| StringData JSString
| TypedArrayData (forall e. SomeTypedArray e Immutable)
| FormData [(JSString, FormDataVal)]
deriving (Typeable)
data Response a = Response { contents :: Maybe a
, status :: Int
, getAllResponseHeaders :: IO JSString
, getResponseHeader :: JSString -> IO (Maybe JSString)
}
instance Functor Response where fmap f r = r { contents = fmap f (contents r) }
class ResponseType a where
getResponseTypeString :: Proxy a -> JSString
wrapResponseType :: JSVal -> a
instance ResponseType ArrayBuffer where
getResponseTypeString _ = "arraybuffer"
wrapResponseType = SomeArrayBuffer
instance m ~ Immutable => ResponseType JSString where
getResponseTypeString _ = "text"
wrapResponseType = JSString
instance ResponseType Blob where
getResponseTypeString _ = "blob"
wrapResponseType = SomeBlob
instance m ~ Immutable => ResponseType (SomeValue m) where
getResponseTypeString _ = "json"
wrapResponseType = SomeValue
newtype JSFormData = JSFormData JSVal deriving (Typeable)
newtype XHR = XHR JSVal deriving (Typeable)
-- -----------------------------------------------------------------------------
-- main entry point
xhr :: forall a. ResponseType a => Request -> IO (Response a)
xhr req = js_createXHR >>= \x ->
let doRequest = do
case reqLogin req of
Nothing ->
js_open2 (methodJSString (reqMethod req)) (reqURI req) x
Just (user, pass) ->
js_open4 (methodJSString (reqMethod req)) (reqURI req) user pass x
js_setResponseType
(getResponseTypeString (Proxy :: Proxy a)) x
forM_ (reqHeaders req) (\(n,v) -> js_setRequestHeader n v x)
r <- case reqData req of
NoData ->
js_send0 x
StringData str ->
js_send1 (pToJSVal str) x
TypedArrayData (SomeTypedArray t) ->
js_send1 t x
FormData xs -> do
fd@(JSFormData fd') <- js_createFormData
forM_ xs $ \(name, val) -> case val of
StringVal str ->
js_appendFormData2 name (pToJSVal str) fd
BlobVal (SomeBlob b) mbFile ->
appendFormData name b mbFile fd
FileVal (SomeBlob b) mbFile ->
appendFormData name b mbFile fd
js_send1 fd' x
case r of
0 -> do
status <- js_getStatus x
r <- do
hr <- js_hasResponse x
if hr then Just . wrapResponseType <$> js_getResponse x
else pure Nothing
return $ Response r
status
(js_getAllResponseHeaders x)
(\h -> getResponseHeader' h x)
1 -> throwIO XHRAborted
2 -> throwIO (XHRError "some error")
in doRequest `onException` js_abort x
appendFormData :: JSString -> JSVal
-> Maybe JSString -> JSFormData -> IO ()
appendFormData name val Nothing fd =
js_appendFormData2 name val fd
appendFormData name val (Just fileName) fd =
js_appendFormData3 name val fileName fd
getResponseHeader' :: JSString -> XHR -> IO (Maybe JSString)
getResponseHeader' name x = do
h <- js_getResponseHeader name x
return $ if isNull h then Nothing else Just (JSString h)
-- -----------------------------------------------------------------------------
-- utilities
xhrString :: Request -> IO (Response String)
xhrString = fmap (fmap JSS.unpack) . xhr
xhrText :: Request -> IO (Response Text)
xhrText = fmap (fmap textFromJSString) . xhr
xhrByteString :: Request -> IO (Response ByteString)
xhrByteString = fmap
(fmap (Buffer.toByteString 0 Nothing . Buffer.createFromArrayBuffer)) . xhr
-- -----------------------------------------------------------------------------
foreign import javascript unsafe
"new XMLHttpRequest()"
js_createXHR :: IO XHR
foreign import javascript unsafe
"$2.responseType = $1;"
js_setResponseType :: JSString -> XHR -> IO ()
foreign import javascript unsafe
"$1.abort();"
js_abort :: XHR -> IO ()
foreign import javascript unsafe
"$3.setRequestHeader($1,$2);"
js_setRequestHeader :: JSString -> JSString -> XHR -> IO ()
foreign import javascript unsafe
"$3.open($1,$2)"
js_open2 :: JSString -> JSString -> XHR -> IO ()
foreign import javascript unsafe
"$5.open($1,$2,true,$4,$5);"
js_open4 :: JSString -> JSString -> JSString -> JSString -> XHR -> IO ()
foreign import javascript unsafe
"new FormData()"
js_createFormData :: IO JSFormData
foreign import javascript unsafe
"$3.append($1,$2)"
js_appendFormData2 :: JSString -> JSVal -> JSFormData -> IO ()
foreign import javascript unsafe
"$4.append($1,$2,$3)"
js_appendFormData3 :: JSString -> JSVal -> JSString -> JSFormData -> IO ()
foreign import javascript unsafe
"$1.status"
js_getStatus :: XHR -> IO Int
foreign import javascript unsafe
"$1.response"
js_getResponse :: XHR -> IO JSVal
foreign import javascript unsafe
"$1.response ? true : false"
js_hasResponse :: XHR -> IO Bool
foreign import javascript unsafe
"$1.getAllResponseHeaders()"
js_getAllResponseHeaders :: XHR -> IO JSString
foreign import javascript unsafe
"$2.getResponseHeader($1)"
js_getResponseHeader :: JSString -> XHR -> IO JSVal
-- -----------------------------------------------------------------------------
foreign import javascript interruptible
"h$sendXHR($1, null, $c);"
js_send0 :: XHR -> IO Int
foreign import javascript interruptible
"h$sendXHR($2, $1, $c);"
js_send1 :: JSVal -> XHR -> IO Int
|
NewByteOrder/ghcjs-base
|
JavaScript/Web/XMLHttpRequest.hs
|
Haskell
|
mit
| 8,721
|
{-# LANGUAGE OverloadedStrings #-}
module Domain.StatText (wordCount) where
import qualified Data.Text.Lazy as T
import Data.Function(on)
import Data.List(sortBy)
import Data.Map.Lazy (Map, empty, insertWith, assocs)
import Debug.Trace
wordCount :: T.Text -> [(T.Text, Integer)]
wordCount = count . filter specialWord . filter (\w -> T.length w > 3) . T.split wordSeparator . T.toCaseFold
where
wordSeparator :: Char -> Bool
wordSeparator = flip elem ".,;`()-_=></\"\\#%' \n\r\t" -- Todo use regexp
specialWord :: T.Text -> Bool
specialWord = not . flip elem ["the", "be", "to", "of", "and", "a", "in", "that", "have", "I", "it", "for", "not", "on", "with", "he", "as", "you", "do", "at", "this", "but", "his", "by", "from", "they", "we", "say", "her", "she", "or", "an", "will", "my", "one", "all", "would", "there", "their", "what", "so", "up", "out", "if", "about", "who", "get", "which", "go", "me", "when", "make", "can", "like", "time", "no", "just", "him", "know", "take", "people", "into", "year", "your", "good", "some", "could", "them", "see", "other", "than", "then", "now", "look", "only", "come", "its", "over", "think", "also", "back", "us", "after", "use", "two", "how", "our", "work", "first", "well", "way", "even", "new", "want", "because", "any", "these", "give", "day", "most"]
count :: Ord a => [a] -> [(a, Integer)]
count = sortBy (flip $ on compare snd) . assocs . foldr f empty
where f a = insertWith (+) a 1
|
johangirod/statext
|
src/server/Domain/StatText.hs
|
Haskell
|
mit
| 1,445
|
module Main where
import TralaParser
import TralaLexer
import TralaLexerInternal
import Conduit
import System.Environment
main :: IO ()
main = do
filename <- head <$> getArgs
runResult <- runResourceT $ runLexerConduitFromStart $ alexInputsFromFile filename .| tralaTokens .| mapM_C (liftIO . putStrLn . show)
either (putStrLn . show) (return) runResult
|
tilgalas/trala-lala
|
app/Main.hs
|
Haskell
|
mit
| 365
|
{-# LANGUAGE FlexibleContexts #-}
module ZipperGalaxy
where
import Control.Monad
import qualified Data.Map as M
import Data.Maybe
import Libaddutil.Named
import Galaxy
import Utils
import qualified Data.Edison.Assoc.StandardMap as E
type GalaxyZipper a = (Galaxy a, Maybe (StarSystem a, Maybe (Star a, [Planet a])))
galaxyZipper :: Galaxy a -> GalaxyZipper a
galaxyZipper g = (g, Nothing)
starsystemZipper :: Galaxy a -> StarSystem a -> GalaxyZipper a
starsystemZipper g s = (g, Just (s, Nothing))
starZipper :: GalaxyZipper a -> Star a -> GalaxyZipper a
starZipper (g, Just (ss, _)) s = (g, Just (ss, Just (s, [])))
starZipper _ _ = error "Invalid zipper"
expandStarsystemZipper :: GalaxyZipper a -> [GalaxyZipper a]
expandStarsystemZipper (g, Just (ss, _)) = map (\s -> (g, Just (ss, Just (s, [])))) (M.elems (stars ss))
expandStarsystemZipper _ = []
expandStarZipper :: GalaxyZipper a -> [GalaxyZipper a]
expandStarZipper (g, Just (ss, Just (s, _))) = map (\p -> (g, Just (ss, Just (s, [p])))) (M.elems (planets s))
expandStarZipper _ = []
expandPlanetZipper :: GalaxyZipper a -> [GalaxyZipper a]
expandPlanetZipper z@(g, Just (ss, Just (s, [p1]))) = z:map (\p2 -> (g, Just (ss, Just (s, p2:[p1])))) (M.elems (satellites p1))
expandPlanetZipper _ = []
addPlanetToZipper :: GalaxyZipper a -> Planet a -> GalaxyZipper a
addPlanetToZipper (g, Just (ss, Just (s, ps))) p = (g, Just (ss, Just (s, p:ps)))
addPlanetToZipper _ _ = error "Invalid zipper"
galaxyInZipper :: GalaxyZipper a -> Galaxy a
galaxyInZipper (g, _) = g
starsystemInZipper :: GalaxyZipper a -> Maybe (StarSystem a)
starsystemInZipper (_, Nothing) = Nothing
starsystemInZipper (_, Just (s, _)) = Just s
starInZipper :: GalaxyZipper a -> Maybe (Star a)
starInZipper (_, Nothing) = Nothing
starInZipper (_, Just (ss, Nothing)) = Nothing
starInZipper (_, Just (ss, Just (s, _))) = Just s
satelliteThreadInZipper :: GalaxyZipper a -> [Planet a]
satelliteThreadInZipper (_, Nothing) = []
satelliteThreadInZipper (_, Just (ss, Nothing)) = []
satelliteThreadInZipper (_, Just (ss, Just (s, sats))) = sats
satelliteInZipper :: GalaxyZipper a -> Maybe (Planet a)
satelliteInZipper z = safeHead (satelliteThreadInZipper z)
tryDown :: Name -> GalaxyZipper a -> Maybe (GalaxyZipper a)
tryDown i (g, Nothing) =
let mss = M.lookup i (starsystems g)
in case mss of
Nothing -> Nothing
Just x -> Just $ (g, Just (x, Nothing))
tryDown i (g, Just (ss, Nothing)) =
let ms = M.lookup i (stars ss)
in case ms of
Nothing -> Nothing
Just x -> Just $ (g, Just (ss, (Just (x, []))))
tryDown i (g, Just (ss, Just (s, []))) =
let msat = M.lookup i (planets s)
in case msat of
Nothing -> Nothing
Just x -> Just $ (g, Just (ss, (Just (s, [x]))))
tryDown i (g, Just (ss, Just (s, allsats@(sat:sats)))) =
let msat = M.lookup i (satellites sat)
in case msat of
Nothing -> Nothing
Just x -> Just $ (g, Just (ss, (Just (s, x:allsats))))
tryDownNum :: Int -> GalaxyZipper a -> Maybe (GalaxyZipper a)
tryDownNum i z@(g, Nothing) =
case safeIndex (E.keys $ starsystems g) i of
Nothing -> Nothing
Just x -> tryDown x z
tryDownNum i z@(g, Just (ss, Nothing)) =
case safeIndex (E.keys $ stars ss) i of
Nothing -> Nothing
Just x -> tryDown x z
tryDownNum i z@(g, Just (ss, Just (s, []))) =
case safeIndex (E.keys $ planets s) i of
Nothing -> Nothing
Just x -> tryDown x z
tryDownNum i z@(g, Just (ss, Just (s, (p:ps)))) =
case safeIndex (E.keys $ satellites p) i of
Nothing -> Nothing
Just x -> tryDown x z
up :: GalaxyZipper a -> GalaxyZipper a
up z@(g, Nothing) = z
up (g, Just (ss, Nothing)) = (g, Nothing)
up (g, Just (ss, Just (s, []))) = (g, Just (ss, Nothing))
up (g, Just (ss, Just (s, (sat:sats)))) = (g, Just (ss, Just (s, sats)))
type GalaxyLocation = [Name]
findLocation :: GalaxyLocation -> Galaxy a -> Maybe (Planet a)
findLocation l g = do
let z = galaxyZipper g
nz <- foldM (flip tryDown) z l
satelliteInZipper nz
zipperToNames :: GalaxyZipper a -> [String]
zipperToNames z =
let g = galaxyInZipper z
ss = starsystemInZipper z
s = starInZipper z
ps = reverse $ satelliteThreadInZipper z
ns = [name g, getName ss, getName s] ++ map name ps
getName :: (Named a) => Maybe a -> String
getName m = case m of
Nothing -> ""
Just x -> name x
in filter (not . null) ns
|
anttisalonen/starrover
|
src/ZipperGalaxy.hs
|
Haskell
|
mit
| 4,557
|
-- | This transforms the output from ReadRawSpecFile for consumption into the
-- generator.
module Gen.Specifications
( CloudFormationSpec (..)
, specFromRaw
, PropertyType (..)
, Property (..)
, SpecType (..)
, subPropertyTypeNames
, customTypeNames
, AtomicType (..)
, ResourceType (..)
) where
import Control.Lens
import Data.List (sortOn)
import Data.Maybe (catMaybes)
import Data.Map (Map, toList)
import Data.Text
import GHC.Generics hiding (to)
import Gen.ReadRawSpecFile
data CloudFormationSpec
= CloudFormationSpec
{ cloudFormationSpecPropertyTypes :: [PropertyType]
, clousFormationSpecResourceSpecificationVersion :: Text
, cloudFormationSpecResourceTypes :: [ResourceType]
}
deriving (Show, Eq)
specFromRaw :: RawCloudFormationSpec -> CloudFormationSpec
specFromRaw spec = CloudFormationSpec props version resources
where
(RawCloudFormationSpec rawProps version rawResources) = fixSpecBugs spec
props = uncurry propertyTypeFromRaw <$> sortOn fst (toList rawProps)
resources = uncurry resourceTypeFromRaw <$> sortOn fst (toList rawResources)
-- | There are a few missing properties and resources in the official spec
-- document, as well as inconsistent or incorrect naming. There is an open
-- support ticket with AWS support to fix these things, but for now we are
-- patching things up manually.
fixSpecBugs :: RawCloudFormationSpec -> RawCloudFormationSpec
fixSpecBugs spec =
spec
-- There are a few naming conflicts with security group types. For example,
-- there is a resource named AWS::RDS::DBSecurityGroupIngress, and a property
-- named AWS::RDS::DBSecurityGroup.Ingress. There is a corresponding fix in
-- the function to render the full type name for
-- AWS::RDS::DBSecurityGroup.Ingress.
& propertyTypesLens
. at "AWS::RDS::DBSecurityGroup.IngressProperty"
.~ (spec ^. propertyTypesLens . at "AWS::RDS::DBSecurityGroup.Ingress")
& propertyTypesLens
. at "AWS::RDS::DBSecurityGroup.Ingress"
.~ Nothing
& propertyTypesLens
. at "AWS::EC2::SecurityGroup.IngressProperty"
.~ (spec ^. propertyTypesLens . at "AWS::EC2::SecurityGroup.Ingress")
& propertyTypesLens
. at "AWS::EC2::SecurityGroup.Ingress"
.~ Nothing
& propertyTypesLens
. at "AWS::EC2::SecurityGroup.EgressProperty"
.~ (spec ^. propertyTypesLens . at "AWS::EC2::SecurityGroup.Egress")
& propertyTypesLens
. at "AWS::EC2::SecurityGroup.Egress"
.~ Nothing
-- Rename AWS::IoT::TopicRule.DynamoDBv2Action to capitalize the "v" so it is
-- different from AWS::IoT::TopicRule.DynamoDBAction
& propertyTypesLens
. at "AWS::IoT::TopicRule.DynamoDBV2Action"
.~ (spec ^. propertyTypesLens . at "AWS::IoT::TopicRule.DynamoDBv2Action")
& propertyTypesLens
. at "AWS::IoT::TopicRule.DynamoDBv2Action"
.~ Nothing
-- AWS::ECS::TaskDefinition.ContainerDefinition has two properties that are
-- required, but the doc says they aren't.
& propertyTypesLens
. ix "AWS::ECS::TaskDefinition.ContainerDefinition"
. propertyPropsLens
. at "Image"
%~ (\(Just rawProp) -> Just rawProp { rawPropertyRequired = True })
& propertyTypesLens
. ix "AWS::ECS::TaskDefinition.ContainerDefinition"
. propertyPropsLens
. at "Name"
%~ (\(Just rawProp) -> Just rawProp { rawPropertyRequired = True })
where
propertyTypesLens :: Lens' RawCloudFormationSpec (Map Text RawPropertyType)
propertyTypesLens = lens rawCloudFormationSpecPropertyTypes (\s a -> s { rawCloudFormationSpecPropertyTypes = a })
propertyPropsLens :: Lens' RawPropertyType (Map Text RawProperty)
propertyPropsLens = lens rawPropertyTypeProperties (\s a -> s { rawPropertyTypeProperties = a })
-- resourceTypesLens :: Lens' RawCloudFormationSpec (Map Text RawResourceType)
-- resourceTypesLens = lens rawCloudFormationSpecResourceTypes (\s a -> s { rawCloudFormationSpecResourceTypes = a })
-- resourcePropsLens :: Lens' RawResourceType (Map Text RawProperty)
-- resourcePropsLens = lens rawResourceTypeProperties (\s a -> s { rawResourceTypeProperties = a })
data PropertyType
= PropertyType
{ propertyTypeName :: Text
, propertyTypeDocumentation :: Text
, propertyTypeProperties :: [Property]
}
deriving (Show, Eq)
propertyTypeFromRaw :: Text -> RawPropertyType -> PropertyType
propertyTypeFromRaw fullName (RawPropertyType doc props) =
PropertyType fullName doc (uncurry (propertyFromRaw fullName) <$> sortOn fst (toList props))
data Property
= Property
{ propertyName :: Text
, propertyDocumentation :: Text
--, propertyDuplicatesAllowed :: Maybe Bool -- Don't care about this
, propertySpecType :: SpecType
, propertyRequired :: Bool
--, propertyUpdateType :: Maybe Text -- Don't care about this
}
deriving (Show, Eq)
propertyFromRaw :: Text -> Text -> RawProperty -> Property
propertyFromRaw fullTypeName name (RawProperty doc _ itemType primItemType primType required type' _) =
Property name doc (rawToSpecType fullTypeName name primType type' primItemType itemType) required
data SpecType
= AtomicType AtomicType
| ListType AtomicType
| MapType AtomicType
deriving (Show, Eq)
rawToSpecType :: Text -> Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Text -> SpecType
-- Overrides for our custom types
rawToSpecType "AWS::ApiGateway::Authorizer" "Type" _ _ _ _ = AtomicType $ CustomType "AuthorizerType"
rawToSpecType "AWS::ApiGateway::Method" "AuthorizationType" _ _ _ _ = AtomicType $ CustomType "AuthorizationType"
rawToSpecType "AWS::ApiGateway::Method.Integration" "IntegrationHttpMethod" _ _ _ _ = AtomicType $ CustomType "HttpMethod"
rawToSpecType "AWS::ApiGateway::Method.Integration" "PassthroughBehavior" _ _ _ _ = AtomicType $ CustomType "PassthroughBehavior"
rawToSpecType "AWS::ApiGateway::Method.Integration" "Type" _ _ _ _ = AtomicType $ CustomType "ApiBackendType"
rawToSpecType "AWS::ApiGateway::UsagePlan.QuotaSettings" "Period" _ _ _ _ = AtomicType $ CustomType "Period"
rawToSpecType "AWS::DynamoDB::Table.AttributeDefinition" "AttributeType" _ _ _ _ = AtomicType $ CustomType "AttributeType"
rawToSpecType "AWS::DynamoDB::Table.KeySchema" "KeyType" _ _ _ _ = AtomicType $ CustomType "KeyType"
rawToSpecType "AWS::DynamoDB::Table.Projection" "ProjectionType" _ _ _ _ = AtomicType $ CustomType "ProjectionType"
rawToSpecType "AWS::DynamoDB::Table.StreamSpecification" "StreamViewType" _ _ _ _ = AtomicType $ CustomType "StreamViewType"
rawToSpecType "AWS::Events::Rule" "State" _ _ _ _ = AtomicType $ CustomType "EnabledState"
rawToSpecType "AWS::KinesisFirehose::DeliveryStream.S3DestinationConfiguration" "CompressionFormat" _ _ _ _ = AtomicType $ CustomType "KinesisFirehoseS3CompressionFormat"
rawToSpecType "AWS::KinesisFirehose::DeliveryStream.ElasticsearchDestinationConfiguration" "S3BackupMode" _ _ _ _ = AtomicType $ CustomType "KinesisFirehoseElasticsearchS3BackupMode"
rawToSpecType "AWS::KinesisFirehose::DeliveryStream.EncryptionConfiguration" "NoEncryptionConfig" _ _ _ _ = AtomicType $ CustomType "KinesisFirehoseNoEncryptionConfig"
rawToSpecType "AWS::Lambda::Function" "Runtime" _ _ _ _ = AtomicType $ CustomType "Runtime"
rawToSpecType "AWS::S3::Bucket" "AccessControl" _ _ _ _ = AtomicType $ CustomType "CannedACL"
rawToSpecType "AWS::SNS::Subscription" "Protocol" _ _ _ _ = AtomicType $ CustomType "SNSProtocol"
rawToSpecType "AWS::SNS::Topic.Subscription" "Protocol" _ _ _ _ = AtomicType $ CustomType "SNSProtocol"
rawToSpecType _ "HttpMethod" _ _ _ _ = AtomicType $ CustomType "HttpMethod"
rawToSpecType _ "LoggingLevel" _ _ _ _ = AtomicType $ CustomType "LoggingLevel"
-- Default
rawToSpecType _ _ primType type' primItemType itemType = rawToSpecType' primType type' primItemType itemType
rawToSpecType'
:: Maybe Text -- PrimitiveType
-> Maybe Text -- Type
-> Maybe Text -- PrimitiveItemType
-> Maybe Text -- ItemType
-> SpecType
-- Just primitive type, nothing else
rawToSpecType' (Just prim) Nothing Nothing Nothing = AtomicType $ textToPrimitiveType prim
-- A list of primitives
rawToSpecType' Nothing (Just "List") (Just prim) Nothing = ListType $ textToPrimitiveType prim
-- A list of non-primitives
rawToSpecType' Nothing (Just "List") Nothing (Just item) = ListType $ SubPropertyType item
-- A map of primitives
rawToSpecType' Nothing (Just "Map") (Just prim) Nothing = MapType $ textToPrimitiveType prim
-- A map of non-primitives
rawToSpecType' Nothing (Just "Map") Nothing (Just item) = MapType $ SubPropertyType item
-- A non-primitive type
rawToSpecType' Nothing (Just prop) Nothing Nothing = AtomicType $ SubPropertyType prop
rawToSpecType' prim type' primItem item = error $ "Unknown raw type: " ++ show (prim, type', primItem, item)
data AtomicType
= StringPrimitive
| IntegerPrimitive
| DoublePrimitive
| BoolPrimitive
| JsonPrimitive
| SubPropertyType Text
| CustomType Text
deriving (Show, Eq)
textToPrimitiveType :: Text -> AtomicType
textToPrimitiveType "String" = StringPrimitive
textToPrimitiveType "Long" = IntegerPrimitive
textToPrimitiveType "Integer" = IntegerPrimitive
textToPrimitiveType "Double" = DoublePrimitive
textToPrimitiveType "Boolean" = BoolPrimitive
textToPrimitiveType "Timestamp" = StringPrimitive
textToPrimitiveType "Json" = JsonPrimitive
textToPrimitiveType t = error $ "Unknown primitive type: " ++ unpack t
subPropertyTypeName :: SpecType -> Maybe Text
subPropertyTypeName (AtomicType (SubPropertyType name)) = Just name
subPropertyTypeName (ListType (SubPropertyType name)) = Just name
subPropertyTypeName (MapType (SubPropertyType name)) = Just name
subPropertyTypeName _ = Nothing
customTypeName :: SpecType -> Maybe Text
customTypeName (AtomicType (CustomType name)) = Just name
customTypeName (ListType (CustomType name)) = Just name
customTypeName (MapType (CustomType name)) = Just name
customTypeName _ = Nothing
subPropertyTypeNames :: [Property] -> [Text]
subPropertyTypeNames = catMaybes . fmap (subPropertyTypeName . propertySpecType)
customTypeNames :: [Property] -> [Text]
customTypeNames = catMaybes . fmap (customTypeName . propertySpecType)
data ResourceType
= ResourceType
{ resourceTypeFullName :: Text
--, resourceTypeAttributes :: [ResourceAttribute] -- Don't care about this yet, could be useful
, resourceTypeDocumentation :: Text
, resourceTypeProperties :: [Property]
}
deriving (Show, Eq, Generic)
resourceTypeFromRaw :: Text -> RawResourceType -> ResourceType
resourceTypeFromRaw fullName (RawResourceType _ doc props) =
ResourceType fullName doc (uncurry (propertyFromRaw fullName) <$> sortOn fst (toList props))
|
frontrowed/stratosphere
|
gen/src/Gen/Specifications.hs
|
Haskell
|
mit
| 10,530
|
#!/usr/bin/env stack
{-
stack
--resolver lts-11.10
--install-ghc
runghc
--package base
--
-hide-all-packages
-}
-- Copyright 2018 Google LLC. All Rights Reserved.
--
-- 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.
import qualified Data.Map as M
data Op2 = Minus | Times | Eq
deriving Show
data Term
= Var String
| Lam String Term
| Rec String Term
| App Term Term
| Op2 Op2 Term Term
| Lit Int
| If Term Term Term
deriving Show
type Env = M.Map String Val
data Val
= VInt Int
| VBool Bool
| VClosure Term Env
| VRClosure String Term Env
deriving Show
data Frame
= EvalOp2SecondArg Op2 Term Env
| EvalOp2 Op2 Val
| EvalArg Term Env
| EvalBody String Term Env
| EvalRecBody Val
| Branch Term Term Env
deriving Show
vOp2 Minus (VInt i) (VInt j) = VInt (i - j)
vOp2 Times (VInt i) (VInt j) = VInt (i * j)
vOp2 Eq (VInt i) (VInt j) = VBool (i == j)
apply [] v = v
apply (EvalOp2 op v2 : k) v1 = apply k (vOp2 op v2 v1)
apply (EvalOp2SecondArg op e env : k) v = eval e env (EvalOp2 op v : k)
apply (EvalBody x e env : k) v = eval e (M.insert x v env) k
apply (EvalRecBody vf@(VRClosure f (Lam x e) env) : k) v = eval e (M.insert x v (M.insert f vf env)) k
apply (EvalArg e1 env : k) (VClosure (Lam x e2) env') = eval e1 env (EvalBody x e2 env' : k)
apply (EvalArg e1 env : k) vf@(VRClosure _ _ _) = eval e1 env (EvalRecBody vf : k)
apply (Branch e1 e2 env : k) (VBool True) = eval e1 env k
apply (Branch e1 e2 env : k) (VBool False) = eval e2 env k
eval e env k = eval' e
where
eval' (Lit i) = apply k (VInt i)
eval' (Op2 op e1 e2) = eval e1 env (EvalOp2SecondArg op e2 env : k)
eval' (App f e) = eval f env (EvalArg e env : k)
eval' (Lam x e) = apply k (VClosure (Lam x e) env)
eval' (Rec f (Lam x e)) = apply k (VRClosure f (Lam x e) env)
eval' (Var x) = apply k (env M.! x)
eval' (If e1 e2 e3) = eval e1 env (Branch e2 e3 env : k)
fact = Rec
"fact"
(Lam
"n"
(If (Op2 Eq (Var "n") (Lit 0))
(Lit 1)
(Op2 Times (Var "n") (App (Var "fact") (Op2 Minus (Var "n") (Lit 1))))
)
)
main = print $ eval (App fact (Lit 20)) M.empty []
|
polux/snippets
|
cps_defunc_evaluator.hs
|
Haskell
|
apache-2.0
| 2,645
|
sq x = x * x
main = print $ sq 12
|
egaburov/funstuff
|
Haskell/BartoszBofH/2_MyFirstProgram/a.hs
|
Haskell
|
apache-2.0
| 35
|
module Main (main) where
import qualified System.Exit as Exit
import Hecate (configure, run)
main :: IO ()
main = configure >>= run >>= Exit.exitWith
|
henrytill/hecate
|
executables/Main.hs
|
Haskell
|
apache-2.0
| 169
|
import Data.List
tab = [("black", 0, 0, 0),
("blue", 0, 0,255),
("lime", 0,255, 0),
("aqua", 0,255,255),
("red", 255, 0, 0),
("fuchsia",255, 0,255),
("yellow", 255,255, 0),
("white", 255,255,255)]
h2d x = read ("0x"++x) :: Int
ans x =
let r = h2d $ take 2 $ drop 1 x
g = h2d $ take 2 $ drop 3 x
b = h2d $ take 2 $ drop 5 x
d = map (\ (c,r1,g1,b1) -> (c, (r1-r)^2+(g1-g)^2+(b1-b)^2 ) ) tab
s = sortBy (\ (c0,d0) (c1,d1) -> compare d0 d1 ) d
in
fst $ head s
main = do
c <- getContents
let i = takeWhile (/= "0") $ lines c
o = map ans i
mapM_ putStrLn o
|
a143753/AOJ
|
0176.hs
|
Haskell
|
apache-2.0
| 681
|
{-# LANGUAGE OverloadedStrings #-}
import Data.Text as T
import Data.RDF
import Data.RDF.Namespace
globalPrefix :: PrefixMappings
globalPrefix = ns_mappings []
baseURL :: Maybe BaseUrl
baseURL = Just $ BaseUrl "file://"
testURL = "file:///this/is/not/a/palindrome"
tris :: [Triple]
tris = [Triple
(unode testURL)
(unode testURL)
(LNode . PlainL . T.pack $ "literal string")]
testRdf :: TriplesGraph
testRdf = mkRdf tris baseURL globalPrefix
main :: IO ()
main = print testRdf
|
bergey/metastic
|
src/TestCase.hs
|
Haskell
|
bsd-2-clause
| 506
|
{-| Implementation of the RAPI client interface.
-}
{-
Copyright (C) 2009, 2010, 2011, 2012, 2013 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
{-# LANGUAGE BangPatterns, CPP #-}
module Ganeti.HTools.Backend.Rapi
( loadData
, parseData
) where
import Control.Exception
import Data.List (isPrefixOf)
import Data.Maybe (fromMaybe)
import Network.Curl
import Network.Curl.Types ()
import Control.Monad
import Text.JSON (JSObject, fromJSObject, decodeStrict)
import Text.JSON.Types (JSValue(..))
import Text.Printf (printf)
import System.FilePath
import Ganeti.BasicTypes
import Ganeti.Types (Hypervisor(..))
import Ganeti.HTools.Loader
import Ganeti.HTools.Types
import Ganeti.JSON (loadJSArray, JSRecord, tryFromObj, fromJVal, maybeFromObj,
fromJResult, tryArrayMaybeFromObj, readEitherString,
fromObjWithDefault, asJSObject)
import qualified Ganeti.HTools.Group as Group
import qualified Ganeti.HTools.Node as Node
import qualified Ganeti.HTools.Instance as Instance
import qualified Ganeti.HTools.Container as Container
import qualified Ganeti.Constants as C
{-# ANN module "HLint: ignore Eta reduce" #-}
-- | File method prefix.
filePrefix :: String
filePrefix = "file://"
-- | Read an URL via curl and return the body if successful.
getUrl :: (Monad m) => String -> IO (m String)
-- | Connection timeout (when using non-file methods).
connTimeout :: Long
connTimeout = 15
-- | The default timeout for queries (when using non-file methods).
queryTimeout :: Long
queryTimeout = 60
-- | The curl options we use.
curlOpts :: [CurlOption]
curlOpts = [ CurlSSLVerifyPeer False
, CurlSSLVerifyHost 0
, CurlTimeout queryTimeout
, CurlConnectTimeout connTimeout
]
getUrl url = do
(code, !body) <- curlGetString url curlOpts
return (case code of
CurlOK -> return body
_ -> fail $ printf "Curl error for '%s', error %s"
url (show code))
-- | Helper to convert I/O errors in 'Bad' values.
ioErrToResult :: IO a -> IO (Result a)
ioErrToResult ioaction =
Control.Exception.catch (liftM Ok ioaction)
(\e -> return . Bad . show $ (e::IOException))
-- | Append the default port if not passed in.
formatHost :: String -> String
formatHost master =
if ':' `elem` master
then master
else "https://" ++ master ++ ":" ++ show C.defaultRapiPort
-- | Parse a instance list in JSON format.
getInstances :: NameAssoc
-> String
-> Result [(String, Instance.Instance)]
getInstances ktn body =
loadJSArray "Parsing instance data" body >>=
mapM (parseInstance ktn . fromJSObject)
-- | Parse a node list in JSON format.
getNodes :: NameAssoc -> String -> Result [(String, Node.Node)]
getNodes ktg body = loadJSArray "Parsing node data" body >>=
mapM (parseNode ktg . fromJSObject)
-- | Parse a group list in JSON format.
getGroups :: String -> Result [(String, Group.Group)]
getGroups body = loadJSArray "Parsing group data" body >>=
mapM (parseGroup . fromJSObject)
-- | Construct an instance from a JSON object.
parseInstance :: NameAssoc
-> JSRecord
-> Result (String, Instance.Instance)
parseInstance ktn a = do
name <- tryFromObj "Parsing new instance" a "name"
let owner_name = "Instance '" ++ name ++ "', error while parsing data"
let extract s x = tryFromObj owner_name x s
disk <- extract "disk_usage" a
dsizes <- extract "disk.sizes" a
dspindles <- tryArrayMaybeFromObj owner_name a "disk.spindles"
beparams <- liftM fromJSObject (extract "beparams" a)
omem <- extract "oper_ram" a
mem <- case omem of
JSRational _ _ -> annotateResult owner_name (fromJVal omem)
_ -> extract "memory" beparams `mplus` extract "maxmem" beparams
vcpus <- extract "vcpus" beparams
pnode <- extract "pnode" a >>= lookupNode ktn name
snodes <- extract "snodes" a
snode <- case snodes of
[] -> return Node.noSecondary
x:_ -> readEitherString x >>= lookupNode ktn name
running <- extract "status" a
tags <- extract "tags" a
auto_balance <- extract "auto_balance" beparams
dt <- extract "disk_template" a
su <- extract "spindle_use" beparams
-- Not forthcoming by default.
forthcoming <- extract "forthcoming" a `orElse` Ok False
let disks = zipWith Instance.Disk dsizes dspindles
let inst = Instance.create name mem disk disks vcpus running tags
auto_balance pnode snode dt su [] forthcoming
return (name, inst)
-- | Construct a node from a JSON object.
parseNode :: NameAssoc -> JSRecord -> Result (String, Node.Node)
parseNode ktg a = do
name <- tryFromObj "Parsing new node" a "name"
let desc = "Node '" ++ name ++ "', error while parsing data"
extract key = tryFromObj desc a key
extractDef def key = fromObjWithDefault a key def
offline <- extract "offline"
drained <- extract "drained"
vm_cap <- annotateResult desc $ maybeFromObj a "vm_capable"
let vm_cap' = fromMaybe True vm_cap
ndparams <- extract "ndparams" >>= asJSObject
excl_stor <- tryFromObj desc (fromJSObject ndparams) "exclusive_storage"
guuid <- annotateResult desc $ maybeFromObj a "group.uuid"
guuid' <- lookupGroup ktg name (fromMaybe defaultGroupID guuid)
let live = not offline && vm_cap'
lvextract def = eitherLive live def . extract
lvextractDef def = eitherLive live def . extractDef def
sptotal <- if excl_stor
then lvextract 0 "sptotal"
else tryFromObj desc (fromJSObject ndparams) "spindle_count"
spfree <- lvextractDef 0 "spfree"
mtotal <- lvextract 0.0 "mtotal"
mnode <- lvextract 0 "mnode"
mfree <- lvextract 0 "mfree"
dtotal <- lvextractDef 0.0 "dtotal"
dfree <- lvextractDef 0 "dfree"
ctotal <- lvextract 0.0 "ctotal"
cnos <- lvextract 0 "cnos"
tags <- extract "tags"
let node = flip Node.setNodeTags tags $
Node.create name mtotal mnode mfree dtotal dfree ctotal cnos
(not live || drained) sptotal spfree guuid' excl_stor
return (name, node)
-- | Construct a group from a JSON object.
parseGroup :: JSRecord -> Result (String, Group.Group)
parseGroup a = do
name <- tryFromObj "Parsing new group" a "name"
let extract s = tryFromObj ("Group '" ++ name ++ "'") a s
uuid <- extract "uuid"
apol <- extract "alloc_policy"
ipol <- extract "ipolicy"
tags <- extract "tags"
-- TODO: parse networks to which this group is connected
return (uuid, Group.create name uuid apol [] ipol tags)
-- | Parse cluster data from the info resource.
parseCluster :: JSObject JSValue -> Result ([String], IPolicy,
String, Hypervisor)
parseCluster obj = do
let obj' = fromJSObject obj
extract s = tryFromObj "Parsing cluster data" obj' s
master <- extract "master"
tags <- extract "tags"
ipolicy <- extract "ipolicy"
hypervisor <- extract "default_hypervisor"
return (tags, ipolicy, master, hypervisor)
-- | Loads the raw cluster data from an URL.
readDataHttp :: String -- ^ Cluster or URL to use as source
-> IO (Result String, Result String, Result String, Result String)
readDataHttp master = do
let url = formatHost master
group_body <- getUrl $ printf "%s/2/groups?bulk=1" url
node_body <- getUrl $ printf "%s/2/nodes?bulk=1" url
inst_body <- getUrl $ printf "%s/2/instances?bulk=1" url
info_body <- getUrl $ printf "%s/2/info" url
return (group_body, node_body, inst_body, info_body)
-- | Loads the raw cluster data from the filesystem.
readDataFile:: String -- ^ Path to the directory containing the files
-> IO (Result String, Result String, Result String, Result String)
readDataFile path = do
group_body <- ioErrToResult . readFile $ path </> "groups.json"
node_body <- ioErrToResult . readFile $ path </> "nodes.json"
inst_body <- ioErrToResult . readFile $ path </> "instances.json"
info_body <- ioErrToResult . readFile $ path </> "info.json"
return (group_body, node_body, inst_body, info_body)
-- | Loads data via either 'readDataFile' or 'readDataHttp'.
readData :: String -- ^ URL to use as source
-> IO (Result String, Result String, Result String, Result String)
readData url =
if filePrefix `isPrefixOf` url
then readDataFile (drop (length filePrefix) url)
else readDataHttp url
-- | Builds the cluster data from the raw Rapi content.
parseData :: (Result String, Result String, Result String, Result String)
-> Result ClusterData
parseData (group_body, node_body, inst_body, info_body) = do
group_data <- group_body >>= getGroups
let (group_names, group_idx) = assignIndices group_data
node_data <- node_body >>= getNodes group_names
let (node_names, node_idx) = assignIndices node_data
inst_data <- inst_body >>= getInstances node_names
let (_, inst_idx) = assignIndices inst_data
(tags, ipolicy, master, hypervisor) <-
info_body >>=
(fromJResult "Parsing cluster info" . decodeStrict) >>=
parseCluster
node_idx' <- setMaster node_names node_idx master
let node_idx'' = Container.map (`Node.setHypervisor` hypervisor) node_idx'
return (ClusterData group_idx node_idx'' inst_idx tags ipolicy)
-- | Top level function for data loading.
loadData :: String -- ^ Cluster or URL to use as source
-> IO (Result ClusterData)
loadData = fmap parseData . readData
|
mbakke/ganeti
|
src/Ganeti/HTools/Backend/Rapi.hs
|
Haskell
|
bsd-2-clause
| 10,629
|
module Cube where
import Shader
import Data.Foldable
import Foreign
import Graphics.GL
import Linear
import Mesh
import Shader
data Cube = Cube
{ cubeVAO :: VertexArrayObject
, cubeShader :: GLProgram
, cubeIndexCount :: GLsizei
, cubeUniformMVP :: UniformLocation
}
----------------------------------------------------------
-- Make Cube
----------------------------------------------------------
renderCube :: Cube -> M44 GLfloat -> IO ()
renderCube cube mvp = do
useProgram (cubeShader cube)
uniformM44 (cubeUniformMVP cube) mvp
glBindVertexArray (unVertexArrayObject (cubeVAO cube))
glDrawElements GL_TRIANGLES (cubeIndexCount cube) GL_UNSIGNED_INT nullPtr
glBindVertexArray 0
makeCube :: GLProgram -> IO Cube
makeCube program = do
aPosition <- getShaderAttribute program "aPosition"
aColor <- getShaderAttribute program "aColor"
aID <- getShaderAttribute program "aID"
uMVP <- getShaderUniform program "uMVP"
-- Setup a VAO
vaoCube <- overPtr (glGenVertexArrays 1)
glBindVertexArray vaoCube
-----------------
-- Cube Positions
-----------------
-- Buffer the cube vertices
let cubeVertices =
--- front
[ -1.0 , -1.0 , 1.0
, 1.0 , -1.0 , 1.0
, 1.0 , 1.0 , 1.0
, -1.0 , 1.0 , 1.0
--- back
, -1.0 , -1.0 , -1.0
, 1.0 , -1.0 , -1.0
, 1.0 , 1.0 , -1.0
, -1.0 , 1.0 , -1.0 ] :: [GLfloat]
vaoCubeVertices <- overPtr (glGenBuffers 1)
glBindBuffer GL_ARRAY_BUFFER vaoCubeVertices
let cubeVerticesSize = fromIntegral (sizeOf (undefined :: GLfloat) * length cubeVertices)
withArray cubeVertices $
\cubeVerticesPtr ->
glBufferData GL_ARRAY_BUFFER cubeVerticesSize (castPtr cubeVerticesPtr) GL_STATIC_DRAW
-- Describe our vertices array to OpenGL
glEnableVertexAttribArray (fromIntegral (unAttributeLocation aPosition))
glVertexAttribPointer
(fromIntegral (unAttributeLocation aPosition)) -- attribute
3 -- number of elements per vertex, here (x,y,z)
GL_FLOAT -- the type of each element
GL_FALSE -- don't normalize
0 -- no extra data between each position
nullPtr -- offset of first element
--------------
-- Cube Colors
--------------
-- Buffer the cube colors
let cubeColors =
-- front colors
[ 1.0, 0.0, 0.0
, 0.0, 1.0, 0.0
, 0.0, 0.0, 1.0
, 1.0, 1.0, 1.0
-- back colors
, 1.0, 0.0, 0.0
, 0.0, 1.0, 0.0
, 0.0, 0.0, 1.0
, 1.0, 1.0, 1.0 ] :: [GLfloat]
vboCubeColors <- overPtr (glGenBuffers 1)
glBindBuffer GL_ARRAY_BUFFER vboCubeColors
let cubeColorsSize = fromIntegral (sizeOf (undefined :: GLfloat) * length cubeColors)
withArray cubeColors $
\cubeColorsPtr ->
glBufferData GL_ARRAY_BUFFER cubeColorsSize (castPtr cubeColorsPtr) GL_STATIC_DRAW
glEnableVertexAttribArray (fromIntegral (unAttributeLocation aColor))
glVertexAttribPointer
(fromIntegral (unAttributeLocation aColor)) -- attribute
3 -- number of elements per vertex, here (R,G,B)
GL_FLOAT -- the type of each element
GL_FALSE -- don't normalize
0 -- no extra data between each position
nullPtr -- offset of first element
-----------
-- Cube IDs
-----------
-- Buffer the cube ids
let cubeIDs =
[ 0
, 1
, 2
, 3
, 4
, 5 ] :: [GLfloat]
vboCubeIDs <- overPtr (glGenBuffers 1)
glBindBuffer GL_ARRAY_BUFFER vboCubeIDs
let cubeIDsSize = fromIntegral (sizeOf (undefined :: GLfloat) * length cubeIDs)
withArray cubeIDs $
\cubeIDsPtr ->
glBufferData GL_ARRAY_BUFFER cubeIDsSize (castPtr cubeIDsPtr) GL_STATIC_DRAW
glEnableVertexAttribArray (fromIntegral (unAttributeLocation aID))
glVertexAttribPointer
(fromIntegral (unAttributeLocation aID)) -- attribute
1 -- number of elements per vertex, here (R,G,B)
GL_FLOAT -- the type of each element
GL_FALSE -- don't normalize
0 -- no extra data between each position
nullPtr -- offset of first element
----------------
-- Cube Indicies
----------------
-- Buffer the cube indices
let cubeIndices =
-- front
[ 0, 1, 2
, 2, 3, 0
-- top
, 1, 5, 6
, 6, 2, 1
-- back
, 7, 6, 5
, 5, 4, 7
-- bottom
, 4, 0, 3
, 3, 7, 4
-- left
, 4, 5, 1
, 1, 0, 4
-- right
, 3, 2, 6
, 6, 7, 3 ] :: [GLuint]
iboCubeElements <- overPtr (glGenBuffers 1)
glBindBuffer GL_ELEMENT_ARRAY_BUFFER iboCubeElements
let cubeElementsSize = fromIntegral (sizeOf (undefined :: GLuint) * length cubeIndices)
withArray cubeIndices $
\cubeIndicesPtr ->
glBufferData GL_ELEMENT_ARRAY_BUFFER cubeElementsSize (castPtr cubeIndicesPtr) GL_STATIC_DRAW
glBindVertexArray 0
return $ Cube
{ cubeVAO = VertexArrayObject vaoCube
, cubeShader = program
, cubeIndexCount = fromIntegral (length cubeIndices)
, cubeUniformMVP = uMVP
}
|
lukexi/wboit
|
test/Cube.hs
|
Haskell
|
bsd-2-clause
| 5,793
|
{-# OPTIONS -XUndecidableInstances #-}
{-# OPTIONS -XTypeOperators #-}
{-# OPTIONS -XMultiParamTypeClasses #-}
{-# OPTIONS -XFunctionalDependencies #-}
{-# OPTIONS -XFlexibleInstances #-}
module Data.Real.CReal
(CReal, inject, around,
approx, approxRange, integerInterval,
BoundedCReal, compact, choke,
proveNonZeroFrom, proveNonZero,
realNegate, realTranslate, realPlus,
realScale, realMultBound,
realAbs,
realRecipWitness,
realPowerIntBound, realPowerInt,
realBasePolynomialBound, realBasePolynomial2Bound,
rationalExp, realExpBound,
rationalSin, realSin, rationalCos, realCos,
rationalLn, realLnWitness, rationalArcTan, realArcTan,
scalePi, real2Pi, realPi, realPi2, realPi4,
rationalSqrt, realSqrt,
rationalErrorFunction, realErrorFunction,
sumRealList, unsafeMkCReal,
radius, answer) where
import Data.Real.Base
import Data.Real.Complete
import Data.Maybe
import Data.Multinomial
import Data.Interval
import Combinatorics
import Control.Exception
{- Thoughts: Polynomails should always return a Complete Base. Fractions grow to large othewise.
Separate interval aritmetic and (R+Q) optimisations into another file that implements the same interface. -}
radius = 2^^(-51)
newtype CReal = CReal {approx :: Complete Base}
unsafeMkCReal = CReal
inject :: Base -> CReal
inject x = CReal (unit x)
{- The real number is assumed to lie within the closed interval -}
type BoundedCReal = (CReal,Interval Base)
around :: CReal -> Integer
around (CReal f) = round (f (1/2))
integerInterval f = Interval (i-1, i+1)
where
i = fromInteger $ around f
compact :: CReal -> BoundedCReal
compact x = (x,integerInterval x)
choke :: BoundedCReal -> CReal
choke (CReal x, (Interval (lb,ub))) = CReal f
where
f eps | y < lb = lb
| ub < y = ub
| otherwise = y
where
y = x eps
{- produces a regular function whose resulting approximations are
small in memory size -}
compress :: Complete Base -> Complete Base
compress x eps = approxBase (x (eps/2)) (eps/2)
compress' (CReal x) = CReal (compress x)
mapCR f (CReal x) = CReal $ compress $ mapC f x
mapCR2 f (CReal x) (CReal y) = CReal $ compress $ mapC2 f x y
bindR f (CReal x) = CReal $ compress $ bind f x
instance Show CReal where
show x = error "Cannot show a CReal"
{- show x = show $ map (\n -> squish x ((1/2)^n)) [0..] -}
approxRange :: CReal -> Gauge -> Interval Base
approxRange x eps = Interval (r-eps, r+eps)
where
r = approx x eps
{- proveNonZeroFrom will not terminate if the input is 0 -}
{- Finds some y st 0 < (abs y) <= (abs x) -}
proveNonZeroFrom :: Gauge -> CReal -> Base
proveNonZeroFrom g r | high < 0 = high
| 0 < low = low
| otherwise = proveNonZeroFrom (g / (2 ^ 32)) r
where
Interval (low, high) = approxRange r g
proveNonZero x = proveNonZeroFrom 1 x
negateCts = mkUniformCts id negate
realNegate :: CReal -> CReal
realNegate = mapCR negateCts
plusBaseCts :: Base -> Base :=> Base
plusBaseCts a = mkUniformCts id (a+)
realTranslate :: Base -> CReal -> CReal
realTranslate a = mapCR (plusBaseCts a)
plusCts :: Base :=> Base :=> Base
plusCts = mkUniformCts id plusBaseCts
realPlus :: CReal -> CReal -> CReal
realPlus = mapCR2 plusCts
-- (==) never returns True.
instance Eq CReal where
a==b = 0==proveNonZero (realPlus a (realNegate b))
multBaseCts :: Base -> Base :=> Base
multBaseCts 0 = constCts 0
multBaseCts a = mkUniformCts mu (a*)
where
mu eps = eps/(abs a)
realScale :: Base -> CReal -> CReal
realScale a = mapCR (multBaseCts a)
{- \x -> (\y -> (x*y)) is uniformly continuous on the domain (abs y) <= maxy -}
multUniformCts :: Base -> Base :=> Base :=> Base
multUniformCts maxy = mkUniformCts mu multBaseCts
where
mu eps = assert (maxy>0) (eps/maxy)
{- We need to bound the value of x or y. I think it is better to bound
x so I actually compute y*x -}
realMultBound :: BoundedCReal -> CReal -> CReal
realMultBound (x,i) y = mapCR2 (multUniformCts b) y (choke (x,i))
where
b = bound i
absCts = mkUniformCts id abs
realAbs :: CReal -> CReal
realAbs = mapCR absCts
instance Num CReal where
(+) = realPlus
x * y = realMultBound (compact x) y
negate = realNegate
abs = realAbs
signum = inject . signum . proveNonZero
fromInteger = inject . fromInteger
{- domain is (-inf, nonZero] if nonZero < 0
domain is [nonZero, inf) if nonZero > 0 -}
recipUniformCts :: Base -> Base :=> Base
recipUniformCts nonZero = mkUniformCts mu f
where
f a | 0 <= nonZero = recip (max nonZero a)
| otherwise = recip (min a nonZero)
mu eps = eps*(nonZero^2)
realRecipWitness :: Base -> CReal -> CReal
realRecipWitness nonZero = mapCR (recipUniformCts nonZero)
instance Fractional CReal where
recip x = realRecipWitness (proveNonZero x) x
fromRational = inject . fromRational
intPowerCts _ 0 = constCts 1
intPowerCts maxx n = mkUniformCts mu (^n)
where
mu eps = assert (maxx > 0) $ eps/((fromIntegral n)*(maxx^(n-1)))
realPowerIntBound :: (Integral b) => BoundedCReal -> b -> CReal
realPowerIntBound (x,i) n = mapCR (intPowerCts b n) (choke (x,i))
where
b = bound i
realPowerInt :: (Integral b) => CReal -> b -> CReal
realPowerInt = realPowerIntBound . compact
polynomialUniformCts :: Interval Base ->
Polynomial Base -> Base :=> Base
polynomialUniformCts i p |maxSlope == 0 = constCts (evalP p 0)
|otherwise = mkUniformCts mu (evalP p)
where
maxSlope = bound $ boundPolynomial i (dx p)
mu eps = assert (maxSlope > 0) $ eps/maxSlope
realBasePolynomialBound :: Polynomial Base -> BoundedCReal -> CReal
realBasePolynomialBound p (x,i) = mapCR (polynomialUniformCts i p) (choke (x,i))
class MultinomialUniformCts i p r | i p -> r where
multinomialUniformCts :: i -> p -> r
instance MultinomialUniformCts (Interval Base) (Polynomial Base) (Base :=> Base)
where
multinomialUniformCts = polynomialUniformCts
instance (MultinomialUniformCts i p r, VectorQ p, Num p,
BoundPolynomial i p) =>
MultinomialUniformCts (Interval Base,i) (Polynomial p) (Base :=> r)
where
multinomialUniformCts i p | maxSlope == 0 = constCts $
multinomialUniformCts (snd i) (evalP p 0)
| otherwise = mkUniformCts mu $
\x -> multinomialUniformCts (snd i) (evalP p (x<*>1))
where
maxSlope = bound $ boundPolynomial i (dx p)
mu eps = assert (maxSlope > 0) $ eps/maxSlope
realBasePolynomial2Bound ::
Polynomial (Polynomial Base) -> BoundedCReal -> BoundedCReal -> CReal
realBasePolynomial2Bound p (x,i) (y,j) =
mapCR2 (multinomialUniformCts (i,j) p)
(choke (x,i)) (choke (y,j))
{- only valid for x <= ln(2). Works best for |x| <= 1/2 -}
rationalSmallExp :: Base -> CReal
rationalSmallExp x = assert ((abs x)<=(1/2)) $
CReal $ expTaylorApprox
where
m | x <= 0 = 1
| otherwise = 2
expTaylorApprox eps =
sumBase terms
where
terms = takeWhile highError $ zipWith (\x y -> x/(fromInteger y)) (powers x) factorials
highError t = m*(abs t) >= eps
rationalExp :: Base -> Base -> CReal
rationalExp tol x | (abs x) <= tol = rationalSmallExp x
| otherwise = realPowerInt (rationalExp tol (x/2)) 2
expUniformCts :: Integer -> Base :=> (Complete Base)
expUniformCts upperBound = mkUniformCts mu (approx . rationalExp radius)
where
mu eps | upperBound <= 0 = eps*(2^(-upperBound))
| otherwise = eps/(3^upperBound)
realExpBound :: BoundedCReal -> CReal
realExpBound a@(x,(Interval (_,ub))) =
bindR (expUniformCts (ceiling ub)) (choke a)
{-Requires that abs(a!!i+1) < abs(a!!i) and the sign of the terms alternate -}
alternatingSeries :: [Base] -> Complete Base
alternatingSeries a eps = sumBase partSeries
where
partSeries = (takeWhile (\x -> (abs x) > eps) a)
rationalSin :: Base -> Base -> CReal
rationalSin tol x | tol <= (abs x) =
realBasePolynomialBound (3*xP - 4*xP^3)
((rationalSin tol (x/3)),Interval (-1,1))
| otherwise = CReal (alternatingSeries series)
where
series = fst $ unzip $ iterate (\(t,n) -> (-t*(x^2)/(n^2+n),n+2)) (x, 2)
sinCts :: Base :=> (Complete Base)
sinCts = mkUniformCts id (approx . rationalSin radius)
realSin :: CReal -> CReal
realSin = bindR sinCts
{-
realSin :: CReal -> CReal
realSin x | 0==m = realSlowSin x'
| 1==m = realSlowCos x'
| 2==m = negate $ realSlowSin x'
| 3==m = negate $ realSlowCos x'
where
n = around (x / realPi2)
m = n `mod` 4
x' = x - (realScale (fromInteger n) realPi2)
-}
rationalCos :: Base -> Base -> CReal
rationalCos tol x = realBasePolynomialBound (1-2*xP^2)
((rationalSin tol (x/2)),Interval (-1,1))
cosCts :: Base :=> (Complete Base)
cosCts = mkUniformCts id (approx . rationalCos radius)
realCos :: CReal -> CReal
realCos = bindR cosCts
{-
realCos :: CReal -> CReal
realCos x | 3==m = realSlowSin x'
| 0==m = realSlowCos x'
| 1==m = negate $ realSlowSin x'
| 2==m = negate $ realSlowCos x'
where
n = around (x / realPi2)
m = n `mod` 4
x' = x - (realScale (fromInteger n) realPi2)
-}
{- computes ln(x). only valid for 1<=x<2 -}
rationalSmallLn :: Base -> CReal
rationalSmallLn x = assert (1<=x && x<=(3/2)) $
CReal $ alternatingSeries (zipWith (*) (poly 1) (tail (powers (x-1))))
where
poly n = (1/n):(-1/(n+1)):(poly (n+2))
{- requires that 0<=x -}
rationalLn :: Base -> CReal
rationalLn x | x<1 = negate (posLn (recip x))
| otherwise = posLn x
where
ln43 = rationalSmallLn (4/3)
ln2 = wideLn 2
{- good for 1<=x<=2 -}
wideLn x | x < (3/2) = rationalSmallLn x
| otherwise = (rationalSmallLn ((3/4)*x)) + ln43
{- requires that 1<=x -}
posLn x | n==0 = wideLn x
| otherwise = (wideLn x') + (realScale n ln2)
where
(x',n) = until (\(x,n) -> (x<=2)) (\(x,n) -> (x/2,n+1)) (x,0)
{- domain is [nonZero, inf) -}
lnUniformCts :: Base -> Base :=> (Complete Base)
lnUniformCts nonZero = mkUniformCts mu f
where
f x = approx $ rationalLn (max x nonZero)
mu eps = assert (nonZero > 0) $ eps*nonZero
realLnWitness :: Base -> CReal -> CReal
realLnWitness nonZero = bindR (lnUniformCts nonZero)
{- only valid for (abs x) < 1 -}
rationalSmallArcTan :: Base -> CReal
rationalSmallArcTan x = assert ((abs x)<(1/2)) $ CReal $
alternatingSeries (zipWith (\x y->x*(y^2)) (series 0) (powers x))
where
series n = (x/(n+1)):(-x/(n+3)):(series (n+4))
rationalArcTan :: Base -> CReal
rationalArcTan x | x <= (-1/2) = negate $ posArcTan $ negate x
| otherwise = posArcTan x
where
{-requires (-1/2) < x-}
posArcTan x | 2 < x = realPi2 - rationalSmallArcTan (recip x)
| (1/2) <= x = realPi4 + rationalSmallArcTan y
| otherwise = rationalSmallArcTan x
where
y = (x-1)/(x+1)
arcTanCts :: Base :=> (Complete Base)
arcTanCts = mkUniformCts id (approx . rationalArcTan)
realArcTan :: CReal -> CReal
realArcTan = bindR arcTanCts
{- Computes x * Pi -}
{- http://aemes.mae.ufl.edu/~uhk/PI.html -}
scalePi :: Base -> CReal
scalePi x =
((realScale (x*48) (rationalSmallArcTan (1/38))) +
(realScale (x*80) (rationalSmallArcTan (1/57)))) +
((realScale (x*28) (rationalSmallArcTan (1/239))) +
(realScale (x*96) (rationalSmallArcTan (1/268))))
real2Pi = scalePi 2
realPi = scalePi 1
realPi2 = scalePi (1/2)
realPi4 = scalePi (1/4)
{- Wolfram's algorithm -}
rationalSqrt :: Base -> CReal
rationalSqrt n | n < 1 = realScale (1/2) (rationalSqrt (4*n))
| 4 <= n = realScale 2 (rationalSqrt (n/4))
| otherwise = CReal f
where
f eps = vf*ef/8
where
(_,vf,ef) = until (\(u,v,e) -> e <= eps) wolfram (n, 0, 4)
wolfram (u,v,e) | u >= v + 1 = (4*(u-v-1), 2*(v+2), e/2)
| otherwise = (4*u, 2*v, e/2)
sqrtCts :: Base :=> (Complete Base)
sqrtCts = mkUniformCts (^2) (approx . rationalSqrt)
realSqrt :: CReal -> CReal
realSqrt = bindR sqrtCts
instance Floating CReal where
exp x = realExpBound (compact x)
log x = realLnWitness (proveNonZero x) x
pi = realPi
sin = realSin
cos = realCos
atan = realArcTan
sqrt = realSqrt
sinh x = realScale (1/2) (exp x - (exp (-x)))
cosh x = realScale (1/2) (exp x + (exp (-x)))
asin x = atan (x/sqrt(realTranslate 1 (negate (realPowerInt x 2))))
acos x = realPi2 - asin x
acosh x = log (x+sqrt(realTranslate (-1) (realPowerInt x 2)))
asinh x = log (x+sqrt(realTranslate 1 (realPowerInt x 2)))
atanh x = realScale (1/2)
(log ((realTranslate 1 x) / (realTranslate 1 (negate x))))
{- best for (abs x) < 1 -}
rationalErrorFunction :: Base -> CReal
rationalErrorFunction x = (2/(sqrt pi)*) . CReal $
alternatingSeries (zipWith (\x y->x*(y^2)) (series 0) (powers x))
where
series n = (x/((2*n'+1)*facts!!n)):(-x/((2*n'+3)*(facts!!(n+1)))):
(series (n+2))
where
facts = map (fromIntegral) factorials
n' = fromIntegral n
erfCts :: Base :=> (Complete Base)
erfCts = mkUniformCts mu (approx . rationalErrorFunction)
where
mu eps = eps*(4/5)
realErrorFunction :: CReal -> CReal
realErrorFunction = bindR erfCts
sumRealList :: [CReal] -> CReal
sumRealList [] = inject 0
sumRealList l = CReal (\eps -> sum (map (\x -> approx x (eps/n)) l))
where
n = fromIntegral $ length l
{- testing stuff is below -}
test0 = CReal id
answer n x = shows (around (realScale (10^n) x))
"x10^-"++(show n)
|
robbertkrebbers/fewdigits
|
Data/Real/CReal.hs
|
Haskell
|
bsd-2-clause
| 13,570
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
{-# OPTIONS_GHC -Wno-orphans #-}
-----------------------------------------------------------------------------
-- |
-- Module : Control.Applicative.Singletons
-- Copyright : (C) 2018 Ryan Scott
-- License : BSD-style (see LICENSE)
-- Maintainer : Ryan Scott
-- Stability : experimental
-- Portability : non-portable
--
-- Defines the promoted and singled versions of the 'Applicative' type class.
--
----------------------------------------------------------------------------
module Control.Applicative.Singletons (
PApplicative(..), SApplicative(..),
PAlternative(..), SAlternative(..),
Sing, SConst(..), Const, GetConst, sGetConst,
type (<$>), (%<$>), type (<$), (%<$), type (<**>), (%<**>),
LiftA, sLiftA, LiftA3, sLiftA3, Optional, sOptional,
-- * Defunctionalization symbols
PureSym0, PureSym1,
type (<*>@#@$), type (<*>@#@$$), type (<*>@#@$$$),
type (*>@#@$), type (*>@#@$$), type (*>@#@$$$),
type (<*@#@$), type (<*@#@$$), type (<*@#@$$$),
EmptySym0, type (<|>@#@$), type (<|>@#@$$), type (<|>@#@$$$),
ConstSym0, ConstSym1, GetConstSym0, GetConstSym1,
type (<$>@#@$), type (<$>@#@$$), type (<$>@#@$$$),
type (<$@#@$), type (<$@#@$$), type (<$@#@$$$),
type (<**>@#@$), type (<**>@#@$$), type (<**>@#@$$$),
LiftASym0, LiftASym1, LiftASym2,
LiftA2Sym0, LiftA2Sym1, LiftA2Sym2, LiftA2Sym3,
LiftA3Sym0, LiftA3Sym1, LiftA3Sym2, LiftA3Sym3,
OptionalSym0, OptionalSym1
) where
import Control.Applicative
import Control.Monad.Singletons.Internal
import Data.Functor.Const.Singletons
import Data.Functor.Singletons
import Data.Monoid.Singletons
import Data.Ord (Down(..))
import Data.Ord.Singletons
import Data.Singletons.Base.Instances
import Data.Singletons.TH
$(singletonsOnly [d|
-- -| One or none.
optional :: Alternative f => f a -> f (Maybe a)
optional v = Just <$> v <|> pure Nothing
instance Monoid a => Applicative ((,) a) where
pure x = (mempty, x)
(u, f) <*> (v, x) = (u `mappend` v, f x)
liftA2 f (u, x) (v, y) = (u `mappend` v, f x y)
instance Applicative Down where
pure = Down
Down f <*> Down x = Down (f x)
|])
|
goldfirere/singletons
|
singletons-base/src/Control/Applicative/Singletons.hs
|
Haskell
|
bsd-3-clause
| 2,271
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE TypeFamilies #-}
-- | Hides away distracting bookkeeping while lambda lifting into a 'LiftM'
-- monad.
module GHC.Stg.Lift.Monad (
decomposeStgBinding, mkStgBinding,
Env (..),
-- * #floats# Handling floats
-- $floats
FloatLang (..), collectFloats, -- Exported just for the docs
-- * Transformation monad
LiftM, runLiftM,
-- ** Adding bindings
startBindingGroup, endBindingGroup, addTopStringLit, addLiftedBinding,
-- ** Substitution and binders
withSubstBndr, withSubstBndrs, withLiftedBndr, withLiftedBndrs,
-- ** Occurrences
substOcc, isLifted, formerFreeVars, liftedIdsExpander
) where
#include "HsVersions.h"
import GhcPrelude
import BasicTypes
import CostCentre ( isCurrentCCS, dontCareCCS )
import DynFlags
import FastString
import Id
import Name
import Outputable
import OrdList
import GHC.Stg.Subst
import GHC.Stg.Syntax
import Type
import UniqSupply
import Util
import VarEnv
import VarSet
import Control.Arrow ( second )
import Control.Monad.Trans.Class
import Control.Monad.Trans.RWS.Strict ( RWST, runRWST )
import qualified Control.Monad.Trans.RWS.Strict as RWS
import Control.Monad.Trans.Cont ( ContT (..) )
import Data.ByteString ( ByteString )
-- | @uncurry 'mkStgBinding' . 'decomposeStgBinding' = id@
decomposeStgBinding :: GenStgBinding pass -> (RecFlag, [(BinderP pass, GenStgRhs pass)])
decomposeStgBinding (StgRec pairs) = (Recursive, pairs)
decomposeStgBinding (StgNonRec bndr rhs) = (NonRecursive, [(bndr, rhs)])
mkStgBinding :: RecFlag -> [(BinderP pass, GenStgRhs pass)] -> GenStgBinding pass
mkStgBinding Recursive = StgRec
mkStgBinding NonRecursive = uncurry StgNonRec . head
-- | Environment threaded around in a scoped, @Reader@-like fashion.
data Env
= Env
{ e_dflags :: !DynFlags
-- ^ Read-only.
, e_subst :: !Subst
-- ^ We need to track the renamings of local 'InId's to their lifted 'OutId',
-- because shadowing might make a closure's free variables unavailable at its
-- call sites. Consider:
-- @
-- let f y = x + y in let x = 4 in f x
-- @
-- Here, @f@ can't be lifted to top-level, because its free variable @x@ isn't
-- available at its call site.
, e_expansions :: !(IdEnv DIdSet)
-- ^ Lifted 'Id's don't occur as free variables in any closure anymore, because
-- they are bound at the top-level. Every occurrence must supply the formerly
-- free variables of the lifted 'Id', so they in turn become free variables of
-- the call sites. This environment tracks this expansion from lifted 'Id's to
-- their free variables.
--
-- 'InId's to 'OutId's.
--
-- Invariant: 'Id's not present in this map won't be substituted.
}
emptyEnv :: DynFlags -> Env
emptyEnv dflags = Env dflags emptySubst emptyVarEnv
-- Note [Handling floats]
-- ~~~~~~~~~~~~~~~~~~~~~~
-- $floats
-- Consider the following expression:
--
-- @
-- f x =
-- let g y = ... f y ...
-- in g x
-- @
--
-- What happens when we want to lift @g@? Normally, we'd put the lifted @l_g@
-- binding above the binding for @f@:
--
-- @
-- g f y = ... f y ...
-- f x = g f x
-- @
--
-- But this very unnecessarily turns a known call to @f@ into an unknown one, in
-- addition to complicating matters for the analysis.
-- Instead, we'd really like to put both functions in the same recursive group,
-- thereby preserving the known call:
--
-- @
-- Rec {
-- g y = ... f y ...
-- f x = g x
-- }
-- @
--
-- But we don't want this to happen for just /any/ binding. That would create
-- possibly huge recursive groups in the process, calling for an occurrence
-- analyser on STG.
-- So, we need to track when we lift a binding out of a recursive RHS and add
-- the binding to the same recursive group as the enclosing recursive binding
-- (which must have either already been at the top-level or decided to be
-- lifted itself in order to preserve the known call).
--
-- This is done by expressing this kind of nesting structure as a 'Writer' over
-- @['FloatLang']@ and flattening this expression in 'runLiftM' by a call to
-- 'collectFloats'.
-- API-wise, the analysis will not need to know about the whole 'FloatLang'
-- business and will just manipulate it indirectly through actions in 'LiftM'.
-- | We need to detect when we are lifting something out of the RHS of a
-- recursive binding (c.f. "GHC.Stg.Lift.Monad#floats"), in which case that
-- binding needs to be added to the same top-level recursive group. This
-- requires we detect a certain nesting structure, which is encoded by
-- 'StartBindingGroup' and 'EndBindingGroup'.
--
-- Although 'collectFloats' will only ever care if the current binding to be
-- lifted (through 'LiftedBinding') will occur inside such a binding group or
-- not, e.g. doesn't care about the nesting level as long as its greater than 0.
data FloatLang
= StartBindingGroup
| EndBindingGroup
| PlainTopBinding OutStgTopBinding
| LiftedBinding OutStgBinding
instance Outputable FloatLang where
ppr StartBindingGroup = char '('
ppr EndBindingGroup = char ')'
ppr (PlainTopBinding StgTopStringLit{}) = text "<str>"
ppr (PlainTopBinding (StgTopLifted b)) = ppr (LiftedBinding b)
ppr (LiftedBinding bind) = (if isRec rec then char 'r' else char 'n') <+> ppr (map fst pairs)
where
(rec, pairs) = decomposeStgBinding bind
-- | Flattens an expression in @['FloatLang']@ into an STG program, see #floats.
-- Important pre-conditions: The nesting of opening 'StartBindinGroup's and
-- closing 'EndBindinGroup's is balanced. Also, it is crucial that every binding
-- group has at least one recursive binding inside. Otherwise there's no point
-- in announcing the binding group in the first place and an @ASSERT@ will
-- trigger.
collectFloats :: [FloatLang] -> [OutStgTopBinding]
collectFloats = go (0 :: Int) []
where
go 0 [] [] = []
go _ _ [] = pprPanic "collectFloats" (text "unterminated group")
go n binds (f:rest) = case f of
StartBindingGroup -> go (n+1) binds rest
EndBindingGroup
| n == 0 -> pprPanic "collectFloats" (text "no group to end")
| n == 1 -> StgTopLifted (merge_binds binds) : go 0 [] rest
| otherwise -> go (n-1) binds rest
PlainTopBinding top_bind
| n == 0 -> top_bind : go n binds rest
| otherwise -> pprPanic "collectFloats" (text "plain top binding inside group")
LiftedBinding bind
| n == 0 -> StgTopLifted (rm_cccs bind) : go n binds rest
| otherwise -> go n (bind:binds) rest
map_rhss f = uncurry mkStgBinding . second (map (second f)) . decomposeStgBinding
rm_cccs = map_rhss removeRhsCCCS
merge_binds binds = ASSERT( any is_rec binds )
StgRec (concatMap (snd . decomposeStgBinding . rm_cccs) binds)
is_rec StgRec{} = True
is_rec _ = False
-- | Omitting this makes for strange closure allocation schemes that crash the
-- GC.
removeRhsCCCS :: GenStgRhs pass -> GenStgRhs pass
removeRhsCCCS (StgRhsClosure ext ccs upd bndrs body)
| isCurrentCCS ccs
= StgRhsClosure ext dontCareCCS upd bndrs body
removeRhsCCCS (StgRhsCon ccs con args)
| isCurrentCCS ccs
= StgRhsCon dontCareCCS con args
removeRhsCCCS rhs = rhs
-- | The analysis monad consists of the following 'RWST' components:
--
-- * 'Env': Reader-like context. Contains a substitution, info about how
-- how lifted identifiers are to be expanded into applications and details
-- such as 'DynFlags'.
--
-- * @'OrdList' 'FloatLang'@: Writer output for the resulting STG program.
--
-- * No pure state component
--
-- * But wrapping around 'UniqSM' for generating fresh lifted binders.
-- (The @uniqAway@ approach could give the same name to two different
-- lifted binders, so this is necessary.)
newtype LiftM a
= LiftM { unwrapLiftM :: RWST Env (OrdList FloatLang) () UniqSM a }
deriving (Functor, Applicative, Monad)
instance HasDynFlags LiftM where
getDynFlags = LiftM (RWS.asks e_dflags)
instance MonadUnique LiftM where
getUniqueSupplyM = LiftM (lift getUniqueSupplyM)
getUniqueM = LiftM (lift getUniqueM)
getUniquesM = LiftM (lift getUniquesM)
runLiftM :: DynFlags -> UniqSupply -> LiftM () -> [OutStgTopBinding]
runLiftM dflags us (LiftM m) = collectFloats (fromOL floats)
where
(_, _, floats) = initUs_ us (runRWST m (emptyEnv dflags) ())
-- | Writes a plain 'StgTopStringLit' to the output.
addTopStringLit :: OutId -> ByteString -> LiftM ()
addTopStringLit id = LiftM . RWS.tell . unitOL . PlainTopBinding . StgTopStringLit id
-- | Starts a recursive binding group. See #floats# and 'collectFloats'.
startBindingGroup :: LiftM ()
startBindingGroup = LiftM $ RWS.tell $ unitOL $ StartBindingGroup
-- | Ends a recursive binding group. See #floats# and 'collectFloats'.
endBindingGroup :: LiftM ()
endBindingGroup = LiftM $ RWS.tell $ unitOL $ EndBindingGroup
-- | Lifts a binding to top-level. Depending on whether it's declared inside
-- a recursive RHS (see #floats# and 'collectFloats'), this might be added to
-- an existing recursive top-level binding group.
addLiftedBinding :: OutStgBinding -> LiftM ()
addLiftedBinding = LiftM . RWS.tell . unitOL . LiftedBinding
-- | Takes a binder and a continuation which is called with the substituted
-- binder. The continuation will be evaluated in a 'LiftM' context in which that
-- binder is deemed in scope. Think of it as a 'RWS.local' computation: After
-- the continuation finishes, the new binding won't be in scope anymore.
withSubstBndr :: Id -> (Id -> LiftM a) -> LiftM a
withSubstBndr bndr inner = LiftM $ do
subst <- RWS.asks e_subst
let (bndr', subst') = substBndr bndr subst
RWS.local (\e -> e { e_subst = subst' }) (unwrapLiftM (inner bndr'))
-- | See 'withSubstBndr'.
withSubstBndrs :: Traversable f => f Id -> (f Id -> LiftM a) -> LiftM a
withSubstBndrs = runContT . traverse (ContT . withSubstBndr)
-- | Similarly to 'withSubstBndr', this function takes a set of variables to
-- abstract over, the binder to lift (and generate a fresh, substituted name
-- for) and a continuation in which that fresh, lifted binder is in scope.
--
-- It takes care of all the details involved with copying and adjusting the
-- binder and fresh name generation.
withLiftedBndr :: DIdSet -> Id -> (Id -> LiftM a) -> LiftM a
withLiftedBndr abs_ids bndr inner = do
uniq <- getUniqueM
let str = "$l" ++ occNameString (getOccName bndr)
let ty = mkLamTypes (dVarSetElems abs_ids) (idType bndr)
let bndr'
-- See Note [transferPolyIdInfo] in Id.hs. We need to do this at least
-- for arity information.
= transferPolyIdInfo bndr (dVarSetElems abs_ids)
. mkSysLocal (mkFastString str) uniq
$ ty
LiftM $ RWS.local
(\e -> e
{ e_subst = extendSubst bndr bndr' $ extendInScope bndr' $ e_subst e
, e_expansions = extendVarEnv (e_expansions e) bndr abs_ids
})
(unwrapLiftM (inner bndr'))
-- | See 'withLiftedBndr'.
withLiftedBndrs :: Traversable f => DIdSet -> f Id -> (f Id -> LiftM a) -> LiftM a
withLiftedBndrs abs_ids = runContT . traverse (ContT . withLiftedBndr abs_ids)
-- | Substitutes a binder /occurrence/, which was brought in scope earlier by
-- 'withSubstBndr'\/'withLiftedBndr'.
substOcc :: Id -> LiftM Id
substOcc id = LiftM (RWS.asks (lookupIdSubst id . e_subst))
-- | Whether the given binding was decided to be lambda lifted.
isLifted :: InId -> LiftM Bool
isLifted bndr = LiftM (RWS.asks (elemVarEnv bndr . e_expansions))
-- | Returns an empty list for a binding that was not lifted and the list of all
-- local variables the binding abstracts over (so, exactly the additional
-- arguments at adjusted call sites) otherwise.
formerFreeVars :: InId -> LiftM [OutId]
formerFreeVars f = LiftM $ do
expansions <- RWS.asks e_expansions
pure $ case lookupVarEnv expansions f of
Nothing -> []
Just fvs -> dVarSetElems fvs
-- | Creates an /expander function/ for the current set of lifted binders.
-- This expander function will replace any 'InId' by their corresponding 'OutId'
-- and, in addition, will expand any lifted binders by the former free variables
-- it abstracts over.
liftedIdsExpander :: LiftM (DIdSet -> DIdSet)
liftedIdsExpander = LiftM $ do
expansions <- RWS.asks e_expansions
subst <- RWS.asks e_subst
-- We use @noWarnLookupIdSubst@ here in order to suppress "not in scope"
-- warnings generated by 'lookupIdSubst' due to local bindings within RHS.
-- These are not in the InScopeSet of @subst@ and extending the InScopeSet in
-- @goodToLift@/@closureGrowth@ before passing it on to @expander@ is too much
-- trouble.
let go set fv = case lookupVarEnv expansions fv of
Nothing -> extendDVarSet set (noWarnLookupIdSubst fv subst) -- Not lifted
Just fvs' -> unionDVarSet set fvs'
let expander fvs = foldl' go emptyDVarSet (dVarSetElems fvs)
pure expander
|
sdiehl/ghc
|
compiler/GHC/Stg/Lift/Monad.hs
|
Haskell
|
bsd-3-clause
| 12,947
|
{-# LANGUAGE PatternSynonyms #-}
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.GL.ARB.SamplerObjects
-- Copyright : (c) Sven Panne 2019
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
--------------------------------------------------------------------------------
module Graphics.GL.ARB.SamplerObjects (
-- * Extension Support
glGetARBSamplerObjects,
gl_ARB_sampler_objects,
-- * Enums
pattern GL_SAMPLER_BINDING,
-- * Functions
glBindSampler,
glDeleteSamplers,
glGenSamplers,
glGetSamplerParameterIiv,
glGetSamplerParameterIuiv,
glGetSamplerParameterfv,
glGetSamplerParameteriv,
glIsSampler,
glSamplerParameterIiv,
glSamplerParameterIuiv,
glSamplerParameterf,
glSamplerParameterfv,
glSamplerParameteri,
glSamplerParameteriv
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Tokens
import Graphics.GL.Functions
|
haskell-opengl/OpenGLRaw
|
src/Graphics/GL/ARB/SamplerObjects.hs
|
Haskell
|
bsd-3-clause
| 1,024
|
module Main(main) where
import Weeder
import System.Exit
import System.Environment
import Control.Monad
main :: IO ()
main = do
bad <- weeder =<< getArgs
when (bad > 0) exitFailure
|
ndmitchell/weeder
|
src/Main.hs
|
Haskell
|
bsd-3-clause
| 191
|
{-# LANGUAGE OverloadedStrings #-}
module ElmBot (eval) where
import qualified System.IO.Silently as Sys
import qualified Environment as Env
import qualified Eval.Code as Elm
eval :: String -> IO String
eval s = fst <$> Sys.capture (run s)
run :: String -> IO ()
run s = Env.run (Env.empty "elm-make" "node") (Elm.eval (Nothing, s))
|
svanderbleek/elm-bot
|
src/ElmBot.hs
|
Haskell
|
bsd-3-clause
| 337
|
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
module NotifSpec
( spec
)
where
import Kis
import Control.Concurrent
import Control.Exception.Base
import Control.Monad
import Data.Time.Clock
import System.IO.Temp
import Test.Hspec
import qualified Data.Aeson as J
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as BSL
import qualified Data.Text as T
type RequestType = T.Text
spec :: Spec
spec = do
describe "runKis" $ do
it "can be run with single service" $ do
collectedNotifs <- newMVar []
let client =
do bed <- createBed "xy"
pat <- createPatient (Patient "Simon")
void $ placePatient pat bed
withTempFile "/tmp/" "tmpKisDB" $ \fp _ ->
runKis [client] [simpleNotifHandler collectedNotifs "notif1"] (T.pack fp)
notifs <- takeMVar collectedNotifs
tail notifs `shouldBe`
[ T.pack (show (CreatePatient (Patient "Simon")))
, T.pack (show (CreateBed "xy"))
]
describe "Notification handlers" $ do
it "are notified of Notifications" $
do mvar1 <- newMVar []
mvar2 <- newMVar []
let client1 = void $ createPatient $ Patient "Simon"
client2 =
do void $ createBed "xy"
void $ createPatient (Patient "Thomas")
void getPatients
nh1 = simpleNotifHandler mvar1 "notifH1"
nh2 = simpleNotifHandler mvar2 "notifH2"
allHandlers = [nh1, nh2]
allClients = [client1, client2]
prop l =
T.pack (show (CreatePatient $ Patient "Simon")) `elem` l
&& T.pack (show (CreatePatient $ Patient "Thomas")) `elem` l
&& T.pack (show (CreateBed "xy")) `elem` l
&& length l == 3
withTempFile "/tmp/" "tmpKisDB" $ \fp _ ->
runKis allClients allHandlers (T.pack fp)
notifList1 <- takeMVar mvar1
notifList2 <- takeMVar mvar2
notifList1 `shouldSatisfy` prop
notifList2 `shouldSatisfy` prop
it "does not block if nothing happens in service" $
(withTempFile "/tmp/" "tmpKisDB" $ \fp _ ->
runKis [] [] (T.pack fp))
-- ^ The reason for this test was a bug where the notifications thread
-- was blocked and didnt wakeup on the stop signal.
it "can use the Kis interface to access DB" $
do resMvar <- newEmptyMVar
let client =
do pat <- createPatient $ Patient "Simon"
bed <- createBed "xy"
void $ placePatient pat bed
saveFunction :: (Monad m, KisRead m) => (KisRequest a, a) -> m (Maybe BS.ByteString)
saveFunction (request, _) =
case request of
PlacePatient patId _ ->
do patient <- getPatient patId
return $ Just (BSL.toStrict (J.encode patient))
_ -> return Nothing
processFunction _ bs =
putMVar resMvar res
where Just res = J.decode (BSL.fromStrict bs)
nh = NotificationHandler saveFunction processFunction "nh1"
withTempFile "/tmp/" "tmpKisDB" $ \fp _ ->
runKis [client] [nh] (T.pack fp)
result <- takeMVar resMvar
result `shouldBe` Patient "Simon"
it "cannot add two notifHandlers with equal signature" $
let nh1 = NotificationHandler (\_ -> return Nothing) (\_ _ -> return ()) "nh1"
in (withTempFile "/tmp/" "tmpKisDB" $ \fp _ ->
runKis [] [nh1, nh1] (T.pack fp))
`shouldThrow` (== ErrorCall "two notifhandlers with the same signature were added")
it "correctly reads notification timestamps" $
withTempFile "/tmp/" "tmpKisDB" $ \dbFile _ ->
do currentTime <- getCurrentTime
let processNotif timestamp _ = timestamp `shouldBe` currentTime
nh = NotificationHandler (\_ -> return (Just "")) processNotif "nh"
run kis = runClient kis (void $ createPatient (Patient "Simon"))
poolBackend = PoolBackendType (T.pack dbFile) 10
void $ withSqliteKisWithNotifs poolBackend (KisConfig (constClock currentTime)) [nh] run
simpleNotifHandler :: MVar [RequestType] -> T.Text -> NotificationHandler
simpleNotifHandler notifList sig =
NotificationHandler
{ nh_saveNotif = saveRequest
, nh_processNotif = processNotification notifList
, nh_signature = sig
}
saveRequest ::
(Monad m, KisRead m)
=> (KisRequest a, a)
-> m (Maybe BS.ByteString)
saveRequest (request, _) =
return (Just $ BSL.toStrict (J.encode (T.pack (show request))))
processNotification :: MVar [RequestType] -> UTCTime -> BS.ByteString -> IO ()
processNotification notifList _ payload =
do oldList <- takeMVar notifList
let Just reqType = J.decode (BSL.fromStrict payload)
putMVar notifList (reqType:oldList)
|
lslah/kis-proto
|
test/NotifSpec.hs
|
Haskell
|
bsd-3-clause
| 5,385
|
module Util.HTML
( Html
, Attribute
, Attributable
, renderHtml
, toHtml
, attribute
, empty
, parent
, leaf
, makeAttr
, makePar
, makeLeaf
, (!)
, ($<)
) where
import Data.Monoid
data HtmlM a
= Parent !String -- ^ Tag
!String -- ^ Opening tag
!String
!String -- ^ Closing tag
!(HtmlM a) -- ^ Child element
| Leaf !String -- ^ Tag
!String -- ^ Opening tag
!String -- ^ Closing tag
| Content !String -- ^ HTML content
| forall b c.
Append (HtmlM b) -- ^ Concatenation of two
(HtmlM c) -- ^ HTML elements
| Attr !String -- ^ Raw key
!String -- ^ Attribute key
!String -- ^ Attribute value
!(HtmlM a) -- ^ Target element
| Empty -- ^ Empty element
type Html = HtmlM ()
data Attribute = Attribute !String !String !String
instance Monoid a => Monoid (HtmlM a) where
mempty = Empty
mappend = Append
mconcat = foldr Append Empty
instance Monad HtmlM where
return _ = Empty
(>>) = Append
h1 >>= f = h1 >> f (error "")
class Attributable h where
(!) :: h -> Attribute -> h
instance Attributable (HtmlM a) where
(!) h (Attribute raw key val) = Attr raw key val h
instance Attributable (HtmlM a -> HtmlM b) where
(!) f (Attribute raw key val) = Attr raw key val . f
renderHtml :: HtmlM t -> String
renderHtml = go ""
where go :: String -> HtmlM t -> String
go s (Parent _ open r close content)
= open ++ s ++ r ++ renderHtml content ++ close
go s (Leaf _ open close)
= open ++ s ++ close
go s (Content content) = escapeHtmlEntities content
go s (Append h1 h2) = go s h1 ++ go s h2
go s (Attr _ key value h)
= flip go h
$ key
++ escapeHtmlEntities value
++ "\""
++ s
go _ Empty = ""
escapeHtmlEntities :: String -> String
escapeHtmlEntities "" = ""
escapeHtmlEntities (c:cs) =
let c' = case c of
'<' -> "<"
'>' -> ">"
'&' -> "&"
'"' -> """
'\'' -> "'"
x -> [x]
in c' ++ escapeHtmlEntities cs
attribute :: String -> String -> String -> Attribute
attribute = Attribute
empty :: Html
empty = Empty
parent :: String -> String -> String -> String -> Html -> Html
parent = Parent
leaf :: String -> String -> String -> Html
leaf = Leaf
toHtml :: String -> HtmlM a
toHtml = Content
makeAttr :: String -> String -> Attribute
makeAttr a = Attribute a (' ':a ++ "=\"")
makePar :: String -> Html -> Html
makePar h = Parent h ('<':h) ">" ("</" ++ h ++ ">")
makeLeaf :: String -> Html
makeLeaf a = Leaf a ('<':a) ">"
-- Shorthand infix operator
($<) :: (Html -> Html) -> String -> Html
($<) a = a . toHtml
|
johanneshilden/liquid-epsilon
|
Util/HTML.hs
|
Haskell
|
bsd-3-clause
| 3,029
|
{-# LANGUAGE GeneralizedNewtypeDeriving, DeriveDataTypeable, ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
module Development.Shake.Internal.Rules.Rerun(
defaultRuleRerun, alwaysRerun
) where
import Development.Shake.Internal.Core.Rules
import Development.Shake.Internal.Core.Types
import Development.Shake.Internal.Core.Build
import Development.Shake.Internal.Core.Action
import Development.Shake.Classes
import qualified Data.ByteString as BS
import General.Binary
newtype AlwaysRerunQ = AlwaysRerunQ ()
deriving (Typeable,Eq,Hashable,Binary,BinaryEx,NFData)
instance Show AlwaysRerunQ where show _ = "alwaysRerun"
type instance RuleResult AlwaysRerunQ = ()
-- | Always rerun the associated action. Useful for defining rules that query
-- the environment. For example:
--
-- @
-- \"ghcVersion.txt\" 'Development.Shake.%>' \\out -> do
-- 'alwaysRerun'
-- 'Development.Shake.Stdout' stdout <- 'Development.Shake.cmd' \"ghc --numeric-version\"
-- 'Development.Shake.writeFileChanged' out stdout
-- @
--
-- In @make@, the @.PHONY@ attribute on file-producing rules has a similar effect.
--
-- Note that 'alwaysRerun' is applied when a rule is executed. Modifying an existing rule
-- to insert 'alwaysRerun' will /not/ cause that rule to rerun next time.
alwaysRerun :: Action ()
alwaysRerun = do
historyDisable
apply1 $ AlwaysRerunQ ()
defaultRuleRerun :: Rules ()
defaultRuleRerun =
addBuiltinRuleEx noLint noIdentity $
\AlwaysRerunQ{} _ _ -> pure $ RunResult ChangedRecomputeDiff BS.empty ()
|
ndmitchell/shake
|
src/Development/Shake/Internal/Rules/Rerun.hs
|
Haskell
|
bsd-3-clause
| 1,560
|
{-# LANGUAGE QuantifiedConstraints #-}
module Error
( Err
, runErr
, throw
, throwMany
, context
, contextShow
, fromEither
, fromEitherShow
, note
, sequenceV
, traverseV
, traverseV_
, forV
, forV_
, HasErr
, Sem
)
where
import Data.Vector as V
hiding ( toList )
import Polysemy
import qualified Polysemy.Error as E
import Relude
import Validation
type Err = E.Error (Vector Text)
type HasErr r = MemberWithError Err r
runErr :: forall r a. Sem (Err ': r) a -> Sem r (Either (Vector Text) a)
runErr = E.runError
throw :: forall r a. MemberWithError Err r => Text -> Sem r a
throw = E.throw . singleton
throwMany
:: forall r f a . (MemberWithError Err r, Foldable f) => f Text -> Sem r a
throwMany = E.throw . V.fromList . toList
context :: forall r a . MemberWithError Err r => Text -> Sem r a -> Sem r a
context c m = E.catch @(Vector Text) m $ \e -> E.throw ((c <> ":" <+>) <$> e)
contextShow
:: forall c r a . (Show c, MemberWithError Err r) => c -> Sem r a -> Sem r a
contextShow = context . show
fromEither :: MemberWithError Err r => Either Text a -> Sem r a
fromEither = E.fromEither . first singleton
fromEitherShow :: (Show e, MemberWithError Err r) => Either e a -> Sem r a
fromEitherShow = fromEither . first show
note :: MemberWithError Err r => Text -> Maybe a -> Sem r a
note e = \case
Nothing -> throw e
Just x -> pure x
sequenceV
:: forall f r a . (Traversable f, HasErr r) => f (Sem r a) -> Sem r (f a)
sequenceV xs = do
vs <- traverse
(\x -> E.catch @(Vector Text) (Success <$> x) (pure . Failure))
xs
case sequenceA vs of
Success as -> pure as
Failure es -> E.throw es
traverseV
:: forall f r a b
. (Traversable f, HasErr r)
=> (a -> Sem r b)
-> f a
-> Sem r (f b)
traverseV f = sequenceV . fmap f
traverseV_
:: forall f r a b
. (Foldable f, HasErr r)
=> (a -> Sem r b)
-> f a
-> Sem r ()
traverseV_ f = void . traverseV f . toList
forV
:: forall f r a b
. (Traversable f, HasErr r)
=> f a
-> (a -> Sem r b)
-> Sem r (f b)
forV = flip traverseV
forV_
:: forall f r a
. (Foldable f, HasErr r)
=> f a
-> (a -> Sem r ())
-> Sem r ()
forV_ = flip traverseV_
infixr 5 <+>
(<+>) :: (Semigroup a, IsString a) => a -> a -> a
a <+> b = a <> " " <> b
|
expipiplus1/vulkan
|
generate-new/src/Error.hs
|
Haskell
|
bsd-3-clause
| 2,402
|
module Main where
import qualified Web.JWTTests
import qualified Web.JWTInteropTests
import qualified Web.Base64Tests
import qualified Data.Text.ExtendedTests
import Test.Tasty
main :: IO ()
main = defaultMain tests
tests :: TestTree
tests = testGroup "JWT Tests" [
Web.JWTTests.defaultTestGroup
, Web.JWTInteropTests.defaultTestGroup
, Web.Base64Tests.defaultTestGroup
, Data.Text.ExtendedTests.defaultTestGroup
]
|
bitemyapp/haskell-jwt
|
tests/src/TestRunner.hs
|
Haskell
|
mit
| 519
|
module Data.Kicad.PcbnewExpr
(
-- * Types
PcbnewExpr(..)
-- * Parse
, parse
, parseWithFilename
, fromSExpr
-- * Write
, pretty
, write
)
where
import Data.Kicad.PcbnewExpr.PcbnewExpr
import Data.Kicad.PcbnewExpr.Parse
import Data.Kicad.PcbnewExpr.Write
|
kasbah/haskell-kicad-data
|
Data/Kicad/PcbnewExpr.hs
|
Haskell
|
mit
| 256
|
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ViewPatterns #-}
module Acquire.Game.Player where
import Acquire.Game.Hotels
import Acquire.Game.Tiles
import Data.Aeson (FromJSON (..), ToJSON (..), Value (..),
object, (.:), (.=))
import qualified Data.Map as M
import GHC.Generics
data PlayerType = Human | Robot deriving (Eq, Show, Read, Generic)
instance ToJSON PlayerType
instance FromJSON PlayerType
newtype Stock = Stock { stock :: M.Map ChainName Int }
deriving (Eq, Show, Read)
emptyStock :: Stock
emptyStock = Stock M.empty
stockLookup :: ChainName -> Stock -> Maybe Int
stockLookup chain (Stock s) = M.lookup chain s
alterStock :: (Maybe Int -> Maybe Int) -> ChainName -> Stock -> Stock
alterStock f chain (Stock s) = Stock $ M.alter f chain s
adjustStock :: (Int -> Int) -> ChainName -> Stock -> Stock
adjustStock f chain (Stock s) = Stock $ M.adjust f chain s
mapStock :: (ChainName -> Int -> a) -> Stock -> M.Map ChainName a
mapStock f (Stock s) = M.mapWithKey f s
listStock :: Stock -> [(ChainName, Int)]
listStock (Stock s) = M.toList s
findOr0 :: ChainName -> Stock -> Int
findOr0 chain (Stock s) = M.findWithDefault 0 chain s
instance ToJSON Stock where
toJSON (Stock s) = object [ "stock" .= M.toList s ]
instance FromJSON Stock where
parseJSON (Object o) = Stock <$>
(M.fromList <$> o .: "stock")
parseJSON v = fail $ "Cannot parse Stock from JSON " ++ show v
data Player = Player { playerName :: PlayerName
, playerType :: PlayerType
, tiles :: [ Tile ]
, ownedStock :: Stock
, ownedCash :: Int
} deriving (Eq, Show, Read, Generic)
instance ToJSON Player
instance FromJSON Player
type Players = M.Map PlayerName Player
type PlayerName = String
isHuman :: Player -> Bool
isHuman (playerType -> Human) = True
isHuman _ = False
isRobot :: Player -> Bool
isRobot (playerType -> Robot) = True
isRobot _ = False
hasEnoughMoneyToBuyStock :: Player -> HotelChain -> Bool
hasEnoughMoneyToBuyStock player chain = let price = stockPrice chain
in ownedCash player >= price
|
abailly/hsgames
|
acquire/src/Acquire/Game/Player.hs
|
Haskell
|
apache-2.0
| 2,371
|
{-| Utility functions for the maintenance daemon.
-}
{-
Copyright (C) 2015 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.MaintD.Utils
( annotateOpCode
) where
import Control.Lens.Setter (over)
import qualified Ganeti.Constants as C
import Ganeti.JQueue (reasonTrailTimestamp)
import Ganeti.JQueue.Objects (Timestamp)
import Ganeti.OpCodes (OpCode, MetaOpCode, wrapOpCode)
import Ganeti.OpCodes.Lens (metaParamsL, opReasonL)
-- | Wrap an `OpCode` into a `MetaOpCode` and adding an indication
-- that the `OpCode` was submitted by the maintenance daemon.
annotateOpCode :: String -> Timestamp -> OpCode -> MetaOpCode
annotateOpCode reason ts =
over (metaParamsL . opReasonL)
(++ [(C.opcodeReasonSrcMaintd, reason, reasonTrailTimestamp ts)])
. wrapOpCode
|
bitemyapp/ganeti
|
src/Ganeti/MaintD/Utils.hs
|
Haskell
|
bsd-2-clause
| 2,013
|
-- |
-- Utility functions for Mailchimp
--
module Web.Mailchimp.Util
where
import Control.Monad (mzero)
import Data.Aeson (ToJSON(..), FromJSON(..), Value(..), object)
import Data.Text (pack, unpack)
import Data.Char (isAlpha, toLower, isUpper)
import Data.Time.Clock (UTCTime)
import Data.Time.Format (formatTime, parseTime)
import System.Locale (defaultTimeLocale)
-- | Creates Aeson objects after filtering to remove null values.
filterObject list =
object $ filter notNothing list
where
notNothing (_, Null) = False
notNothing _ = True
-- | Represents times in the format expected by Mailchimp's API
newtype MCTime = MCTime {unMCTime :: UTCTime}
deriving (Show, Eq)
mcFormatString :: String
mcFormatString = "%F %T"
instance ToJSON MCTime where
toJSON (MCTime t) = String $ pack $ formatTime defaultTimeLocale mcFormatString t
instance FromJSON MCTime where
parseJSON (String s) = maybe mzero (return . MCTime) $ parseTime defaultTimeLocale mcFormatString (unpack s)
parseJSON _ = mzero
-- | Removes the first Int characters of string, then converts from CamelCase to underscore_case.
-- For use by Aeson template haskell calls.
convertName :: Int -> String -> String
convertName prefixLength pname =
toLower (head name) : camelToUnderscore (tail name)
where
name = drop prefixLength pname
-- | Converts camelcase identifiers to underscored identifiers
camelToUnderscore (x : y : xs) | isAlpha x, isUpper y =
x : '_' : camelToUnderscore (toLower y : xs)
camelToUnderscore (x : xs) = x : camelToUnderscore xs
camelToUnderscore x = x
|
tlaitinen/mailchimp
|
Web/Mailchimp/Util.hs
|
Haskell
|
bsd-3-clause
| 1,584
|
{-# LANGUAGE
DeriveFunctor,
DeriveFoldable,
DeriveTraversable,
NoMonomorphismRestriction,
GeneralizedNewtypeDeriving,
StandaloneDeriving,
TypeFamilies,
ViewPatterns,
MultiParamTypeClasses,
TypeSynonymInstances, -- TODO remove
FlexibleInstances,
OverloadedStrings,
TypeOperators
#-}
module Trans (
-- * Internal
Trans,
tapp,
runTrans,
TList,
tlist,
tlapp,
tlappWhen,
runTList,
-- Tree,
-- MTree,
-- TMTree,
-- * Transformations
Time,
Dur,
Pitch,
Frequency,
Amplitude,
-- * Score
Behaviour,
Articulation,
Score,
runScore,
)
where
import Data.Monoid.Action
import Data.Monoid.MList -- misplaced Action () instance
import Data.Key
import Data.Default
import Data.Basis
import Data.Maybe
import Data.AffineSpace
import Data.AffineSpace.Point
import Data.AdditiveGroup hiding (Sum, getSum)
import Data.VectorSpace hiding (Sum, getSum)
import Data.LinearMap
import Control.Monad
import Control.Monad.Plus
import Control.Arrow
import Control.Applicative
import Control.Monad.Writer hiding ((<>))
import Data.String
import Data.Semigroup
import Data.Foldable (Foldable)
import Data.Traversable (Traversable)
import qualified Data.Traversable as T
import qualified Diagrams.Core.Transform as D
{-
Compare
- Update Monads: Cointerpreting directed containers
-}
-- |
-- 'Trans' is a restricted version of the 'Writer' monad.
--
newtype Trans m a = Trans (Writer m a)
deriving (Monad, MonadWriter m, Functor, Applicative, Foldable, Traversable)
instance (Monoid m, Monoid a) => Semigroup (Trans m a) where
-- TODO not sure this must require Monoid m
Trans w <> Trans u = writer $ runWriter w `mappend` runWriter u
instance (Monoid m, Monoid a) => Monoid (Trans m a) where
mempty = return mempty
mappend = (<>)
type instance Key (Trans m) = m
instance Keyed (Trans m) where
mapWithKey f (Trans w) = Trans $ mapWriter (\(a,w) -> (f w a, w)) w
{-
Alternative implementation:
newtype Write m a = Write (a, m)
deriving (Show, Functor, Foldable, Traversable)
instance Monoid m => Monad (Write m) where
return x = Write (x, mempty)
Write (x1,m1) >>= f = let
Write (x2,m2) = f x1
in Write (x2,m1 `mappend` m2)
Write (x1,m1) >> y = let
Write (x2,m2) = y
in Write (x2,m1 `mappend` m2)
-}
{-
Same thing with orinary pairs:
deriving instance Monoid m => Foldable ((,) m)
deriving instance Monoid m => Traversable ((,) m)
instance Monoid m => Monad ((,) m) where
return x = (mempty, x)
(m1,x1) >>= f = let
(m2,x2) = f x1
in (m1 `mappend` m2,x2)
-}
{-
newtype LTrans m a = LTrans { getLTrans :: Trans m [a] }
deriving (Semigroup, Monoid, Functor, Foldable, Traversable)
Trans m [a]
Trans m [Trans m [a]] -- fmap (fmap f)
Trans m (Trans m [[a]]) -- fmap sequence
Trans m (Trans m [a]) -- fmap (fmap join)
Trans m [a] -- join
This is NOT equivalent to TList, it will compose transformations over the
*entire* list using monadic sequencing rather than *propagating* the traversion over the list
Compare:
> runTransWith (fmap.appEndo) $ T.sequence $ fmap (tapp (e (+1)) . Trans . return) [1,2,3]
> fmap (runTransWith appEndo) $ T.sequence $ (tapp (e (+1)) . Trans . return) [1,2,3]
-}
{-
TODO
Assure consistency of act with fmap
We need something like:
> tlapp m . fmap g = fmap (act m . g)
> fmap g . tlapp m = fmap (g . act m)
Can this be derived from the Action laws (satisfied for Endo).
> act mempty = id
> act (m1 `mappend` m2) = act m1 . act m2
Try
> fmap g . tlapp m = fmap (g . act m)
-- tlapp law
> fmap g . fmap (tapp m) = fmap (g . act m)
-- definition
> fmap (g . tapp m) = fmap (g . act m)
-- functor law
Need to prove
> fmap (g . tapp m) = fmap (g . act m)
-- theorem
> fmap (g . (tell m >>)) = fmap (g . act m)
-- definition
> fmap (g . (Write ((), m) >>)) = fmap (g . act m)
-- definition
> fmap (g . (\x -> Write ((), m) >> x)) = fmap (g . act m)
-- expand section
> fmap (g . (\Write (x2,m2) -> Write ((), m) >> Write (x2,m2))) = fmap (g . act m)
-- expand
> fmap (g . (\Write (x2,m2) -> Write (x2,m <> m2))) = fmap (g . act m)
-- expand
> \Write (x2,m2) -> Write (x2,m <> m2))) = act m
-- simplify
> act mempty = id
> act (m1 `mappend` m2) = act m1 . act m2
Try
> fmap g . tlapp m = fmap (g . act m)
-- tlapp law
> fmap g . fmap (ar . tapp m) = fmap (g . act m)
-- definition
> fmap (g . ar . tapp m) = fmap (g . act m)
-- functor law
Need to prove
> fmap (g . ar . tapp m) = fmap (g . act m)
-- theorem
> fmap (g . ar . (tell m >>)) = fmap (g . act m)
-- definition
> fmap (g . ar . (Write ((), m) >>)) = fmap (g . act m)
-- definition
> fmap (g . ar . (\x -> Write ((), m) >> x)) = fmap (g . act m)
-- expand section
> fmap (g . ar . (\Write (x2,m2) -> Write ((), m) >> Write (x2,m2))) = fmap (g . act m)
-- expand
> fmap (g . ar . (\Write (x2,m2) -> Write (x2,m <> m2))) = fmap (g . act m)
-- expand
> ar . \Write (x2,m2) -> Write (x2,m <> m2) = act m
-- simplify
> return . uncurry (flip act) . runWriter . \Write (x2,m2) -> Write (x2,m <> m2) = act m
-- simplify
> return . uncurry (flip act) . \(x2,m2) -> (x2,m <> m2))) = act m
-- removes Write wrapper
> (\x -> (x,mempty)) . uncurry (flip act) . \(x2,m2) -> (x2,m <> m2) = act m
> (\x -> (uncurry (flip act) x,mempty)) . \(x2,m2) -> (x2,m <> m2) = act m
> (\(x,m2) -> (act m2 x, mempty)) . fmap (m <>) = act m
> (\(x,m2) -> (act (m <> m2) x, mempty)) = act m
ar = return . uncurry (flip act) . runWriter
tell w = Write ((), w)
Write (_,m1) >> Write (x2,m2) = Write (x2,m1 `mappend` m2)
-}
-- |
-- Transformable list.
--
-- > type TList m a = [Trans m a]
--
-- See Jones and Duponcheel, /Composing Monads/ (1993).
--
newtype TList m a = TList { getTList :: [Trans m a] }
deriving (Semigroup, Monoid, Functor, Foldable, Traversable)
instance (IsString a, Monoid m) => IsString (TList m a) where
fromString = return . fromString
instance Monoid m => Applicative (TList m) where
pure = return
(<*>) = ap
instance Monoid m => Monad (TList m) where
return = TList . return . return
TList xs >>= f = TList $ join . fmap (fmap join . T.sequence . fmap (getTList . f)) $ xs
instance Monoid m => MonadPlus (TList m) where
mzero = mempty
mplus = (<>)
type instance Key (TList m) = m
instance Keyed (TList m) where
mapWithKey f (TList xs) = TList $ fmap (mapWithKey f) xs
-- [Trans m a]
-- [Trans m [Trans m a]] -- fmap (fmap f)
-- [[Trans m (Trans m a)]] -- fmap sequence
-- [[Trans m a]] -- fmap (fmap join)
-- [Trans m a] -- join
runTrans :: Action m a => Trans m a -> a
runTrans = runTransWith act
runTransWith :: (m -> a -> a) -> Trans m a -> a
runTransWith f = uncurry (flip f) . renderTrans
assureRun :: (Monoid m, Action m a) => Trans m a -> Trans m a
assureRun = return . runTrans
renderTrans :: Trans m a -> (a, m)
renderTrans (Trans x) = runWriter x
-- |
-- > tapp m = fmap (act m)
tapp :: (Action m a, Monoid m) => m -> Trans m a -> Trans m a
tapp m = assureRun . tapp' m
tapp' :: Monoid m => m -> Trans m a -> Trans m a
tapp' m = (tell m >>)
-- | Construct a 'TList' from a transformation and a list.
tlist :: (Action m a, Monoid m) => m -> [a] -> TList m a
tlist m xs = tlapp m (fromList xs)
-- | Construct a 'TList' from a list.
fromList :: Monoid m => [a] -> TList m a
fromList = mfromList
-- | Transform a list.
--
-- > tlapp m = fmap (act m)
--
-- TODO does it follow:
--
-- > tlapp (f <> g) = tlapp f . tlapp g
--
tlapp :: (Action m a, Monoid m) => m -> TList m a -> TList m a
tlapp m (TList xs) = TList $ fmap (tapp m) xs
-- FIXME violates which law?
-- | Transform a list if the predicate holds.
--
tlappWhen :: (Action m a, Monoid m) => (a -> Bool) -> m -> TList m a -> TList m a
tlappWhen p f xs = let (ts, fs) = mpartition p xs
in tlapp f ts `mplus` fs
-- | Extract the components.
runTList :: Action m a => TList m a -> [a]
runTList (TList xs) = fmap runTrans xs
-- | Extract the components using the supplied function to render the cached transformations.
runTListWith :: (m -> a -> a) -> TList m a -> [a]
runTListWith f (TList xs) = fmap (runTransWith f) xs
-- FIXME not what you'd expect!
getTListMonoid :: Monoid m => TList m a -> m
getTListMonoid = mconcat . runTListWith (const) . fmap (const undefined)
-- | Extract the components and cached transformations.
renderTList :: TList m a -> [(a, m)]
renderTList (TList xs) = fmap renderTrans xs
data Tree a = Tip a | Bin (Tree a) (Tree a)
deriving (Functor, Foldable, Traversable)
instance Semigroup (Tree a) where
(<>) = Bin
-- TODO Default
instance Monoid a => Monoid (Tree a) where
mempty = Tip mempty
mappend = (<>)
instance Monad Tree where
return = Tip
Tip x >>= f = f x
Bin x y >>= f = Bin (x >>= f) (y >>= f)
newtype TTree m a = TTree { getTTree :: Tree (Trans m a) }
deriving (Semigroup, Monoid, Functor, Foldable, Traversable)
instance (IsString a, Monoid m) => IsString (TTree m a) where
fromString = return . fromString
instance Monoid m => Applicative (TTree m) where
pure = return
(<*>) = ap
instance Monoid m => Monad (TTree m) where
return = TTree . return . return
TTree xs >>= f = TTree $ join . fmap (fmap join . T.mapM (getTTree . f)) $ xs
newtype MTree a = MTree { getMTree :: (Maybe (Tree a)) }
deriving (Semigroup, Functor, Foldable, Traversable)
instance Monoid (MTree a) where
mempty = MTree Nothing
mappend = (<>)
instance Monad MTree where
return = MTree . return . return
MTree xs >>= f = MTree $ join . fmap (fmap join . T.mapM (getMTree . f)) $ xs
instance MonadPlus MTree where
mzero = mempty
mplus = (<>)
newtype TMTree m a = TMTree { getTMTree :: MTree (Trans m a) }
deriving (Semigroup, Monoid, Functor, Foldable, Traversable)
instance (IsString a, Monoid m) => IsString (TMTree m a) where
fromString = return . fromString
instance Monoid m => Applicative (TMTree m) where
pure = return
(<*>) = ap
instance Monoid m => Monad (TMTree m) where
return = TMTree . return . return
TMTree xs >>= f = TMTree $ join . fmap (fmap join . T.mapM (getTMTree . f)) $ xs
instance Monoid m => MonadPlus (TMTree m) where
mzero = mempty
mplus = (<>)
{-
----------------------------------------------------------------------
-- Minimal API
type Transformation t p a = TT ::: PT ::: AT ::: () -- Monoid
class HasTransformation a where
makeTransformation :: a -> Transformation t p a
instance HasTransformation TT where
makeTransformation = inj
instance HasTransformation PT where
makeTransformation = inj
instance HasTransformation AT where
makeTransformation = inj
-- Use identity if no such transformation
get' = option mempty id . get
transform :: Transformation t p a -> (Amplitude,Pitch,Span) -> (Amplitude,Pitch,Span)
transform u (a,p,s) = (a2,p2,s2)
where
a2 = act (get' u :: AT) a
p2 = act (get' u :: PT) p
s2 = act (get' u :: TT) s
----------------------------------------------------------------------
newtype TT = TT (D.Transformation Span)
deriving (Monoid, Semigroup)
-- TODO generalize all of these from TT to arbitrary T
instance Action TT Span where
act (TT t) = unPoint . D.papply t . P
delaying :: Time -> Transformation t p a
delaying x = makeTransformation $ TT $ D.translation (x,0)
stretching :: Dur -> Transformation t p a
stretching = makeTransformation . TT . D.scaling
----------------------------------------------------------------------
newtype PT = PT (D.Transformation Pitch)
deriving (Monoid, Semigroup)
instance Action PT Pitch where
act (PT t) = unPoint . D.papply t . P
transposing :: Pitch -> Transformation t p a
transposing x = makeTransformation $ PT $ D.translation x
----------------------------------------------------------------------
newtype AT = AT (D.Transformation Amplitude)
deriving (Monoid, Semigroup)
instance Action AT Amplitude where
act (AT t) = unPoint . D.papply t . P
amplifying :: Amplitude -> Transformation t p a
amplifying = makeTransformation . AT . D.scaling
----------------------------------------------------------------------
-- Accumulate transformations
delay x = tlapp (delaying x)
stretch x = tlapp (stretching x)
transpose x = tlapp (transposing x)
amplify x = tlapp (amplifying x)
-}
type Time = Double
type Dur = Double
type Span = (Time, Dur)
type Pitch = Double
type Amplitude = Double
-- foo :: Score String
-- foo = stretch 2 $ "c" <> (delay 1 ("d" <> stretch 0.1 "e"))
--
-- foo :: Score String
-- foo = amplify 2 $ transpose 1 $ delay 2 $ "c"
type Onset = Sum Time
type Offset = Sum Time
type Frequency = Double
type Part = Int
type Behaviour a = Time -> a
type R2 = (Double, Double)
-- Time transformation is a function that acts over (time,dur) notes by ?
-- Pitch transformation is a pitch function that acts over notes by fmap
-- Dynamic transformation is a pitch function that acts over notes by fmap
-- Space transformation is a pitch function that acts over notes by fmap
-- Part transformation is a pitch function that acts over notes by fmap
-- (Most part functions are const!)
-- Articulation is a transformation that acts over (pitch, dynamics, onset, offset) by ?
type Articulation = (Endo (Pitch -> Pitch), Endo (Amplitude -> Amplitude))
{-
return x
-}
type Score a = TList
((Sum Time, Sum Time),
(Time -> Product Pitch, Time -> Product Amplitude),
Option (Data.Semigroup.Last Part),
Time -> Endo (R2 -> R2),
Time -> Articulation
)
(Either Pitch (Behaviour Pitch),
Either Amplitude (Behaviour Amplitude),
Part,
Behaviour R2,
a)
foo :: Score a
foo = undefined
-- This requires the transformation type to be a Monoid
bar = join (return foo)
-- runScore :: {-(Action m-type n-type) =>-} Score a -> [n-type]
runScore = runTList . asScore
asScore = (id :: Score a -> Score a)
{-
Time:
For each note: onset and onset (or equivalently onset and duration)
Optionally more paramters such as pre-onset, post-onset, post-offset
[preOn A on D postOn S off R postOff]
Pitch:
For each note a custom pitch value (usually Common.Pitch)
Optionally for each note a gliss/slide curve, indicating shape to next note
(generally a simple slope function)
Alternatively, for each part a (Behaviour Frequency) etc
Dynamics:
For each note an integral dynamic value (usually Common.Level)
Optionally for each note a cresc/dim curve, indicating shape to next note
(generally a simple slope function)
Alternatively, for each part a (Behaviour Amplitude) etc
Part:
For each note an ordered integral (or fractional) indicator of instrument and/or subpart
Space:
For each note a point in R2 or R3
Alternatively, for each part a (Behaviour R2) etc
Misc/Timbre:
Instrument changes, playing technique or timbral changes, i.e "sul pont -> sul tasto"
Articulation:
Affects pitch, dynamics and timbre
-}
-- ((0.0,2.0),"c")
-- ((2.0,2.0),"d")
-- ((2.0,0.2),"e")
-- ((["stretch 2.0"],(0,1)),"c")
-- ((["stretch 2.0","delay 1.0"],(0,1)),"d")
-- ((["stretch 2.0","delay 1.0","stretch 0.1"],(0,1)),"e")
-- (0,1)
-- (0,0.5)
-- (1,0.5)
-- (2,1)
{-
instance (Monoid a, Monoid b, Monoid c, Monoid d, Monoid e, Monoid f) => Monoid (a,b,c,d,e,f) where
mempty = (mempty,mempty,mempty,mempty,mempty)
(a,b,c,d,e,f) `mappend` (a1,b1,c1,d1,e1,f1) =
(a <> a1, b <> b1, c <> c1, d <> d1, e <> e1, f <> f1)
where (<>) = mappend
-}
{-
unpack3 :: ((a, b), c) -> (a, b, c)
unpack4 :: (((a, b), c), d) -> (a, b, c, d)
unpack5 :: ((((a, b), c), d), e) -> (a, b, c, d, e)
unpack6 :: (((((a, b), c), d), e), f) -> (a, b, c, d, e, f)
unpack3 ((c,b),a) = (c,b,a)
unpack4 ((unpack3 -> (d,c,b),a)) = (d,c,b,a)
unpack5 ((unpack4 -> (e,d,c,b),a)) = (e,d,c,b,a)
unpack6 ((unpack5 -> (f,e,d,c,b),a)) = (f,e,d,c,b,a)
pack3 :: (b, c, a) -> ((b, c), a)
pack4 :: (c, d, b, a) -> (((c, d), b), a)
pack5 :: (d, e, c, b, a) -> ((((d, e), c), b), a)
pack6 :: (e, f, d, c, b, a) -> (((((e, f), d), c), b), a)
pack3 (c,b,a) = ((c,b),a)
pack4 (d,c,b,a) = (pack3 (d,c,b),a)
pack5 (e,d,c,b,a) = (pack4 (e,d,c,b),a)
pack6 (f,e,d,c,b,a) = (pack5 (f,e,d,c,b),a)
-}
{-
-- TODO move
mapplyIf :: (Functor f, MonadPlus f) => (a -> Maybe a) -> f a -> f a
mapplyIf f = mapplyWhen (predicate f) (fromMaybe (error "mapplyIf") . f)
mapplyWhen :: (Functor f, MonadPlus f) => (a -> Bool) -> (a -> a) -> f a -> f a
mapplyWhen p f xs = let (ts, fs) = mpartition p xs
in fmap f ts `mplus` fs
-}
e = Endo
appE = tlapp . e
appWhenE p = tlappWhen p . e
default (Integer)
test :: [Integer]
test = runTList $
appWhenE (/= (0::Integer)) (*(10::Integer)) $ (return (-1)) <> return 2
main = print test
swap (x,y) = (y,x)
-- FIXME move
instance Action (Endo a) a where
act = appEndo
|
FranklinChen/music-score
|
sketch/old/trans/trans.hs
|
Haskell
|
bsd-3-clause
| 17,874
|
{-# LANGUAGE CPP #-}
module System.Console.CmdArgs.Explicit.Type where
import Control.Arrow
import Control.Monad
import Data.Char
import Data.List
import Data.Maybe
#if __GLASGOW_HASKELL__ < 709
import Data.Monoid
#endif
-- | A name, either the name of a flag (@--/foo/@) or the name of a mode.
type Name = String
-- | A help message that goes with either a flag or a mode.
type Help = String
-- | The type of a flag, i.e. @--foo=/TYPE/@.
type FlagHelp = String
---------------------------------------------------------------------
-- UTILITY
-- | Parse a boolean, accepts as True: true yes on enabled 1.
parseBool :: String -> Maybe Bool
parseBool s | ls `elem` true = Just True
| ls `elem` false = Just False
| otherwise = Nothing
where
ls = map toLower s
true = ["true","yes","on","enabled","1"]
false = ["false","no","off","disabled","0"]
---------------------------------------------------------------------
-- GROUPS
-- | A group of items (modes or flags). The items are treated as a list, but the
-- group structure is used when displaying the help message.
data Group a = Group
{groupUnnamed :: [a] -- ^ Normal items.
,groupHidden :: [a] -- ^ Items that are hidden (not displayed in the help message).
,groupNamed :: [(Help, [a])] -- ^ Items that have been grouped, along with a description of each group.
} deriving Show
instance Functor Group where
fmap f (Group a b c) = Group (map f a) (map f b) (map (second $ map f) c)
instance Monoid (Group a) where
mempty = Group [] [] []
mappend (Group x1 x2 x3) (Group y1 y2 y3) = Group (x1++y1) (x2++y2) (x3++y3)
-- | Convert a group into a list.
fromGroup :: Group a -> [a]
fromGroup (Group x y z) = x ++ y ++ concatMap snd z
-- | Convert a list into a group, placing all fields in 'groupUnnamed'.
toGroup :: [a] -> Group a
toGroup x = Group x [] []
---------------------------------------------------------------------
-- TYPES
-- | A mode. Do not use the 'Mode' constructor directly, instead
-- use 'mode' to construct the 'Mode' and then record updates.
-- Each mode has three main features:
--
-- * A list of submodes ('modeGroupModes')
--
-- * A list of flags ('modeGroupFlags')
--
-- * Optionally an unnamed argument ('modeArgs')
--
-- To produce the help information for a mode, either use 'helpText' or 'show'.
data Mode a = Mode
{modeGroupModes :: Group (Mode a) -- ^ The available sub-modes
,modeNames :: [Name] -- ^ The names assigned to this mode (for the root mode, this name is used as the program name)
,modeValue :: a -- ^ Value to start with
,modeCheck :: a -> Either String a -- ^ Check the value reprsented by a mode is correct, after applying all flags
,modeReform :: a -> Maybe [String] -- ^ Given a value, try to generate the input arguments.
,modeExpandAt :: Bool -- ^ Expand @\@@ arguments with 'expandArgsAt', defaults to 'True', only applied if using an 'IO' processing function.
-- Only the root 'Mode's value will be used.
,modeHelp :: Help -- ^ Help text
,modeHelpSuffix :: [String] -- ^ A longer help suffix displayed after a mode
,modeArgs :: ([Arg a], Maybe (Arg a)) -- ^ The unnamed arguments, a series of arguments, followed optionally by one for all remaining slots
,modeGroupFlags :: Group (Flag a) -- ^ Groups of flags
}
-- | Extract the modes from a 'Mode'
modeModes :: Mode a -> [Mode a]
modeModes = fromGroup . modeGroupModes
-- | Extract the flags from a 'Mode'
modeFlags :: Mode a -> [Flag a]
modeFlags = fromGroup . modeGroupFlags
-- | The 'FlagInfo' type has the following meaning:
--
--
-- > FlagReq FlagOpt FlagOptRare/FlagNone
-- > -xfoo -x=foo -x=foo -x -foo
-- > -x foo -x=foo -x foo -x foo
-- > -x=foo -x=foo -x=foo -x=foo
-- > --xx foo --xx=foo --xx foo --xx foo
-- > --xx=foo --xx=foo --xx=foo --xx=foo
data FlagInfo
= FlagReq -- ^ Required argument
| FlagOpt String -- ^ Optional argument
| FlagOptRare String -- ^ Optional argument that requires an = before the value
| FlagNone -- ^ No argument
deriving (Eq,Ord,Show)
-- | Extract the value from inside a 'FlagOpt' or 'FlagOptRare', or raises an error.
fromFlagOpt :: FlagInfo -> String
fromFlagOpt (FlagOpt x) = x
fromFlagOpt (FlagOptRare x) = x
-- | A function to take a string, and a value, and either produce an error message
-- (@Left@), or a modified value (@Right@).
type Update a = String -> a -> Either String a
-- | A flag, consisting of a list of flag names and other information.
data Flag a = Flag
{flagNames :: [Name] -- ^ The names for the flag.
,flagInfo :: FlagInfo -- ^ Information about a flag's arguments.
,flagValue :: Update a -- ^ The way of processing a flag.
,flagType :: FlagHelp -- ^ The type of data for the flag argument, i.e. FILE\/DIR\/EXT
,flagHelp :: Help -- ^ The help message associated with this flag.
}
-- | An unnamed argument. Anything not starting with @-@ is considered an argument,
-- apart from @\"-\"@ which is considered to be the argument @\"-\"@, and any arguments
-- following @\"--\"@. For example:
--
-- > programname arg1 -j - --foo arg3 -- -arg4 --arg5=1 arg6
--
-- Would have the arguments:
--
-- > ["arg1","-","arg3","-arg4","--arg5=1","arg6"]
data Arg a = Arg
{argValue :: Update a -- ^ A way of processing the argument.
,argType :: FlagHelp -- ^ The type of data for the argument, i.e. FILE\/DIR\/EXT
,argRequire :: Bool -- ^ Is at least one of these arguments required, the command line will fail if none are set
}
---------------------------------------------------------------------
-- CHECK FLAGS
-- | Check that a mode is well formed.
checkMode :: Mode a -> Maybe String
checkMode x = msum
[checkNames "modes" $ concatMap modeNames $ modeModes x
,msum $ map checkMode $ modeModes x
,checkGroup $ modeGroupModes x
,checkGroup $ modeGroupFlags x
,checkNames "flag names" $ concatMap flagNames $ modeFlags x]
where
checkGroup :: Group a -> Maybe String
checkGroup x = msum
[check "Empty group name" $ all (not . null . fst) $ groupNamed x
,check "Empty group contents" $ all (not . null . snd) $ groupNamed x]
checkNames :: String -> [Name] -> Maybe String
checkNames msg xs = check "Empty names" (all (not . null) xs) `mplus` do
bad <- listToMaybe $ xs \\ nub xs
let dupe = filter (== bad) xs
return $ "Sanity check failed, multiple " ++ msg ++ ": " ++ unwords (map show dupe)
check :: String -> Bool -> Maybe String
check msg True = Nothing
check msg False = Just msg
---------------------------------------------------------------------
-- REMAP
class Remap m where
remap :: (a -> b) -- ^ Embed a value
-> (b -> (a, a -> b)) -- ^ Extract the mode and give a way of re-embedding
-> m a -> m b
remap2 :: Remap m => (a -> b) -> (b -> a) -> m a -> m b
remap2 f g = remap f (\x -> (g x, f))
instance Remap Mode where
remap f g x = x
{modeGroupModes = fmap (remap f g) $ modeGroupModes x
,modeValue = f $ modeValue x
,modeCheck = \v -> let (a,b) = g v in fmap b $ modeCheck x a
,modeReform = modeReform x . fst . g
,modeArgs = (fmap (remap f g) *** fmap (remap f g)) $ modeArgs x
,modeGroupFlags = fmap (remap f g) $ modeGroupFlags x}
instance Remap Flag where
remap f g x = x{flagValue = remapUpdate f g $ flagValue x}
instance Remap Arg where
remap f g x = x{argValue = remapUpdate f g $ argValue x}
remapUpdate f g upd = \s v -> let (a,b) = g v in fmap b $ upd s a
---------------------------------------------------------------------
-- MODE/MODES CREATORS
-- | Create an empty mode specifying only 'modeValue'. All other fields will usually be populated
-- using record updates.
modeEmpty :: a -> Mode a
modeEmpty x = Mode mempty [] x Right (const Nothing) True "" [] ([],Nothing) mempty
-- | Create a mode with a name, an initial value, some help text, a way of processing arguments
-- and a list of flags.
mode :: Name -> a -> Help -> Arg a -> [Flag a] -> Mode a
mode name value help arg flags = (modeEmpty value){modeNames=[name], modeHelp=help, modeArgs=([],Just arg), modeGroupFlags=toGroup flags}
-- | Create a list of modes, with a program name, an initial value, some help text and the child modes.
modes :: String -> a -> Help -> [Mode a] -> Mode a
modes name value help xs = (modeEmpty value){modeNames=[name], modeHelp=help, modeGroupModes=toGroup xs}
---------------------------------------------------------------------
-- FLAG CREATORS
-- | Create a flag taking no argument value, with a list of flag names, an update function
-- and some help text.
flagNone :: [Name] -> (a -> a) -> Help -> Flag a
flagNone names f help = Flag names FlagNone upd "" help
where upd _ x = Right $ f x
-- | Create a flag taking an optional argument value, with an optional value, a list of flag names,
-- an update function, the type of the argument and some help text.
flagOpt :: String -> [Name] -> Update a -> FlagHelp -> Help -> Flag a
flagOpt def names upd typ help = Flag names (FlagOpt def) upd typ help
-- | Create a flag taking a required argument value, with a list of flag names,
-- an update function, the type of the argument and some help text.
flagReq :: [Name] -> Update a -> FlagHelp -> Help -> Flag a
flagReq names upd typ help = Flag names FlagReq upd typ help
-- | Create an argument flag, with an update function and the type of the argument.
flagArg :: Update a -> FlagHelp -> Arg a
flagArg upd typ = Arg upd typ False
-- | Create a boolean flag, with a list of flag names, an update function and some help text.
flagBool :: [Name] -> (Bool -> a -> a) -> Help -> Flag a
flagBool names f help = Flag names (FlagOptRare "") upd "" help
where
upd s x = case if s == "" then Just True else parseBool s of
Just b -> Right $ f b x
Nothing -> Left "expected boolean value (true/false)"
|
copland/cmdargs
|
System/Console/CmdArgs/Explicit/Type.hs
|
Haskell
|
bsd-3-clause
| 10,204
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
-- We never want to link against terminfo while bootstrapping.
#if defined(BOOTSTRAPPING)
#if defined(WITH_TERMINFO)
#undef WITH_TERMINFO
#endif
#endif
-----------------------------------------------------------------------------
--
-- (c) The University of Glasgow 2004-2009.
--
-- Package management tool
--
-----------------------------------------------------------------------------
module Main (main) where
import Version ( version, targetOS, targetARCH )
import qualified GHC.PackageDb as GhcPkg
import GHC.PackageDb (BinaryStringRep(..))
import qualified Distribution.Simple.PackageIndex as PackageIndex
import qualified Data.Graph as Graph
import qualified Distribution.ModuleName as ModuleName
import Distribution.ModuleName (ModuleName)
import Distribution.InstalledPackageInfo as Cabal
import Distribution.Compat.ReadP hiding (get)
import Distribution.ParseUtils
import Distribution.Package hiding (installedUnitId)
import Distribution.Text
import Distribution.Version
import Distribution.Backpack
import Distribution.Types.UnqualComponentName
import Distribution.Types.MungedPackageName
import Distribution.Types.MungedPackageId
import Distribution.Simple.Utils (fromUTF8BS, toUTF8BS, writeUTF8File, readUTF8File)
import qualified Data.Version as Version
import System.FilePath as FilePath
import qualified System.FilePath.Posix as FilePath.Posix
import System.Directory ( getAppUserDataDirectory, createDirectoryIfMissing,
getModificationTime )
import Text.Printf
import Prelude
import System.Console.GetOpt
import qualified Control.Exception as Exception
import Data.Maybe
import Data.Char ( isSpace, toLower )
import Control.Monad
import System.Directory ( doesDirectoryExist, getDirectoryContents,
doesFileExist, removeFile,
getCurrentDirectory )
import System.Exit ( exitWith, ExitCode(..) )
import System.Environment ( getArgs, getProgName, getEnv )
#if defined(darwin_HOST_OS) || defined(linux_HOST_OS)
import System.Environment ( getExecutablePath )
#endif
import System.IO
import System.IO.Error
import GHC.IO.Exception (IOErrorType(InappropriateType))
import Data.List
import Control.Concurrent
import qualified Data.Foldable as F
import qualified Data.Traversable as F
import qualified Data.Set as Set
import qualified Data.Map as Map
#if defined(mingw32_HOST_OS)
-- mingw32 needs these for getExecDir
import Foreign
import Foreign.C
import System.Directory ( canonicalizePath )
import GHC.ConsoleHandler
#else
import System.Posix hiding (fdToHandle)
#endif
#if defined(GLOB)
import qualified System.Info(os)
#endif
#if defined(WITH_TERMINFO)
import System.Console.Terminfo as Terminfo
#endif
#if defined(mingw32_HOST_OS)
# if defined(i386_HOST_ARCH)
# define WINDOWS_CCONV stdcall
# elif defined(x86_64_HOST_ARCH)
# define WINDOWS_CCONV ccall
# else
# error Unknown mingw32 arch
# endif
#endif
-- | Short-circuit 'any' with a \"monadic predicate\".
anyM :: (Monad m) => (a -> m Bool) -> [a] -> m Bool
anyM _ [] = return False
anyM p (x:xs) = do
b <- p x
if b
then return True
else anyM p xs
-- -----------------------------------------------------------------------------
-- Entry point
main :: IO ()
main = do
args <- getArgs
case getOpt Permute (flags ++ deprecFlags) args of
(cli,_,[]) | FlagHelp `elem` cli -> do
prog <- getProgramName
bye (usageInfo (usageHeader prog) flags)
(cli,_,[]) | FlagVersion `elem` cli ->
bye ourCopyright
(cli,nonopts,[]) ->
case getVerbosity Normal cli of
Right v -> runit v cli nonopts
Left err -> die err
(_,_,errors) -> do
prog <- getProgramName
die (concat errors ++ shortUsage prog)
-- -----------------------------------------------------------------------------
-- Command-line syntax
data Flag
= FlagUser
| FlagGlobal
| FlagHelp
| FlagVersion
| FlagConfig FilePath
| FlagGlobalConfig FilePath
| FlagUserConfig FilePath
| FlagForce
| FlagForceFiles
| FlagMultiInstance
| FlagExpandEnvVars
| FlagExpandPkgroot
| FlagNoExpandPkgroot
| FlagSimpleOutput
| FlagNamesOnly
| FlagIgnoreCase
| FlagNoUserDb
| FlagVerbosity (Maybe String)
| FlagUnitId
deriving Eq
flags :: [OptDescr Flag]
flags = [
Option [] ["user"] (NoArg FlagUser)
"use the current user's package database",
Option [] ["global"] (NoArg FlagGlobal)
"use the global package database",
Option ['f'] ["package-db"] (ReqArg FlagConfig "FILE/DIR")
"use the specified package database",
Option [] ["package-conf"] (ReqArg FlagConfig "FILE/DIR")
"use the specified package database (DEPRECATED)",
Option [] ["global-package-db"] (ReqArg FlagGlobalConfig "DIR")
"location of the global package database",
Option [] ["no-user-package-db"] (NoArg FlagNoUserDb)
"never read the user package database",
Option [] ["user-package-db"] (ReqArg FlagUserConfig "DIR")
"location of the user package database (use instead of default)",
Option [] ["no-user-package-conf"] (NoArg FlagNoUserDb)
"never read the user package database (DEPRECATED)",
Option [] ["force"] (NoArg FlagForce)
"ignore missing dependencies, directories, and libraries",
Option [] ["force-files"] (NoArg FlagForceFiles)
"ignore missing directories and libraries only",
Option [] ["enable-multi-instance"] (NoArg FlagMultiInstance)
"allow registering multiple instances of the same package version",
Option [] ["expand-env-vars"] (NoArg FlagExpandEnvVars)
"expand environment variables (${name}-style) in input package descriptions",
Option [] ["expand-pkgroot"] (NoArg FlagExpandPkgroot)
"expand ${pkgroot}-relative paths to absolute in output package descriptions",
Option [] ["no-expand-pkgroot"] (NoArg FlagNoExpandPkgroot)
"preserve ${pkgroot}-relative paths in output package descriptions",
Option ['?'] ["help"] (NoArg FlagHelp)
"display this help and exit",
Option ['V'] ["version"] (NoArg FlagVersion)
"output version information and exit",
Option [] ["simple-output"] (NoArg FlagSimpleOutput)
"print output in easy-to-parse format for some commands",
Option [] ["names-only"] (NoArg FlagNamesOnly)
"only print package names, not versions; can only be used with list --simple-output",
Option [] ["ignore-case"] (NoArg FlagIgnoreCase)
"ignore case for substring matching",
Option [] ["ipid", "unit-id"] (NoArg FlagUnitId)
"interpret package arguments as unit IDs (e.g. installed package IDs)",
Option ['v'] ["verbose"] (OptArg FlagVerbosity "Verbosity")
"verbosity level (0-2, default 1)"
]
data Verbosity = Silent | Normal | Verbose
deriving (Show, Eq, Ord)
getVerbosity :: Verbosity -> [Flag] -> Either String Verbosity
getVerbosity v [] = Right v
getVerbosity _ (FlagVerbosity Nothing : fs) = getVerbosity Verbose fs
getVerbosity _ (FlagVerbosity (Just "0") : fs) = getVerbosity Silent fs
getVerbosity _ (FlagVerbosity (Just "1") : fs) = getVerbosity Normal fs
getVerbosity _ (FlagVerbosity (Just "2") : fs) = getVerbosity Verbose fs
getVerbosity _ (FlagVerbosity v : _) = Left ("Bad verbosity: " ++ show v)
getVerbosity v (_ : fs) = getVerbosity v fs
deprecFlags :: [OptDescr Flag]
deprecFlags = [
-- put deprecated flags here
]
ourCopyright :: String
ourCopyright = "GHC package manager version " ++ Version.version ++ "\n"
shortUsage :: String -> String
shortUsage prog = "For usage information see '" ++ prog ++ " --help'."
usageHeader :: String -> String
usageHeader prog = substProg prog $
"Usage:\n" ++
" $p init {path}\n" ++
" Create and initialise a package database at the location {path}.\n" ++
" Packages can be registered in the new database using the register\n" ++
" command with --package-db={path}. To use the new database with GHC,\n" ++
" use GHC's -package-db flag.\n" ++
"\n" ++
" $p register {filename | -}\n" ++
" Register the package using the specified installed package\n" ++
" description. The syntax for the latter is given in the $p\n" ++
" documentation. The input file should be encoded in UTF-8.\n" ++
"\n" ++
" $p update {filename | -}\n" ++
" Register the package, overwriting any other package with the\n" ++
" same name. The input file should be encoded in UTF-8.\n" ++
"\n" ++
" $p unregister [pkg-id] \n" ++
" Unregister the specified packages in the order given.\n" ++
"\n" ++
" $p expose {pkg-id}\n" ++
" Expose the specified package.\n" ++
"\n" ++
" $p hide {pkg-id}\n" ++
" Hide the specified package.\n" ++
"\n" ++
" $p trust {pkg-id}\n" ++
" Trust the specified package.\n" ++
"\n" ++
" $p distrust {pkg-id}\n" ++
" Distrust the specified package.\n" ++
"\n" ++
" $p list [pkg]\n" ++
" List registered packages in the global database, and also the\n" ++
" user database if --user is given. If a package name is given\n" ++
" all the registered versions will be listed in ascending order.\n" ++
" Accepts the --simple-output flag.\n" ++
"\n" ++
" $p dot\n" ++
" Generate a graph of the package dependencies in a form suitable\n" ++
" for input for the graphviz tools. For example, to generate a PDF\n" ++
" of the dependency graph: ghc-pkg dot | tred | dot -Tpdf >pkgs.pdf\n" ++
"\n" ++
" $p find-module {module}\n" ++
" List registered packages exposing module {module} in the global\n" ++
" database, and also the user database if --user is given.\n" ++
" All the registered versions will be listed in ascending order.\n" ++
" Accepts the --simple-output flag.\n" ++
"\n" ++
" $p latest {pkg-id}\n" ++
" Prints the highest registered version of a package.\n" ++
"\n" ++
" $p check\n" ++
" Check the consistency of package dependencies and list broken packages.\n" ++
" Accepts the --simple-output flag.\n" ++
"\n" ++
" $p describe {pkg}\n" ++
" Give the registered description for the specified package. The\n" ++
" description is returned in precisely the syntax required by $p\n" ++
" register.\n" ++
"\n" ++
" $p field {pkg} {field}\n" ++
" Extract the specified field of the package description for the\n" ++
" specified package. Accepts comma-separated multiple fields.\n" ++
"\n" ++
" $p dump\n" ++
" Dump the registered description for every package. This is like\n" ++
" \"ghc-pkg describe '*'\", except that it is intended to be used\n" ++
" by tools that parse the results, rather than humans. The output is\n" ++
" always encoded in UTF-8, regardless of the current locale.\n" ++
"\n" ++
" $p recache\n" ++
" Regenerate the package database cache. This command should only be\n" ++
" necessary if you added a package to the database by dropping a file\n" ++
" into the database directory manually. By default, the global DB\n" ++
" is recached; to recache a different DB use --user or --package-db\n" ++
" as appropriate.\n" ++
"\n" ++
" Substring matching is supported for {module} in find-module and\n" ++
" for {pkg} in list, describe, and field, where a '*' indicates\n" ++
" open substring ends (prefix*, *suffix, *infix*). Use --ipid to\n" ++
" match against the installed package ID instead.\n" ++
"\n" ++
" When asked to modify a database (register, unregister, update,\n"++
" hide, expose, and also check), ghc-pkg modifies the global database by\n"++
" default. Specifying --user causes it to act on the user database,\n"++
" or --package-db can be used to act on another database\n"++
" entirely. When multiple of these options are given, the rightmost\n"++
" one is used as the database to act upon.\n"++
"\n"++
" Commands that query the package database (list, tree, latest, describe,\n"++
" field) operate on the list of databases specified by the flags\n"++
" --user, --global, and --package-db. If none of these flags are\n"++
" given, the default is --global --user.\n"++
"\n" ++
" The following optional flags are also accepted:\n"
substProg :: String -> String -> String
substProg _ [] = []
substProg prog ('$':'p':xs) = prog ++ substProg prog xs
substProg prog (c:xs) = c : substProg prog xs
-- -----------------------------------------------------------------------------
-- Do the business
data Force = NoForce | ForceFiles | ForceAll | CannotForce
deriving (Eq,Ord)
-- | Enum flag representing argument type
data AsPackageArg
= AsUnitId
| AsDefault
-- | Represents how a package may be specified by a user on the command line.
data PackageArg
-- | A package identifier foo-0.1, or a glob foo-*
= Id GlobPackageIdentifier
-- | An installed package ID foo-0.1-HASH. This is guaranteed to uniquely
-- match a single entry in the package database.
| IUId UnitId
-- | A glob against the package name. The first string is the literal
-- glob, the second is a function which returns @True@ if the argument
-- matches.
| Substring String (String->Bool)
runit :: Verbosity -> [Flag] -> [String] -> IO ()
runit verbosity cli nonopts = do
installSignalHandlers -- catch ^C and clean up
when (verbosity >= Verbose)
(putStr ourCopyright)
prog <- getProgramName
let
force
| FlagForce `elem` cli = ForceAll
| FlagForceFiles `elem` cli = ForceFiles
| otherwise = NoForce
as_arg | FlagUnitId `elem` cli = AsUnitId
| otherwise = AsDefault
multi_instance = FlagMultiInstance `elem` cli
expand_env_vars= FlagExpandEnvVars `elem` cli
mexpand_pkgroot= foldl' accumExpandPkgroot Nothing cli
where accumExpandPkgroot _ FlagExpandPkgroot = Just True
accumExpandPkgroot _ FlagNoExpandPkgroot = Just False
accumExpandPkgroot x _ = x
splitFields fields = unfoldr splitComma (',':fields)
where splitComma "" = Nothing
splitComma fs = Just $ break (==',') (tail fs)
-- | Parses a glob into a predicate which tests if a string matches
-- the glob. Returns Nothing if the string in question is not a glob.
-- At the moment, we only support globs at the beginning and/or end of
-- strings. This function respects case sensitivity.
--
-- >>> fromJust (substringCheck "*") "anything"
-- True
--
-- >>> fromJust (substringCheck "string") "string"
-- True
--
-- >>> fromJust (substringCheck "*bar") "foobar"
-- True
--
-- >>> fromJust (substringCheck "foo*") "foobar"
-- True
--
-- >>> fromJust (substringCheck "*ooba*") "foobar"
-- True
--
-- >>> fromJust (substringCheck "f*bar") "foobar"
-- False
substringCheck :: String -> Maybe (String -> Bool)
substringCheck "" = Nothing
substringCheck "*" = Just (const True)
substringCheck [_] = Nothing
substringCheck (h:t) =
case (h, init t, last t) of
('*',s,'*') -> Just (isInfixOf (f s) . f)
('*',_, _ ) -> Just (isSuffixOf (f t) . f)
( _ ,s,'*') -> Just (isPrefixOf (f (h:s)) . f)
_ -> Nothing
where f | FlagIgnoreCase `elem` cli = map toLower
| otherwise = id
#if defined(GLOB)
glob x | System.Info.os=="mingw32" = do
-- glob echoes its argument, after win32 filename globbing
(_,o,_,_) <- runInteractiveCommand ("glob "++x)
txt <- hGetContents o
return (read txt)
glob x | otherwise = return [x]
#endif
--
-- first, parse the command
case nonopts of
#if defined(GLOB)
-- dummy command to demonstrate usage and permit testing
-- without messing things up; use glob to selectively enable
-- windows filename globbing for file parameters
-- register, update, FlagGlobalConfig, FlagConfig; others?
["glob", filename] -> do
print filename
glob filename >>= print
#endif
["init", filename] ->
initPackageDB filename verbosity cli
["register", filename] ->
registerPackage filename verbosity cli
multi_instance
expand_env_vars False force
["update", filename] ->
registerPackage filename verbosity cli
multi_instance
expand_env_vars True force
"unregister" : pkgarg_strs@(_:_) -> do
forM_ pkgarg_strs $ \pkgarg_str -> do
pkgarg <- readPackageArg as_arg pkgarg_str
unregisterPackage pkgarg verbosity cli force
["expose", pkgarg_str] -> do
pkgarg <- readPackageArg as_arg pkgarg_str
exposePackage pkgarg verbosity cli force
["hide", pkgarg_str] -> do
pkgarg <- readPackageArg as_arg pkgarg_str
hidePackage pkgarg verbosity cli force
["trust", pkgarg_str] -> do
pkgarg <- readPackageArg as_arg pkgarg_str
trustPackage pkgarg verbosity cli force
["distrust", pkgarg_str] -> do
pkgarg <- readPackageArg as_arg pkgarg_str
distrustPackage pkgarg verbosity cli force
["list"] -> do
listPackages verbosity cli Nothing Nothing
["list", pkgarg_str] ->
case substringCheck pkgarg_str of
Nothing -> do pkgarg <- readPackageArg as_arg pkgarg_str
listPackages verbosity cli (Just pkgarg) Nothing
Just m -> listPackages verbosity cli
(Just (Substring pkgarg_str m)) Nothing
["dot"] -> do
showPackageDot verbosity cli
["find-module", mod_name] -> do
let match = maybe (==mod_name) id (substringCheck mod_name)
listPackages verbosity cli Nothing (Just match)
["latest", pkgid_str] -> do
pkgid <- readGlobPkgId pkgid_str
latestPackage verbosity cli pkgid
["describe", pkgid_str] -> do
pkgarg <- case substringCheck pkgid_str of
Nothing -> readPackageArg as_arg pkgid_str
Just m -> return (Substring pkgid_str m)
describePackage verbosity cli pkgarg (fromMaybe False mexpand_pkgroot)
["field", pkgid_str, fields] -> do
pkgarg <- case substringCheck pkgid_str of
Nothing -> readPackageArg as_arg pkgid_str
Just m -> return (Substring pkgid_str m)
describeField verbosity cli pkgarg
(splitFields fields) (fromMaybe True mexpand_pkgroot)
["check"] -> do
checkConsistency verbosity cli
["dump"] -> do
dumpPackages verbosity cli (fromMaybe False mexpand_pkgroot)
["recache"] -> do
recache verbosity cli
[] -> do
die ("missing command\n" ++ shortUsage prog)
(_cmd:_) -> do
die ("command-line syntax error\n" ++ shortUsage prog)
parseCheck :: ReadP a a -> String -> String -> IO a
parseCheck parser str what =
case [ x | (x,ys) <- readP_to_S parser str, all isSpace ys ] of
[x] -> return x
_ -> die ("cannot parse \'" ++ str ++ "\' as a " ++ what)
-- | Either an exact 'PackageIdentifier', or a glob for all packages
-- matching 'PackageName'.
data GlobPackageIdentifier
= ExactPackageIdentifier MungedPackageId
| GlobPackageIdentifier MungedPackageName
displayGlobPkgId :: GlobPackageIdentifier -> String
displayGlobPkgId (ExactPackageIdentifier pid) = display pid
displayGlobPkgId (GlobPackageIdentifier pn) = display pn ++ "-*"
readGlobPkgId :: String -> IO GlobPackageIdentifier
readGlobPkgId str = parseCheck parseGlobPackageId str "package identifier"
parseGlobPackageId :: ReadP r GlobPackageIdentifier
parseGlobPackageId =
fmap ExactPackageIdentifier parse
+++
(do n <- parse
_ <- string "-*"
return (GlobPackageIdentifier n))
readPackageArg :: AsPackageArg -> String -> IO PackageArg
readPackageArg AsUnitId str =
parseCheck (IUId `fmap` parse) str "installed package id"
readPackageArg AsDefault str = Id `fmap` readGlobPkgId str
-- -----------------------------------------------------------------------------
-- Package databases
-- Some commands operate on a single database:
-- register, unregister, expose, hide, trust, distrust
-- however these commands also check the union of the available databases
-- in order to check consistency. For example, register will check that
-- dependencies exist before registering a package.
--
-- Some commands operate on multiple databases, with overlapping semantics:
-- list, describe, field
data PackageDB (mode :: GhcPkg.DbMode)
= PackageDB {
location, locationAbsolute :: !FilePath,
-- We need both possibly-relative and definitely-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.
packageDbLock :: !(GhcPkg.DbOpenMode mode GhcPkg.PackageDbLock),
-- If package db is open in read write mode, we keep its lock around for
-- transactional updates.
packages :: [InstalledPackageInfo]
}
type PackageDBStack = [PackageDB 'GhcPkg.DbReadOnly]
-- A stack of package databases. Convention: head is the topmost
-- in the stack.
-- | Selector for picking the right package DB to modify as 'register' and
-- 'recache' operate on the database on top of the stack, whereas 'modify'
-- changes the first database that contains a specific package.
data DbModifySelector = TopOne | ContainsPkg PackageArg
allPackagesInStack :: PackageDBStack -> [InstalledPackageInfo]
allPackagesInStack = concatMap packages
getPkgDatabases :: Verbosity
-> GhcPkg.DbOpenMode mode DbModifySelector
-> 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.
GhcPkg.DbOpenMode mode (PackageDB mode),
-- 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 mode use_user use_cache expand_vars my_flags = do
-- first we determine the location of the global package config. On Windows,
-- this is found relative to the ghc-pkg.exe binary, whereas on Unix the
-- location is passed to the binary using the --global-package-db flag by the
-- wrapper script.
let err_msg = "missing --global-package-db option, location of global package database unknown\n"
global_conf <-
case [ f | FlagGlobalConfig f <- my_flags ] of
[] -> do mb_dir <- getLibDir
case mb_dir of
Nothing -> die err_msg
Just dir -> do
r <- lookForPackageDBIn dir
case r of
Nothing -> die ("Can't find package database in " ++ dir)
Just path -> return path
fs -> return (last fs)
-- The value of the $topdir variable used in some package descriptions
-- Note that the way we calculate this is slightly different to how it
-- is done in ghc itself. We rely on the convention that the global
-- package db lives in ghc's libdir.
top_dir <- absolutePath (takeDirectory global_conf)
let no_user_db = FlagNoUserDb `elem` my_flags
-- get the location of the user package database, and create it if necessary
-- getAppUserDataDirectory can fail (e.g. if $HOME isn't set)
e_appdir <- tryIO $ getAppUserDataDirectory "ghc"
mb_user_conf <-
case [ f | FlagUserConfig f <- my_flags ] of
_ | no_user_db -> return Nothing
[] -> case e_appdir of
Left _ -> return Nothing
Right appdir -> do
let subdir = targetARCH ++ '-':targetOS ++ '-':Version.version
dir = appdir </> subdir
r <- lookForPackageDBIn dir
case r of
Nothing -> return (Just (dir </> "package.conf.d", False))
Just f -> return (Just (f, True))
fs -> return (Just (last fs, True))
-- If the user database exists, and for "use_user" commands (which includes
-- "ghc-pkg check" and all commands that modify the db) we will attempt to
-- use the user db.
let sys_databases
| Just (user_conf,user_exists) <- mb_user_conf,
use_user || user_exists = [user_conf, global_conf]
| otherwise = [global_conf]
e_pkg_path <- tryIO (System.Environment.getEnv "GHC_PACKAGE_PATH")
let env_stack =
case e_pkg_path of
Left _ -> sys_databases
Right path
| not (null path) && isSearchPathSeparator (last path)
-> splitSearchPath (init path) ++ sys_databases
| otherwise
-> splitSearchPath path
-- The "global" database is always the one at the bottom of the stack.
-- This is the database we modify by default.
virt_global_conf = last env_stack
let db_flags = [ f | Just f <- map is_db_flag my_flags ]
where is_db_flag FlagUser
| Just (user_conf, _user_exists) <- mb_user_conf
= Just user_conf
is_db_flag FlagGlobal = Just virt_global_conf
is_db_flag (FlagConfig f) = Just f
is_db_flag _ = Nothing
let flag_db_names | null db_flags = env_stack
| otherwise = reverse (nub db_flags)
-- For a "modify" command, treat all the databases as
-- a stack, where we are modifying the top one, but it
-- can refer to packages in databases further down the
-- stack.
-- -f flags on the command line add to the database
-- stack, unless any of them are present in the stack
-- already.
let final_stack = filter (`notElem` env_stack)
[ f | FlagConfig f <- reverse my_flags ]
++ env_stack
top_db = if null db_flags
then virt_global_conf
else last db_flags
(db_stack, db_to_operate_on) <- getDatabases top_dir mb_user_conf
flag_db_names final_stack top_db
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))
F.forM_ db_to_operate_on $ \db ->
infoLn ("modifying: " ++ (location db))
infoLn ("flag db stack: " ++ show (map location flag_db_stack))
return (db_stack, db_to_operate_on, flag_db_stack)
where
getDatabases top_dir mb_user_conf flag_db_names
final_stack top_db = case mode of
-- When we open in read only mode, we simply read all of the databases/
GhcPkg.DbOpenReadOnly -> do
db_stack <- mapM readDatabase final_stack
return (db_stack, GhcPkg.DbOpenReadOnly)
-- The only package db we open in read write mode is the one on the top of
-- the stack.
GhcPkg.DbOpenReadWrite TopOne -> do
(db_stack, mto_modify) <- stateSequence Nothing
[ \case
to_modify@(Just _) -> (, to_modify) <$> readDatabase db_path
Nothing -> if db_path /= top_db
then (, Nothing) <$> readDatabase db_path
else do
db <- readParseDatabase verbosity mb_user_conf
mode use_cache db_path
`Exception.catch` couldntOpenDbForModification db_path
let ro_db = db { packageDbLock = GhcPkg.DbOpenReadOnly }
return (ro_db, Just db)
| db_path <- final_stack ]
to_modify <- case mto_modify of
Just db -> return db
Nothing -> die "no database selected for modification"
return (db_stack, GhcPkg.DbOpenReadWrite to_modify)
-- The package db we open in read write mode is the first one included in
-- flag_db_names that contains specified package. Therefore we need to
-- open each one in read/write mode first and decide whether it's for
-- modification based on its contents.
GhcPkg.DbOpenReadWrite (ContainsPkg pkgarg) -> do
(db_stack, mto_modify) <- stateSequence Nothing
[ \case
to_modify@(Just _) -> (, to_modify) <$> readDatabase db_path
Nothing -> if db_path `notElem` flag_db_names
then (, Nothing) <$> readDatabase db_path
else do
let hasPkg :: PackageDB mode -> Bool
hasPkg = not . null . findPackage pkgarg . packages
openRo (e::IOError) = do
db <- readDatabase db_path
if hasPkg db
then couldntOpenDbForModification db_path e
else return (db, Nothing)
-- If we fail to open the database in read/write mode, we need
-- to check if it's for modification first before throwing an
-- error, so we attempt to open it in read only mode.
Exception.handle openRo $ do
db <- readParseDatabase verbosity mb_user_conf
mode use_cache db_path
let ro_db = db { packageDbLock = GhcPkg.DbOpenReadOnly }
if hasPkg db
then return (ro_db, Just db)
else do
-- If the database is not for modification after all,
-- drop the write lock as we are already finished with
-- the database.
case packageDbLock db of
GhcPkg.DbOpenReadWrite lock ->
GhcPkg.unlockPackageDb lock
return (ro_db, Nothing)
| db_path <- final_stack ]
to_modify <- case mto_modify of
Just db -> return db
Nothing -> cannotFindPackage pkgarg Nothing
return (db_stack, GhcPkg.DbOpenReadWrite to_modify)
where
couldntOpenDbForModification :: FilePath -> IOError -> IO a
couldntOpenDbForModification db_path e = die $ "Couldn't open database "
++ db_path ++ " for modification: " ++ show e
-- Parse package db in read-only mode.
readDatabase :: FilePath -> IO (PackageDB 'GhcPkg.DbReadOnly)
readDatabase db_path = do
db <- readParseDatabase verbosity mb_user_conf
GhcPkg.DbOpenReadOnly use_cache db_path
if expand_vars
then return $ mungePackageDBPaths top_dir db
else return db
stateSequence :: Monad m => s -> [s -> m (a, s)] -> m ([a], s)
stateSequence s [] = return ([], s)
stateSequence s (m:ms) = do
(a, s') <- m s
(as, s'') <- stateSequence s' ms
return (a : as, s'')
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 :: forall mode t. Verbosity
-> Maybe (FilePath,Bool)
-> GhcPkg.DbOpenMode mode t
-> Bool -- use cache
-> FilePath
-> IO (PackageDB mode)
readParseDatabase verbosity mb_user_conf mode use_cache path
-- the user database (only) is allowed to be non-existent
| Just (user_conf,False) <- mb_user_conf, path == user_conf
= do lock <- F.forM mode $ \_ -> do
createDirectoryIfMissing True path
GhcPkg.lockPackageDb cache
mkPackageDB [] lock
| otherwise
= do e <- tryIO $ getDirectoryContents path
case e of
Left err
| ioeGetErrorType err == InappropriateType -> do
-- We provide a limited degree of backwards compatibility for
-- old single-file style db:
mdb <- tryReadParseOldFileStyleDatabase verbosity
mb_user_conf mode use_cache path
case mdb of
Just db -> return db
Nothing ->
die $ "ghc no longer supports single-file style package "
++ "databases (" ++ path ++ ") use 'ghc-pkg init'"
++ "to create the database with the correct format."
| otherwise -> ioError err
Right fs
| not use_cache -> ignore_cache (const $ return ())
| otherwise -> do
e_tcache <- tryIO $ getModificationTime cache
case e_tcache of
Left ex -> do
whenReportCacheErrors $
if isDoesNotExistError ex
then
-- It's fine if the cache is not there as long as the
-- database is empty.
when (not $ null confs) $ do
warn ("WARNING: cache does not exist: " ++ cache)
warn ("ghc will fail to read this package db. " ++
recacheAdvice)
else do
warn ("WARNING: cache cannot be read: " ++ show ex)
warn "ghc will fail to read this package db."
ignore_cache (const $ return ())
Right tcache -> do
when (verbosity >= Verbose) $ do
warn ("Timestamp " ++ show tcache ++ " for " ++ cache)
-- If any of the .conf files is newer than package.cache, we
-- assume that cache is out of date.
cache_outdated <- (`anyM` confs) $ \conf ->
(tcache <) <$> getModificationTime conf
if not cache_outdated
then do
when (verbosity > Normal) $
infoLn ("using cache: " ++ cache)
GhcPkg.readPackageDbForGhcPkg cache mode
>>= uncurry mkPackageDB
else do
whenReportCacheErrors $ do
warn ("WARNING: cache is out of date: " ++ cache)
warn ("ghc will see an old view of this " ++
"package db. " ++ recacheAdvice)
ignore_cache $ \file -> do
when (verbosity >= Verbose) $ do
tFile <- getModificationTime file
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)
where
confs = map (path </>) $ filter (".conf" `isSuffixOf`) fs
ignore_cache :: (FilePath -> IO ()) -> IO (PackageDB mode)
ignore_cache checkTime = do
-- If we're opening for modification, we need to acquire a
-- lock even if we don't open the cache now, because we are
-- going to modify it later.
lock <- F.mapM (const $ GhcPkg.lockPackageDb cache) mode
let doFile f = do checkTime f
parseSingletonPackageConf verbosity f
pkgs <- mapM doFile confs
mkPackageDB pkgs lock
-- We normally report cache errors for read-only commands,
-- since modify commands will usually fix the cache.
whenReportCacheErrors = when $ verbosity > Normal
|| verbosity >= Normal && GhcPkg.isDbOpenReadMode mode
where
cache = path </> cachefilename
recacheAdvice
| Just (user_conf, True) <- mb_user_conf, path == user_conf
= "Use 'ghc-pkg recache --user' to fix."
| otherwise
= "Use 'ghc-pkg recache' to fix."
mkPackageDB :: [InstalledPackageInfo]
-> GhcPkg.DbOpenMode mode GhcPkg.PackageDbLock
-> IO (PackageDB mode)
mkPackageDB pkgs lock = do
path_abs <- absolutePath path
return $ PackageDB {
location = path,
locationAbsolute = path_abs,
packageDbLock = lock,
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 mode -> PackageDB mode
mungePackageDBPaths top_dir db@PackageDB { packages = pkgs } =
db { packages = map (mungePackagePaths top_dir pkgroot) pkgs }
where
pkgroot = takeDirectory $ dropTrailingPathSeparator (locationAbsolute db)
-- It so happens that for both styles of package db ("package.conf"
-- files and "package.conf.d" dirs) the pkgroot is the parent directory
-- ${pkgroot}/package.conf or ${pkgroot}/package.conf.d/
-- TODO: This code is duplicated in compiler/main/Packages.hs
mungePackagePaths :: FilePath -> FilePath
-> InstalledPackageInfo -> InstalledPackageInfo
-- Perform path/URL variable substitution as per the Cabal ${pkgroot} spec
-- (http://www.haskell.org/pipermail/libraries/2009-May/011772.html)
-- Paths/URLs can be relative to ${pkgroot} or ${pkgrooturl}.
-- The "pkgroot" is the directory containing the package database.
--
-- Also perform a similar substitution for the older GHC-specific
-- "$topdir" variable. The "topdir" is the location of the ghc
-- installation (obtained from the -B option).
mungePackagePaths top_dir pkgroot pkg =
pkg {
importDirs = munge_paths (importDirs pkg),
includeDirs = munge_paths (includeDirs pkg),
libraryDirs = munge_paths (libraryDirs pkg),
libraryDynDirs = munge_paths (libraryDynDirs pkg),
frameworkDirs = munge_paths (frameworkDirs pkg),
haddockInterfaces = munge_paths (haddockInterfaces pkg),
-- haddock-html is allowed to be either a URL or a file
haddockHTMLs = munge_paths (munge_urls (haddockHTMLs pkg))
}
where
munge_paths = map munge_path
munge_urls = map munge_url
munge_path p
| Just p' <- stripVarPrefix "${pkgroot}" p = pkgroot ++ p'
| Just p' <- stripVarPrefix "$topdir" p = top_dir ++ p'
| otherwise = p
munge_url p
| Just p' <- stripVarPrefix "${pkgrooturl}" p = toUrlPath pkgroot p'
| Just p' <- stripVarPrefix "$httptopdir" p = toUrlPath top_dir p'
| otherwise = p
toUrlPath r p = "file:///"
-- URLs always use posix style '/' separators:
++ FilePath.Posix.joinPath
(r : -- We need to drop a leading "/" or "\\"
-- if there is one:
dropWhile (all isPathSeparator)
(FilePath.splitDirectories p))
-- We could drop the separator here, and then use </> above. However,
-- by leaving it in and using ++ we keep the same path separator
-- rather than letting FilePath change it to use \ as the separator
stripVarPrefix var path = case stripPrefix var path of
Just [] -> Just []
Just cs@(c : _) | isPathSeparator c -> Just cs
_ -> Nothing
-- -----------------------------------------------------------------------------
-- Workaround for old single-file style package dbs
-- Single-file style package dbs have been deprecated for some time, but
-- it turns out that Cabal was using them in one place. So this code is for a
-- workaround to allow older Cabal versions to use this newer ghc.
-- We check if the file db contains just "[]" and if so, we look for a new
-- dir-style db in path.d/, ie in a dir next to the given file.
-- We cannot just replace the file with a new dir style since Cabal still
-- assumes it's a file and tries to overwrite with 'writeFile'.
-- ghc itself also cooperates in this workaround
tryReadParseOldFileStyleDatabase :: Verbosity -> Maybe (FilePath, Bool)
-> GhcPkg.DbOpenMode mode t -> Bool -> FilePath
-> IO (Maybe (PackageDB mode))
tryReadParseOldFileStyleDatabase verbosity mb_user_conf
mode use_cache path = do
-- assumes we've already established that path exists and is not a dir
content <- readFile path `catchIO` \_ -> return ""
if take 2 content == "[]"
then do
path_abs <- absolutePath path
let path_dir = adjustOldDatabasePath path
warn $ "Warning: ignoring old file-style db and trying " ++ path_dir
direxists <- doesDirectoryExist path_dir
if direxists
then do
db <- readParseDatabase verbosity mb_user_conf mode use_cache path_dir
-- but pretend it was at the original location
return $ Just db {
location = path,
locationAbsolute = path_abs
}
else do
lock <- F.forM mode $ \_ -> do
createDirectoryIfMissing True path_dir
GhcPkg.lockPackageDb $ path_dir </> cachefilename
return $ Just PackageDB {
location = path,
locationAbsolute = path_abs,
packageDbLock = lock,
packages = []
}
-- if the path is not a file, or is not an empty db then we fail
else return Nothing
adjustOldFileStylePackageDB :: PackageDB mode -> IO (PackageDB mode)
adjustOldFileStylePackageDB db = do
-- assumes we have not yet established if it's an old style or not
mcontent <- liftM Just (readFile (location db)) `catchIO` \_ -> return Nothing
case fmap (take 2) mcontent of
-- it is an old style and empty db, so look for a dir kind in location.d/
Just "[]" -> return db {
location = adjustOldDatabasePath $ location db,
locationAbsolute = adjustOldDatabasePath $ locationAbsolute db
}
-- it is old style but not empty, we have to bail
Just _ -> die $ "ghc no longer supports single-file style package "
++ "databases (" ++ location db ++ ") use 'ghc-pkg init'"
++ "to create the database with the correct format."
-- probably not old style, carry on as normal
Nothing -> return db
adjustOldDatabasePath :: FilePath -> FilePath
adjustOldDatabasePath = (<.> "d")
-- -----------------------------------------------------------------------------
-- 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
createDirectoryIfMissing True filename
lock <- GhcPkg.lockPackageDb $ filename </> cachefilename
filename_abs <- absolutePath filename
changeDB verbosity [] PackageDB {
location = filename,
locationAbsolute = filename_abs,
packageDbLock = GhcPkg.DbOpenReadWrite lock,
packages = []
}
-- -----------------------------------------------------------------------------
-- Registering
registerPackage :: FilePath
-> Verbosity
-> [Flag]
-> Bool -- multi_instance
-> Bool -- expand_env_vars
-> Bool -- update
-> Force
-> IO ()
registerPackage input verbosity my_flags multi_instance
expand_env_vars update force = do
(db_stack, GhcPkg.DbOpenReadWrite db_to_operate_on, _flag_dbs) <-
getPkgDatabases verbosity (GhcPkg.DbOpenReadWrite TopOne)
True{-use user-} True{-use cache-} False{-expand vars-} my_flags
let to_modify = location db_to_operate_on
s <-
case input of
"-" -> do
when (verbosity >= Normal) $
info "Reading package info from stdin ... "
-- fix the encoding to UTF-8, since this is an interchange format
hSetEncoding stdin utf8
getContents
f -> do
when (verbosity >= Normal) $
info ("Reading package info from " ++ show f ++ " ... ")
readUTF8File f
expanded <- if expand_env_vars then expandEnvVars s force
else return s
(pkg, ws) <- parsePackageInfo expanded
when (verbosity >= Normal) $
infoLn "done."
-- report any warnings from the parse phase
_ <- reportValidateErrors verbosity [] ws
(display (mungedId pkg) ++ ": Warning: ") Nothing
-- validate the expanded pkg, but register the unexpanded
pkgroot <- absolutePath (takeDirectory to_modify)
let top_dir = takeDirectory (location (last db_stack))
pkg_expanded = mungePackagePaths top_dir pkgroot pkg
let truncated_stack = dropWhile ((/= to_modify).location) db_stack
-- truncate the stack for validation, because we don't allow
-- packages lower in the stack to refer to those higher up.
validatePackageConfig pkg_expanded verbosity truncated_stack
multi_instance update force
let
-- In the normal mode, we only allow one version of each package, so we
-- remove all instances with the same source package id as the one we're
-- adding. In the multi instance mode we don't do that, thus allowing
-- multiple instances with the same source package id.
removes = [ RemovePackage p
| not multi_instance,
p <- packages db_to_operate_on,
mungedId p == mungedId pkg,
-- Only remove things that were instantiated the same way!
instantiatedWith p == instantiatedWith pkg ]
--
changeDB verbosity (removes ++ [AddPackage pkg]) db_to_operate_on
parsePackageInfo
:: String
-> IO (InstalledPackageInfo, [ValidateWarning])
parsePackageInfo str =
case parseInstalledPackageInfo str of
ParseOk warnings ok -> return (mungePackageInfo ok, ws)
where
ws = [ msg | PWarning msg <- warnings
, not ("Unrecognized field pkgroot" `isPrefixOf` msg) ]
ParseFailed err -> case locatedErrorMsg err of
(Nothing, s) -> die s
(Just l, s) -> die (show l ++ ": " ++ s)
mungePackageInfo :: InstalledPackageInfo -> InstalledPackageInfo
mungePackageInfo ipi = ipi
-- -----------------------------------------------------------------------------
-- Making changes to a package database
data DBOp = RemovePackage InstalledPackageInfo
| AddPackage InstalledPackageInfo
| ModifyPackage InstalledPackageInfo
changeDB :: Verbosity -> [DBOp] -> PackageDB 'GhcPkg.DbReadWrite -> IO ()
changeDB verbosity cmds db = do
let db' = updateInternalDB db cmds
db'' <- adjustOldFileStylePackageDB db'
createDirectoryIfMissing True (location db'')
changeDBDir verbosity cmds db''
updateInternalDB :: PackageDB 'GhcPkg.DbReadWrite
-> [DBOp] -> PackageDB 'GhcPkg.DbReadWrite
updateInternalDB db cmds = db{ packages = foldl do_cmd (packages db) cmds }
where
do_cmd pkgs (RemovePackage p) =
filter ((/= installedUnitId p) . installedUnitId) pkgs
do_cmd pkgs (AddPackage p) = p : pkgs
do_cmd pkgs (ModifyPackage p) =
do_cmd (do_cmd pkgs (RemovePackage p)) (AddPackage p)
changeDBDir :: Verbosity -> [DBOp] -> PackageDB 'GhcPkg.DbReadWrite -> IO ()
changeDBDir verbosity cmds db = do
mapM_ do_cmd cmds
updateDBCache verbosity db
where
do_cmd (RemovePackage p) = do
let file = location db </> display (installedUnitId p) <.> "conf"
when (verbosity > Normal) $ infoLn ("removing " ++ file)
removeFileSafe file
do_cmd (AddPackage p) = do
let file = location db </> display (installedUnitId p) <.> "conf"
when (verbosity > Normal) $ infoLn ("writing " ++ file)
writeUTF8File file (showInstalledPackageInfo p)
do_cmd (ModifyPackage p) =
do_cmd (AddPackage p)
updateDBCache :: Verbosity -> PackageDB 'GhcPkg.DbReadWrite -> 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
case packageDbLock db of
GhcPkg.DbOpenReadWrite lock -> GhcPkg.unlockPackageDb lock
type PackageCacheFormat = GhcPkg.InstalledPackageInfo
ComponentId
PackageIdentifier
PackageName
UnitId
OpenUnitId
ModuleName
OpenModule
convertPackageInfoToCacheFormat :: InstalledPackageInfo -> PackageCacheFormat
convertPackageInfoToCacheFormat pkg =
GhcPkg.InstalledPackageInfo {
GhcPkg.unitId = installedUnitId pkg,
GhcPkg.componentId = installedComponentId pkg,
GhcPkg.instantiatedWith = instantiatedWith pkg,
GhcPkg.sourcePackageId = sourcePackageId pkg,
GhcPkg.packageName = packageName pkg,
GhcPkg.packageVersion = Version.Version (versionNumbers (packageVersion pkg)) [],
GhcPkg.sourceLibName =
fmap (mkPackageName . unUnqualComponentName) (sourceLibName pkg),
GhcPkg.depends = depends pkg,
GhcPkg.abiDepends = map (\(AbiDependency k v) -> (k,unAbiHash v)) (abiDepends pkg),
GhcPkg.abiHash = unAbiHash (abiHash pkg),
GhcPkg.importDirs = importDirs pkg,
GhcPkg.hsLibraries = hsLibraries pkg,
GhcPkg.extraLibraries = extraLibraries pkg,
GhcPkg.extraGHCiLibraries = extraGHCiLibraries pkg,
GhcPkg.libraryDirs = libraryDirs pkg,
GhcPkg.libraryDynDirs = libraryDynDirs pkg,
GhcPkg.frameworks = frameworks pkg,
GhcPkg.frameworkDirs = frameworkDirs pkg,
GhcPkg.ldOptions = ldOptions pkg,
GhcPkg.ccOptions = ccOptions pkg,
GhcPkg.includes = includes pkg,
GhcPkg.includeDirs = includeDirs pkg,
GhcPkg.haddockInterfaces = haddockInterfaces pkg,
GhcPkg.haddockHTMLs = haddockHTMLs pkg,
GhcPkg.exposedModules = map convertExposed (exposedModules pkg),
GhcPkg.hiddenModules = hiddenModules pkg,
GhcPkg.indefinite = indefinite pkg,
GhcPkg.exposed = exposed pkg,
GhcPkg.trusted = trusted pkg
}
where
convertExposed (ExposedModule n reexport) = (n, reexport)
instance GhcPkg.BinaryStringRep ComponentId where
fromStringRep = mkComponentId . fromStringRep
toStringRep = toStringRep . display
instance GhcPkg.BinaryStringRep PackageName where
fromStringRep = mkPackageName . fromStringRep
toStringRep = toStringRep . display
instance GhcPkg.BinaryStringRep PackageIdentifier where
fromStringRep = fromMaybe (error "BinaryStringRep PackageIdentifier")
. simpleParse . fromStringRep
toStringRep = toStringRep . display
instance GhcPkg.BinaryStringRep ModuleName where
fromStringRep = ModuleName.fromString . fromStringRep
toStringRep = toStringRep . display
instance GhcPkg.BinaryStringRep String where
fromStringRep = fromUTF8BS
toStringRep = toUTF8BS
instance GhcPkg.BinaryStringRep UnitId where
fromStringRep = mkUnitId . fromStringRep
toStringRep = toStringRep . display
instance GhcPkg.DbUnitIdModuleRep UnitId ComponentId OpenUnitId ModuleName OpenModule where
fromDbModule (GhcPkg.DbModule uid mod_name) = OpenModule uid mod_name
fromDbModule (GhcPkg.DbModuleVar mod_name) = OpenModuleVar mod_name
toDbModule (OpenModule uid mod_name) = GhcPkg.DbModule uid mod_name
toDbModule (OpenModuleVar mod_name) = GhcPkg.DbModuleVar mod_name
fromDbUnitId (GhcPkg.DbUnitId cid insts) = IndefFullUnitId cid (Map.fromList insts)
fromDbUnitId (GhcPkg.DbInstalledUnitId uid)
= DefiniteUnitId (unsafeMkDefUnitId uid)
toDbUnitId (IndefFullUnitId cid insts) = GhcPkg.DbUnitId cid (Map.toList insts)
toDbUnitId (DefiniteUnitId def_uid)
= GhcPkg.DbInstalledUnitId (unDefUnitId def_uid)
-- -----------------------------------------------------------------------------
-- Exposing, Hiding, Trusting, Distrusting, Unregistering are all similar
exposePackage :: PackageArg -> Verbosity -> [Flag] -> Force -> IO ()
exposePackage = modifyPackage (\p -> ModifyPackage p{exposed=True})
hidePackage :: PackageArg -> Verbosity -> [Flag] -> Force -> IO ()
hidePackage = modifyPackage (\p -> ModifyPackage p{exposed=False})
trustPackage :: PackageArg -> Verbosity -> [Flag] -> Force -> IO ()
trustPackage = modifyPackage (\p -> ModifyPackage p{trusted=True})
distrustPackage :: PackageArg -> Verbosity -> [Flag] -> Force -> IO ()
distrustPackage = modifyPackage (\p -> ModifyPackage p{trusted=False})
unregisterPackage :: PackageArg -> Verbosity -> [Flag] -> Force -> IO ()
unregisterPackage = modifyPackage RemovePackage
modifyPackage
:: (InstalledPackageInfo -> DBOp)
-> PackageArg
-> Verbosity
-> [Flag]
-> Force
-> IO ()
modifyPackage fn pkgarg verbosity my_flags force = do
(db_stack, GhcPkg.DbOpenReadWrite db, _flag_dbs) <-
getPkgDatabases verbosity (GhcPkg.DbOpenReadWrite $ ContainsPkg pkgarg)
True{-use user-} True{-use cache-} False{-expand vars-} my_flags
let db_name = location db
pkgs = packages db
-- Get package respecting flags...
ps = findPackage pkgarg pkgs
-- This shouldn't happen if getPkgDatabases picks the DB correctly.
when (null ps) $ cannotFindPackage pkgarg $ Just db
let pks = map installedUnitId ps
cmds = [ fn pkg | pkg <- pkgs, installedUnitId pkg `elem` pks ]
new_db = updateInternalDB db cmds
new_db_ro = new_db { packageDbLock = GhcPkg.DbOpenReadOnly }
-- ...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_ro : rest_of_stack
new_broken = brokenPackages (allPackagesInStack new_stack)
newly_broken = filter ((`notElem` map installedUnitId old_broken)
. installedUnitId) new_broken
--
let displayQualPkgId pkg
| [_] <- filter ((== pkgid) . mungedId)
(allPackagesInStack db_stack)
= display pkgid
| otherwise = display pkgid ++ "@" ++ display (installedUnitId pkg)
where pkgid = mungedId 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, GhcPkg.DbOpenReadWrite db_to_operate_on, _flag_dbs) <-
getPkgDatabases verbosity (GhcPkg.DbOpenReadWrite TopOne)
True{-use user-} False{-no cache-} False{-expand vars-} my_flags
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, GhcPkg.DbOpenReadOnly, flag_db_stack) <-
getPkgDatabases verbosity GhcPkg.DbOpenReadOnly
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 mungedName p1 `compare` mungedName p2 of
LT -> LT
GT -> GT
EQ -> case mungedVersion p1 `compare` mungedVersion p2 of
LT -> LT
GT -> GT
EQ -> installedUnitId pkg1 `compare` installedUnitId pkg2
where (p1,p2) = (mungedId pkg1, mungedId pkg2)
stack = reverse db_stack_sorted
match `exposedInPkg` pkg = any match (map display $ exposedModules pkg)
pkg_map = allPackagesInStack db_stack
broken = map installedUnitId (brokenPackages pkg_map)
show_normal PackageDB{ location = db_name, packages = pkg_confs } =
do hPutStrLn stdout db_name
if null pkg_confs
then hPutStrLn stdout " (no packages)"
else hPutStrLn stdout $ unlines (map (" " ++) (map pp_pkg pkg_confs))
where
pp_pkg p
| installedUnitId p `elem` broken = printf "{%s}" doc
| exposed p = doc
| otherwise = printf "(%s)" doc
where doc | verbosity >= Verbose = printf "%s (%s)" pkg (display (installedUnitId p))
| otherwise = pkg
where
pkg = display (mungedId 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(WITH_TERMINFO)
mapM_ show_normal stack
#else
let
show_colour withF db@PackageDB{ packages = pkg_confs } =
if null pkg_confs
then termText (location db) <#> termText "\n (no packages)\n"
else
mconcat $ map (<#> termText "\n") $
(termText (location db)
: map (termText " " <#>) (map pp_pkg pkg_confs))
where
pp_pkg p
| installedUnitId p `elem` broken = withF Red doc
| exposed p = doc
| otherwise = withF Blue doc
where doc | verbosity >= Verbose
= termText (printf "%s (%s)" pkg (display (installedUnitId p)))
| otherwise
= termText pkg
where
pkg = display (mungedId 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 . mungedName
else display
strs = map showPkg $ map mungedId pkgs
when (not (null pkgs)) $
hPutStrLn stdout $ concat $ intersperse " " strs
showPackageDot :: Verbosity -> [Flag] -> IO ()
showPackageDot verbosity myflags = do
(_, GhcPkg.DbOpenReadOnly, flag_db_stack) <-
getPkgDatabases verbosity GhcPkg.DbOpenReadOnly
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 (mungedId p),
key <- depends p,
Just dep <- [PackageIndex.lookupUnitId ipix key],
let to = display (mungedId dep)
]
putStrLn "}"
-- -----------------------------------------------------------------------------
-- Prints the highest (hidden or exposed) version of a package
-- ToDo: This is no longer well-defined with unit ids, because the
-- dependencies may be varying versions
latestPackage :: Verbosity -> [Flag] -> GlobPackageIdentifier -> IO ()
latestPackage verbosity my_flags pkgid = do
(_, GhcPkg.DbOpenReadOnly, flag_db_stack) <-
getPkgDatabases verbosity GhcPkg.DbOpenReadOnly
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 mungedId $ ps
where
show_pkg pid = hPutStrLn stdout (display pid)
-- -----------------------------------------------------------------------------
-- Describe
describePackage :: Verbosity -> [Flag] -> PackageArg -> Bool -> IO ()
describePackage verbosity my_flags pkgarg expand_pkgroot = do
(_, GhcPkg.DbOpenReadOnly, flag_db_stack) <-
getPkgDatabases verbosity GhcPkg.DbOpenReadOnly
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
(_, GhcPkg.DbOpenReadOnly, flag_db_stack) <-
getPkgDatabases verbosity GhcPkg.DbOpenReadOnly
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
findPackage :: PackageArg -> [InstalledPackageInfo] -> [InstalledPackageInfo]
findPackage pkgarg pkgs = filter (pkgarg `matchesPkg`) pkgs
findPackagesByDB :: PackageDBStack -> PackageArg
-> IO [(PackageDB 'GhcPkg.DbReadOnly, [InstalledPackageInfo])]
findPackagesByDB db_stack pkgarg
= case [ (db, matched)
| db <- db_stack,
let matched = findPackage pkgarg $ packages db,
not (null matched) ] of
[] -> cannotFindPackage pkgarg Nothing
ps -> return ps
cannotFindPackage :: PackageArg -> Maybe (PackageDB mode) -> IO a
cannotFindPackage pkgarg mdb = die $ "cannot find package " ++ pkg_msg pkgarg
++ maybe "" (\db -> " in " ++ location db) mdb
where
pkg_msg (Id pkgid) = displayGlobPkgId pkgid
pkg_msg (IUId ipid) = display ipid
pkg_msg (Substring pkgpat _) = "matching " ++ pkgpat
matches :: GlobPackageIdentifier -> MungedPackageId -> Bool
GlobPackageIdentifier pn `matches` pid'
= (pn == mungedName pid')
ExactPackageIdentifier pid `matches` pid'
= mungedName pid == mungedName pid' &&
(mungedVersion pid == mungedVersion pid' || mungedVersion pid == nullVersion)
matchesPkg :: PackageArg -> InstalledPackageInfo -> Bool
(Id pid) `matchesPkg` pkg = pid `matches` mungedId pkg
(IUId ipid) `matchesPkg` pkg = ipid == installedUnitId pkg
(Substring _ m) `matchesPkg` pkg = m (display (mungedId pkg))
-- -----------------------------------------------------------------------------
-- Field
describeField :: Verbosity -> [Flag] -> PackageArg -> [String] -> Bool -> IO ()
describeField verbosity my_flags pkgarg fields expand_pkgroot = do
(_, GhcPkg.DbOpenReadOnly, flag_db_stack) <-
getPkgDatabases verbosity GhcPkg.DbOpenReadOnly
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, GhcPkg.DbOpenReadOnly, _) <-
getPkgDatabases verbosity GhcPkg.DbOpenReadOnly
True{-use user-} True{-use cache-} True{-expand vars-} my_flags
-- although check is not a modify command, we do need to use the user
-- db, because we may need it to verify package deps.
let simple_output = FlagSimpleOutput `elem` my_flags
let pkgs = allPackagesInStack db_stack
checkPackage p = do
(_,es,ws) <- runValidate $ checkPackageConfig p verbosity db_stack
True True
if null es
then do when (not simple_output) $ do
_ <- reportValidateErrors verbosity [] ws "" Nothing
return ()
return []
else do
when (not simple_output) $ do
reportError ("There are problems in package " ++ display (mungedId p) ++ ":")
_ <- reportValidateErrors verbosity es ws " " Nothing
return ()
return [p]
broken_pkgs <- concat `fmap` mapM checkPackage pkgs
let filterOut pkgs1 pkgs2 = filter not_in pkgs2
where not_in p = mungedId p `notElem` all_ps
all_ps = map mungedId 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 . mungedId) all_broken_pkgs
when (not (null all_broken_pkgs)) $ exitWith (ExitFailure 1)
closure :: [InstalledPackageInfo] -> [InstalledPackageInfo]
-> ([InstalledPackageInfo], [InstalledPackageInfo])
closure pkgs db_stack = go pkgs db_stack
where
go avail not_avail =
case partition (depsAvailable avail) not_avail of
([], not_avail') -> (avail, not_avail')
(new_avail, not_avail') -> go (new_avail ++ avail) not_avail'
depsAvailable :: [InstalledPackageInfo] -> InstalledPackageInfo
-> Bool
depsAvailable pkgs_ok pkg = null dangling
where dangling = filter (`notElem` pids) (depends pkg)
pids = map installedUnitId pkgs_ok
-- we want mutually recursive groups of package to show up
-- as broken. (#1750)
brokenPackages :: [InstalledPackageInfo] -> [InstalledPackageInfo]
brokenPackages pkgs = snd (closure [] pkgs)
-----------------------------------------------------------------------------
-- Sanity-check a new package config, and automatically build GHCi libs
-- if requested.
type ValidateError = (Force,String)
type ValidateWarning = String
newtype Validate a = V { runValidate :: IO (a, [ValidateError],[ValidateWarning]) }
instance Functor Validate where
fmap = liftM
instance Applicative Validate where
pure a = V $ pure (a, [], [])
(<*>) = ap
instance Monad Validate where
m >>= k = V $ do
(a, es, ws) <- runValidate m
(b, es', ws') <- runValidate (k a)
return (b,es++es',ws++ws')
verror :: Force -> String -> Validate ()
verror f s = V (return ((),[(f,s)],[]))
vwarn :: String -> Validate ()
vwarn s = V (return ((),[],["Warning: " ++ s]))
liftIO :: IO a -> Validate a
liftIO k = V (k >>= \a -> return (a,[],[]))
-- returns False if we should die
reportValidateErrors :: Verbosity -> [ValidateError] -> [ValidateWarning]
-> String -> Maybe Force -> IO Bool
reportValidateErrors verbosity es ws prefix mb_force = do
mapM_ (warn . (prefix++)) ws
oks <- mapM report es
return (and oks)
where
report (f,s)
| Just force <- mb_force
= if (force >= f)
then do when (verbosity >= Normal) $
reportError (prefix ++ s ++ " (ignoring)")
return True
else if f < CannotForce
then do reportError (prefix ++ s ++ " (use --force to override)")
return False
else do reportError err
return False
| otherwise = do reportError err
return False
where
err = prefix ++ s
validatePackageConfig :: InstalledPackageInfo
-> Verbosity
-> PackageDBStack
-> Bool -- multi_instance
-> Bool -- update, or check
-> Force
-> IO ()
validatePackageConfig pkg verbosity db_stack
multi_instance update force = do
(_,es,ws) <- runValidate $
checkPackageConfig pkg verbosity db_stack
multi_instance update
ok <- reportValidateErrors verbosity es ws
(display (mungedId pkg) ++ ": ") (Just force)
when (not ok) $ exitWith (ExitFailure 1)
checkPackageConfig :: InstalledPackageInfo
-> Verbosity
-> PackageDBStack
-> Bool -- multi_instance
-> Bool -- update, or check
-> Validate ()
checkPackageConfig pkg verbosity db_stack
multi_instance update = do
checkPackageId pkg
checkUnitId pkg db_stack update
checkDuplicates db_stack pkg multi_instance update
mapM_ (checkDep db_stack) (depends pkg)
checkDuplicateDepends (depends pkg)
mapM_ (checkDir False "import-dirs") (importDirs pkg)
mapM_ (checkDir True "library-dirs") (libraryDirs pkg)
mapM_ (checkDir True "dynamic-library-dirs") (libraryDynDirs pkg)
mapM_ (checkDir True "include-dirs") (includeDirs pkg)
mapM_ (checkDir True "framework-dirs") (frameworkDirs pkg)
mapM_ (checkFile True "haddock-interfaces") (haddockInterfaces pkg)
mapM_ (checkDirURL True "haddock-html") (haddockHTMLs pkg)
checkDuplicateModules pkg
checkExposedModules db_stack pkg
checkOtherModules pkg
let has_code = Set.null (openModuleSubstFreeHoles (Map.fromList (instantiatedWith pkg)))
when has_code $ mapM_ (checkHSLib verbosity (libraryDirs pkg ++ libraryDynDirs pkg)) (hsLibraries pkg)
-- ToDo: check these somehow?
-- extra_libraries :: [String],
-- c_includes :: [String],
-- When the package name and version are put together, sometimes we can
-- end up with a package id that cannot be parsed. This will lead to
-- difficulties when the user wants to refer to the package later, so
-- we check that the package id can be parsed properly here.
checkPackageId :: InstalledPackageInfo -> Validate ()
checkPackageId ipi =
let str = display (mungedId ipi) in
case [ x :: MungedPackageId | (x,ys) <- readP_to_S parse str, all isSpace ys ] of
[_] -> return ()
[] -> verror CannotForce ("invalid package identifier: " ++ str)
_ -> verror CannotForce ("ambiguous package identifier: " ++ str)
checkUnitId :: InstalledPackageInfo -> PackageDBStack -> Bool
-> Validate ()
checkUnitId ipi db_stack update = do
let uid = installedUnitId ipi
when (null (display uid)) $ verror CannotForce "missing id field"
when (display uid /= compatPackageKey ipi) $
verror CannotForce $ "installed package info from too old version of Cabal "
++ "(key field does not match id field)"
let dups = [ p | p <- allPackagesInStack db_stack,
installedUnitId p == uid ]
when (not update && not (null dups)) $
verror CannotForce $
"package(s) with this id already exist: " ++
unwords (map (display.installedUnitId) dups)
checkDuplicates :: PackageDBStack -> InstalledPackageInfo
-> Bool -> Bool-> Validate ()
checkDuplicates db_stack pkg multi_instance update = do
let
pkgid = mungedId 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 mungedId pkgs)) $
verror CannotForce $
"package " ++ display pkgid ++ " is already installed"
let
uncasep = map toLower . display
dups = filter ((== uncasep pkgid) . uncasep) (map mungedId pkgs)
when (not update && not multi_instance
&& not (null dups)) $ verror ForceAll $
"Package names may be treated case-insensitively in the future.\n"++
"Package " ++ display pkgid ++
" overlaps with: " ++ unwords (map display dups)
checkDir, checkFile, checkDirURL :: Bool -> String -> FilePath -> Validate ()
checkDir = checkPath False True
checkFile = checkPath False False
checkDirURL = checkPath True True
checkPath :: Bool -> Bool -> Bool -> String -> FilePath -> Validate ()
checkPath url_ok is_dir warn_only thisfield d
| url_ok && ("http://" `isPrefixOf` d
|| "https://" `isPrefixOf` d) = return ()
| url_ok
, Just d' <- stripPrefix "file://" d
= checkPath False is_dir warn_only thisfield d'
-- Note: we don't check for $topdir/${pkgroot} here. We rely on these
-- variables having been expanded already, see mungePackagePaths.
| isRelative d = verror ForceFiles $
thisfield ++ ": " ++ d ++ " is a relative path which "
++ "makes no sense (as there is nothing for it to be "
++ "relative to). You can make paths relative to the "
++ "package database itself by using ${pkgroot}."
-- relative paths don't make any sense; #4134
| otherwise = do
there <- liftIO $ if is_dir then doesDirectoryExist d else doesFileExist d
when (not there) $
let msg = thisfield ++ ": " ++ d ++ " doesn't exist or isn't a "
++ if is_dir then "directory" else "file"
in
if warn_only
then vwarn msg
else verror ForceFiles msg
checkDep :: PackageDBStack -> UnitId -> Validate ()
checkDep db_stack pkgid
| pkgid `elem` pkgids = return ()
| otherwise = verror ForceAll ("dependency \"" ++ display pkgid
++ "\" doesn't exist")
where
all_pkgs = allPackagesInStack db_stack
pkgids = map installedUnitId all_pkgs
checkDuplicateDepends :: [UnitId] -> Validate ()
checkDuplicateDepends deps
| null dups = return ()
| otherwise = verror ForceAll ("package has duplicate dependencies: " ++
unwords (map display dups))
where
dups = [ p | (p:_:_) <- group (sort deps) ]
checkHSLib :: Verbosity -> [String] -> String -> Validate ()
checkHSLib _verbosity dirs lib = do
let filenames = ["lib" ++ lib ++ ".a",
"lib" ++ lib ++ ".p_a",
"lib" ++ lib ++ "-ghc" ++ Version.version ++ ".so",
"lib" ++ lib ++ "-ghc" ++ Version.version ++ ".dylib",
lib ++ "-ghc" ++ Version.version ++ ".dll"]
b <- liftIO $ doesFileExistOnPath filenames dirs
when (not b) $
verror ForceFiles ("cannot find any of " ++ show filenames ++
" on library path")
doesFileExistOnPath :: [FilePath] -> [FilePath] -> IO Bool
doesFileExistOnPath filenames paths = anyM doesFileExist fullFilenames
where fullFilenames = [ path </> filename
| filename <- filenames
, path <- paths ]
-- | Perform validation checks (module file existence checks) on the
-- @hidden-modules@ field.
checkOtherModules :: InstalledPackageInfo -> Validate ()
checkOtherModules pkg = mapM_ (checkModuleFile pkg) (hiddenModules pkg)
-- | Perform validation checks (module file existence checks and module
-- reexport checks) on the @exposed-modules@ field.
checkExposedModules :: PackageDBStack -> InstalledPackageInfo -> Validate ()
checkExposedModules db_stack pkg =
mapM_ checkExposedModule (exposedModules pkg)
where
checkExposedModule (ExposedModule modl reexport) = do
let checkOriginal = checkModuleFile pkg modl
checkReexport = checkModule "module reexport" db_stack pkg
maybe checkOriginal checkReexport reexport
-- | Validates the existence of an appropriate @hi@ file associated with
-- a module. Used for both @hidden-modules@ and @exposed-modules@ which
-- are not reexports.
checkModuleFile :: InstalledPackageInfo -> ModuleName -> Validate ()
checkModuleFile pkg modl =
-- there's no interface file for GHC.Prim
unless (modl == ModuleName.fromString "GHC.Prim") $ do
let files = [ ModuleName.toFilePath modl <.> extension
| extension <- ["hi", "p_hi", "dyn_hi" ] ]
b <- liftIO $ doesFileExistOnPath files (importDirs pkg)
when (not b) $
verror ForceFiles ("cannot find any of " ++ show files)
-- | Validates that @exposed-modules@ and @hidden-modules@ do not have duplicate
-- entries.
-- ToDo: this needs updating for signatures: signatures can validly show up
-- multiple times in the @exposed-modules@ list as long as their backing
-- implementations agree.
checkDuplicateModules :: InstalledPackageInfo -> Validate ()
checkDuplicateModules pkg
| null dups = return ()
| otherwise = verror ForceAll ("package has duplicate modules: " ++
unwords (map display dups))
where
dups = [ m | (m:_:_) <- group (sort mods) ]
mods = map exposedName (exposedModules pkg) ++ hiddenModules pkg
-- | Validates an original module entry, either the origin of a module reexport
-- or the backing implementation of a signature, by checking that it exists,
-- really is an original definition, and is accessible from the dependencies of
-- the package.
-- ToDo: If the original module in question is a backing signature
-- implementation, then we should also check that the original module in
-- question is NOT a signature (however, if it is a reexport, then it's fine
-- for the original module to be a signature.)
checkModule :: String
-> PackageDBStack
-> InstalledPackageInfo
-> OpenModule
-> Validate ()
checkModule _ _ _ (OpenModuleVar _) = error "Impermissible reexport"
checkModule field_name db_stack pkg
(OpenModule (DefiniteUnitId def_uid) definingModule) =
let definingPkgId = unDefUnitId def_uid
mpkg = if definingPkgId == installedUnitId pkg
then Just pkg
else PackageIndex.lookupUnitId ipix definingPkgId
in case mpkg of
Nothing
-> verror ForceAll (field_name ++ " refers to a non-existent " ++
"defining package: " ++
display definingPkgId)
Just definingPkg
| not (isIndirectDependency definingPkgId)
-> verror ForceAll (field_name ++ " refers to a defining " ++
"package that is not a direct (or indirect) " ++
"dependency of this package: " ++
display definingPkgId)
| otherwise
-> case find ((==definingModule).exposedName)
(exposedModules definingPkg) of
Nothing ->
verror ForceAll (field_name ++ " refers to a module " ++
display definingModule ++ " " ++
"that is not exposed in the " ++
"defining package " ++ display definingPkgId)
Just (ExposedModule {exposedReexport = Just _} ) ->
verror ForceAll (field_name ++ " refers to a module " ++
display definingModule ++ " " ++
"that is reexported but not defined in the " ++
"defining package " ++ display definingPkgId)
_ -> return ()
where
all_pkgs = allPackagesInStack db_stack
ipix = PackageIndex.fromList all_pkgs
isIndirectDependency pkgid = fromMaybe False $ do
thispkg <- graphVertex (installedUnitId pkg)
otherpkg <- graphVertex pkgid
return (Graph.path depgraph thispkg otherpkg)
(depgraph, _, graphVertex) =
PackageIndex.dependencyGraph (PackageIndex.insert pkg ipix)
checkModule _ _ _ (OpenModule (IndefFullUnitId _ _) _) =
-- TODO: add some checks here
return ()
-- ---------------------------------------------------------------------------
-- expanding environment variables in the package configuration
expandEnvVars :: String -> Force -> IO String
expandEnvVars str0 force = go str0 ""
where
go "" acc = return $! reverse acc
go ('$':'{':str) acc | (var, '}':rest) <- break close str
= do value <- lookupEnvVar var
go rest (reverse value ++ acc)
where close c = c == '}' || c == '\n' -- don't span newlines
go (c:str) acc
= go str (c:acc)
lookupEnvVar :: String -> IO String
lookupEnvVar "pkgroot" = return "${pkgroot}" -- these two are special,
lookupEnvVar "pkgrooturl" = return "${pkgrooturl}" -- we don't expand them
lookupEnvVar nm =
catchIO (System.Environment.getEnv nm)
(\ _ -> do dieOrForceAll force ("Unable to expand variable " ++
show nm)
return "")
-----------------------------------------------------------------------------
getProgramName :: IO String
getProgramName = liftM (`withoutSuffix` ".bin") getProgName
where str `withoutSuffix` suff
| suff `isSuffixOf` str = take (length str - length suff) str
| otherwise = str
bye :: String -> IO a
bye s = putStr s >> exitWith ExitSuccess
die :: String -> IO a
die = dieWith 1
dieWith :: Int -> String -> IO a
dieWith ec s = do
prog <- getProgramName
reportError (prog ++ ": " ++ s)
exitWith (ExitFailure ec)
dieOrForceAll :: Force -> String -> IO ()
dieOrForceAll ForceAll s = ignoreError s
dieOrForceAll _other s = dieForcible s
warn :: String -> IO ()
warn = reportError
-- send info messages to stdout
infoLn :: String -> IO ()
infoLn = putStrLn
info :: String -> IO ()
info = putStr
ignoreError :: String -> IO ()
ignoreError s = reportError (s ++ " (ignoring)")
reportError :: String -> IO ()
reportError s = do hFlush stdout; hPutStrLn stderr s
dieForcible :: String -> IO ()
dieForcible s = die (s ++ " (use --force to override)")
-----------------------------------------
-- Cut and pasted from ghc/compiler/main/SysTools
getLibDir :: IO (Maybe String)
#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 = do base <- getExecDir "/ghc-pkg.exe"
case base of
Nothing -> return Nothing
Just base' -> do
libdir <- canonicalizePath $ base' </> "../lib"
exists <- doesDirectoryExist libdir
if exists
then return $ Just libdir
else return Nothing
-- (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
#elif defined(darwin_HOST_OS) || defined(linux_HOST_OS)
-- TODO: a) this is copy-pasta from SysTools.hs / getBaseDir. Why can't we reuse
-- this here? and parameterise getBaseDir over the executable (for
-- windows)?
-- Answer: we can not, because if we share `getBaseDir` via `ghc-boot`,
-- that would add `base` as a dependency for windows.
-- b) why is the windows getBaseDir logic, not part of getExecutablePath?
-- it would be much wider available then and we could drop all the
-- custom logic?
-- Answer: yes this should happen. No one has found the time just yet.
getLibDir = Just . (\p -> p </> "lib") . takeDirectory . takeDirectory <$> getExecutablePath
#else
getLibDir = return Nothing
#endif
-----------------------------------------
-- Adapted from ghc/compiler/utils/Panic
installSignalHandlers :: IO ()
installSignalHandlers = do
threadid <- myThreadId
let
interrupt = Exception.throwTo threadid
(Exception.ErrorCall "interrupted")
--
#if !defined(mingw32_HOST_OS)
_ <- installHandler sigQUIT (Catch interrupt) Nothing
_ <- installHandler sigINT (Catch interrupt) Nothing
return ()
#else
-- GHC 6.3+ has support for console events on Windows
-- NOTE: running GHCi under a bash shell for some reason requires
-- you to press Ctrl-Break rather than Ctrl-C to provoke
-- an interrupt. Ctrl-C is getting blocked somewhere, I don't know
-- why --SDM 17/12/2004
let sig_handler ControlC = interrupt
sig_handler Break = interrupt
sig_handler _ = return ()
_ <- installHandler (Catch sig_handler)
return ()
#endif
catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a
catchIO = Exception.catch
tryIO :: IO a -> IO (Either Exception.IOException a)
tryIO = Exception.try
-- removeFileSave doesn't throw an exceptions, if the file is already deleted
removeFileSafe :: FilePath -> IO ()
removeFileSafe fn =
removeFile fn `catchIO` \ e ->
when (not $ isDoesNotExistError e) $ ioError e
-- | Turn a path relative to the current directory into a (normalised)
-- absolute path.
absolutePath :: FilePath -> IO FilePath
absolutePath path = return . normalise . (</> path) =<< getCurrentDirectory
|
ezyang/ghc
|
utils/ghc-pkg/Main.hs
|
Haskell
|
bsd-3-clause
| 90,493
|
{-# Language FlexibleContexts, ScopedTypeVariables #-}
-- | A multitap looper.
module Csound.Air.Looper (
LoopSpec(..), LoopControl(..),
sigLoop, midiLoop, sfLoop, patchLoop
) where
import Control.Monad
import Data.List
import Data.Default
import Data.Boolean
import Csound.Typed
import Csound.Typed.Gui hiding (button)
import Csound.Control.Evt
import Csound.Control.Instr
import Csound.Control.Gui
import Csound.Control.Sf
import Csound.Typed.Opcode hiding (space, button)
import Csound.SigSpace
import Csound.Air.Live
import Csound.Air.Wave
import Csound.Air.Fx
import Csound.Air.Filter
import Csound.Air.Patch
import Csound.Air.Misc
-- | The type for fine tuning of the looper. Let's review the values:
--
-- * @loopMixVal@ - list of initial values for mix levels (default is 0.5 for all taps)
--
-- * @loopPrefx@ - list of pre-loop effects (the default is do-nothing effect)
--
-- * @loopPostfx@ - list of post-loop effects (the default is do-nothing effect)
--
-- * @loopPrefxVal@ - list of dry/wet values for pre-looop effects (the default is 0.5 for all taps)
--
-- * @loopPostfxVal@ - list of dry/wet values for post-looop effects (the default is 0.5 for all taps)
--
-- * @loopInitInstr@ - the initial sounding tap (sound source) (what tap we are going to record when the looper starts up).
--
-- * @loopFades@ - the list of instrument groups to fade/out. Eachl list item is a list of integers
-- where an integer points to a tap number. By default a single fader is given to each tap.
-- with lists of integers we can group the sound sources by their functions in the song.
-- We may group all harmonic instruments in a single group and all drums into another group.
--
-- * @loopReeatFades@ -- a repeat fade weight is a value that represents
-- an amount of repetition. A looping tap is implemented as a delay tap with
-- big feedback. The repeat fades equals to the feedback amount. It have to be not bigger
-- than 1. If the value equals to 1 than the loop is repeated forever. If it's lower
-- than 1 the loop is gradually going to fade.
--
-- * @loopControl@ -- specifies an external controllers for the looper.
-- See the docs for the type @LoopSpec@.
data LoopSpec = LoopSpec
{ loopMixVal :: [Sig]
, loopPrefx :: [FxFun]
, loopPostfx :: [FxFun]
, loopPrefxVal :: [Sig]
, loopPostfxVal :: [Sig]
, loopInitInstr :: Int
, loopFades :: [[Int]]
, loopRepeatFades :: [Sig]
, loopControl :: LoopControl
}
instance Default LoopSpec where
def = LoopSpec {
loopPrefx = []
, loopPostfx = []
, loopPrefxVal = []
, loopPostfxVal = []
, loopMixVal = []
, loopInitInstr = 0
, loopFades = []
, loopRepeatFades = []
, loopControl = def
}
-- | External controllers. We can control the looper with
-- UI-widgets but sometimes it's convenient to control the
-- loper with some external midi-device. This structure mocks
-- all controls (except knobs for effects and mix).
--
-- * @loopTap@ - selects the current tap. It's a stream of integers (from 0 to a given integer).
--
-- * @loopFade@ - can fade in or fade out a group of taps. It's a list of toggle-like event streams.
-- they produce 1s for on and 0s for off.
--
-- * @loopDel@ - is for deleting the content of a given tap. It's just a click of the button.
-- So the value should be an event stream of units (which is @Tick = Evt Unit@).
--
-- * @loopThrough@ - is an event stream of toggles.
--
-- All values are wrapped in the @Maybe@ type. If the value is @Nothing@ in the given cell
-- the looper is controled only with virtual widgets.
--
-- There is an instance of @Default@ for @LoopControl@ with all values set to @Nothing@.
-- It's useful when we want to control only a part of parameters externally.
-- We can use the value @def@ to set the rest parameters:
--
-- > def { loopTap = Just someEvt }
data LoopControl = LoopControl
{ loopTap :: Maybe (Evt D)
, loopFade :: Maybe ([Evt D])
, loopDel :: Maybe Tick
, loopThrough :: Maybe (Evt D)
}
instance Default LoopControl where
def = LoopControl {
loopTap = Nothing
, loopFade = Nothing
, loopDel = Nothing
, loopThrough = Nothing }
type TapControl = [String] -> Int -> Source Sig
type FadeControl = [String -> Source (Evt D)]
type DelControl = Source Tick
type ThroughControl = Source Sig
-- | The @midiLoop@ that is adapted for usage with soundfonts.
-- It takes in a list of pairs of sound fonts as sound sources.
-- The second value in the pair is the release time for the given sound font.
sfLoop :: LoopSpec -> D -> [D] -> [(Sf, D)] -> Source Sig2
sfLoop spec dtBpm times fonts = midiLoop spec dtBpm times $ fmap (uncurry sfMsg) fonts
-- | The @sigLoop@ that is adapted for usage with midi instruments.
-- It takes a list of midi instruments in place of signal inputs. The rest is the same
midiLoop :: LoopSpec -> D -> [D] -> [Msg -> SE Sig2] -> Source Sig2
midiLoop = genLoop $ \cond midiInstr -> midi $ playWhen cond midiInstr
-- | Some instruments not work well with the looper. Alwo be aware of limitation of software resources.
patchLoop :: LoopSpec -> D -> [D] -> [Patch2] -> Source Sig2
patchLoop = genLoop $ \cond p -> atMidi (patchWhen cond p)
-- | Simple multitap Looper. We can create as many taps as we like
-- also we can create fade outs/ins insert effects and control mix.
--
-- > sigLoop spec bpm times imputs
--
-- Arguments:
--
-- * looper @spec@ (see the docs for the type)
--
-- * main @bpm@ rate. All taps are aligned with the main rate
--
-- * list of multipliers for each tap. Each tap is going to have a fixed
-- length that is a multiplier of the main rate. It doesn't have to be
-- an integer. So we can create weird drum patterns with odd loop durations.
--
-- * list of signal sources. By convention all sources are stereo signals.
-- We can use the function @fromMono@ to convert the mono signal to stereo.
sigLoop :: LoopSpec -> D -> [D] -> [Sig2] -> Source Sig2
sigLoop = genLoop $ \cond asig -> return $ mul (ifB cond 1 0) asig
getControls :: LoopControl -> (TapControl, FadeControl, DelControl, ThroughControl)
getControls a =
( maybe hradioSig (hradioSig' . evtToSig (-1)) (loopTap a)
, fmap (\f x -> f x True) $ maybe (repeat toggle) (\xs -> fmap toggle' xs ++ repeat toggle) (loopFade a)
, ( $ "del") $ maybe button button' (loopDel a)
, (\f -> f "through" False) $ maybe toggleSig (toggleSig' . evtToSig (-1)) (loopThrough a))
genLoop :: forall a. (BoolSig -> a -> SE Sig2) -> LoopSpec -> D -> [D] -> [a] -> Source Sig2
genLoop playInstr spec dtBpm times' instrs = do
(preFxKnobGui, preFxKnobWrite, preFxKnobRead) <- setKnob "pre" (linSpan 0 1) 0.5
(postFxKnobGui, postFxKnobWrite, postFxKnobRead) <- setKnob "post" (linSpan 0 1) 0.5
(mixKnobGui, mixKnobWrite, mixKnobRead) <- setKnob "mix" (linSpan 0 1) 0.5
let knobGuis = ver [mixKnobGui, preFxKnobGui, postFxKnobGui]
mapGuiSource (\gs -> hor [knobGuis, sca 12 gs]) $ joinSource $ vlift3 (\(thr, delEvt) x sils -> do
-- knobs
mixCoeffs <- tabSigs mixKnobWrite mixKnobRead x initMixVals
preCoeffs <- tabSigs preFxKnobWrite preFxKnobRead x initPreVals
postCoeffs <- tabSigs postFxKnobWrite postFxKnobRead x initPostVals
refs <- mapM (const $ newRef (1 :: Sig)) ids
delRefs <- mapM (const $ newRef (0 :: Sig)) ids
zipWithM_ (setSilencer refs) silencer sils
at smallRoom2 $ sum $ zipWith3 (f delEvt thr x) (zip3 times ids repeatFades) (zip5 mixCoeffs preFx preCoeffs postFx postCoeffs) $ zip3 delRefs refs instrs) throughDel sw sil
where
(tapControl, fadeControl, delControl, throughControl) = getControls (loopControl spec)
dt = 60 / dtBpm
times = take len $ times' ++ repeat 1
postFx = take len $ loopPostfx spec ++ repeat return
preFx = take len $ loopPrefx spec ++ repeat return
repeatFades = loopRepeatFades spec ++ repeat 1
len = length ids
initMixVals = take len $ loopMixVal spec ++ repeat 0.5
initPreVals = take len $ loopPrefxVal spec ++ repeat 0.5
initPostVals = take len $ loopPostfxVal spec ++ repeat 0.5
silencer
| null (loopFades spec) = fmap return ids
| otherwise = loopFades spec
initInstr = loopInitInstr spec
ids = [0 .. length instrs - 1]
through = throughControl
delete = delControl
throughDel = hlift2' 6 1 (\a b -> (a, b)) through delete
sw = tapControl (fmap show ids) initInstr
sil = hlifts id $ zipWith (\f n -> f (show n)) fadeControl [0 .. length silencer - 1]
maxDel = 3
f :: Tick -> Sig -> Sig -> (D, Int, Sig) -> (Sig, FxFun, Sig, FxFun, Sig) -> (Ref Sig, Ref Sig, a) -> SE Sig2
f delEvt thr x (t, n, repeatFadeWeight) (mixCoeff, preFx, preCoeff, postFx, postCoeff) (delRef, silRef, instr) = do
silVal <- readRef silRef
runEvt delEvt $ \_ -> do
a <- readRef delRef
when1 isCurrent $ writeRef delRef (ifB (a + 1 `lessThan` maxDel) (a + 1) 0)
delVal <- readRef delRef
echoSig <- playSf 0
let d0 = delVal ==* 0
d1 = delVal ==* 1
d2 = delVal ==* 2
let playEcho dId = mul (smooth 0.05 $ ifB dId 1 0) $ mul (smooth 0.1 silVal) $ at (echo (dt * t) (ifB dId repeatFadeWeight 0)) $ ifB dId echoSig 0
mul mixCoeff $ mixAt postCoeff postFx $ sum [ sum $ fmap playEcho [d0, d1, d2]
, playSf 1]
where
playSf thrVal = mixAt preCoeff preFx $ playInstr (isCurrent &&* thr ==* thrVal) instr
isCurrent = x ==* (sig $ int n)
setSilencer refs silIds evt = runEvt evt $ \v ->
mapM_ (\ref -> writeRef ref $ sig v) $ fmap (refs !! ) silIds
tabSigs :: Output Sig -> Input Sig -> Sig -> [Sig] -> SE [Sig]
tabSigs writeWidget readWidget switch initVals = do
refs <- mapM newGlobalRef initVals
vs <- mapM readRef refs
runEvt (changedE [switch]) $ \_ -> do
mapM_ (\(v, x) -> when1 (x ==* switch) $ writeWidget v) $ zip vs $ fmap (sig . int) [0 .. length initVals - 1]
forM_ (zip [0..] refs) $ \(n, ref) -> do
when1 ((sig $ int n) ==* switch) $ writeRef ref readWidget
return vs
|
isomorphism/csound-expression
|
src/Csound/Air/Looper.hs
|
Haskell
|
bsd-3-clause
| 9,934
|
-- This is a modification of the calendar program described in section 4.5
-- of Bird and Wadler's ``Introduction to functional programming'', with
-- two ways of printing the calendar ... as in B+W, or like UNIX `cal':
import IO -- 1.3
import System -- 1.3
import List -- 1.3
import Char -- 1.3
-- Picture handling:
infixr 5 `above`, `beside`
type Picture = [[Char]]
height, width :: Picture -> Int
height p = length p
width p = length (head p)
above, beside :: Picture -> Picture -> Picture
above = (++)
beside = zipWith (++)
stack, spread :: [Picture] -> Picture
stack = foldr1 above
spread = foldr1 beside
empty :: (Int,Int) -> Picture
empty (h,w) = copy h (copy w ' ')
block, blockT :: Int -> [Picture] -> Picture
block n = stack . map spread . groop n
blockT n = spread . map stack . groop n
groop :: Int -> [a] -> [[a]]
groop n [] = []
groop n xs = take n xs : groop n (drop n xs)
lframe :: (Int,Int) -> Picture -> Picture
lframe (m,n) p = (p `beside` empty (h,n-w)) `above` empty (m-h,n)
where h = height p
w = width p
-- Information about the months in a year:
monthLengths year = [31,feb,31,30,31,30,31,31,30,31,30,31]
where feb | leap year = 29
| otherwise = 28
leap year = if year`mod`100 == 0 then year`mod`400 == 0
else year`mod`4 == 0
monthNames = ["January","February","March","April",
"May","June","July","August",
"September","October","November","December"]
jan1st year = (year + last`div`4 - last`div`100 + last`div`400) `mod` 7
where last = year - 1
firstDays year = take 12
(map (`mod`7)
(scanl (+) (jan1st year) (monthLengths year)))
-- Producing the information necessary for one month:
dates fd ml = map (date ml) [1-fd..42-fd]
where date ml d | d<1 || ml<d = [" "]
| otherwise = [rjustify 3 (show d)]
-- The original B+W calendar:
calendar :: Int -> String
calendar = unlines . block 3 . map picture . months
where picture (mn,yr,fd,ml) = title mn yr `above` table fd ml
title mn yr = lframe (2,25) [mn ++ " " ++ show yr]
table fd ml = lframe (8,25)
(daynames `beside` entries fd ml)
daynames = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]
entries fd ml = blockT 7 (dates fd ml)
months year = zip4 monthNames
(copy 12 year)
(firstDays year)
(monthLengths year)
-- In a format somewhat closer to UNIX cal:
cal year = unlines (banner year `above` body year)
where banner yr = [cjustify 75 (show yr)] `above` empty (1,75)
body = block 3 . map (pad . pic) . months
pic (mn,fd,ml) = title mn `above` table fd ml
pad p = (side`beside`p`beside`side)`above`end
side = empty (8,2)
end = empty (1,25)
title mn = [cjustify 21 mn]
table fd ml = daynames `above` entries fd ml
daynames = [" Su Mo Tu We Th Fr Sa"]
entries fd ml = block 7 (dates fd ml)
months year = zip3 monthNames
(firstDays year)
(monthLengths year)
-- For a standalone calendar program:
main = do
strs <- getArgs
case strs of [year] -> calFor year
_ -> fail ("Usage: cal year\n")
calFor year | illFormed = fail ("Bad argument")
| otherwise = putStr (cal yr)
where illFormed = null ds || not (null rs)
(ds,rs) = span isDigit year
yr = atoi ds
atoi s = foldl (\a d -> 10*a+d) 0 (map toDigit s)
toDigit d = fromEnum d - fromEnum '0'
-- End of calendar program
-- tacked on by partain
copy :: Int -> a -> [a]
copy n x = take n (repeat x)
cjustify, ljustify, rjustify :: Int -> String -> String
cjustify n s = space halfm ++ s ++ space (m - halfm)
where m = n - length s
halfm = m `div` 2
ljustify n s = s ++ space (n - length s)
rjustify n s = space (n - length s) ++ s
space :: Int -> String
space n = copy n ' '
-- end of tack
|
hvr/jhc
|
regress/tests/9_nofib/spectral/Calendar.hs
|
Haskell
|
mit
| 4,727
|
{-# LANGUAGE BangPatterns, CPP, MagicHash, UnboxedTuples #-}
{-# OPTIONS_GHC -O #-}
-- We always optimise this, otherwise performance of a non-optimised
-- compiler is severely affected
-- -----------------------------------------------------------------------------
--
-- (c) The University of Glasgow, 1997-2006
--
-- Character encodings
--
-- -----------------------------------------------------------------------------
module Encoding (
-- * UTF-8
utf8DecodeChar#,
utf8PrevChar,
utf8CharStart,
utf8DecodeChar,
utf8DecodeString,
utf8EncodeChar,
utf8EncodeString,
utf8EncodedLength,
countUTF8Chars,
-- * Z-encoding
zEncodeString,
zDecodeString
) where
#include "HsVersions.h"
import Foreign
import Data.Char
import Numeric
import ExtsCompat46
-- -----------------------------------------------------------------------------
-- UTF-8
-- We can't write the decoder as efficiently as we'd like without
-- resorting to unboxed extensions, unfortunately. I tried to write
-- an IO version of this function, but GHC can't eliminate boxed
-- results from an IO-returning function.
--
-- We assume we can ignore overflow when parsing a multibyte character here.
-- To make this safe, we add extra sentinel bytes to unparsed UTF-8 sequences
-- before decoding them (see StringBuffer.hs).
{-# INLINE utf8DecodeChar# #-}
utf8DecodeChar# :: Addr# -> (# Char#, Addr# #)
utf8DecodeChar# a# =
let !ch0 = word2Int# (indexWord8OffAddr# a# 0#) in
case () of
_ | ch0 <=# 0x7F# -> (# chr# ch0, a# `plusAddr#` 1# #)
| ch0 >=# 0xC0# && ch0 <=# 0xDF# ->
let !ch1 = word2Int# (indexWord8OffAddr# a# 1#) in
if ch1 <# 0x80# || ch1 >=# 0xC0# then fail 1# else
(# chr# (((ch0 -# 0xC0#) `uncheckedIShiftL#` 6#) +#
(ch1 -# 0x80#)),
a# `plusAddr#` 2# #)
| ch0 >=# 0xE0# && ch0 <=# 0xEF# ->
let !ch1 = word2Int# (indexWord8OffAddr# a# 1#) in
if ch1 <# 0x80# || ch1 >=# 0xC0# then fail 1# else
let !ch2 = word2Int# (indexWord8OffAddr# a# 2#) in
if ch2 <# 0x80# || ch2 >=# 0xC0# then fail 2# else
(# chr# (((ch0 -# 0xE0#) `uncheckedIShiftL#` 12#) +#
((ch1 -# 0x80#) `uncheckedIShiftL#` 6#) +#
(ch2 -# 0x80#)),
a# `plusAddr#` 3# #)
| ch0 >=# 0xF0# && ch0 <=# 0xF8# ->
let !ch1 = word2Int# (indexWord8OffAddr# a# 1#) in
if ch1 <# 0x80# || ch1 >=# 0xC0# then fail 1# else
let !ch2 = word2Int# (indexWord8OffAddr# a# 2#) in
if ch2 <# 0x80# || ch2 >=# 0xC0# then fail 2# else
let !ch3 = word2Int# (indexWord8OffAddr# a# 3#) in
if ch3 <# 0x80# || ch3 >=# 0xC0# then fail 3# else
(# chr# (((ch0 -# 0xF0#) `uncheckedIShiftL#` 18#) +#
((ch1 -# 0x80#) `uncheckedIShiftL#` 12#) +#
((ch2 -# 0x80#) `uncheckedIShiftL#` 6#) +#
(ch3 -# 0x80#)),
a# `plusAddr#` 4# #)
| otherwise -> fail 1#
where
-- all invalid sequences end up here:
fail n = (# '\0'#, a# `plusAddr#` n #)
-- '\xFFFD' would be the usual replacement character, but
-- that's a valid symbol in Haskell, so will result in a
-- confusing parse error later on. Instead we use '\0' which
-- will signal a lexer error immediately.
utf8DecodeChar :: Ptr Word8 -> (Char, Ptr Word8)
utf8DecodeChar (Ptr a#) =
case utf8DecodeChar# a# of (# c#, b# #) -> ( C# c#, Ptr b# )
-- UTF-8 is cleverly designed so that we can always figure out where
-- the start of the current character is, given any position in a
-- stream. This function finds the start of the previous character,
-- assuming there *is* a previous character.
utf8PrevChar :: Ptr Word8 -> IO (Ptr Word8)
utf8PrevChar p = utf8CharStart (p `plusPtr` (-1))
utf8CharStart :: Ptr Word8 -> IO (Ptr Word8)
utf8CharStart p = go p
where go p = do w <- peek p
if w >= 0x80 && w < 0xC0
then go (p `plusPtr` (-1))
else return p
utf8DecodeString :: Ptr Word8 -> Int -> IO [Char]
STRICT2(utf8DecodeString)
utf8DecodeString (Ptr a#) (I# len#)
= unpack a#
where
!end# = addr2Int# (a# `plusAddr#` len#)
unpack p#
| addr2Int# p# >=# end# = return []
| otherwise =
case utf8DecodeChar# p# of
(# c#, q# #) -> do
chs <- unpack q#
return (C# c# : chs)
countUTF8Chars :: Ptr Word8 -> Int -> IO Int
countUTF8Chars ptr bytes = go ptr 0
where
end = ptr `plusPtr` bytes
STRICT2(go)
go ptr n
| ptr >= end = return n
| otherwise = do
case utf8DecodeChar# (unPtr ptr) of
(# _, a #) -> go (Ptr a) (n+1)
unPtr :: Ptr a -> Addr#
unPtr (Ptr a) = a
utf8EncodeChar :: Char -> Ptr Word8 -> IO (Ptr Word8)
utf8EncodeChar c ptr =
let x = ord c in
case () of
_ | x > 0 && x <= 0x007f -> do
poke ptr (fromIntegral x)
return (ptr `plusPtr` 1)
-- NB. '\0' is encoded as '\xC0\x80', not '\0'. This is so that we
-- can have 0-terminated UTF-8 strings (see GHC.Base.unpackCStringUtf8).
| x <= 0x07ff -> do
poke ptr (fromIntegral (0xC0 .|. ((x `shiftR` 6) .&. 0x1F)))
pokeElemOff ptr 1 (fromIntegral (0x80 .|. (x .&. 0x3F)))
return (ptr `plusPtr` 2)
| x <= 0xffff -> do
poke ptr (fromIntegral (0xE0 .|. (x `shiftR` 12) .&. 0x0F))
pokeElemOff ptr 1 (fromIntegral (0x80 .|. (x `shiftR` 6) .&. 0x3F))
pokeElemOff ptr 2 (fromIntegral (0x80 .|. (x .&. 0x3F)))
return (ptr `plusPtr` 3)
| otherwise -> do
poke ptr (fromIntegral (0xF0 .|. (x `shiftR` 18)))
pokeElemOff ptr 1 (fromIntegral (0x80 .|. ((x `shiftR` 12) .&. 0x3F)))
pokeElemOff ptr 2 (fromIntegral (0x80 .|. ((x `shiftR` 6) .&. 0x3F)))
pokeElemOff ptr 3 (fromIntegral (0x80 .|. (x .&. 0x3F)))
return (ptr `plusPtr` 4)
utf8EncodeString :: Ptr Word8 -> String -> IO ()
utf8EncodeString ptr str = go ptr str
where STRICT2(go)
go _ [] = return ()
go ptr (c:cs) = do
ptr' <- utf8EncodeChar c ptr
go ptr' cs
utf8EncodedLength :: String -> Int
utf8EncodedLength str = go 0 str
where STRICT2(go)
go n [] = n
go n (c:cs)
| ord c > 0 && ord c <= 0x007f = go (n+1) cs
| ord c <= 0x07ff = go (n+2) cs
| ord c <= 0xffff = go (n+3) cs
| otherwise = go (n+4) cs
-- -----------------------------------------------------------------------------
-- The Z-encoding
{-
This is the main name-encoding and decoding function. It encodes any
string into a string that is acceptable as a C name. This is done
right before we emit a symbol name into the compiled C or asm code.
Z-encoding of strings is cached in the FastString interface, so we
never encode the same string more than once.
The basic encoding scheme is this.
* Tuples (,,,) are coded as Z3T
* Alphabetic characters (upper and lower) and digits
all translate to themselves;
except 'Z', which translates to 'ZZ'
and 'z', which translates to 'zz'
We need both so that we can preserve the variable/tycon distinction
* Most other printable characters translate to 'zx' or 'Zx' for some
alphabetic character x
* The others translate as 'znnnU' where 'nnn' is the decimal number
of the character
Before After
--------------------------
Trak Trak
foo_wib foozuwib
> zg
>1 zg1
foo# foozh
foo## foozhzh
foo##1 foozhzh1
fooZ fooZZ
:+ ZCzp
() Z0T 0-tuple
(,,,,) Z5T 5-tuple
(# #) Z1H unboxed 1-tuple (note the space)
(#,,,,#) Z5H unboxed 5-tuple
(NB: There is no Z1T nor Z0H.)
-}
type UserString = String -- As the user typed it
type EncodedString = String -- Encoded form
zEncodeString :: UserString -> EncodedString
zEncodeString cs = case maybe_tuple cs of
Just n -> n -- Tuples go to Z2T etc
Nothing -> go cs
where
go [] = []
go (c:cs) = encode_digit_ch c ++ go' cs
go' [] = []
go' (c:cs) = encode_ch c ++ go' cs
unencodedChar :: Char -> Bool -- True for chars that don't need encoding
unencodedChar 'Z' = False
unencodedChar 'z' = False
unencodedChar c = c >= 'a' && c <= 'z'
|| c >= 'A' && c <= 'Z'
|| c >= '0' && c <= '9'
-- If a digit is at the start of a symbol then we need to encode it.
-- Otherwise package names like 9pH-0.1 give linker errors.
encode_digit_ch :: Char -> EncodedString
encode_digit_ch c | c >= '0' && c <= '9' = encode_as_unicode_char c
encode_digit_ch c | otherwise = encode_ch c
encode_ch :: Char -> EncodedString
encode_ch c | unencodedChar c = [c] -- Common case first
-- Constructors
encode_ch '(' = "ZL" -- Needed for things like (,), and (->)
encode_ch ')' = "ZR" -- For symmetry with (
encode_ch '[' = "ZM"
encode_ch ']' = "ZN"
encode_ch ':' = "ZC"
encode_ch 'Z' = "ZZ"
-- Variables
encode_ch 'z' = "zz"
encode_ch '&' = "za"
encode_ch '|' = "zb"
encode_ch '^' = "zc"
encode_ch '$' = "zd"
encode_ch '=' = "ze"
encode_ch '>' = "zg"
encode_ch '#' = "zh"
encode_ch '.' = "zi"
encode_ch '<' = "zl"
encode_ch '-' = "zm"
encode_ch '!' = "zn"
encode_ch '+' = "zp"
encode_ch '\'' = "zq"
encode_ch '\\' = "zr"
encode_ch '/' = "zs"
encode_ch '*' = "zt"
encode_ch '_' = "zu"
encode_ch '%' = "zv"
encode_ch c = encode_as_unicode_char c
encode_as_unicode_char :: Char -> EncodedString
encode_as_unicode_char c = 'z' : if isDigit (head hex_str) then hex_str
else '0':hex_str
where hex_str = showHex (ord c) "U"
-- ToDo: we could improve the encoding here in various ways.
-- eg. strings of unicode characters come out as 'z1234Uz5678U', we
-- could remove the 'U' in the middle (the 'z' works as a separator).
zDecodeString :: EncodedString -> UserString
zDecodeString [] = []
zDecodeString ('Z' : d : rest)
| isDigit d = decode_tuple d rest
| otherwise = decode_upper d : zDecodeString rest
zDecodeString ('z' : d : rest)
| isDigit d = decode_num_esc d rest
| otherwise = decode_lower d : zDecodeString rest
zDecodeString (c : rest) = c : zDecodeString rest
decode_upper, decode_lower :: Char -> Char
decode_upper 'L' = '('
decode_upper 'R' = ')'
decode_upper 'M' = '['
decode_upper 'N' = ']'
decode_upper 'C' = ':'
decode_upper 'Z' = 'Z'
decode_upper ch = {-pprTrace "decode_upper" (char ch)-} ch
decode_lower 'z' = 'z'
decode_lower 'a' = '&'
decode_lower 'b' = '|'
decode_lower 'c' = '^'
decode_lower 'd' = '$'
decode_lower 'e' = '='
decode_lower 'g' = '>'
decode_lower 'h' = '#'
decode_lower 'i' = '.'
decode_lower 'l' = '<'
decode_lower 'm' = '-'
decode_lower 'n' = '!'
decode_lower 'p' = '+'
decode_lower 'q' = '\''
decode_lower 'r' = '\\'
decode_lower 's' = '/'
decode_lower 't' = '*'
decode_lower 'u' = '_'
decode_lower 'v' = '%'
decode_lower ch = {-pprTrace "decode_lower" (char ch)-} ch
-- Characters not having a specific code are coded as z224U (in hex)
decode_num_esc :: Char -> EncodedString -> UserString
decode_num_esc d rest
= go (digitToInt d) rest
where
go n (c : rest) | isHexDigit c = go (16*n + digitToInt c) rest
go n ('U' : rest) = chr n : zDecodeString rest
go n other = error ("decode_num_esc: " ++ show n ++ ' ':other)
decode_tuple :: Char -> EncodedString -> UserString
decode_tuple d rest
= go (digitToInt d) rest
where
-- NB. recurse back to zDecodeString after decoding the tuple, because
-- the tuple might be embedded in a longer name.
go n (c : rest) | isDigit c = go (10*n + digitToInt c) rest
go 0 ('T':rest) = "()" ++ zDecodeString rest
go n ('T':rest) = '(' : replicate (n-1) ',' ++ ")" ++ zDecodeString rest
go 1 ('H':rest) = "(# #)" ++ zDecodeString rest
go n ('H':rest) = '(' : '#' : replicate (n-1) ',' ++ "#)" ++ zDecodeString rest
go n other = error ("decode_tuple: " ++ show n ++ ' ':other)
{-
Tuples are encoded as
Z3T or Z3H
for 3-tuples or unboxed 3-tuples respectively. No other encoding starts
Z<digit>
* "(# #)" is the tycon for an unboxed 1-tuple (not 0-tuple)
There are no unboxed 0-tuples.
* "()" is the tycon for a boxed 0-tuple.
There are no boxed 1-tuples.
-}
maybe_tuple :: UserString -> Maybe EncodedString
maybe_tuple "(# #)" = Just("Z1H")
maybe_tuple ('(' : '#' : cs) = case count_commas (0::Int) cs of
(n, '#' : ')' : _) -> Just ('Z' : shows (n+1) "H")
_ -> Nothing
maybe_tuple "()" = Just("Z0T")
maybe_tuple ('(' : cs) = case count_commas (0::Int) cs of
(n, ')' : _) -> Just ('Z' : shows (n+1) "T")
_ -> Nothing
maybe_tuple _ = Nothing
count_commas :: Int -> String -> (Int, String)
count_commas n (',' : cs) = count_commas (n+1) cs
count_commas n cs = (n,cs)
|
ryantm/ghc
|
compiler/utils/Encoding.hs
|
Haskell
|
bsd-3-clause
| 13,525
|
-- Check that "->" is an instance of Eval
module ShouldSucceed where
instance Show (a->b) where
show _ = error "attempt to show function"
instance (Eq b) => Eq (a -> b) where
(==) f g = error "attempt to compare functions"
-- Since Eval is a superclass of Num this fails
-- unless -> is an instance of Eval
instance (Num b) => Num (a -> b) where
f + g = \a -> f a + g a
f - g = \a -> f a - g a
f * g = \a -> f a * g a
negate f = \a -> negate (f a)
abs f = \a -> abs (f a)
signum f = \a -> signum (f a)
fromInteger n = \a -> fromInteger n
|
forked-upstream-packages-for-ghcjs/ghc
|
testsuite/tests/typecheck/should_compile/tc088.hs
|
Haskell
|
bsd-3-clause
| 715
|
-- This one killed GHC 6.4 because it bogusly attributed
-- the CPR property to the construtor T
-- Result: a mkWWcpr crash
-- Needs -prof -auto-all to show it up
module ShouldCompile where
newtype T a = T { unT :: a }
f = unT
test cs = f $ case cs of
[] -> T []
(x:xs) -> T $ test cs
|
forked-upstream-packages-for-ghcjs/ghc
|
testsuite/tests/stranal/should_compile/newtype.hs
|
Haskell
|
bsd-3-clause
| 300
|
{-# LANGUAGE Trustworthy #-}
module Check03_A (
trace
) where
import qualified Debug.Trace as D
import qualified Data.ByteString.Lazy.Char8 as BS
-- | Allowed declasification
trace :: String -> a -> a
trace s = D.trace $ s ++ show a3
a3 :: BS.ByteString
a3 = BS.take 3 $ BS.repeat 'a'
|
urbanslug/ghc
|
testsuite/tests/safeHaskell/check/Check03_A.hs
|
Haskell
|
bsd-3-clause
| 301
|
module Tests.Machine (tests) where
import Machine
import Data.Machine
import Test.Framework
import Test.Framework.Providers.QuickCheck2 (testProperty)
import Test.QuickCheck
import Test.QuickCheck.Property as Property
tests :: [Test]
tests = [ (testProperty "concatenation of result equal to input" prop_groupBy_concat)
, (testProperty "sublists contain only equal elements" prop_groupBy_equalelem)
, (testProperty "adjacent sublists do not contain equal elements" prop_groupBy_adjacentsNotEqual)]
prop_groupBy_concat :: [Int] -> Property.Result
prop_groupBy_concat xs =
mkResult (Just $ concat grouped == xs) msg
where
grouped = run (source xs ~> groupBy (==))
msg = "grouping: " ++ (show grouped)
prop_groupBy_equalelem :: [Int] -> Property.Result
prop_groupBy_equalelem xs =
mkResult (Just $ all sublistEq grouped) msg
where
grouped = run (source xs ~> groupBy (==))
msg = "grouping: " ++ (show grouped)
sublistEq [] = True
sublistEq (x:xs) = all (==x) xs
prop_groupBy_adjacentsNotEqual :: [Int] -> Property.Result
prop_groupBy_adjacentsNotEqual xs =
mkResult (Just $ adjNotEqual grouped) msg
where
grouped = run (source xs ~> groupBy (==))
msg = "grouping: " ++ (show grouped)
adjNotEqual (a:b:xs) = (not $ eq a b) && adjNotEqual (b:xs)
adjNotEqual _ = True
eq (a:_) (b:_) = a == b
eq _ _ = False
mkResult :: Maybe Bool -> String -> Property.Result
mkResult result msg = MkResult result True msg Nothing False [] []
|
danstiner/clod
|
test/Tests/Machine.hs
|
Haskell
|
mit
| 1,504
|
{-|
Module : Language.Vigil.Simplify.Top
Description :
Copyright : (c) Jacob Errington and Frederic Lafrance, 2016
License : MIT
Maintainer : goto@mail.jerrington.me
Stability : experimental
Simplifications for the top-level (globals and function declarations).
-}
{-# LANGUAGE OverloadedStrings #-}
module Language.Vigil.Simplify.Top where
import Data.List ( partition )
import Language.Common.Monad.Traverse
import Language.GoLite.Syntax.Types as G
import qualified Language.GoLite.Types as T
import Language.Vigil.Simplify.Core
import Language.Vigil.Simplify.Expr
import Language.Vigil.Simplify.Stmt
import Language.Vigil.Syntax as V
import Language.Vigil.Syntax.TyAnn
import Language.Vigil.Types
import Language.X86.Mangling
import qualified Data.Map as M
import qualified Data.Set as S
import Data.Maybe ( catMaybes )
import Data.Tuple ( swap )
-- | Simplifies a GoLite package into a Vigil program.
--
-- Global variables are separated from functions, and their initializations are
-- moved to a specific function. Functions themselves have their body simplified.
simplifyPackage :: TySrcAnnPackage -> Simplify TyAnnProgram
simplifyPackage (Package _ decls) = do
let (globs, funs) = partition isGlob decls
let globs' = filter isVar globs
fs <- fmap catMaybes $ forM funs $ \(G.TopLevelFun (G.FunDecl i ps _ bod)) -> do
modify (\s -> s { newDeclarations = [] }) -- Reset state of declarations.
bod' <- forM bod simplifyStmt -- Simplify body
ps' <- fmap catMaybes $ forM ps $ \(pid, _) -> do
m <- reinterpretGlobalIdEx pid
pure $ case m of
Nothing -> Nothing
Just i' -> Just $ V.VarDecl i'
nis' <- gets newDeclarations
let nvs' = map (swap . fmap V.VarDecl . swap) nis'
-- Look at the
forM_ nvs' (\(V.VarDecl i, b) ->
when (not b) $ modify $ \s -> s { inis = S.insert i $ inis s })
m <- reinterpretGlobalIdEx i
case m of
Nothing -> pure Nothing
Just i' -> pure $ Just $ V.FunDecl
{ _funDeclName = i'
, _funDeclArgs = ps'
, _funDeclVars = map fst nvs'
, _funDeclBody = concat bod'
}
vs <- forM globs' $ \(G.TopLevelDecl (G.VarDecl (G.VarDeclBody is _ es))) -> do
case es of
[] -> forM is $ \i -> do
m <- reinterpretGlobalIdEx i
case m of
Nothing -> pure (Nothing, [])
-- Come up with an initializer right here
Just i' -> pure (Just $ V.VarDecl i', [Fix $ V.Initialize i'])
_ -> forM (zip is es) $ \(i, e) -> do
m <- reinterpretGlobalIdEx i
(e', s) <- realizeToExpr =<< simplifyExpr e
pure $ case m of
Nothing ->
( Nothing
, s ++ [Fix $ V.ExprStmt e']
)
Just i' ->
( Just $ V.VarDecl i'
, s ++ [
Fix $ V.Assign (Ann (gidTy i') $ ValRef $ IdentVal i') e'
]
)
ss <- gets strings
-- create the initialization calls for the string literals
(vs2, ss') <- fmap unzip $ forM (M.assocs ss) $ \(g, str) -> do
gi <- makeIdent
stringType
(T.symbolFromString $ T.stringFromSymbol (gidOrigName g) ++ "data")
pure $
( ( Just $ V.VarDecl g
, [Fix $ V.Assign
(Ann (gidTy g) $ ValRef $ IdentVal g)
(Ann stringType $ V.InternalCall
(mangleFuncName "from_cstr")
[IdentValD gi]
)
]
)
, (gi, str)
)
modify $ \s -> s { strings = M.fromList ss' }
-- vs: pairs of declarations and their initializing statements
let vs' = concat vs ++ vs2
nis <- gets newDeclarations
let nvs = map (swap . fmap V.VarDecl . swap) nis
let fInit = V.FunDecl
{ _funDeclName = artificialGlobalId
(-1)
(mangleFuncName "gocode_init")
(funcType [] voidType)
, _funDeclArgs = []
, _funDeclVars = (map fst nvs)
, _funDeclBody = concat $ map snd vs'
}
let (main, notMain) = partition
(\(V.FunDecl i _ _ _) -> gidOrigName i == "main") (fInit:fs)
when (length main > 1) (throwError $ InvariantViolation "More than one main")
pure V.Program
{ _globals = catMaybes $ map fst vs'
, _funcs = notMain
, _main = case main of
[x] -> Just x
[] -> Nothing
_ -> error "Laws of physics broken"
}
where
isGlob (TopLevelDecl _) = True
isGlob _ = False
isVar (TopLevelDecl (G.VarDecl _)) = True
isVar _ = False
|
djeik/goto
|
libgoto/Language/Vigil/Simplify/Top.hs
|
Haskell
|
mit
| 5,105
|
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PatternSynonyms #-}
module Hickory.Graphics.Shader
( loadShader,
loadShaderFromPaths,
useShader,
getAttribLocation,
UniformLoc,
retrieveLoc,
ShaderID,
Shader (..),
)
where
import Control.Monad
import qualified Data.HashMap.Strict as HashMap
import Data.Int (Int32)
import Data.Text (Text, unpack)
import qualified Data.Text.Foreign as FText
import Data.Word (Word32)
import Foreign.C.String
import Foreign.Marshal.Alloc
import Foreign.Marshal.Array
import Foreign.Marshal.Utils
import Foreign.Ptr
import Foreign.Storable
import Graphics.GL.Compatibility41 as GL
import Hickory.Utils.Utils
import Data.Maybe (catMaybes, fromMaybe)
data Shader = Shader
{ program :: ProgramID,
shaderIds :: [ShaderID],
uniformLocs :: HashMap.HashMap String UniformLoc
}
deriving (Show)
type UniformLoc = Int32
type ShaderID = Word32
type ProgramID = Word32
retrieveLoc :: String -> Shader -> Maybe UniformLoc
retrieveLoc name shader = HashMap.lookup name (uniformLocs shader)
glGetShaderi shaderId x = alloca (\ptr -> glGetShaderiv shaderId x ptr >> peek ptr)
glGetProgrami programId x = alloca (\ptr -> glGetProgramiv programId x ptr >> peek ptr)
glGetBoolean boolean = (== GL_TRUE) <$> alloca (\ptr -> glGetBooleanv boolean ptr >> peek ptr)
retrieveLog :: (GLenum -> IO GLint) -> (GLsizei -> Ptr GLsizei -> Ptr GLchar -> IO ()) -> IO (Maybe String)
retrieveLog lenFun infoFun = do
infoLen <- lenFun GL_INFO_LOG_LENGTH
let infoLen' = fromIntegral infoLen
if infoLen > 1
then do
info <- allocaArray infoLen' $ \buf -> do
infoFun infoLen nullPtr buf
peekCStringLen (buf, infoLen' - 1)
return $ Just info
else return Nothing
compileShader :: Text -> GLenum -> IO (Maybe GLuint)
compileShader source shaderType = do
compileSupported <- glGetBoolean GL_SHADER_COMPILER
unless compileSupported (error "ERROR: Shader compilation not supported.")
shaderId <- glCreateShader shaderType
withMany FText.withCStringLen [source] $ \strLens -> do
let (strs, lengths) = unzip strLens
withArray strs $ \strsArr ->
withArray (map fromIntegral lengths) $ \lenArr ->
glShaderSource shaderId 1 strsArr lenArr
glCompileShader shaderId
compiled <- glGetShaderi shaderId GL_COMPILE_STATUS
let didCompile = compiled /= 0
if didCompile
then return $ Just shaderId
else do
infoLog <- retrieveLog (glGetShaderi shaderId) (glGetShaderInfoLog shaderId)
case infoLog of
Just i -> do
print ("*** ERROR: Couldn't compile shader" :: String)
print i
_ -> return ()
glDeleteShader shaderId
return Nothing
linkProgram :: GLuint -> [GLuint] -> IO Bool
linkProgram programId shaders = do
mapM_ (glAttachShader programId) shaders
glLinkProgram programId
linked <- glGetProgrami programId GL_LINK_STATUS
let didLink = linked /= 0
unless didLink $ do
infoLog <- retrieveLog (glGetProgrami programId) (glGetProgramInfoLog programId)
case infoLog of
Just i -> do
print ("*** ERROR: Can't link shader program" :: String)
print i
_ -> return ()
return didLink
getAttribLocation progId name = withCString name (glGetAttribLocation progId)
getUniformLocation progId name = withCString name (glGetUniformLocation progId)
shaderSourceForPath :: String -> IO Text
shaderSourceForPath = readFileAsText
loadShaderFromPaths :: String -> String -> String -> [String] -> IO Shader
loadShaderFromPaths resPath vert frag uniforms = do
let prefix = resPath ++ "/Shaders/"
vpath = prefix ++ vert
fpath = prefix ++ frag
vsource <- shaderSourceForPath vpath
fsource <- shaderSourceForPath fpath
loadShader vsource Nothing fsource uniforms
loadShader :: Text -> Maybe Text -> Text -> [String] -> IO Shader
loadShader vert mgeom frag uniforms = do
let shaders = catMaybes
[ (,GL_GEOMETRY_SHADER) <$> mgeom
, Just (vert, GL_VERTEX_SHADER)
, Just (frag, GL_FRAGMENT_SHADER)
]
shIds <- forM shaders \(source, typ) -> do
fromMaybe (error $ "Couldn't compile shader: " ++ unpack source) <$>
compileShader source typ
prog <- buildShaderProgram shIds uniforms
case prog of
Just pr -> return pr
Nothing -> do
mapM_ glDeleteShader shIds
error $ "Failed to link shader program: " ++ unpack vert ++ "\n\n" ++ maybe "" unpack mgeom ++ "\n\n" ++ unpack frag
buildShaderProgram :: [ShaderID] -> [String] -> IO (Maybe Shader)
buildShaderProgram shaders uniforms = do
programId <- glCreateProgram
linked <- linkProgram programId shaders
if not linked
then return Nothing
else do
let sh = Shader programId shaders
res <-
sh
<$> ( foldM
( \hsh name -> do
loc <- getUniformLocation programId name
return $ HashMap.insert name loc hsh
)
HashMap.empty
uniforms
)
return $ Just res
useShader :: Shader -> IO ()
useShader Shader {program} = glUseProgram program
|
asivitz/Hickory
|
Hickory/Graphics/Shader.hs
|
Haskell
|
mit
| 5,182
|
import Data.List
phi :: Int -> Int
phi n = product xs
where
xs = map (\(p, m) -> (p - 1) * p ^ (m - 1)) (primeFactorsMult n)
primeFactorsMult :: Int -> [(Int, Int)]
primeFactorsMult = map encoder . group . primeFactors
where
encoder xs = (head xs, length xs)
primeFactors :: Int -> [Int]
primeFactors n = primeFactors' n 2
primeFactors' :: Int -> Int -> [Int]
primeFactors' n p
| isFactor n p && n' > 1 = p : primeFactors' n' p
| not $ isFactor n p && n > 1 = primeFactors' n (p + 1)
| otherwise = [p]
where
n' = n `div` p
isFactor n p = n `mod` p == 0
nextPrime :: Int -> Int
nextPrime n
| isPrime (n + 1) = n + 1
| otherwise = nextPrime (n + 1)
isPrime :: Int -> Bool
isPrime n = isPrime' n 2
isPrime' :: Int -> Int -> Bool
isPrime' 2 _ = True
isPrime' n k
| (n - 1) == k = True
| n `mod` k == 0 = False
| otherwise = isPrime' n (k + 1)
|
curiousily/haskell-99problems
|
37.hs
|
Haskell
|
mit
| 870
|
-- -------------------------------------------------------------------------------------
-- Author: Sourabh S Joshi (cbrghostrider); Copyright - All rights reserved.
-- For email, run on linux (perl v5.8.5):
-- perl -e 'print pack "H*","736f75726162682e732e6a6f73686940676d61696c2e636f6d0a"'
-- -------------------------------------------------------------------------------------
import Data.List
import Data.HashTable.IO as HT
import Control.Monad
type HashTable k v = HT.BasicHashTable k v
createHashTable ::IO (HashTable Int Int)
createHashTable = do
ht <- HT.new
return ht
solveProblem :: String -> String -> IO [Int]
solveProblem ips nsstr = do
htable <- createHashTable
let [n, k] = map read . words $ ips
let ns = map read . words $ nsstr
forM_ ns $ \n -> do
check <- HT.lookup htable n
if check == Nothing
then do
HT.insert htable n 1
else do
let Just val = check
HT.insert htable n (val+1)
kvs <- HT.toList htable
let fns = map fst . filter ((>=k) . snd) $ kvs
let os = filter (`elem` fns) $ ns
if null os then return [-1] else return (nub os)
runTestCase :: Int -> IO ()
runTestCase 0 = return ()
runTestCase n = do
ips <- getLine
ns <- getLine
ans <- solveProblem ips ns
putStrLn $ unwords . map show $ ans
runTestCase (n-1)
main :: IO ()
main = do
ntc <- getLine
runTestCase (read ntc)
|
cbrghostrider/Hacking
|
HackerRank/FunctionalProgramming/Recursion/filterElements_HashTable_fast.hs
|
Haskell
|
mit
| 1,458
|
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeSynonymInstances #-}
module Firestone.Player ( drawCard
, summonMinionAt
) where
import Firestone.Types
import Firestone.Utils
import Control.Monad.State
import Control.Lens
drawCard :: State Player ()
drawCard = do
player <- get
case length (player^.deck.cards) of
0 -> do
hero.health -= player^.fatigue
fatigue += 1
otherwise -> do
let (x:xs) = player^.deck.cards
hand %= take 10 . (|> x)
deck.cards .= xs
summonMinionAt :: Int -> Minion -> State Player ()
summonMinionAt pos m = activeMinions %= insertAt pos m
|
Jinxit/firestone
|
src/Firestone/Player.hs
|
Haskell
|
mit
| 870
|
module Test (
testWorldRod
, testWorldCircle
, testWorldRigidSkin
, testWorldBlob
, testWorldGrid
) where
import Data.Tuple
import Control.Monad as M
import Control.Monad.State.Lazy
import Control.Applicative
import Internal
import Vector
import Types
testWorldRod :: World
testWorldRod = execState f $ makeEmptyWorld "testWorldRod"
where
f = do
node1 <- insPointMass (PointMass (Vector2D 100 100) (Vector2D 0 0) 1)
node2 <- insPointMass (PointMass (Vector2D 200 200) (Vector2D 0 0) 1)
insSpring (Spring 1 50 0) node1 node2
testWorldCircle :: World
testWorldCircle = execState f $ makeEmptyWorld "testWorldCircle"
where
f = let nodeCount = 32
r = 100
(cx, cy) = (400, 200)
spring = Spring 1 25 0
rotate n = take . length <*> drop n . cycle
in do
nodeList <- M.forM (drop 1 [0, 2 * pi / nodeCount .. 2 * pi]) $ \angle ->
insPointMass $ PointMass (Vector2D ((cos angle) * r + cx)
((sin angle) * r + cy))
(Vector2D 0 0)
1
M.sequence $ zipWith (insSpring spring) <*> rotate 1 $ nodeList
testWorldBlob :: World
testWorldBlob = execState f $ makeEmptyWorld "testWorldBlob"
where
f = let nodeCount = 16
r1 = 100
r2 = 150
(cx, cy) = (400, 200)
innerSpring = Spring 0.3 70 0.5
outerSpring = Spring 1 50 0.5
rigidSpring = Spring 3 70 0.5
rotate n = take . length <*> drop n . cycle
in do
centerNode <- insPointMass $ PointMass (Vector2D cx cy) (Vector2D 0 0) 1
nodeList1 <- M.forM (drop 1 [0, 2 * pi / nodeCount .. 2 * pi]) $ \angle ->
insPointMass $ PointMass (Vector2D ((cos angle) * r1 + cx)
((sin angle) * r1 + cy))
(Vector2D 0 0)
1
nodeList2 <- M.forM (drop 1 [0, 2 * pi / nodeCount .. 2 * pi]) $ \angle ->
insPointMass $ PointMass (Vector2D ((cos angle) * r2 + cx)
((sin angle) * r2 + cy))
(Vector2D 0 0)
1
M.sequence_ $ zipWith (insSpring outerSpring) <*> rotate 1 $ nodeList1
M.sequence_ $ zipWith (insSpring outerSpring) <*> rotate 1 $ nodeList2
M.sequence_ $ zipWith (insSpring innerSpring) nodeList1 nodeList2
M.sequence_ $ zipWith (insSpring innerSpring) (rotate 1 nodeList1) nodeList2
M.sequence_ $ zipWith (insSpring innerSpring) nodeList1 (rotate 1 nodeList2)
M.forM nodeList1 $ insSpring rigidSpring centerNode
testWorldRigidSkin :: World
testWorldRigidSkin = execState f $ makeEmptyWorld "testWorldRigidSkin"
where
f = let nodeCount = 16
r = 100
(cx, cy) = (400, 200)
spring1 = Spring 5 50 0.1
spring2 = Spring 5 60 0.1
spring3 = Spring 5 70 0.1
rotate n = take . length <*> drop n . cycle
in do
nodeList <- M.forM (drop 1 [0, 2 * pi / nodeCount .. 2 * pi]) $ \angle ->
insPointMass $ PointMass (Vector2D ((cos angle) * r + cx)
((sin angle) * r + cy))
(Vector2D 0 0)
1
M.sequence_ $ zipWith (insSpring spring1) <*> rotate 1 $ nodeList
M.sequence_ $ zipWith (insSpring spring2) <*> rotate 2 $ nodeList
M.sequence_ $ zipWith (insSpring spring3) <*> rotate 3 $ nodeList
testWorldGrid :: World
testWorldGrid = execState f $ makeEmptyWorld "testWorldGrid"
where
f = let spring = Spring 50 50 0.1
in do
nodeListXY <- M.forM [0, 1..5] $ \x -> do
nodeListY <- M.forM [0, 1..5] $ \y -> do
let sx = x * 50
sy = y * 50
insPointMass (PointMass (Vector2D (400 + sx) (50 + sy)) (Vector2D 0 0) 1)
M.sequence_ $ zipWith (insSpring spring) <*> drop 1 $ nodeListY
return nodeListY
M.sequence_ $ concat $ zipWith (zipWith (insSpring spring)) (drop 1 nodeListXY) nodeListXY
|
ThatSnail/hs-softbody
|
Test.hs
|
Haskell
|
mit
| 4,841
|
module Main where
import LI11718
import SimulateT6
import AnimateT6
import System.Environment
import Text.Read
main = do
animaT6 (${mapa}) (${pista}) (${frames}) (${players})
|
hpacheco/HAAP
|
examples/plab/oracle/AnimateT6Match.hs
|
Haskell
|
mit
| 182
|
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE ForeignFunctionInterface #-}
{-# LANGUAGE OverloadedStrings #-}
import Control.Monad (void)
import Data.Monoid ((<>))
import qualified Data.Vector.Storable.Mutable as V
import Foreign.C.Types
import Foreign.ForeignPtr (mallocForeignPtrBytes)
import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr)
import qualified Language.Haskell.TH as TH
import Prelude
import qualified Test.Hspec as Hspec
import Text.RawString.QQ (r)
import Foreign.Marshal.Alloc (alloca)
import Foreign.Storable (peek, poke)
import qualified Language.C.Inline as C
import qualified Language.C.Inline.Unsafe as CU
import qualified Language.C.Inline.Interruptible as CI
import qualified Language.C.Inline.Internal as C
import qualified Language.C.Inline.ContextSpec
import qualified Language.C.Inline.ParseSpec
import qualified Language.C.Types as C
import qualified Language.C.Types.ParseSpec
import Dummy
C.context (C.baseCtx <> C.fptrCtx <> C.funCtx <> C.vecCtx <> C.bsCtx)
C.include "<math.h>"
C.include "<stddef.h>"
C.include "<stdint.h>"
C.include "<stdio.h>"
C.verbatim [r|
int francescos_mul(int x, int y) {
return x * y;
}
|]
foreign import ccall "francescos_mul" francescos_mul :: Int -> Int -> Int
main :: IO ()
main = Hspec.hspec $ do
Hspec.describe "Language.C.Types.Parse" Language.C.Types.ParseSpec.spec
Hspec.describe "Language.C.Inline.Context" Language.C.Inline.ContextSpec.spec
Hspec.describe "Language.C.Inline.Parse" Language.C.Inline.ParseSpec.spec
Hspec.describe "TH integration" $ do
Hspec.it "inlineCode" $ do
let c_add = $(C.inlineCode $ C.Code
TH.Unsafe -- Call safety
Nothing
[t| Int -> Int -> Int |] -- Call type
"francescos_add" -- Call name
-- C Code
[r| int francescos_add(int x, int y) { int z = x + y; return z; } |]
False) -- not a function pointer
c_add 3 4 `Hspec.shouldBe` 7
Hspec.it "inlineItems" $ do
let c_add3 = $(do
here <- TH.location
C.inlineItems
TH.Unsafe
False -- not a function pointer
Nothing -- no postfix
here
[t| CInt -> CInt |]
(C.quickCParser_ True "int" C.parseType)
[("x", C.quickCParser_ True "int" C.parseType)]
[r| return x + 3; |])
c_add3 1 `Hspec.shouldBe` 1 + 3
Hspec.it "inlineExp" $ do
let x = $(do
here <- TH.location
C.inlineExp
TH.Safe
here
[t| CInt |]
(C.quickCParser_ True "int" C.parseType)
[]
[r| 1 + 4 |])
x `Hspec.shouldBe` 1 + 4
Hspec.it "inlineCode" $ do
francescos_mul 3 4 `Hspec.shouldBe` 12
Hspec.it "exp" $ do
let x = 3
let y = 4
z <- [C.exp| int{ $(int x) + $(int y) + 5 } |]
z `Hspec.shouldBe` x + y + 5
Hspec.it "pure" $ do
let x = 2
let y = 10
let z = [C.pure| int{ $(int x) + 10 + $(int y) } |]
z `Hspec.shouldBe` x + y + 10
Hspec.it "unsafe exp" $ do
let x = 2
let y = 10
z <- [CU.exp| int{ 7 + $(int x) + $(int y) } |]
z `Hspec.shouldBe` x + y + 7
Hspec.it "interruptible exp" $ do
let x = 2
let y = 10
z <- [CI.exp| int{ 7 + $(int x) + $(int y) } |]
z `Hspec.shouldBe` x + y + 7
Hspec.it "void exp" $ do
[C.exp| void { printf("Hello\n") } |]
Hspec.it "Foreign.C.Types library types" $ do
let x = 1
pd <- [C.block| ptrdiff_t { char a[2]; return &a[1] - &a[0] + $(ptrdiff_t x); } |]
pd `Hspec.shouldBe` 2
sz <- [C.exp| size_t { sizeof (char) } |]
sz `Hspec.shouldBe` 1
um <- [C.exp| uintmax_t { UINTMAX_MAX } |]
um `Hspec.shouldBe` maxBound
Hspec.it "stdint.h types" $ do
let x = 2
i16 <- [C.exp| int16_t { 1 + $(int16_t x) } |]
i16 `Hspec.shouldBe` 3
let y = 9
u32 <- [C.exp| uint32_t { $(uint32_t y) * 7 } |]
u32 `Hspec.shouldBe` 63
Hspec.it "foreign pointer argument" $ do
fptr <- mallocForeignPtrBytes 32
ptr <- [C.exp| int* { $fptr-ptr:(int *fptr) } |]
ptr `Hspec.shouldBe` unsafeForeignPtrToPtr fptr
Hspec.it "function pointer argument" $ do
let ackermann m n
| m == 0 = n + 1
| m > 0 && n == 0 = ackermann (m - 1) 1
| m > 0 && n > 0 = ackermann (m - 1) (ackermann m (n - 1))
| otherwise = error "ackermann"
ackermannPtr <- $(C.mkFunPtr [t| CInt -> CInt -> IO CInt |]) $ \m n -> return $ ackermann m n
let x = 3
let y = 4
z <- [C.exp| int { $(int (*ackermannPtr)(int, int))($(int x), $(int y)) } |]
z `Hspec.shouldBe` ackermann x y
Hspec.it "function pointer result" $ do
c_add <- [C.exp| int (*)(int, int) { &francescos_add } |]
x <- $(C.peekFunPtr [t| CInt -> CInt -> IO CInt |]) c_add 1 2
x `Hspec.shouldBe` 1 + 2
Hspec.it "quick function pointer argument" $ do
let ackermann m n
| m == 0 = n + 1
| m > 0 && n == 0 = ackermann (m - 1) 1
| m > 0 && n > 0 = ackermann (m - 1) (ackermann m (n - 1))
| otherwise = error "ackermann"
let ackermann_ m n = return $ ackermann m n
let x = 3
let y = 4
z <- [C.exp| int { $fun:(int (*ackermann_)(int, int))($(int x), $(int y)) } |]
z `Hspec.shouldBe` ackermann x y
Hspec.it "function pointer argument (pure)" $ do
let ackermann m n
| m == 0 = n + 1
| m > 0 && n == 0 = ackermann (m - 1) 1
| m > 0 && n > 0 = ackermann (m - 1) (ackermann m (n - 1))
| otherwise = error "ackermann"
ackermannPtr <- $(C.mkFunPtr [t| CInt -> CInt -> CInt |]) ackermann
let x = 3
let y = 4
let z = [C.pure| int { $(int (*ackermannPtr)(int, int))($(int x), $(int y)) } |]
z `Hspec.shouldBe` ackermann x y
Hspec.it "quick function pointer argument (pure)" $ do
let ackermann m n
| m == 0 = n + 1
| m > 0 && n == 0 = ackermann (m - 1) 1
| m > 0 && n > 0 = ackermann (m - 1) (ackermann m (n - 1))
| otherwise = error "ackermann"
let x = 3
let y = 4
let z = [C.pure| int { $fun:(int (*ackermann)(int, int))($(int x), $(int y)) } |]
z `Hspec.shouldBe` ackermann x y
Hspec.it "test mkFunPtrFromName" $ do
fun <- $(C.mkFunPtrFromName 'dummyFun)
z <- [C.exp| double { $(double (*fun)(double))(3.0) } |]
z' <- dummyFun 3.0
z `Hspec.shouldBe` z'
Hspec.it "vectors" $ do
let n = 10
vec <- V.replicate (fromIntegral n) 3
sum' <- V.unsafeWith vec $ \ptr -> [C.block| int {
int i;
int x = 0;
for (i = 0; i < $(int n); i++) {
x += $(int *ptr)[i];
}
return x;
} |]
sum' `Hspec.shouldBe` 3 * 10
Hspec.it "quick vectors" $ do
vec <- V.replicate 10 3
sum' <- [C.block| int {
int i;
int x = 0;
for (i = 0; i < $vec-len:vec; i++) {
x += $vec-ptr:(int *vec)[i];
}
return x;
} |]
sum' `Hspec.shouldBe` 3 * 10
Hspec.it "bytestrings" $ do
let bs = "foo"
bits <- [C.block| int {
int i, bits = 0;
for (i = 0; i < $bs-len:bs; i++) {
char ch = $bs-ptr:bs[i];
bits += (ch * 01001001001ULL & 042104210421ULL) % 017;
}
return bits;
} |]
bits `Hspec.shouldBe` 16
Hspec.it "Haskell identifiers" $ do
let x' = 3
void $ [C.exp| int { $(int x') } |]
let ä = 3
void $ [C.exp| int { $(int ä) } |]
void $ [C.exp| int { $(int Prelude.maxBound) } |]
Hspec.it "Function pointers" $ do
alloca $ \x_ptr -> do
poke x_ptr 7
let fp = [C.funPtr| void poke42(int *ptr) { *ptr = 42; } |]
[C.exp| void { $(void (*fp)(int *))($(int *x_ptr)) } |]
x <- peek x_ptr
x `Hspec.shouldBe` 42
Hspec.it "cpp namespace identifiers" $ do
C.cIdentifierFromString True "Test::Test" `Hspec.shouldBe` Right "Test::Test"
Hspec.it "cpp template identifiers" $ do
C.cIdentifierFromString True "std::vector" `Hspec.shouldBe` Right "std::vector"
|
fpco/inline-c
|
inline-c/test/tests.hs
|
Haskell
|
mit
| 8,498
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
-- | This is a Haskell port of the Hashids library by Ivan Akimov.
-- This is /not/ a cryptographic hashing algorithm. Hashids is typically
-- used to encode numbers to a format suitable for appearance in places
-- like urls.
--
-- See the official Hashids home page: <http://hashids.org>
--
-- Hashids is a small open-source library that generates short, unique,
-- non-sequential ids from numbers. It converts numbers like 347 into
-- strings like @yr8@, or a list of numbers like [27, 986] into @3kTMd@.
-- You can also decode those ids back. This is useful in bundling several
-- parameters into one or simply using them as short UIDs.
module Web.Hashids
( HashidsContext
-- * How to use
-- $howto
-- ** Encoding
-- $encoding
-- ** Decoding
-- $decoding
-- ** Randomness
-- $randomness
-- *** Repeating numbers
-- $repeating
-- *** Incrementing number sequence
-- $incrementing
-- ** Curses\! \#\$\%\@
-- $curses
-- * API
, version
-- ** Context object constructors
, createHashidsContext
, hashidsSimple
, hashidsMinimum
-- ** Encoding and decoding
, encodeHex
, decodeHex
, encode
, encodeList
, decode
-- ** Convenience wrappers
, encodeUsingSalt
, encodeListUsingSalt
, decodeUsingSalt
, encodeHexUsingSalt
, decodeHexUsingSalt
) where
import Data.ByteString ( ByteString )
import Data.Foldable ( toList )
import Data.List ( (\\), nub, intersect, foldl' )
import Data.List.Split ( chunksOf )
import Data.Sequence ( Seq )
import Numeric ( showHex, readHex )
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as C8
import qualified Data.Sequence as Seq
-- $howto
--
-- Note that most of the examples on this page require the OverloadedStrings extension.
-- $encoding
--
-- Unless you require a minimum length for the generated hash, create a
-- context using 'hashidsSimple' and then call 'encode' and 'decode' with
-- this object.
--
-- > {-# LANGUAGE OverloadedStrings #-}
-- >
-- > import Web.Hashids
-- >
-- > main :: IO ()
-- > main = do
-- > let context = hashidsSimple "oldsaltyswedishseadog"
-- > print $ encode context 42
--
-- This program will output
--
-- > "kg"
--
-- To specify a minimum hash length, use 'hashidsMinimum' instead.
--
-- > main = do
-- > let context = hashidsMinimum "oldsaltyswedishseadog" 12
-- > print $ encode context 42
--
-- The output will now be
--
-- > "W3xbdkgdy42v"
--
-- If you only need the context once, you can use one of the provided wrappers
-- to simplify things.
--
-- > main :: IO ()
-- > main = print $ encodeUsingSalt "oldsaltyswedishseadog" 42
--
-- On the other hand, if your implementation invokes the hashing algorithm
-- frequently without changing the configuration, it is probably better to
-- define partially applied versions of 'encode', 'encodeList', and 'decode'.
--
-- > import Web.Hashids
-- >
-- > context :: HashidsContext
-- > context = createHashidsContext "oldsaltyswedishseadog" 12 "abcdefghijklmnopqrstuvwxyz"
-- >
-- > encode' = encode context
-- > encodeList' = encodeList context
-- > decode' = decode context
-- >
-- > main :: IO ()
-- > main = print $ encode' 12345
--
-- Use a custom alphabet and 'createHashidsContext' if you want to make your
-- hashes \"unique\".
--
-- > main = do
-- > let context = createHashidsContext "oldsaltyswedishseadog" 0 "XbrNfdylm5qtnP19R"
-- > print $ encode context 1
--
-- The output is now
--
-- > "Rd"
--
-- To encode a list of numbers, use `encodeList`.
--
-- > let context = hashidsSimple "this is my salt" in encodeList context [0, 1, 2]
--
-- > "yJUWHx"
-- $decoding
--
-- Decoding a hash returns a list of numbers,
--
-- > let context = hashidsSimple "this is my salt"
-- > hash = decode context "rD" -- == [5]
--
-- Decoding will not work if the salt is changed:
--
-- > main = do
-- > let context = hashidsSimple "this is my salt"
-- > hash = encode context 5
-- >
-- > print $ decodeUsingSalt "this is my pepper" hash
--
-- When decoding fails, the empty list is returned.
--
-- > []
--
-- $randomness
--
-- Hashids is based on a modified version of the Fisher-Yates shuffle. The
-- primary purpose is to obfuscate ids, and it is not meant for security
-- purposes or compression. Having said that, the algorithm does try to make
-- hashes unguessable and unpredictable. See the official Hashids home page
-- for details: <http://hashids.org>
-- $repeating
--
-- > let context = hashidsSimple "this is my salt" in encodeList context $ replicate 4 5
--
-- There are no repeating patterns in the hash to suggest that four identical
-- numbers are used:
--
-- > "1Wc8cwcE"
--
-- The same is true for increasing numbers:
--
-- > let context = hashidsSimple "this is my salt" in encodeList context [1..10]
--
-- > "kRHnurhptKcjIDTWC3sx"
-- $incrementing
--
-- > let context = hashidsSimple "this is my salt" in map (encode context) [1..5]
--
-- > ["NV","6m","yD","2l","rD"]
-- $curses
--
-- The algorithm tries to avoid generating common curse words in English by
-- never placing the following letters next to each other:
--
-- > c, C, s, S, f, F, h, H, u, U, i, I, t, T
{-# INLINE (|>) #-}
(|>) :: a -> (a -> b) -> b
(|>) a f = f a
{-# INLINE splitOn #-}
splitOn :: ByteString -> ByteString -> [ByteString]
splitOn = BS.splitWith . flip BS.elem
-- | Opaque data type with various internals required for encoding and decoding.
data HashidsContext = Context
{ guards :: !ByteString
, seps :: !ByteString
, salt :: !ByteString
, minHashLength :: !Int
, alphabet :: !ByteString }
-- | Hashids version number.
version :: String
version = "1.0.2"
-- | Create a context object using the given salt, a minimum hash length, and
-- a custom alphabet. If you only need to supply the salt, or the first two
-- arguments, use 'hashidsSimple' or 'hashidsMinimum' instead.
--
-- Changing the alphabet is useful if you want to make your hashes unique,
-- i.e., create hashes different from those generated by other applications
-- relying on the same algorithm.
createHashidsContext :: ByteString -- ^ Salt
-> Int -- ^ Minimum required hash length
-> String -- ^ Alphabet
-> HashidsContext
createHashidsContext salt minHashLen alphabet
| length uniqueAlphabet < minAlphabetLength
= error $ "alphabet must contain at least " ++ show minAlphabetLength ++ " unique characters"
| ' ' `elem` uniqueAlphabet
= error "alphabet cannot contain spaces"
| BS.null seps'' || fromIntegral (BS.length alphabet') / fromIntegral (BS.length seps'') > sepDiv
= case sepsLength - BS.length seps'' of
diff | diff > 0
-> res (BS.drop diff alphabet') (seps'' `BS.append` BS.take diff alphabet')
_ -> res alphabet' (BS.take sepsLength seps'')
| otherwise = res alphabet' seps''
where
res ab _seps =
let shuffled = consistentShuffle ab salt
guardCount = ceiling (fromIntegral (BS.length shuffled) / guardDiv)
context = Context
{ guards = BS.take guardCount _seps
, seps = BS.drop guardCount _seps
, salt = salt
, minHashLength = minHashLen
, alphabet = shuffled }
in if BS.length shuffled < 3
then context
else context{ guards = BS.take guardCount shuffled
, seps = _seps
, alphabet = BS.drop guardCount shuffled }
seps' = C8.pack $ uniqueAlphabet `intersect` seps
seps'' = consistentShuffle seps' salt
sepsLength =
case ceiling (fromIntegral (BS.length alphabet') / sepDiv) of
1 -> 2
n -> n
uniqueAlphabet = nub alphabet
alphabet' = C8.pack $ uniqueAlphabet \\ seps
minAlphabetLength = 16
sepDiv = 3.5
guardDiv = 12
seps = "cfhistuCFHISTU"
defaultAlphabet :: String
defaultAlphabet = ['a'..'z'] ++ ['A'..'Z'] ++ "1234567890"
-- | Create a context object using the default alphabet and the provided salt,
-- without any minimum required length.
hashidsSimple :: ByteString -- ^ Salt
-> HashidsContext
hashidsSimple salt = createHashidsContext salt 0 defaultAlphabet
-- | Create a context object using the default alphabet and the provided salt.
-- The generated hashes will have a minimum length as specified by the second
-- argument.
hashidsMinimum :: ByteString -- ^ Salt
-> Int -- ^ Minimum required hash length
-> HashidsContext
hashidsMinimum salt minimum = createHashidsContext salt minimum defaultAlphabet
-- | Decode a hash generated with 'encodeHex'.
--
-- /Example use:/
--
-- > decodeHex context "yzgwD"
--
decodeHex :: HashidsContext -- ^ A Hashids context object
-> ByteString -- ^ Hash
-> String
decodeHex context hash = concatMap (drop 1 . flip showHex "") numbers
where
numbers = decode context hash
-- | Encode a hexadecimal number.
--
-- /Example use:/
--
-- > encodeHex context "ff83"
--
encodeHex :: HashidsContext -- ^ A Hashids context object
-> String -- ^ Hexadecimal number represented as a string
-> ByteString
encodeHex context str
| not (all hexChar str) = ""
| otherwise = encodeList context $ map go $ chunksOf 12 str
where
go str = let [(a,_)] = readHex ('1':str) in a
hexChar c = c `elem` ("0123456789abcdefABCDEF" :: String)
-- | Decode a hash.
--
-- /Example use:/
--
-- > let context = hashidsSimple "this is my salt"
-- > hash = decode context "rD" -- == [5]
--
decode :: HashidsContext -- ^ A Hashids context object
-> ByteString -- ^ Hash
-> [Int]
decode ctx@Context{..} hash
| BS.null hash = []
| encodeList ctx res /= hash = []
| otherwise = res
where
res = splitOn seps tail
|> foldl' go ([], alphabet)
|> fst
|> reverse
hashArray = splitOn guards hash
alphabetLength = BS.length alphabet
Just str@(lottery, tail) =
BS.uncons $ hashArray !! case length hashArray of
0 -> error "Internal error."
2 -> 1
3 -> 1
_ -> 0
prefix = BS.cons lottery salt
go (xs, ab) ssh =
let buffer = prefix `BS.append` ab
ab' = consistentShuffle ab buffer
in (unhash ssh ab':xs, ab')
numbersHashInt :: [Int] -> Int
numbersHashInt xs = foldr ((+) . uncurry mod) 0 $ zip xs [100 .. ]
-- | Encode a single number.
--
-- /Example use:/
--
-- > let context = hashidsSimple "this is my salt"
-- > hash = encode context 5 -- == "rD"
--
encode :: HashidsContext -- ^ A Hashids context object
-> Int -- ^ Number to encode
-> ByteString
encode context n = encodeList context [n]
-- | Encode a list of numbers.
--
-- /Example use:/
--
-- > let context = hashidsSimple "this is my salt"
-- > hash = encodeList context [2, 3, 5, 7, 11] -- == "EOurh6cbTD"
--
encodeList :: HashidsContext -- ^ A Hashids context object
-> [Int] -- ^ List of numbers
-> ByteString
encodeList _ [] = error "encodeList: empty list"
encodeList Context{..} numbers =
res |> expand False |> BS.reverse
|> expand True |> BS.reverse
|> expand' alphabet'
where
(res, alphabet') = foldl' go (BS.singleton lottery, alphabet) (zip [0 .. ] numbers)
expand rep str
| BS.length str < minHashLength
= let ix = if rep then BS.length str - 3 else 0
jx = fromIntegral (BS.index str ix) + hashInt
in BS.index guards (jx `mod` guardsLength) `BS.cons` str
| otherwise = str
expand' ab str
| BS.length str < minHashLength
= let ab' = consistentShuffle ab ab
str' = BS.concat [BS.drop halfLength ab', str, BS.take halfLength ab']
in expand' ab' $ case BS.length str' - minHashLength of
n | n > 0
-> BS.take minHashLength $ BS.drop (div n 2) str'
_ -> str'
| otherwise = str
hashInt = numbersHashInt numbers
lottery = alphabet `BS.index` (hashInt `mod` alphabetLength)
prefix = BS.cons lottery salt
numLast = length numbers - 1
guardsLength = BS.length guards
alphabetLength = BS.length alphabet
halfLength = div alphabetLength 2
go (r, ab) (i, number)
| number < 0 = error "all numbers must be non-negative"
| otherwise =
let shuffled = consistentShuffle ab (BS.append prefix ab)
last = hash number shuffled
n = number `mod` (fromIntegral (BS.head last) + i) `mod` BS.length seps
suffix = if i < numLast
then BS.singleton (seps `BS.index` n)
else BS.empty
in (BS.concat [r,last,suffix], shuffled)
-- Exchange elements at positions i and j in a sequence.
exchange :: Int -> Int -> Seq a -> Seq a
exchange i j seq = i <--> j $ j <--> i $ seq
where
a <--> b = Seq.update a $ Seq.index seq b
consistentShuffle :: ByteString -> ByteString -> ByteString
consistentShuffle alphabet salt
| 0 == saltLength = alphabet
| otherwise = BS.pack $ toList x
where
(_,x) = zip3 [len, pred len .. 1] xs ys |> foldl' go (0, toSeq alphabet)
xs = cycle [0 .. saltLength - 1]
ys = map (fromIntegral . saltLookup) xs
saltLookup ix = BS.index salt (ix `mod` saltLength)
saltLength = BS.length salt
toSeq = BS.foldl' (Seq.|>) Seq.empty
len = BS.length alphabet - 1
go (p, ab) (i, v, ch) =
let shuffled = exchange i j ab
p' = p + ch
j = mod (ch + v + p') i
in (p', shuffled)
unhash :: ByteString -> ByteString -> Int
unhash input alphabet = BS.foldl' go 0 input
where
go carry item =
let Just index = BS.elemIndex item alphabet
in carry * alphabetLength + index
alphabetLength = BS.length alphabet
hash :: Int -> ByteString -> ByteString
hash input alphabet
| 0 == input = BS.take 1 alphabet
| otherwise = BS.reverse $ BS.unfoldr go input
where
len = BS.length alphabet
go 0 = Nothing
go i = Just (alphabet `BS.index` (i `mod` len), div i len)
-- | Encode a number using the provided salt.
--
-- This convenience function creates a context with the default alphabet.
-- If the same context is used repeatedly, use 'encode' with one of the
-- constructors instead.
encodeUsingSalt :: ByteString -- ^ Salt
-> Int -- ^ Number
-> ByteString
encodeUsingSalt = encode . hashidsSimple
-- | Encode a list of numbers using the provided salt.
--
-- This function wrapper creates a context with the default alphabet.
-- If the same context is used repeatedly, use 'encodeList' with one of the
-- constructors instead.
encodeListUsingSalt :: ByteString -- ^ Salt
-> [Int] -- ^ Numbers
-> ByteString
encodeListUsingSalt = encodeList . hashidsSimple
-- | Decode a hash using the provided salt.
--
-- This convenience function creates a context with the default alphabet.
-- If the same context is used repeatedly, use 'decode' with one of the
-- constructors instead.
decodeUsingSalt :: ByteString -- ^ Salt
-> ByteString -- ^ Hash
-> [Int]
decodeUsingSalt = decode . hashidsSimple
-- | Shortcut for 'encodeHex'.
encodeHexUsingSalt :: ByteString -- ^ Salt
-> String -- ^ Hexadecimal number represented as a string
-> ByteString
encodeHexUsingSalt = encodeHex . hashidsSimple
-- | Shortcut for 'decodeHex'.
decodeHexUsingSalt :: ByteString -- ^ Salt
-> ByteString -- ^ Hash
-> String
decodeHexUsingSalt = decodeHex . hashidsSimple
|
jkramarz/hashids-haskell
|
Web/Hashids.hs
|
Haskell
|
mit
| 16,464
|
-- vim: set ts=2 sw=2 sts=0 ff=unix foldmethod=indent:
module Main where
import Test.DocTest
main :: IO ()
main = doctest ["-isrc/lib", "src/cli/Main.hs"]
|
eji/mix-kenall-geocode
|
test/doctest.hs
|
Haskell
|
mit
| 159
|
module Main where
f::Int -> Int -> Int -> Int
f x1 x2 x3 = if x1 == 1
then x2
else f (x1 - 1) x3 ((x2 * x2) + (x3 * x3))
main = do x1 <- readLn
print (f x1 1 1)
|
sebschrader/programmierung-ss2015
|
E12/A2b.hs
|
Haskell
|
mit
| 202
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.