code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
{-# LANGUAGE FlexibleInstances #-} -- This is to make GetCfg's getItem work with String result as well. {-# LANGUAGE TypeSynonymInstances #-} -- Same topic. Both seem to be widely used. -- | Author: Thorsten Rangwich -- | See file LICENSE for details on using this code. -- | This module contains some base tools like reading a configuration file. module BaseTools ( readConfigFile, readConfigList, emptyConfig, ConfigItem(..), Dictionary, UnpackCfg(..), DateInt, getDateInt, fromDateInt, dateFromDateInt, getDateIntFromDayOfYearInt, dateAdd, PositiveInt, fromPositiveInt, getPositiveInt, getItems, splitBy, splitBy', strip, mergeWith ) where import qualified Data.Map as Map import qualified System.IO as FileIO import qualified Data.List as List import qualified Data.Maybe as Maybe import qualified Control.Monad as MControl import qualified Data.Time.Calendar as Date -- | All items currently supported in config file: None, Int, Float, String and Dictionary String to ConfigItem list. data ConfigItem = CfNone -- ^ Empty item. | CfInt Int -- ^ Int value. | CfFloat Float -- ^ Float value. | CfString String -- ^ String value. | CfDict (Map.Map String [ConfigItem]) -- ^ Dictionary, only ConfigItem lists as values, no single values. deriving Show type Dictionary = Map.Map String [ConfigItem] -- | Type class to retrieve the various values in native format class UnpackCfg a where get :: ConfigItem -> a get _ = error "Unexpected type for config item" getIndex :: Int -> [ConfigItem] -> a getIndex i l = get (l!!i) getList :: [ConfigItem] -> [a] getList = map get instance UnpackCfg Int where get (CfInt v) = v get _ = error "No integer value in config item" instance UnpackCfg Float where get (CfFloat v) = v instance UnpackCfg String where get (CfString v) = v get _ = error "There is no string value in config here" instance UnpackCfg Dictionary where get (CfDict v) = v get _ = error "No section / dictionary here" -- | Get CfgItem from String (as supposed to be in cfg file). FIXME: Error handling for invalid float or integer strings. _getCfgFromString :: String -> ConfigItem _getCfgFromString "" = CfNone _getCfgFromString ('"':[]) = error "Parse error, single quote value" _getCfgFromString ('"':xs) = if last xs == '"' then CfString (take (length xs - 1) xs) else error "Parse error, string not terminated by quote" _getCfgFromString a = if '.' `elem` a then CfFloat (read a) else CfInt (read a) -- | Extract the name of a section. First [ is omitted, last is checked and left out. This is a help stub. _extractSectionName :: String -> String _extractSectionName [] = error "Invalid section line, almost empty" _extractSectionName s = if last s == ']' then take (length s - 1) s else error "Invalid, unterminated section line (missing ])." -- | Return empty list or current list of values for a given key in a section or top level dictionary. -- | You can use it to retrieve a section list as well. getItems :: String -> Dictionary -> [ConfigItem] getItems key = Maybe.fromMaybe [] . Map.lookup key -- | Add a config file line to the top level or to a section dictionary. _addConfigValue :: String -- ^ Current line to parse (already stripped from leading and trailing whitespaces). -> Dictionary -- ^ Current section or top level dictionary. -> Dictionary -- ^ Returns updated section or top level dictionary. _addConfigValue "" dic = dic _addConfigValue ('#':_) dic = dic _addConfigValue line dic = let (key, val) = case List.elemIndex '=' line of Just i -> (take i line, drop (i + 1) line) Nothing -> error "Non comment, non section line missing =" in Map.insert key (getItems key dic ++ [_getCfgFromString val]) dic -- | Read a section, return rest of list to parse and updated dictionary. _readSection :: [String] -- ^ Rest of the list to be parsed. -> Dictionary -- ^ Current section dictionary. -> ([String], Dictionary) -- ^ Returns rest of lines to parse, section dictionary. _readSection [] dic = ([], dic) _readSection (x:xs) dic = let strippedLine = strip x in case strippedLine of "" -> _readSection xs dic '#':rs -> _readSection xs dic '[':rs -> (x:xs, dic) --new section, end parsing of this section. _ -> _readSection xs (_addConfigValue strippedLine dic) -- | Parse part of a config list. Receives the rest of a config list and an unfinished dictionary and completes it. -- | Calling itself it adds top level keys or calls _readConfigSection to parse a whole section. _readConfig :: [String] -- ^ Rest of lines still to parse -> Dictionary -- ^ Current config dictionary -> Dictionary -- ^ Returns updated config dictionary _readConfig [] dic = dic _readConfig (x:xs) dic = let strippedLine = strip x in case strippedLine of "" -> _readConfig xs dic '#':_ -> _readConfig xs dic ('[':section) -> let (rs, sdic) = _readSection xs Map.empty sectionName = _extractSectionName section in _readConfig rs (Map.insert sectionName (getItems sectionName dic ++ [CfDict sdic]) dic) _ -> _readConfig xs (_addConfigValue strippedLine dic) -- | Take a list of config file lines and parse them into cfg dict. -- | A strict function would be nice. I did not do up to now, seq would -- | have to be carried out further down, it's no one liner. readConfigList :: [String] -> Dictionary readConfigList a = _readConfig a Map.empty -- | Read the whole config file. Splits file into line list and calls readConfigList. readConfigFile :: String -> IO Dictionary readConfigFile = MControl.liftM (readConfigList . lines) . FileIO.readFile -- The above is a bit hard to understand. An equivalent definition is: -- -- readConfigFile fileName = FileIO.readFile fileName >>= return . readConfigList . lines -- -- And all this was derived by desugaring this do syntax: -- -- readConfigFile fileName = do -- theFile <- File.readFile fileName -- let theLines = lines theFile -- return (readConfigList theLines) emptyConfig :: Dictionary emptyConfig = Map.empty -- | Replace that with internal function in Data.Text when switching to Data.Text instead of String. -- Function doing both left and right strip of white spaces. strip :: String -> String strip unstripped = walk unstripped [] 0 0 where walk :: String -- ^ Rest of string to process -> String -- ^ Lstripped string. Empty in the beginning, non empty and constant when first chart is found. -> Int -- ^ Number of cheracters in lstripped string. Maximum non wghitespace character position. -> Int -- ^ Position in lstripped string currently processed. -> String -- ^ Result string. walk [] s l _ = take l s walk (x:xs) [] l n | isWspace x = walk xs [] l n | otherwise = walk xs (x:xs) 1 1 walk (x:xs) ys l n | isWspace x = walk xs ys l (n + 1) | otherwise = walk xs ys (n + 1) (n + 1) isWspace c = c `elem` " \t\r\n" -- | Split string by character. Do not merge mutliple separators in a row but instead -- | generate empty strings. splitBy :: Char -- ^ Character to split at -> String -- ^ String to split at character -> [String] -- ^ Result list of substrings. splitBy _ [] = [] splitBy c s = w : splitBy c (drop 1 s') where (w, s') = break (== c) s -- | Split string by character. Merges multiple separators. This was derived 1:1 from the -- | ghc implementation of words. splitBy' :: Char -- ^ Character to split at -> String -- ^ String to split -> [String] -- ^ Result list of substrings splitBy' c s = case dropWhile (== c) s of "" -> [] s' -> w : splitBy' c s'' where (w, s'') = break (== c) s' -- | Merge a list of strings to a single string, seperated by the given separator. mergeWith :: Char -- ^ Character to insert between -> [String] -- ^ List of strings to merge -> String -- ^ Merged string mergeWith _ [] = [] mergeWith _ (x:[]) = x mergeWith s (x:xs) = x ++ s : mergeWith s xs -- Stuff for date support. This is a very cheap implementation. Date is stored in Int as e.g. 20081231. So -- interitance from Num can be used for Eq and Ord comparison. Compared to Day it throws an exception -- when the date is constructed from an invalid date and is not adjusted to the next proper date. -- | Data type to receive a valid date coded in an integer in human readable form, like 19751025 for 25.10.1975. -- | Constructor is not published, only unsafe function to create it. data DateInt = CreateDateInt Int -- ^ Create type from unchecked integer. deriving (Eq, Ord) instance Show DateInt where show = show . fromDateInt -- | There should be a function in Haskell already. Returns True, if the year is a leap year. isLeapYear :: Int -- ^ Year to check -> Bool -- ^ True if year is leap year, otherwise False. isLeapYear y = and [(y `mod` 4) == 0, or [(y `mod` 100) > 0, (y `mod` 400) == 0]] -- | Static table containing the number of days within a month. unadjustedMaxInMonth :: [Int] unadjustedMaxInMonth = [31,28,31,30,31,30,31,31,30,31,30,31] -- | Unsecure function to return the number of days of a month in a particular year. maxInMonth :: Int -- ^ Month to check, MUST be between 1 and 12 - otherwise exception raised. -> Int -- ^ Year to check the month for. -> Int -- ^ Number of days in this month. Between 1 and 31. maxInMonth m y = let unadjusted = unadjustedMaxInMonth !! (m - 1) in if isLeapYear y then unadjusted + 1 else unadjusted -- | Small helper stub to extract the year, month, day components -- | from an integer used as a date. Internally used, not exported. dateComponentsFromInt :: Int -- ^ Integer to extract components -> (Int, Int, Int) -- ^ Year, month, day of month dateComponentsFromInt di = let d = di `mod` 100 ym = di `div` 100 in let y = ym `div` 100 m = ym `mod` 100 in (y, m, d) -- | Function to initialise a date from an integer. This function raises an exception if the date is invalid. -- | This function is exported. getDateInt :: Int -- ^ Integer input -> DateInt -- ^ packaged DateInt getDateInt di = let (y, m, d) = dateComponentsFromInt di in if and [(di >= 19000101), (di <= 20991231), (m >= 1), (m <= 12), (d >= 1), (d <= maxInMonth m y)] then CreateDateInt di else error ("Invalid integer to create date:" ++ show di) -- | Unusual format: 12005 for 01.01.2005, 322005 for 01.02.2005. HolidayServer needs that. getDateIntFromDayOfYearInt :: Int -> DateInt getDateIntFromDayOfYearInt d = let year = fromIntegral $ d `mod` 10000 dInYear = fromIntegral $ d `div` 10000 in let (_, month, day) = Date.toGregorian . Date.addDays (dInYear-1) $ Date.fromGregorian year 1 1 in getDateInt (fromIntegral year * 10000 + month * 100 + day) -- | Create unusual format: 12005 from 01.01.2005 getDateOfYearIntFromDateInt :: DateInt -> Int getDateOfYearIntFromDateInt di = let d = dateFromDateInt di in let (j,m,t) = Date.toGregorian d in (fromIntegral (Date.diffDays d (Date.fromGregorian j 1 1))) * 10000 + (fromIntegral j) -- | Function to extract Int in which the date is stored from a DateInt. This -- | is needed only for internal usage. No need to export this. fromDateInt :: DateInt -- ^ DateInt input -> Int -- ^ The constructed integer carrying the date information. fromDateInt (CreateDateInt di) = di -- | Function to create a real date from an integer packed date. dateFromDateInt :: DateInt -- ^ DateInt input -> Date.Day -- ^ Haskell standard Day equivalent value. dateFromDateInt di = let (y, m, d) = dateComponentsFromInt (fromDateInt di) in Date.fromGregorian (fromIntegral y) m d -- | Shift a date by a certain positive or negative amount of days. This method fails if the shift -- | is large enough to get out of the allowed range. dateAdd :: DateInt -- ^ DateInt to shift -> Int -- ^ Number of days to shift -> DateInt -- ^ The new, shifted DateInt. dateAdd date offset = let shifted = Date.addDays (fromIntegral offset) (dateFromDateInt date) in let (year, month, day) = Date.toGregorian shifted in getDateInt (day + month * 100 + fromIntegral year * 10000) -- Some number support. -- | Positive integer, constructor is not exported. data PositiveInt = CreatePositiveInt Int deriving (Eq, Ord) instance Show PositiveInt where show = show . fromPositiveInt --getPositiveInt . (read :: Int) -- | Create a positive integer. Unsecure function, raises error if input is not strictly positive. getPositiveInt :: Int -- ^ Input number, nust be a positive integer -> PositiveInt -- ^ Return value packaged in positive integer data type. getPositiveInt i | i > 0 = CreatePositiveInt i | otherwise = error ("Not a positive Integer:" ++ show i) -- | Convert back into an integer fromPositiveInt :: PositiveInt -- ^ PositiveInt input -> Int -- ^ Int output fromPositiveInt (CreatePositiveInt i) = i {- Test code for ghci let a = readConfigFile "test.cfg" let b = liftM (getItems "Instrument") a --retrieve sections instrument let c = (liftM (getIndex 0) b)::IO Dictionary -- retrieve 1st index of dictionaries as dictionary let d = liftM (getItems "test") c --retrieve value list for "test" key (liftM getList d)::IO Int -- Print out list of integers --short: (liftM (getList . (getItems "test") . (getIndex 0) . (getItems "Instrument")) a)::IO [Int] -}
tnrangwi/CompareProgrammingUsingHolidayManager
haskell/BaseTools.hs
mit
14,804
0
18
4,198
2,745
1,497
1,248
205
4
module Rebase.GHC.Read ( module GHC.Read ) where import GHC.Read
nikita-volkov/rebase
library/Rebase/GHC/Read.hs
mit
68
0
5
12
20
13
7
4
0
{-# OPTIONS_GHC -fno-warn-orphans #-} module Unison.Codebase.MemCodebase where import Data.List import Unison.Codebase (Codebase) import Unison.Codebase.Store (Store) import Unison.Note (Noted) import Unison.Hash (Hash) import Unison.Reference (Reference(Derived)) import Unison.Term (Term) import Unison.Type (Type) import Unison.Util.Logger (Logger) import Unison.Var (Var) import qualified Data.ByteString.Builder as Builder import qualified Data.ByteString.Lazy as LB import qualified Data.Digest.Murmur64 as Murmur import qualified Data.Text as Text import qualified Data.Text.Encoding as Encoding import qualified Unison.ABT as ABT import qualified Unison.Builtin as Builtin import qualified Unison.Codebase as Codebase import qualified Unison.Codebase.MemStore as MemStore import qualified Unison.Hash as Hash import qualified Unison.Hashable as Hashable import qualified Unison.Symbol as Symbol import qualified Unison.Term as Term import qualified Unison.View as View hash :: (Var v) => Term.Term v -> Reference hash (Term.Ref' r) = r hash t = Derived (ABT.hash t) instance Hashable.Accumulate Hash where accumulate tokens = finish $ foldl' step (Murmur.hash64 ()) tokens where step acc t = case t of Hashable.Tag i -> Murmur.hash64AddInt (fromIntegral i) acc Hashable.Bytes bs -> Murmur.hash64Add bs acc Hashable.VarInt i -> Murmur.hash64AddInt i acc Hashable.Text txt -> Murmur.hash64Add (Encoding.encodeUtf8 txt) acc Hashable.Hashed h -> Murmur.hash64Add (Hash.toBytes h) acc Hashable.Double d -> Murmur.hash64Add (Encoding.encodeUtf8 (Text.pack (show d))) acc finish h64 = (Hash.fromBytes . LB.toStrict . Builder.toLazyByteString . Builder.word64LE . Murmur.asWord64) h64 fromBytes = Hash.fromBytes toBytes = Hash.toBytes type V = Symbol.Symbol View.DFO make :: (Show v, Var v) => Logger -> IO (Codebase IO v Reference (Type v) (Term v), Term v -> Noted IO (Term v)) make logger = do store <- MemStore.make :: IO (Store IO v) code <- pure $ Codebase.make hash store let builtins = Builtin.make logger Codebase.addBuiltins builtins store code pure (code, Codebase.interpreter builtins code)
nightscape/platform
shared/src/Unison/Codebase/MemCodebase.hs
mit
2,174
0
17
343
726
398
328
50
1
module Main ( main , boolP, maybeP, listP, listP', treeP ) where import Combinators import Test.HUnit import Data.Char goodChar :: Char -> Parser Char goodChar ch = satisfy (== ch) sat :: String -> Parser String sat [] = pure [] sat (x : xs) = (:) <$> goodChar x <*> (sat xs <|> pure []) true :: Parser String true = sat "True" false :: Parser String false = sat "False" -- (0.5 балла) boolP :: Parser Bool boolP = read <$> (true <|> false) nothing :: Parser String nothing = sat "Nothing" just :: Parser String just = sat "Just" -- (0.5 балла) maybeP :: Parser a -> Parser (Maybe a) maybeP p = Just <$> (just *> char ' ' *> p) <|> nothing *> pure Nothing -- (0.5 балла) listP :: Parser a -> Parser [a] listP p = brackets $ sepBy p comma comma :: Parser () comma = char ',' spaced :: Parser a -> Parser a spaced p = spaces *> p <* spaces -- (0.5 балла) listP' :: Parser a -> Parser [a] listP' p = brackets $ sepBy p $ spaced comma data Tree a b = Node (Tree a b) a (Tree a b) | Leaf b deriving (Show, Eq) -- (0.5 балла) treeP :: Parser a -> Parser b -> Parser (Tree a b) treeP p1 p2 = Leaf <$> p2 <|> (angles $ Node <$> (treeP p1 p2) <*> (braces p1) <*> (treeP p1 p2)) main = fmap (const ()) $ runTestTT $ test $ label "pure" [ parserTest (pure 4) "qwerty" $ Just (4, "qwerty") , parserTest (pure 'x') "" $ Just ('x', "") ] ++ label "empty" [ parserTest (empty :: Parser ()) "qwerty" Nothing , parserTest (empty :: Parser ()) "" Nothing ] ++ label "satisfy" [ parserTest (satisfy (/= 'x')) "qwerty" $ Just ('q', "werty") , parserTest (satisfy (/= 'x')) "xwerty" Nothing ] ++ label "<*>" [ parserTest (max <$> satisfy (== 'q') <*> satisfy (/= 'x')) "qwerty" $ Just ('w', "erty") , parserTest ((+) <$> digit <*> digit) "5678" $ Just (11, "78") , parserTest (undefined <$> satisfy (== 'q') <*> satisfy (== 'x') :: Parser ()) "qwerty" Nothing , parserTest (undefined <$> satisfy (== 'x') <*> satisfy (== 'w') :: Parser ()) "qwerty" Nothing ] ++ label "<|>" [ parserTest (satisfy (== 'q') <|> satisfy (== 'x')) "qwerty" $ Just ('q', "werty") , parserTest (satisfy (== 'x') <|> satisfy (== 'q')) "qwerty" $ Just ('q', "werty") , parserTest (satisfy (== 'x') <|> satisfy (== 'y')) "qwerty" Nothing ] ++ label "eof" [ parserTest eof "qwerty" Nothing , parserTest eof "" $ Just ((), "") ] ++ label "char" [ parserTest (char 'q') "qwerty" $ Just ((), "werty") , parserTest (char 'x') "qwerty" Nothing ] ++ label "anyChar" [ parserTest anyChar "qwerty" $ Just ('q', "werty") , parserTest anyChar "" Nothing ] ++ label "digit" [ parserTest digit "qwerty" Nothing , parserTest digit "123qwerty" $ Just (1, "23qwerty") , parserTest digit "" Nothing ] ++ label "string" [ parserTest (string "qwerty") "qwerty" $ Just ((), "") , parserTest (string "qwerty") "qwertyuiop" $ Just ((), "uiop") , parserTest (string "qwerty") "qwerryuiop" Nothing , parserTest (string "qwerty") "qwert" Nothing ] ++ label "oneOf" [ parserTest (oneOf "xyz") "qwerty" Nothing , parserTest (oneOf "xyz") "xwerty" $ Just ('x', "werty") , parserTest (oneOf "xyz") "ywerty" $ Just ('y', "werty") , parserTest (oneOf "xyz") "zwerty" $ Just ('z', "werty") ] ++ label "many" [ parserTest (many (char 'q')) "qwerty" $ Just ([()], "werty") , parserTest (many (char 'q')) "qqqwerty" $ Just ([(),(),()], "werty") , parserTest (many (char 'q')) "werty" $ Just ([], "werty") , parserTest (many (char 'q')) "" $ Just ([], "") ] ++ label "many1" [ parserTest (many1 (char 'q')) "qwerty" $ Just ([()], "werty") , parserTest (many1 (char 'q')) "qqqwerty" $ Just ([(),(),()], "werty") , parserTest (many1 (char 'q')) "werty" Nothing , parserTest (many1 (char 'q')) "" Nothing ] ++ label "natural" [ parserTest natural "qwerty" Nothing , parserTest natural "123qwerty" $ Just (123, "qwerty") , parserTest natural "-123qwerty" Nothing , parserTest natural "" Nothing ] ++ label "integer" [ parserTest integer "qwerty" Nothing , parserTest integer "123qwerty" $ Just (123, "qwerty") , parserTest integer "-123qwerty" $ Just (-123, "qwerty") , parserTest integer "-qwerty" Nothing ] ++ label "spaces" [ parserTest spaces "qwerty" $ Just ((), "qwerty") , parserTest spaces " qwerty" $ Just ((), "qwerty") , parserTest spaces "" $ Just ((), "") ] ++ label "try" [ parserTest (try natural) "123qwerty" $ Just (Just 123, "qwerty") , parserTest (try natural) "qwerty" $ Just (Nothing, "qwerty") , parserTest (try (char 'q')) "qwerty" $ Just (Just (), "werty") , parserTest (try (char 'x')) "qwerty" $ Just (Nothing, "qwerty") , parserTest (try (char 'x')) "" $ Just (Nothing, "") , parserTest (try eof) "qwerty" $ Just (Nothing, "qwerty") , parserTest (try eof) "" $ Just (Just (), "") ] ++ label "endBy" [ parserTest (natural `endBy` char ';') "1;2;3;456;xyz;" $ Just ([1,2,3,456], "xyz;") , parserTest (natural `endBy` char ';') "1;2;3;456" $ Just ([1,2,3], "456") , parserTest (natural `endBy` spaces) "12 25 300" $ Just ([12,25,300], "") , parserTest (natural `endBy` spaces) "qwerty" $ Just ([], "qwerty") , parserTest (natural `endBy` spaces) "" $ Just ([], "") ] ++ label "endBy1" [ parserTest (natural `endBy1` char ';') "1;2;3;456;xyz;" $ Just ([1,2,3,456], "xyz;") , parserTest (natural `endBy1` char ';') "1;2;3;456" $ Just ([1,2,3], "456") , parserTest (natural `endBy1` spaces) "12 25 300" $ Just ([12,25,300], "") , parserTest (natural `endBy1` spaces) "qwerty" Nothing , parserTest (natural `endBy1` spaces) "" Nothing ] ++ label "sepBy" [ parserTest (natural `sepBy` char ';') "1;2;3;456;xyz;" $ Just ([1,2,3,456], ";xyz;") , parserTest (natural `sepBy` char ';') "1;2;3;456" $ Just ([1,2,3,456], "") , parserTest (natural `sepBy` spaces) "12 25 300" $ Just ([12,25,300], "") , parserTest (natural `sepBy` spaces) "qwerty" $ Just ([], "qwerty") , parserTest (natural `sepBy` spaces) "" $ Just ([], "") ] ++ label "sepBy1" [ parserTest (natural `sepBy1` char ';') "1;2;3;456;xyz;" $ Just ([1,2,3,456], ";xyz;") , parserTest (natural `sepBy1` char ';') "1;2;3;456" $ Just ([1,2,3,456], "") , parserTest (natural `sepBy1` spaces) "12 25 300" $ Just ([12,25,300], "") , parserTest (natural `sepBy1` spaces) "qwerty" Nothing , parserTest (natural `sepBy1` spaces) "" Nothing ] ++ label "between" [ parserTest (between (char 'a') (char 'b') (char 'c')) "abc" Nothing , parserTest (between (char 'a') (char 'b') (char 'c')) "acb" $ Just ((), "") ] ++ label "brackets" [ parserTest (brackets (string "qwerty")) "[qwerty]uiop" $ Just ((), "uiop") , parserTest (brackets (string "qwerty")) "[qwertyu]iop" Nothing ] ++ label "parens" [ parserTest (parens spaces) "( )qwerty" $ Just ((), "qwerty") , parserTest (parens spaces) "(q)werty" Nothing ] ++ label "braces" [ parserTest (braces natural) "{123}" $ Just (123, "") , parserTest (braces natural) "{}" Nothing ] ++ label "angles" [ parserTest (angles digit) "<1>" $ Just (1, "") , parserTest (angles digit) "<1 >" Nothing ] ++ label "boolP" [ parserTest boolP "Trueqwerty" $ Just (True, "qwerty") , parserTest boolP "False" $ Just (False, "") , parserTest boolP "qwerty" Nothing ] ++ label "maybeP" [ parserTest (maybeP natural) "Nothingqwerty" $ Just (Nothing, "qwerty") , parserTest (maybeP natural) "Just 123qwerty" $ Just (Just 123, "qwerty") , parserTest (maybeP natural) "Just123qwerty" Nothing ] ++ label "listP" [ evalParser (listP integer) "[1,-23,25,347]" ~?= Just [1,-23,25,347] , evalParser (listP integer) "[1 , -23, 25 ,347]" ~?= Nothing ] ++ label "listP'" [ evalParser (listP' integer) "[1,-23,25,347]" ~?= Just [1,-23,25,347] , evalParser (listP' integer) "[1 , -23, 25 ,347]" ~?= Just [1,-23,25,347] ] ++ label "treeP" [ evalParser (treeP integer integer) "100" ~?= Just (Leaf 100) , evalParser (treeP integer integer) "<1{2}3>" ~?= Just (Node (Leaf 1) 2 (Leaf 3)) , evalParser (treeP integer integer) "<1{2}<3{4}5>>>" ~?= Just (Node (Leaf 1) 2 (Node (Leaf 3) 4 (Leaf 5))) , evalParser (treeP integer integer) "<1{2}<3{4}5>" ~?= Nothing ] ++ label "foldl1P" [ evalParser (foldl1P (\a b c -> a ++ "[" ++ show b ++ "]" ++ c) (many $ satisfy $ not . isDigit) digit) "a1bcd5efg853h" ~?= Just "a[1]bcd[5]efg[8][5][3]h" , evalParser (foldl1P (\a b c -> "(" ++ a ++ [b] ++ c ++ ")") (fmap show natural) anyChar) "12+34+45+56" ~?= Just "(((12+34)+45)+56)" ] ++ label "foldr1P" [ evalParser (foldr1P (\a b c -> a ++ "[" ++ show b ++ "]" ++ c) (many $ satisfy $ not . isDigit) digit) "a1bcd5efg853h" ~?= Just "a[1]bcd[5]efg[8][5][3]h" , evalParser (foldr1P (\a b c -> "(" ++ a ++ [b] ++ c ++ ")") (fmap show natural) anyChar) "12+34+45+56" ~?= Just "(12+(34+(45+56)))" ] where label :: String -> [Test] -> [Test] label l = map (\(i,t) -> TestLabel (l ++ " [" ++ show i ++ "]") t) . zip [1..]
nkartashov/haskell
hw08/Main.hs
gpl-2.0
9,231
0
43
2,054
4,064
2,125
1,939
174
1
{-# LANGUAGE TemplateHaskell, MultiParamTypeClasses #-} module LanguageDef.Data.Proof where {- Creates a proof for a bunch of rules -} import Utils.All import LanguageDef.Utils.LocationInfo import LanguageDef.Utils.ExceptionInfo import LanguageDef.Data.Relation import LanguageDef.Data.Rule import LanguageDef.Data.Expression import LanguageDef.Data.ParseTree import LanguageDef.Data.SyntFormIndex {- When a rule is applied to enough values (parsetrees) it generates a proof of this rule. -} data Proof' a = Proof -- Proof for a relation { _proofConcl :: [ParseTree] -- output of the conclusion of the rule , _proofWith :: Rule' a -- rule which has proven stuff , _proofPreds :: [Proof' a] -- predicates for the rule } | ProofExpr -- Proof that an expression holds { _exprResult :: ParseTree } deriving (Show, Eq) makeLenses ''Proof' type Proof = Proof' SyntFormIndex {-Number of 'layers' in the proof-} depth :: Proof' a -> Int depth proof | null (get proofPreds proof) = 1 | otherwise = get proofPreds proof |> depth & maximum & (+1) {-Number of proof elements-} weight :: Proof' a -> Int weight proof = 1 + (proof & get proofPreds |> weight & sum) data ProofOptions = PO { nameParens :: String -> String, showNames :: Bool, betweenPredicates :: String } defaultProofOptions = PO (\s -> "["++s++"]") True " " -- Extra options to print proofs data ProofOptions' a = PO' { opts' :: ProofOptions, sp :: ParseTree -> String, se :: Expression' a -> String, sr :: Rule' a -> String } instance ToString (Proof' a) where toParsable = toParsable' defaultProofOptions toCoParsable = toCoParsable' defaultProofOptions debug = debug' defaultProofOptions instance ToString' ProofOptions (Proof' a) where show' po proof = let opts = PO' po show debug debug in showProofWith opts proof & unlines toParsable' po proof = let opts = PO' po toParsable toParsable toCoParsable in showProofWith opts proof & unlines toCoParsable' po proof = let opts = PO' po toCoParsable toParsable toParsable in showProofWith opts proof & unlines debug' po proof = let opts = PO' po debug debug debug in showProofWith opts proof & unlines -- shows a proof part; returns lines showProofWith :: ProofOptions' a -> Proof' a -> [String] showProofWith opts (Proof concl proverRule predicates) = let options = opts' opts preds' = predicates |> showProofWith opts preds'' = if null preds' then [] else init preds' ||>> (++ betweenPredicates options) ++ [last preds'] preds = preds'' & foldl (stitch ' ') [] :: [String] predsW = ("":preds) |> length & maximum :: Int conclArgs = concl |> sp opts & commas concl' = (proverRule & get (ruleConcl . conclRelName) & showFQ & inParens) ++ conclArgs lineL = max predsW (length concl') name = if showNames options then " " ++ nameParens options (get ruleName proverRule) else "" lineL' = lineL - if 3 * length name <= lineL && predsW == lineL then length name else 0 line = replicate lineL' '-' :: String line' = line ++ name in (preds ++ [line', concl']) showProofWith opts (ProofExpr pt) = [sp opts pt] showProofWithDepth :: String -> Name -> ProofOptions -> Proof' a -> String showProofWithDepth input relation options proof = ["# "++input++" applied to "++relation ,"# Proof weight: "++show (weight proof)++", proof depth: "++ show (depth proof) , "" , "" , toParsable' options proof, "", "", ""] & unlines
pietervdvn/ALGT2
src/LanguageDef/Data/Proof.hs
gpl-3.0
3,474
134
16
700
1,181
622
559
68
4
module Tests.Testable where import Tests.TestResults data Test = Test { description :: String , result :: TestResult } instance Show Test where show t = (show.result $ t) ++ " " ++ description t class Testable a where test :: a -> TestResult instance Testable Bool where test True = TestPassed test False = TestFailed Nothing
bogwonch/SecPAL
tests/Tests/Testable.hs
gpl-3.0
345
0
10
75
113
60
53
12
0
import Control.Monad( replicateM_ ) palindrome :: Int -> Bool palindrome n = reverse sn == sn where sn = show n testCase = do n <- getLine print . head . dropWhile (not.palindrome) $ [(read n) + 1 ..] main = do num <- getLine replicateM_ (read num) testCase
zhensydow/ljcsandbox
lang/haskell/spoj/PALIN.hs
gpl-3.0
281
0
11
72
121
60
61
10
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.StorageGateway.DescribeGatewayInformation -- Copyright : (c) 2013-2014 Brendan Hay <[email protected]> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | This operation returns metadata about a gateway such as its name, network -- interfaces, configured time zone, and the state (whether the gateway is -- running or not). To specify which gateway to describe, use the Amazon -- Resource Name (ARN) of the gateway in your request. -- -- <http://docs.aws.amazon.com/storagegateway/latest/APIReference/API_DescribeGatewayInformation.html> module Network.AWS.StorageGateway.DescribeGatewayInformation ( -- * Request DescribeGatewayInformation -- ** Request constructor , describeGatewayInformation -- ** Request lenses , dgiGatewayARN -- * Response , DescribeGatewayInformationResponse -- ** Response constructor , describeGatewayInformationResponse -- ** Response lenses , dgirGatewayARN , dgirGatewayId , dgirGatewayNetworkInterfaces , dgirGatewayState , dgirGatewayTimezone , dgirGatewayType , dgirNextUpdateAvailabilityDate ) where import Network.AWS.Prelude import Network.AWS.Request.JSON import Network.AWS.StorageGateway.Types import qualified GHC.Exts newtype DescribeGatewayInformation = DescribeGatewayInformation { _dgiGatewayARN :: Text } deriving (Eq, Ord, Read, Show, Monoid, IsString) -- | 'DescribeGatewayInformation' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'dgiGatewayARN' @::@ 'Text' -- describeGatewayInformation :: Text -- ^ 'dgiGatewayARN' -> DescribeGatewayInformation describeGatewayInformation p1 = DescribeGatewayInformation { _dgiGatewayARN = p1 } dgiGatewayARN :: Lens' DescribeGatewayInformation Text dgiGatewayARN = lens _dgiGatewayARN (\s a -> s { _dgiGatewayARN = a }) data DescribeGatewayInformationResponse = DescribeGatewayInformationResponse { _dgirGatewayARN :: Maybe Text , _dgirGatewayId :: Maybe Text , _dgirGatewayNetworkInterfaces :: List "GatewayNetworkInterfaces" NetworkInterface , _dgirGatewayState :: Maybe Text , _dgirGatewayTimezone :: Maybe Text , _dgirGatewayType :: Maybe Text , _dgirNextUpdateAvailabilityDate :: Maybe Text } deriving (Eq, Read, Show) -- | 'DescribeGatewayInformationResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'dgirGatewayARN' @::@ 'Maybe' 'Text' -- -- * 'dgirGatewayId' @::@ 'Maybe' 'Text' -- -- * 'dgirGatewayNetworkInterfaces' @::@ ['NetworkInterface'] -- -- * 'dgirGatewayState' @::@ 'Maybe' 'Text' -- -- * 'dgirGatewayTimezone' @::@ 'Maybe' 'Text' -- -- * 'dgirGatewayType' @::@ 'Maybe' 'Text' -- -- * 'dgirNextUpdateAvailabilityDate' @::@ 'Maybe' 'Text' -- describeGatewayInformationResponse :: DescribeGatewayInformationResponse describeGatewayInformationResponse = DescribeGatewayInformationResponse { _dgirGatewayARN = Nothing , _dgirGatewayId = Nothing , _dgirGatewayTimezone = Nothing , _dgirGatewayState = Nothing , _dgirGatewayNetworkInterfaces = mempty , _dgirGatewayType = Nothing , _dgirNextUpdateAvailabilityDate = Nothing } dgirGatewayARN :: Lens' DescribeGatewayInformationResponse (Maybe Text) dgirGatewayARN = lens _dgirGatewayARN (\s a -> s { _dgirGatewayARN = a }) -- | The gateway ID. dgirGatewayId :: Lens' DescribeGatewayInformationResponse (Maybe Text) dgirGatewayId = lens _dgirGatewayId (\s a -> s { _dgirGatewayId = a }) -- | A 'NetworkInterface' array that contains descriptions of the gateway network -- interfaces. dgirGatewayNetworkInterfaces :: Lens' DescribeGatewayInformationResponse [NetworkInterface] dgirGatewayNetworkInterfaces = lens _dgirGatewayNetworkInterfaces (\s a -> s { _dgirGatewayNetworkInterfaces = a }) . _List -- | One of the values that indicates the operating state of the gateway. dgirGatewayState :: Lens' DescribeGatewayInformationResponse (Maybe Text) dgirGatewayState = lens _dgirGatewayState (\s a -> s { _dgirGatewayState = a }) -- | One of the values that indicates the time zone configured for the gateway. dgirGatewayTimezone :: Lens' DescribeGatewayInformationResponse (Maybe Text) dgirGatewayTimezone = lens _dgirGatewayTimezone (\s a -> s { _dgirGatewayTimezone = a }) -- | TBD dgirGatewayType :: Lens' DescribeGatewayInformationResponse (Maybe Text) dgirGatewayType = lens _dgirGatewayType (\s a -> s { _dgirGatewayType = a }) -- | The date at which an update to the gateway is available. This date is in the -- time zone of the gateway. If the gateway is not available for an update this -- field is not returned in the response. dgirNextUpdateAvailabilityDate :: Lens' DescribeGatewayInformationResponse (Maybe Text) dgirNextUpdateAvailabilityDate = lens _dgirNextUpdateAvailabilityDate (\s a -> s { _dgirNextUpdateAvailabilityDate = a }) instance ToPath DescribeGatewayInformation where toPath = const "/" instance ToQuery DescribeGatewayInformation where toQuery = const mempty instance ToHeaders DescribeGatewayInformation instance ToJSON DescribeGatewayInformation where toJSON DescribeGatewayInformation{..} = object [ "GatewayARN" .= _dgiGatewayARN ] instance AWSRequest DescribeGatewayInformation where type Sv DescribeGatewayInformation = StorageGateway type Rs DescribeGatewayInformation = DescribeGatewayInformationResponse request = post "DescribeGatewayInformation" response = jsonResponse instance FromJSON DescribeGatewayInformationResponse where parseJSON = withObject "DescribeGatewayInformationResponse" $ \o -> DescribeGatewayInformationResponse <$> o .:? "GatewayARN" <*> o .:? "GatewayId" <*> o .:? "GatewayNetworkInterfaces" .!= mempty <*> o .:? "GatewayState" <*> o .:? "GatewayTimezone" <*> o .:? "GatewayType" <*> o .:? "NextUpdateAvailabilityDate"
dysinger/amazonka
amazonka-storagegateway/gen/Network/AWS/StorageGateway/DescribeGatewayInformation.hs
mpl-2.0
7,015
0
22
1,437
889
526
363
97
1
data Foo = Bar { foo :: Baz }
lspitzner/brittany
data/Test45.hs
agpl-3.0
34
2
5
13
17
9
8
2
0
-- | Settings are centralized, as much as possible, into this file. This -- includes database connection settings, static file locations, etc. -- In addition, you can configure a number of different aspects of Yesod -- by overriding methods in the Yesod typeclass. That instance is -- declared in the Foundation.hs file. module Settings where import BasicPrelude import Data.Default import Control.Exception (throw) import Data.Aeson import Data.FileEmbed (embedFile) import Data.Yaml (decodeEither') import Database.Persist.MySQL (MySQLConf) import Language.Haskell.TH.Syntax (Exp, Name, Q) import Network.Wai.Handler.Warp (HostPreference) import Yesod.Static import Yesod.Default.Config2 (applyEnvValue, configSettingsYml) import Yesod.Default.Util (WidgetFileSettings, widgetFileNoReload, widgetFileReload) -- | Runtime settings to configure this application. These settings can be -- loaded from various sources: defaults, environment variables, config files, -- theoretically even a database. data AppSettings = AppSettings { appStaticDir :: String -- ^ Directory from which to serve static files. , appDatabaseConf :: MySQLConf -- ^ Configuration settings for accessing the database. , appHost :: HostPreference -- ^ Host/interface the server should bind to. , appPort :: Int -- ^ Port to listen on , appIpFromHeader :: Bool -- ^ Get the IP address from the header when logging. Useful when sitting -- behind a reverse proxy. , appDetailedRequestLogging :: Bool -- ^ Use detailed request logging system , appShouldLogAll :: Bool -- ^ Should all log messages be displayed? , appReloadTemplates :: Bool -- ^ Use the reload version of templates , appMutableStatic :: Bool -- ^ Assume that files in the static dir may change after compilation , appSkipCombining :: Bool -- ^ Perform no stylesheet/script combining , appMinify :: Bool -- ^ Minify javascript and css when generating cache , appEmail :: Text -- Example app-specific configuration values. , appCopyright :: Text -- ^ Copyright text to appear in the footer of the page , appAnalytics :: Maybe Text -- ^ Google Analytics code } instance FromJSON AppSettings where parseJSON = withObject "AppSettings" $ \o -> do let defaultDev = #if DEVELOPMENT True #else False #endif appStaticDir <- o .: "static-dir" appDatabaseConf <- o .: "database" appHost <- fromString <$> o .: "host" appPort <- o .: "port" appIpFromHeader <- o .: "ip-from-header" appDetailedRequestLogging <- o .:? "detailed-logging" .!= defaultDev appShouldLogAll <- o .:? "should-log-all" .!= defaultDev appReloadTemplates <- o .:? "reload-templates" .!= defaultDev appMutableStatic <- o .:? "mutable-static" .!= defaultDev appSkipCombining <- o .:? "skip-combining" .!= defaultDev appMinify <- o .:? "minify" .!= (not defaultDev) appEmail <- o .: "email" appCopyright <- o .: "copyright" appAnalytics <- o .:? "analytics" return AppSettings {..} -- | Settings for 'widgetFile', such as which template languages to support and -- default Hamlet settings. -- -- For more information on modifying behavior, see: -- -- https://github.com/yesodweb/yesod/wiki/Overriding-widgetFile widgetFileSettings :: WidgetFileSettings widgetFileSettings = def -- | How static files should be combined. combineSettings :: CombineSettings combineSettings = def -- The rest of this file contains settings which rarely need changing by a -- user. widgetFile :: String -> Q Exp widgetFile = (if appReloadTemplates compileTimeAppSettings then widgetFileReload else widgetFileNoReload) widgetFileSettings -- | Raw bytes at compile time of @config/settings.yml@ configSettingsYmlBS :: ByteString configSettingsYmlBS = $(embedFile configSettingsYml) -- | @config/settings.yml@, parsed to a @Value@. configSettingsYmlValue :: Value configSettingsYmlValue = either throw id $ decodeEither' configSettingsYmlBS -- | A version of @AppSettings@ parsed at compile time from @config/settings.yml@. compileTimeAppSettings :: AppSettings compileTimeAppSettings = case fromJSON $ applyEnvValue False mempty configSettingsYmlValue of Error e -> error e Success settings -> settings -- The following two functions can be used to combine multiple CSS or JS files -- at compile time to decrease the number of http requests. -- Sample usage (inside a Widget): -- -- > $(combineStylesheets 'StaticR [style1_css, style2_css]) combineStylesheets :: Name -> [Route Static] -> Q Exp combineStylesheets = combineStylesheets' (appSkipCombining compileTimeAppSettings) combineSettings combineScripts :: Name -> [Route Static] -> Q Exp combineScripts = combineScripts' (appSkipCombining compileTimeAppSettings) combineSettings
sir-murray/lol
Settings.hs
agpl-3.0
5,420
0
13
1,449
711
403
308
-1
-1
{-# LANGUAGE ScopedTypeVariables, MultiParamTypeClasses #-} module V5D (V5Dfile(..), V5DGrid(..), V5D_field(..), readV5Dfile, showGrid, showFile, dataset) where import System.IO import System.IO.Unsafe(unsafePerformIO) import Foreign.Marshal.Alloc import Foreign.Ptr import Foreign.Storable import Foreign.Marshal.Array import Text.ParserCombinators.Parsec import Text.ParserCombinators.Parsec.Pos import Control.Monad (liftM) import qualified Data.ByteString.Lazy as Lazy import Unsafe.Coerce (unsafeCoerce) import Data.IORef (IORef, readIORef, writeIORef, newIORef, modifyIORef) import Data.Int import Data.Word import Data.List (find) import Data.Maybe import Data.Char (chr) import Data.Array.Repa (shapeOfList, DIM3, fromListUnboxed) import Data.Array.Repa.Index import qualified Data.Map as M import qualified CellTypes as Cell import Dataset import RectGrid import Geometries -- A V5D_field contains information about one timeslice for one of -- the variables whose samples are recorded in a V5D file. data V5D_field = V5D_field { nr_rows :: Int , nr_cols :: Int , nr_levs :: Int , minval :: Maybe Float , maxval :: Maybe Float , name :: String , compress :: Int } deriving Show -- A V5Dfile records data about a collection of variables -- (observables), where the variables may be sampled over a -- range of time points. The following data structure holds -- global information about the collection. -- NOTE: the order of items in "grids" is significant, and -- reflects the order in which grid data is stored on disk; -- this information is used for example to compute the offset -- from the start of file to the data for a specific grid at -- a given time point. data V5Dfile = V5Dfile { handle :: Handle , nr_times :: Int , projection :: Int , tstep_size :: Int , offset :: Integer , grids :: [V5D_field] } deriving Show -- -- The V5D file header is a sequence of variable-length fields, -- each identified by a specific tag. The following are -- symbolic names for file tags. -- t_ID :: Int = 0x5635440a {- hex encoding of "V5D\n" -} t_VERSION :: Int = 1000 t_NUMTIMES :: Int = 1001 t_NUMVARS :: Int = 1002 t_VARNAME :: Int = 1003 t_NR :: Int = 1004 t_NC :: Int = 1005 t_NL :: Int = 1006 t_NL_VAR :: Int = 1007 t_LOWLEV_VAR :: Int = 1008 t_TIME :: Int = 1010 t_DATE :: Int = 1011 t_MINVAL :: Int = 1012 t_MAXVAL :: Int = 1013 t_COMPRESS :: Int = 1014 t_UNITS :: Int = 1015 t_VERTICAL_SYSTEM :: Int = 2000 t_VERT_ARGS :: Int = 2100 t_BOTTOMBOUND :: Int = 2001 t_LEVINC :: Int = 2002 t_HEIGHT :: Int = 2003 t_PROJECTION :: Int = 3000 t_PROJ_ARGS :: Int = 3100 t_NORTHBOUND :: Int = 3001 t_WESTBOUND :: Int = 3002 t_ROWINC :: Int = 3003 t_COLINC :: Int = 3004 t_LAT1 :: Int = 3005 t_LAT2 :: Int = 3006 t_POLE_ROW :: Int = 3007 t_POLE_COL :: Int = 3008 t_CENTLON :: Int = 3009 t_CENTLAT :: Int = 3010 t_CENTROW :: Int = 3011 t_CENTCOL :: Int = 3012 t_ROTATION :: Int = 3013 t_ROWINCKM :: Int = 3014 t_COLINCKM :: Int = 3015 t_END :: Int = 9999 -- Tags can be of two types: global tags are properties -- of all grids; local relate to a specific grid. data TagType = Tglobal | Tlocal deriving Show data Tag = Global { gtag::Int, gval::Value } | Local { ltag::Int, lgid::Int, lval::Value } deriving Show tagType :: Int -> TagType tagType t | t `elem` [ t_VARNAME , t_NL_VAR , t_LOWLEV_VAR , t_TIME , t_DATE , t_MINVAL , t_MAXVAL , t_UNITS ] = Tlocal | otherwise = Tglobal -- Tags are used to mark values; we define the range of value -- types, then map tags to the type of value that should be -- associated with the tag in the file. data ValType = Tint | Tstr Int | Tfloat | Tfarr | Tmap | Targ Int | Tend deriving Show data Value = Vint {asInt :: Int} | Vstr {asStr::String} | Vfloat {asFloat::Float} | Vfarr Int [Float] | Vmap Int Float | Varg Int Float | Vend {fpos :: Int} deriving Show valType t | t `elem` [ t_NUMTIMES, t_NUMVARS , t_NR, t_NC, t_NL , t_NL_VAR, t_LOWLEV_VAR , t_TIME, t_DATE , t_COMPRESS, t_PROJECTION , t_VERTICAL_SYSTEM ] = Tint | t `elem` [ t_VERSION, t_VARNAME] = Tstr 10 | t `elem` [ t_UNITS] = Tstr 20 | t `elem` [ t_MINVAL, t_MAXVAL , t_BOTTOMBOUND, t_LEVINC ] = Tfloat | t `elem` [ t_VERT_ARGS, t_PROJ_ARGS] = Tfarr | t `elem` [ t_HEIGHT] = Tmap | t `elem` [ t_NORTHBOUND, t_WESTBOUND , t_ROWINC, t_COLINC , t_LAT1, t_LAT2 , t_POLE_ROW, t_POLE_COL , t_CENTLON, t_CENTLAT , t_CENTROW, t_CENTCOL , t_ROTATION, t_ROWINCKM , t_COLINCKM] = Targ t | t == t_END = Tend | otherwise = error "Unknown value type" -- PARSING -- -- Parse headers in the file; we use the Parsec library. The -- parser needs to keep track of its offset in the file stream -- so that we can later calculate the offset to the start of -- the first grid data; parser state is used for this. parseV5D :: GenParser Word8 Int [Tag] parseV5D = do { parseHeader ; ts <- parseTags ; return ts } parseHeader :: GenParser Word8 Int () parseHeader = do { tag :: Int <- getVal ; len :: Int <- getVal ; setState 8 ; if tag /= t_ID && len /= 0 then return $ error "Not a V5D file." else return () } parseTags :: GenParser Word8 Int [Tag] parseTags = do { pp <- getState ; tag :: Int <- getVal ; len :: Int <- getVal ; pos <- getState ; let pos' = 8+pos+len ; setState pos' ; if tag == t_END then return $ [Global t_END (Vend $ pos')] else do { let tt = tagType tag ; let vt = valType tag; ; t <- parseTag tt vt tag ; ts <- parseTags ; return $ t:ts } } parseTag :: TagType -> ValType -> Int -> GenParser Word8 Int Tag parseTag Tglobal vtype t = do { val <- parseVal vtype ; return $ Global t val } parseTag Tlocal vtype t = do { var <- getVal ; val <- parseVal vtype ; return $ Local t var val } parseVal :: ValType -> GenParser Word8 Int Value parseVal Tfloat = getVal >>= (return.Vfloat) parseVal Tint = getVal >>= (return.Vint) parseVal (Tstr n) = do { b <- count n anyToken ; let p = unsafePerformIO $ allocaBytes (n+1) (\tmp-> do { pokeArray tmp (b++[0]) ; p <- peekArray0 (toEnum 0) tmp ; return $ map (chr.fromEnum) p }) ; return $ Vstr p } parseVal Tfarr = do { n :: Int <- getVal ; a :: [Float] <- mapM (const $ getVal) [1..n] ; return $ Vfarr n a } parseVal Tmap = do { i :: Int <- getVal ; v :: Float <- getVal ; return $ Vmap i v } parseVal (Targ t) = getVal >>= (return.(Varg t)) parseVal Tend = error $ "Processed Tend: Should never happen." -- Low-level binary IO. -- -- Reading of 32-bit integers, floats, and strings, taking into -- account that our machines are big-endian while the data is -- stored low-endian. -- UGLY! getVal :: (Show a, Storable a) => GenParser Word8 Int a getVal = do { a <- anyToken ; b <- anyToken ; c <- anyToken ; d <- anyToken ; let ai :: Word32 = fromIntegral a ; let bi :: Word32 = fromIntegral b ; let ci :: Word32 = fromIntegral c ; let di :: Word32 = fromIntegral d -- ; let v :: Word32 = ai + 256*(bi + 256*(ci + 256*di)) ; let v :: Word32 = di + 256*(ci + 256*(bi + 256*ai)) ; return $ unsafeCoerce v } -- Convert a stream of word 8's into a stream of values. stream :: (Show a, Storable a) => Int -> [Word8] -> [a] stream n vs = case runParser (count n getVal) 0 "" vs of Left err -> error $ "Failure in stream: " ++ (show err) Right vs -> vs -- INTERPRETATION -- -- Convert a list of tags into a V5D file and grid descriptors {-# NOINLINE cache #-} cache :: IORef (M.Map String (V5Dfile, (Int,Int,Int))) cache = unsafePerformIO(return =<< newIORef M.empty) readV5Dfile :: String -> IO(V5Dfile, (Int, Int, Int)) readV5Dfile fn = do { mem <- readIORef cache ; if M.member fn mem then return $ mem M.! fn else do { h <-openBinaryFile fn ReadMode ; b <- Lazy.hGetContents h ; case runParser parseV5D 0 fn (Lazy.unpack b) of Left err -> error $ "Parse error in file: " ++ (show err) Right ds -> do { let v = v5dfile h ds ; writeIORef cache (M.insert fn v mem) ; return v } } } v5dfile :: Handle -> [Tag] -> (V5Dfile, (Int,Int,Int)) v5dfile h fs = (V5Dfile h nrt proj time offs gs, (xsz,ysz,zsz)) where nrt = asInt $ global t_NUMTIMES fs com = asInt $ global t_COMPRESS fs proj = asInt $ global t_PROJECTION fs nrvs = asInt $ global t_NUMVARS fs time = sum $ map gridsize gs offs = toInteger.fpos $ global t_END fs gs = map (grid fs com) [0..nrvs-1] xsz = maximum . (map nr_rows) $ gs ysz = maximum . (map nr_cols) $ gs zsz = maximum . (map nr_levs) $ gs grid :: [Tag] -> Int -> Int -> V5D_field grid fs comp i = V5D_field nr_r nr_c nr_l minv maxv name comp where nr_r = asInt $ global t_NR fs nr_c = asInt $ global t_NC fs nr_l = asInt $ ((local t_NL_VAR i fs) `orElse` (global t_NL fs)) minv = fmap asFloat $ local t_MINVAL i fs maxv = fmap asFloat $ local t_MAXVAL i fs name = asStr.fromJust $ local t_VARNAME i fs global :: Int -> [Tag] -> Value global t = gval . fromJust . find globalTest where globalTest (Global t' v) = (t == t') globalTest _ = False local :: Int -> Int -> [Tag] -> Maybe Value local t i = liftM lval . find localTest where localTest (Local t' i' v) = (t == t' && i == i') localTest _ = False orElse :: (Maybe a) -> a -> a (Just v) `orElse` _ = v Nothing `orElse` v = v -- GRID EXTRACTION -- -- Given a V5D file, a grid name, and a time, return a regular cubic -- grid containing the V5D data extracted from file then decompressed. -- type V5Ddata = Cells Cell8 Cell.MyVertex Float type V5Ddata = [Float] -- Constant used in V5D to represent missing data; currently -- only used in "decompress" but defined globally as it may -- be required in the future, e.g. writing grids. missing :: Float = 1.0e35 gridsize :: V5D_field -> Int gridsize g = 8*(nr_levs g) + (nr_rows g)*(nr_cols g)*(nr_levs g)*(compress g) -- Return a given grid contained within the V5D file for a specified timepoint. -- At this level, find the grid within the list of grids associated within the -- file, computing the offet to the start of data for that grid. dataset :: V5Dfile -> String -> Int -> (V5Ddata, V5D_field) dataset v5d nm t = case post of [] -> error $ "No grid named "++nm (g:gs) -> (extract g (handle v5d) grid_pos, g) where (pre,post) = span ((/=nm).name) (grids v5d) grid_pos = (offset v5d) + (toInteger $ t*tstep_size v5d) + pre_size pre_size = toInteger.sum $ map gridsize pre -- Convert the V5D grid to a dataset, given the offset to the start -- of that grid's data, by unpacking the stream of bytes read from -- the file starting at that offset. extract :: V5D_field -> Handle -> Integer -> V5Ddata extract gr h fpos = {- regularCubicData dim1 -}(unpack gr str) where dim1 = (nr_rows gr - 1, nr_cols gr - 1, nr_levs gr - 1) dim = (nr_rows gr, nr_cols gr, nr_levs gr) gsz = gridsize gr str = unsafePerformIO $ do { hSeek h AbsoluteSeek fpos ; b <- Lazy.hGetContents h ; return $ take gsz $ Lazy.unpack b } -- Data is stored as a sequence of bytes: its conversion into floats -- is mediated by a set of decompression factors, one per "level" of -- data within the grid. At this point we split the compression -- factors from the front of the stream, then re-organise the rest -- of the stream into a list of layers to be matched against the -- corresponding decompression factors. unpack :: V5D_field -> [Word8] -> [Float] unpack gr str = concat $ zipWith3 (decompress gr) gas gbs levs where n = nr_levs gr (gas,gbs) = splitAt n $ stream (2*n) str levs = clumps n (nr_rows gr * nr_cols gr) $ drop (n*8) str clumps :: Int -> Int -> [a] -> [[a]] clumps 0 _ _ = [] clumps n csz vs = ts:clumps (n-1) csz ds where (ts,ds) = splitAt csz vs -- Decompress a single layer of V5D data, given its decompression -- factor. Work required depends on the kind of compression used; -- whether floats have been reduced to 1, 2 or 4 bytes. The latter -- case corresponds to no compression. decompress :: V5D_field -> Float -> Float -> [Word8] -> [Float] decompress gr a b vs = case compress gr of 1 -> map (bound.(trans 255)) $ vs 2 -> map (trans 65535) $ short vs 4 -> stream (nr_rows gr * nr_cols gr) vs where trans :: Real a => a -> a -> Float trans k v | v == k = missing | otherwise = (float v) * a + b short :: [Word8] -> [Word16] short [] = [] short (a:b:vs) = let a' :: Word16 = toEnum . fromEnum $ a b' :: Word16 = toEnum . fromEnum $ b in (256*a' + b') : short vs bound :: Float -> Float bound = let d :: Float = b/a l :: Int = if a > 0.0000000001 then floor d else 1 d' :: Float = d - (float l) aa = a * 0.000001 in if -254 <= l && l <= 0 && d' < aa then \v -> if abs(v) < aa then aa else v else id float :: Real a => a -> Float float = fromRational . toRational data V5DGrid = V5DGrid { v5d_file :: String , v5d_field :: String , v5d_time :: Int } instance Show V5DGrid where show (V5DGrid fnm fld t) = fnm ++ "." ++ fld ++ "." ++ (show t) instance Dataset V5DGrid Float where resource d = v5d_file d read_data (V5DGrid fnm fld t) = do { (ds, _) <- readV5Dfile fnm ; let (vals, grd) = dataset ds fld t ; let dimx = (nr_rows grd) ; let dimy = (nr_cols grd) ; let dimz = (nr_levs grd) ; let sh = shapeOfList [dimx, dimy, dimz] :: DIM3 ; let n = dimx * dimy * dimz ; return $ Grid (fnm++"."++fld++"."++(show t)) fld sh t (fromJust.minval $ grd) (fromJust.maxval $ grd) (fromListUnboxed (Z :. n :: DIM1) vals) } -- UTILITY showFile :: V5Dfile -> IO() showFile v = do { putStrLn $ "Number of time slices: "++(show $ nr_times v) ; putStrLn $ "FIELDS: " ; mapM_ showGrid (grids v) } showGrid :: V5D_field -> IO() showGrid gr = do { putStrLn $ " name: " ++ (show.name $ gr) ; putStrLn $ " dim: " ++ snr ++ ", " ++ snc ++ ", " ++ snl ; putStrLn $ " rng: " ++ srng ; putStrLn $ " ----" } where snr = show.nr_rows $ gr snc = show.nr_cols $ gr snl = show.nr_levs $ gr srng = case (minval gr, maxval gr) of (Nothing, Nothing) -> "unknown" (Just lb, Nothing) -> "("++(show lb)++", ?)" (Nothing, Just ub) -> "(?, "++(show ub)++")" (Just lb, Just ub) -> "("++(show lb)++", "++(show ub)++")"
kvelicka/Fizz
UNUSED_V5D.hs
lgpl-2.1
17,941
12
19
6,959
4,955
2,648
2,307
329
7
{-| Module : Data.JustParse.Common Description : Common char parsers Copyright : Copyright Waived License : PublicDomain Maintainer : [email protected] Stability : experimental Portability : portable Several useful parsers for dealing with 'String's. -} {-# LANGUAGE Safe #-} module Data.JustParse.Char ( char , anyChar , caseInsensitiveChar , ascii , latin1 , control , space , spaces , lower , upper , alpha , alphaNum , print , digit , octDigit , hexDigit , string , caseInsensitiveString , eol ) where import Prelude hiding (print) import Data.Char import Data.JustParse.Internal import Data.JustParse.Combinator -- | Parse a specic char. char :: Stream s Char => Char -> Parser s Char char = token {-# INLINE char #-} -- | Parse any char. anyChar :: Stream s Char => Parser s Char anyChar = anyToken {-# INLINE anyChar #-} -- | Parse a specific char, ignoring case. caseInsensitiveChar :: Stream s Char => Char -> Parser s Char caseInsensitiveChar c = char (toUpper c) <|> char (toLower c) {-# INLINE caseInsensitiveChar #-} -- | Parse any char that is ASCII. ascii :: Stream s Char => Parser s Char ascii = satisfy isAscii {-# INLINE ascii #-} -- | Parse any char that is Latin-1. latin1 :: Stream s Char => Parser s Char latin1 = satisfy isLatin1 {-# INLINE latin1 #-} -- | Parse a control character. control :: Stream s Char => Parser s Char control = satisfy isControl {-# INLINE control #-} -- | Parse a space. space :: Stream s Char => Parser s Char space = satisfy isSpace {-# INLINE space #-} -- | Parse many spaces. spaces :: Stream s Char => Parser s String spaces = many space {-# INLINE spaces #-} -- | Parse a lowercase character. lower :: Stream s Char => Parser s Char lower = satisfy isLower {-# INLINE lower #-} -- | Parse an uppercase character. upper :: Stream s Char => Parser s Char upper = satisfy isUpper {-# INLINE upper #-} -- | Parse an alphabetic character. alpha :: Stream s Char => Parser s Char alpha = satisfy isAlpha {-# INLINE alpha #-} -- | Parse an alphanumeric character. alphaNum :: Stream s Char => Parser s Char alphaNum = satisfy isAlphaNum {-# INLINE alphaNum #-} -- | Parse a printable (non-control) character. print :: Stream s Char => Parser s Char print = satisfy isPrint {-# INLINE print #-} -- | Parse a digit. digit :: Stream s Char => Parser s Char digit = satisfy isDigit {-# INLINE digit #-} -- | Parse an octal digit. octDigit :: Stream s Char => Parser s Char octDigit = satisfy isOctDigit {-# INLINE octDigit #-} -- | Parse a hexadeciaml digit. hexDigit :: Stream s Char => Parser s Char hexDigit = satisfy isHexDigit {-# INLINE hexDigit #-} -- | Parse a specific string. string :: Stream s Char => String -> Parser s String string = mapM char {-# INLINE string #-} -- | Parse a specfic string, ignoring case. caseInsensitiveString :: Stream s Char => String -> Parser s String caseInsensitiveString = mapM caseInsensitiveChar {-# INLINE caseInsensitiveString #-} -- | Parses until a newline, carriage return, carriage return + newline, or newline + carriage return. eol :: Stream s Char => Parser s String eol = choice [string "\r\n", string "\n\r", string "\n", string "\r"] {-# INLINE eol #-} -- | Makes common types such as 'String's into a @Stream@. instance Eq t => Stream [t] t where uncons [] = Nothing uncons (x:xs) = Just (x, xs)
grantslatton/JustParse
src/Data/JustParse/Char.hs
unlicense
3,442
0
8
728
756
405
351
-1
-1
{- teapot.hs - Scene containing the teapot. - - Timothy A. Chagnon - CS 636 - Spring 2009 -} import RayTracer main = do rayTracer scene scene = Scene { outfile = "teapot.ppm", width = 512, height = 512, camera = Camera { dist = 3, fovAngle = 56, location = vec3f 0 1.5 8, direction = vec3f 0 0 (-1), up = vec3f 0 1 0 }, background = black, objects = Group [ LoadMesh "models/teapot.smf" ] }
tchagnon/cs636-raytracer
a1/teapot.hs
apache-2.0
631
0
11
319
126
73
53
19
1
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-} module Language.C.Obfuscate.CFF where import Data.Char import Data.List (nubBy) import Data.Maybe import qualified Data.Map as M import qualified Data.Set as S import qualified Language.C.Syntax.AST as AST import qualified Language.C.Data.Node as N import Language.C.Syntax.Constants import Language.C.Data.Ident import Language.C.Obfuscate.Var import Language.C.Obfuscate.ASTUtils import Language.C.Obfuscate.CFG import Language.C.Obfuscate.SSA import Language.C.Obfuscate.CPS (cps_trans_phis, cps_trans_exp, ctxtParamName, renameDeclWithLabeledBlocks, declLHSEq, cps_trans_declaration, dropConstTyQual, dropStorageQual ) -- import for testing import Language.C (parseCFile, parseCFilePre) import Language.C.System.GCC (newGCC) import Language.C.Pretty (pretty) import Text.PrettyPrint.HughesPJ (render, text, (<+>), hsep) import System.IO.Unsafe (unsafePerformIO) type ContextName = String swParamName = "swParam" -- CL_cff -- unlike the paper, we use switch instead of nested if cff_trans_blks :: Bool -> -- ^ is return void S.Set Ident -> -- ^ local vars S.Set Ident -> -- ^ formal args ContextName -> Ident -> -- ^ top level function name M.Map Ident LabeledBlock -> -- ^ KEnv [(Ident, LabeledBlock)] -> -- ^ [(label, { phi ; s })] [AST.CCompoundBlockItem N.NodeInfo] cff_trans_blks isVoid localVars formalArgs ctxtName fname kenv [] = [] cff_trans_blks isVoid localVars formalArgs ctxtName fname kenv ((l, blk):rest) = let stmts = lb_stmts blk sw = iid swParamName stmts' = cff_trans_stmts isVoid localVars formalArgs ctxtName fname sw kenv l stmts -- must be all Block Statement rest' = cff_trans_blks isVoid localVars formalArgs ctxtName fname kenv rest e = AST.CConst (AST.CIntConst (cInteger (unLabPref l)) N.undefNode) --- stmts'' = (stmts'++ [AST.CBlockStmt (AST.CBreak N.undefNode)]) -- need to insert "return;" if it is the last statement; otherwise it loops infinitely ret | isVoid && (null (lb_succs blk)) && (not (endsWithReturn stmts')) = [AST.CBlockStmt (AST.CReturn Nothing N.undefNode)] | otherwise = [] in (cCase e (stmts'++ret))++rest' cff_trans_stmts :: Bool -> -- ^ is return type void S.Set Ident -> -- ^ local vars S.Set Ident -> -- ^ formal args ContextName -> Ident -> -- ^ fname Ident -> -- ^ sw M.Map Ident LabeledBlock -> -- ^ \bar{b} kenv Ident -> -- ^ label for the current block [AST.CCompoundBlockItem N.NodeInfo] -> -- ^ stmts [AST.CCompoundBlockItem N.NodeInfo] cff_trans_stmts isReturnVoid localVars fargs ctxtName fname sw kenv l stmts = concatMap (\stmt -> cff_trans_stmt isReturnVoid localVars fargs ctxtName fname sw kenv l stmt) stmts cff_trans_stmt :: Bool -> -- ^ is return type void S.Set Ident -> -- ^ local vars S.Set Ident -> -- ^ formal args ContextName -> Ident -> -- ^ fname Ident -> -- ^ sw M.Map Ident LabeledBlock -> -- ^ \bar{b} kenv Ident -> -- ^ label for the current block AST.CCompoundBlockItem N.NodeInfo -> -- ^ stmt [AST.CCompoundBlockItem N.NodeInfo] {- CS_cff (goto l_i) kenv lj = \overline{X = E}; sw = i; break; where (\overline{\phi}, s) = kenv l_i \overline{(X,E)} = CF_cff \overline{\phi} l_j -} cff_trans_stmt isReturnVoid localVars fargs ctxtName fname sw kenv l_j (AST.CBlockStmt (AST.CGoto l_i nodeInfo)) = case M.lookup l_i kenv of { Just lb -> let asgmts = cff_trans_phis ctxtName l_j l_i (lb_phis lb) i = AST.CConst (AST.CIntConst (cInteger (unLabPref l_i)) N.undefNode) sw_assg = AST.CBlockStmt (AST.CExpr (Just ((cvar sw) .=. i)) N.undefNode) in asgmts ++ [ sw_assg, cBreak ] ; Nothing -> error "cff_trans_stmt failed at a non existent label." } {- CS_cff (return e) kenv lj = res = (CE_cff e); return; -- in the actual C backend, we do use the go() sub proc. We can return CS_cff (return e) kenv lj = return (CE_cff e); -} cff_trans_stmt isReturnVoid localVars fargs ctxtName fname sw kenv l_i (AST.CBlockStmt (AST.CReturn Nothing nodeInfo)) = [ (AST.CBlockStmt (AST.CReturn Nothing nodeInfo)) ] cff_trans_stmt isReturnVoid localVars fargs ctxtName fname sw kenv l_i (AST.CBlockStmt (AST.CReturn (Just e) nodeInfo)) = let e' = cff_trans_exp localVars fargs ctxtName e in [ (AST.CBlockStmt (AST.CReturn (Just e') nodeInfo)) ] {- CS_cff (x = e; \overline{ x = e }; goto l_i) kenv lj = X = E; S where X = x E = CE_cff e S = CS_cff (\overline{ x = e }; goto l_i) kenv lj -} cff_trans_stmt isReturnVoid localVars fargs ctxtName fname sw kenv l_i (AST.CBlockStmt (AST.CCompound ids stmts nodeInfo)) = let stmts' = cff_trans_stmts isReturnVoid localVars fargs ctxtName fname sw kenv l_i stmts in [AST.CBlockStmt (AST.CCompound ids stmts' nodeInfo)] cff_trans_stmt isReturnVoid localVars fargs ctxtName fname sw kenv l_j (AST.CBlockStmt (AST.CExpr (Just e) nodeInfo)) = -- exp let e' = cff_trans_exp localVars fargs ctxtName e in [AST.CBlockStmt (AST.CExpr (Just e') nodeInfo)] {- CS_cff (if e { goto l_i} else { goto l_j }) kenv l_k = if (CE_cff e) {Si} else { Sj} where Si = CS_cff (goto l_i) kenv l_k Sj = CS_cff (goto l_i) kenv l_k -} cff_trans_stmt isReturnVoid localVars fargs ctxtName fname sw kenv l_k (AST.CBlockStmt (AST.CIf e trueStmt (Just falseStmt) nodeInfo)) = let e' = cff_trans_exp localVars fargs ctxtName e trueStmt' = cff_trans_stmt isReturnVoid localVars fargs ctxtName fname sw kenv l_k (AST.CBlockStmt trueStmt) falseStmt' = cff_trans_stmt isReturnVoid localVars fargs ctxtName fname sw kenv l_k (AST.CBlockStmt falseStmt) in [ AST.CBlockStmt (AST.CIf e' (AST.CCompound [] trueStmt' N.undefNode) (Just (AST.CCompound [] falseStmt' N.undefNode)) nodeInfo) ] cff_trans_stmt isReturnVoid localVars fargs ctxtName fname sw kenv l_k b = error ("cff_trans_stmt : unsupported case " ++ (render $ pretty b)) cff_trans_phis = cps_trans_phis cff_trans_exp = cps_trans_exp cff_trans_declaration = cps_trans_declaration {- CP_cff (t' f (t x) {\overline{d}; \overline{b} }) = T' F (T X) {\overline{D'}; sw = entry; ign = go() ; return res; } where T' = t' F = f T = t X = x \overline{D} = CD_cff \overline{d} (kenv, l_entry) = B_ssa \overline{b} S = CB_cff \overline{b} kenv D = void => void go() => { S } \overline{D'} = \overline{D}; D; T res; int sw; void ign; -} ssa2cff :: (AST.CFunctionDef N.NodeInfo) -> SSA -> CFF ssa2cff fundef ssa@(SSA scopedDecls labelledBlocks sdom local_decl_vars fargs) = let -- scraping the information from the top level function under obfuscation funName = case getFunName fundef of { Just s -> s ; Nothing -> "unanmed" } formalArgDecls :: [AST.CDeclaration N.NodeInfo] formalArgDecls = getFormalArgs fundef formalArgIds :: [Ident] formalArgIds = concatMap (\declaration -> getFormalArgIds declaration) formalArgDecls (returnTy,ptrArrs) = getFunReturnTy fundef isReturnVoid = isVoidDeclSpec returnTy ctxtStructName = funName ++ "Ctxt" -- the context struct declaration context = mkContext ctxtStructName labelledBlocks formalArgDecls scopedDecls returnTy ptrArrs local_decl_vars fargs ctxtName = map toLower ctxtStructName -- alias name is inlower case and will be used in the the rest of the code sw = iid swParamName cases = cff_trans_blks isReturnVoid local_decl_vars fargs ctxtName (iid funName) labelledBlocks (M.toList labelledBlocks) main_decls = -- 1. malloc the context obj in the main func -- ctxtTy * ctxt = (ctxtTy *) malloc(sizeof(ctxtTy)); [ AST.CBlockDecl (AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] [(Just (AST.CDeclr (Just (iid ctxtParamName)) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode), Just (AST.CInitExpr (AST.CCast (AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] [(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode) (AST.CCall (AST.CVar (iid "malloc") N.undefNode) [AST.CSizeofType (AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] [] N.undefNode) N.undefNode] N.undefNode) N.undefNode) N.undefNode),Nothing)] N.undefNode) , AST.CBlockDecl (AST.CDecl [AST.CTypeSpec intTy] [(Just (AST.CDeclr (Just sw) [] Nothing [] N.undefNode), Just (AST.CInitExpr (AST.CConst (AST.CIntConst (cInteger 0) N.undefNode)) N.undefNode), Nothing)] N.undefNode) ] main_stmts = -- 2. initialize the counter-part in the context of the formal args -- forall arg. ctxt->arg_label0 = arg [ AST.CBlockStmt (AST.CExpr (Just (((cvar (iid ctxtParamName)) .->. (arg `app` (iid $ labPref ++ "0" ))) .=. (AST.CVar arg N.undefNode))) N.undefNode) | arg <- formalArgIds] ++ -- 3. initialize the collection which are the local vars, e.g. a locally declared array -- int a[3]; -- will be reinitialized as ctxt->a_0 = (int *)malloc(sizeof(int)*3); [ AST.CBlockStmt (AST.CExpr (Just (((cvar (iid ctxtParamName)) .->. (var `app` (iid $ labPref ++ "0" ))) .=. rhs)) N.undefNode) | scopedDecl <- scopedDecls , isJust (containerDeclToInit scopedDecl) , let (Just (var,rhs)) = containerDeclToInit $ dropStorageQual $ dropConstTyQual scopedDecl ] ++ -- 4. initialize the sw = 0; -- [ AST.CBlockStmt (AST.CExpr (Just ((cvar sw) .=. (AST.CConst (AST.CIntConst (cInteger 0) N.undefNode)))) N.undefNode) ] ++ -- 5. constructing the while (1) { switch sw of { ... } } [ cWhile (AST.CConst (AST.CIntConst (cInteger 1) N.undefNode)) [cSwitch (cvar sw) cases] ] main_func = case fundef of { AST.CFunDef tySpecfs declarator decls _ nodeInfo -> AST.CFunDef tySpecfs declarator decls (AST.CCompound [] (main_decls ++ main_stmts) N.undefNode) nodeInfo } -- io = unsafePerformIO $ print scopedDecls in CFF main_decls main_stmts context main_func prettyCFF :: CFF -> String prettyCFF cff = let declExts = map (\d -> AST.CDeclExt d) [(cff_ctxt cff)] funDeclExts = map (\f -> AST.CFDefExt f) [cff_main cff] in render $ pretty (AST.CTranslUnit (declExts ++ funDeclExts) N.undefNode) -- ^ a CFF function declaration AST data CFF = CFF { cff_decls :: [AST.CCompoundBlockItem N.NodeInfo] -- ^ main function decls , cff_stmts :: [AST.CCompoundBlockItem N.NodeInfo] -- ^ main function stmts , cff_ctxt :: AST.CDeclaration N.NodeInfo -- ^ the context for the closure , cff_main :: AST.CFunctionDef N.NodeInfo -- ^ the main function } deriving Show -- ^ making the context struct declaration mkContext :: String -> -- ^ context name M.Map Ident LabeledBlock -> -- ^ labeled blocks [AST.CDeclaration N.NodeInfo] -> -- ^ formal arguments [AST.CDeclaration N.NodeInfo] -> -- ^ local variable declarations [AST.CDeclarationSpecifier N.NodeInfo] -> -- ^ return Type [AST.CDerivedDeclarator N.NodeInfo] -> -- ^ the pointer or array postfix S.Set Ident -> S.Set Ident -> AST.CDeclaration N.NodeInfo mkContext name labeledBlocks formal_arg_decls local_var_decls returnType ptrArrs local_decl_vars fargs = let structName = iid name ctxtAlias = AST.CDeclr (Just (internalIdent (map toLower name))) [] Nothing [] N.undefNode attrs = [] isReturnVoid = isVoidDeclSpec returnType funcResult | isReturnVoid = [] | otherwise = [AST.CDecl returnType [(Just (AST.CDeclr (Just $ iid "func_result") ptrArrs Nothing [] N.undefNode), Nothing, Nothing)] N.undefNode] decls' = -- formal_arg_decls ++ -- note: we remove local decl duplicate, maybe we should let different label block to have different type decl in the ctxt, see test/scoped_dup_var.c concatMap (\d -> renameDeclWithLabeledBlocks d labeledBlocks local_decl_vars fargs) (nubBy declLHSEq $ map (cff_trans_declaration . dropConstTyQual . dropStorageQual) (formal_arg_decls ++ local_var_decls)) ++ funcResult tyDef = AST.CStorageSpec (AST.CTypedef N.undefNode) structDef = AST.CTypeSpec (AST.CSUType (AST.CStruct AST.CStructTag (Just structName) (Just decls') attrs N.undefNode) N.undefNode) in AST.CDecl [tyDef, structDef] [(Just ctxtAlias, Nothing, Nothing)] N.undefNode -- ^ turn a scope declaration into a rhs initalization. -- ^ refer to local_array.c containerDeclToInit :: AST.CDeclaration N.NodeInfo -> Maybe (Ident, AST.CExpression N.NodeInfo) containerDeclToInit (AST.CDecl typespecs tripls nodeInfo0) = case tripls of { (Just decl@(AST.CDeclr (Just arrName) [arrDecl] _ _ _), mb_init, _):_ -> case arrDecl of { AST.CArrDeclr _ (AST.CArrSize _ size) _ -> let ptrToTy = AST.CDecl typespecs [(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode malloc = AST.CCall (AST.CVar (iid "malloc") N.undefNode) [AST.CBinary AST.CMulOp (AST.CSizeofType (AST.CDecl typespecs [] N.undefNode) N.undefNode) size N.undefNode] N.undefNode cast = AST.CCast ptrToTy malloc N.undefNode in Just (arrName, cast) {- not needed, the size is recovered during the construction of SSA, see Var.hs splitDecl ; AST.CArrDeclr _ (AST.CNoArrSize _) _ -> -- no size of the array, derive from the init list case mb_init of { Just (AST.CInitList l _) -> let size = AST.CConst (AST.CIntConst (cInteger (fromIntegral $ length l)) N.undefNode) ptrToTy = AST.CDecl typespecs [(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode malloc = AST.CCall (AST.CVar (iid "malloc") N.undefNode) [AST.CBinary AST.CMulOp (AST.CSizeofType (AST.CDecl typespecs [] N.undefNode) N.undefNode) size N.undefNode] N.undefNode cast = AST.CCast ptrToTy malloc N.undefNode in Just (arrName, cast) ; Nothing -> Nothing } -} ; _ -> Nothing } ; _ -> Nothing }
luzhuomi/cpp-obs
Language/C/Obfuscate/CFF.hs
apache-2.0
16,226
0
31
4,923
3,584
1,889
1,695
181
3
-- Copyright 2020 Google LLC -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. module Main (main) where main :: IO () main = return ()
google/cabal2bazel
bzl/tests/ffi/LinkInputsTest.hs
apache-2.0
646
0
6
114
42
29
13
3
1
{-# LANGUAGE TemplateHaskell, CPP, FlexibleContexts, FlexibleInstances, MultiParamTypeClasses, FunctionalDependencies, UndecidableInstances #-} ----------------------------------------------------------------------------- -- | -- Module : Data.Type.Hex.Stage3 -- Copyright : (C) 2006-2011 Edward Kmett -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : Edward Kmett <[email protected]> -- Stability : experimental -- Portability : non-portable (MPTC, FD, TH, undecidable instances, missing constructors) -- -- Stage3: Define everything else. The juicier bits are then exposed via "Data.Type.Hex" ----------------------------------------------------------------------------- module Data.Type.Hex.Stage3 where import Data.Type.Boolean import Control.Monad import Data.Type.Hex.Stage1 import Data.Type.Hex.Stage2 import Data.Type.Sign import Data.Type.Ord import Data.Bits import Language.Haskell.TH import qualified Data.Type.Binary as B instance TSucc T F instance TSucc F (D1 F) instance TSucc (DE T) T instance (TSucc n m, ExtF n, Ext0 m) => TSucc (DF n) (D0 m) return $ wrapI (zip (init x0) (tail x0)) $ \(x1,x2) -> ConT tsucc `AppT` AppT x1 (ConT f) `AppT` AppT x2 (ConT f) return $ wrapI (zip (init xF) (tail xF)) $ \(x1,x2) -> ConT tsucc `AppT` AppT x1 (ConT t) `AppT` AppT x2 (ConT t) return $ wrapI (liftM2 (,) (zip xF x0) x) $ \((xn, xm), x) -> let b = AppT x (VarT a) in ConT tsucc `AppT` AppT xn b `AppT` AppT xm b tSucc :: TSucc n m => n -> m; tSucc = undefined tPred :: TSucc n m => m -> n; tPred = undefined class TNeg a b | a -> b, b -> a instance (TNot a b, TSucc b c) => TNeg a c tNeg :: TNeg a b => a -> b; tNeg = undefined instance Trichotomy T Negative instance Trichotomy F SignZero return $ wrapI x0 $ \x -> ConT trichotomy `AppT` AppT x (ConT f) `AppT` ConT positive return $ wrapI xF $ \x -> ConT trichotomy `AppT` AppT x (ConT t) `AppT` ConT negative let es = [extf, ext0] ext0 = mkName "Ext0" extf = mkName "ExtF" df = mkName "DF" in return $ flip map (zip x es) $ \(x, e) -> InstanceD [ClassP trichotomy [VarT a, VarT b], ClassP e [VarT a]] (ConT trichotomy `AppT` (x `AppT` (ConT df `AppT` VarT a)) `AppT` VarT b) [] class TIsPositive n b | n -> b instance (Trichotomy n s, TEq s Positive b) => TIsPositive n b tIsPositive :: TIsPositive n b => n -> b; tIsPositive = undefined class TIsNegative n b | n -> b instance (Trichotomy n s, TEq s Negative b) => TIsNegative n b tIsNegative :: TIsNegative n b => n -> b; tIsNegative = undefined class TIsZero n b | n -> b instance (Trichotomy n s, TEq s SignZero b) => TIsZero n b tIsZero :: TIsZero n b => n -> b; tIsZero = undefined instance TAddC' F F F F instance TAddC' T F T F instance TAddC' F T F T instance TAddC' T T T T instance TAddC' T F F T instance TAddC' F T T F instance TAddC' F F T (D1 F) instance TAddC' T T F (DE T) instance TSucc a b => TAddC' F (DF a) T (D0 b) instance TSucc b a => TAddC' T (D0 a) F (DF b) instance TSucc a b => TAddC' (DF a) F T (D0 b) instance TSucc b a => TAddC' (D0 a) T F (DF b) return $ wrapI (liftM2 (,) [t, f] x) $ \(tf, dx) -> let dxa = AppT dx (VarT a) in ConT taddc' `AppT` ConT tf `AppT` dxa `AppT` ConT tf `AppT` dxa return $ wrapI (liftM2 (,) [t, f] x) $ \(tf, dx) -> let dxa = AppT dx (VarT a) in ConT taddc' `AppT` dxa `AppT` ConT tf `AppT` ConT tf `AppT` dxa return $ wrapI (zip xF x0) $ \(dn, dm) -> ConT taddc' `AppT` ConT f `AppT` AppT dn (VarT a) `AppT` ConT t `AppT` AppT dm (VarT a) return $ wrapI (zip xF x0) $ \(dn, dm) -> ConT taddc' `AppT` ConT t `AppT` AppT dm (VarT a) `AppT` ConT f `AppT` AppT dn (VarT a) return $ wrapI (zip xF x0) $ \(dn, dm) -> ConT taddc' `AppT` AppT dn (VarT a) `AppT` ConT f `AppT` ConT t `AppT` AppT dm (VarT a) return $ wrapI (zip xF x0) $ \(dn, dm) -> ConT taddc' `AppT` AppT dm (VarT a) `AppT` ConT t `AppT` ConT f `AppT` AppT dn (VarT a) return $ (flip map) (liftM3 (,,) (zip x [0..15]) (zip x [0..15]) [(f, 0), (t, 1)]) $ \((x0, n0), (x1, n1), (thing1, thing2)) -> let total = n0 + n1 + thing2 pcarry = if total > 15 then t else f x2 = x !! (total `mod` 16) in InstanceD [ClassP taddc' [VarT a, VarT b, ConT pcarry, VarT c]] (ConT taddc' `AppT` AppT x0 (VarT a) `AppT` AppT x1 (VarT b) `AppT` ConT thing1 `AppT` AppT x2 (VarT c)) [] tAddC' :: TAddC' a b c d => a -> b -> c -> d; tAddC' = undefined tAddF' :: TAddC' a b F d => a -> b -> d; tAddF' = undefined class TNF a b | a -> b instance TNF' a b c => TNF a b tNF :: TNF a b => a -> b; tNF = undefined class TAdd' a b c | a b -> c instance (TAddC' a b F d, TNF d d') => TAdd' a b d' tAdd' :: (TAdd' a b c ) => a -> b -> c; tAdd' = undefined class TSub' a b c | a b -> c instance (TNeg b b', TAdd' a b' c) => TSub' a b c tSub' :: TSub' a b c => a -> b -> c; tSub' = undefined class TAdd a b c | a b -> c, a c -> b, b c -> a instance (TAdd' a b c, TNeg b b', TAdd' c b' a, TNeg a a', TAdd' c a' b) => TAdd a b c tAdd :: (TAdd a b c) => a -> b -> c;tAdd = undefined tSub :: (TAdd a b c) => c -> a -> b;tSub = undefined -- | $(hexT n) returns the appropriate THex instance hexT :: Integral a => a -> Type hexT n = case n of 0 -> ConT f -1 -> ConT t n -> AppT (x !! mod (fromIntegral n) 16) $ hexT $ n `div` 16 -- | $(hexE n) returns an undefined value of the appropriate THex instance hexE :: Integral a => a -> Exp hexE n = SigE (VarE $ mkName "undefined") $ hexT n instance THex (D0 a) => Show (D0 a) where show n = "$(hexE "++ (show $ fromTHex n)++")" instance THex (D1 a) => Show (D1 a) where show n = "$(hexE "++ (show $ fromTHex n)++")" instance THex (D2 a) => Show (D2 a) where show n = "$(hexE "++ (show $ fromTHex n)++")" instance THex (D3 a) => Show (D3 a) where show n = "$(hexE "++ (show $ fromTHex n)++")" instance THex (D4 a) => Show (D4 a) where show n = "$(hexE "++ (show $ fromTHex n)++")" instance THex (D5 a) => Show (D5 a) where show n = "$(hexE "++ (show $ fromTHex n)++")" instance THex (D6 a) => Show (D6 a) where show n = "$(hexE "++ (show $ fromTHex n)++")" instance THex (D7 a) => Show (D7 a) where show n = "$(hexE "++ (show $ fromTHex n)++")" instance THex (D8 a) => Show (D8 a) where show n = "$(hexE "++ (show $ fromTHex n)++")" instance THex (D9 a) => Show (D9 a) where show n = "$(hexE "++ (show $ fromTHex n)++")" instance THex (DA a) => Show (DA a) where show n = "$(hexE "++ (show $ fromTHex n)++")" instance THex (DB a) => Show (DB a) where show n = "$(hexE "++ (show $ fromTHex n)++")" instance THex (DC a) => Show (DC a) where show n = "$(hexE "++ (show $ fromTHex n)++")" instance THex (DD a) => Show (DD a) where show n = "$(hexE "++ (show $ fromTHex n)++")" instance THex (DE a) => Show (DE a) where show n = "$(hexE "++ (show $ fromTHex n)++")" instance THex (DF a) => Show (DF a) where show n = "$(hexE "++ (show $ fromTHex n)++")" instance SHR1 H0 F F instance SHR1 H1 F (D1 F) instance SHR1 H0 T (DE T) instance SHR1 H1 T (DE T) return $ wrapI (liftM3 (,,) (zip x [0..15]) (zip h [0..1]) (zip [t, f] [15, 0])) $ \((d, dn), (c, cn), (tf, tfn)) -> let dlsn = x !! ((dn*2+cn) `mod` 16) dmsn = x !! (((dn `div` 8) + tfn*2) `mod` 16) nmsn = dn `div` 8 dcase = if ((tfn .&. 1) `xor` nmsn) /= 0 then AppT dmsn (ConT tf) else ConT tf in ConT shr1 `AppT` c `AppT` AppT d (ConT tf) `AppT` AppT dlsn dcase return $ (flip map) (liftM3 (,,) (zip x [0..15]) (zip h [0..1]) (zip x [0..15])) $ \((dm, dmi), (c, cn), (dn, dni)) -> let msb_m = dmi `div` 8 dn' = x !! ((msb_m + (dni*2)) `mod` 16) dm' = x !! ((cn + (dmi*2)) `mod` 16) pre_c = h !! msb_m dna = AppT dn (VarT a) dn'b = AppT dn' (VarT b) in InstanceD [ClassP shr1 [pre_c, dna, dn'b]] (ConT shr1 `AppT` c `AppT` AppT dm dna `AppT` AppT dm' dn'b) [] -- | A simple peasant multiplier. TODO: exploit 2s complement and reverse the worst cases class TMul a b c | a b -> c instance TMul a F F instance TNeg a b => TMul a T b instance TMul (D0 a1) b c => TMul a1 (D0 b) c instance ( TMul (D0 a1) b c , TAdd' a1 c d) => TMul a1 (D1 b) d instance ( TMul (D0 a1) b c , SHR1 H0 a1 a2 , TAdd' a2 c d) => TMul a1 (D2 b) d instance ( TMul (D0 a1) b c , SHR1 H0 a1 a2 , TAdd' a1 a2 a3 , TAdd' a3 c d) => TMul a1 (D3 b) d instance ( TMul (D0 a1) b c , SHR1 H0 a1 a2 , SHR1 H0 a2 a4 , TAdd' a4 c d) => TMul a1 (D4 b) d instance ( TMul (D0 a1) b c , SHR1 H0 a1 a2 , SHR1 H0 a2 a4 , TAdd' a1 a4 a5 , TAdd' a5 c d) => TMul a1 (D5 b) d instance ( TMul (D0 a1) b c , SHR1 H0 a1 a2 , SHR1 H0 a2 a4 , TAdd' a2 a4 a6 , TAdd' a6 c d) => TMul a1 (D6 b) d instance ( TMul (D0 a1) b c , SHR1 H0 a1 a2 , SHR1 H0 a2 a4 , TAdd' a2 a4 a6 , TAdd' a1 a6 a7 , TAdd' a7 c d) => TMul a1 (D7 b) d instance ( TMul (D0 a1) b c , SHR1 H0 a1 a2 , SHR1 H0 a2 a4 , SHR1 H0 a4 a8 , TAdd' a8 c d) => TMul a1 (D8 b) d instance ( TMul (D0 a1) b c , SHR1 H0 a1 a2 , SHR1 H0 a2 a4 , SHR1 H0 a4 a8 , TAdd' a1 a8 a9 , TAdd' a9 c d) => TMul a1 (D9 b) d instance ( TMul (D0 a1) b c , SHR1 H0 a1 a2 , SHR1 H0 a2 a4 , SHR1 H0 a4 a8 , TAdd' a2 a8 aA , TAdd' aA c d) => TMul a1 (DA b) d instance ( TMul (D0 a1) b c , SHR1 H0 a1 a2 , SHR1 H0 a2 a4 , SHR1 H0 a4 a8 , TAdd' a2 a8 a0 , TAdd' a1 a0 aB , TAdd' aB c d) => TMul a1 (DB b) d instance ( TMul (D0 a1) b c , SHR1 H0 a1 a2 , SHR1 H0 a2 a4 , SHR1 H0 a4 a8 , TAdd' a4 a8 aC , TAdd' aC c d) => TMul a1 (DC b) d instance ( TMul (D0 a1) b c , SHR1 H0 a1 a2 , SHR1 H0 a2 a4 , SHR1 H0 a4 a8 , TAdd' a4 a8 aC , TAdd' a1 aC aD , TAdd' aD c d) => TMul a1 (DD b) d instance ( TMul (D0 a1) b c , SHR1 H0 a1 a2 , SHR1 H0 a2 a4 , SHR1 H0 a4 a8 , TAdd' a4 a8 aC , TAdd' a2 aC aE , TAdd' aE c d) => TMul a1 (DE b) d instance ( TMul (D0 a1) b c , SHR1 H0 a1 a2 , SHR1 H0 a2 a4 , SHR1 H0 a4 a8 , TAdd' a4 a8 aC , TAdd' a2 aC aE , TAdd' a1 aE aF , TAdd' aF c d) => TMul a1 (DF b) d tMul :: TMul a b c => a -> b -> c tMul = undefined class THex2Binary' a b | a -> b, b -> a instance THex2Binary' F F instance THex2Binary' T T instance THex2Binary' a b => THex2Binary' (D0 a) (B.O(B.O(B.O(B.O b)))) instance THex2Binary' a b => THex2Binary' (D1 a) (B.I(B.O(B.O(B.O b)))) instance THex2Binary' a b => THex2Binary' (D2 a) (B.O(B.I(B.O(B.O b)))) instance THex2Binary' a b => THex2Binary' (D3 a) (B.I(B.I(B.O(B.O b)))) instance THex2Binary' a b => THex2Binary' (D4 a) (B.O(B.O(B.I(B.O b)))) instance THex2Binary' a b => THex2Binary' (D5 a) (B.I(B.O(B.I(B.O b)))) instance THex2Binary' a b => THex2Binary' (D6 a) (B.O(B.I(B.I(B.O b)))) instance THex2Binary' a b => THex2Binary' (D7 a) (B.I(B.I(B.I(B.O b)))) instance THex2Binary' a b => THex2Binary' (D8 a) (B.O(B.O(B.O(B.I b)))) instance THex2Binary' a b => THex2Binary' (D9 a) (B.I(B.O(B.O(B.I b)))) instance THex2Binary' a b => THex2Binary' (DA a) (B.O(B.I(B.O(B.I b)))) instance THex2Binary' a b => THex2Binary' (DB a) (B.I(B.I(B.O(B.I b)))) instance THex2Binary' a b => THex2Binary' (DC a) (B.O(B.O(B.I(B.I b)))) instance THex2Binary' a b => THex2Binary' (DD a) (B.I(B.O(B.I(B.I b)))) instance THex2Binary' a b => THex2Binary' (DE a) (B.O(B.I(B.I(B.I b)))) instance THex2Binary' a b => THex2Binary' (DF a) (B.I(B.I(B.I(B.I b)))) class THex2Binary a b | a -> b instance (THex2Binary' a b, B.TNF b b') => THex2Binary a b' tHex2Binary :: THex2Binary a b => a -> b; tHex2Binary = undefined class TBinary2Hex a b | a -> b instance (THex2Binary' a b, TNF a a') => TBinary2Hex b a' tBinary2Hex :: TBinary2Hex a b => a -> b; tBinary2Hex = undefined class THexBinary a b | a -> b, b -> a instance (THex2Binary a b, TBinary2Hex b a) => THexBinary a b -- | peasant exponentiator with explicit binary exponent class TPow' a b c | a b -> c instance TPow' a F (D1 F) instance (TPow' a k c, TMul c c d) => TPow' a (B.O k) d instance (TPow' a k c, TMul c c d, TMul a d e) => TPow' a (B.I k) e -- | peasant exponentiator class TPow a b c | a b -> c instance (THex2Binary b b', TPow' a b' c) => TPow a b c tPow :: TPow a b c => a -> b -> c tPow = undefined
ekmett/type-int
Data/Type/Hex/Stage3.hs
bsd-2-clause
14,658
0
18
5,485
6,800
3,488
3,312
-1
-1
{-# OPTIONS_HADDOCK hide #-} module Network.Xmpp.Concurrent.Basic where import Control.Applicative import Control.Concurrent.STM import qualified Control.Exception as Ex import Control.Monad.State.Strict import qualified Data.ByteString as BS import Network.Xmpp.Concurrent.Types import Network.Xmpp.Marshal import Network.Xmpp.Stream import Network.Xmpp.Types import Network.Xmpp.Utilities semWrite :: WriteSemaphore -> BS.ByteString -> IO (Either XmppFailure ()) semWrite sem bs = Ex.bracket (atomically $ takeTMVar sem) (atomically . putTMVar sem) ($ bs) writeStanza :: WriteSemaphore -> Stanza -> IO (Either XmppFailure ()) writeStanza sem a = do let outData = renderElement $ nsHack (pickleElem xpStanza a) debugOut outData semWrite sem outData -- | Send a stanza to the server without running plugins. (The stanza is sent as -- is) sendRawStanza :: Stanza -> Session -> IO (Either XmppFailure ()) sendRawStanza a session = writeStanza (writeSemaphore session) a -- | Send a stanza to the server, managed by plugins sendStanza :: Stanza -> Session -> IO (Either XmppFailure ()) sendStanza = flip sendStanza' -- | Get the channel of incoming stanzas. getStanzaChan :: Session -> TChan (Stanza, [Annotation]) getStanzaChan session = stanzaCh session -- | Get the next incoming stanza getStanza :: Session -> IO (Stanza, [Annotation]) getStanza session = atomically . readTChan $ stanzaCh session -- | Duplicate the inbound channel of the session object. Most receiving -- functions discard stanzas they are not interested in from the inbound -- channel. Duplicating the channel ensures that those stanzas can aren't lost -- and can still be handled somewhere else. dupSession :: Session -> IO Session dupSession session = do stanzaCh' <- atomically $ cloneTChan (stanzaCh session) return $ session {stanzaCh = stanzaCh'} -- | Return the JID assigned to us by the server getJid :: Session -> IO (Maybe Jid) getJid Session{streamRef = st} = do s <- atomically $ readTMVar st withStream' (gets streamJid) s -- | Return the stream features the server announced getFeatures :: Session -> IO StreamFeatures getFeatures Session{streamRef = st} = do s <- atomically $ readTMVar st withStream' (gets streamFeatures) s -- | Wait until the connection of the stream is re-established waitForStream :: Session -> IO () waitForStream Session{streamRef = sr} = atomically $ do s <- readTMVar sr ss <- readTMVar $ unStream s case streamConnectionState ss of Plain -> return () Secured -> return () _ -> retry streamState :: Session -> STM ConnectionState streamState Session{streamRef = sr} = do s <- readTMVar sr streamConnectionState <$> (readTMVar $ unStream s)
Philonous/pontarius-xmpp
source/Network/Xmpp/Concurrent/Basic.hs
bsd-3-clause
2,878
0
13
621
712
368
344
53
3
{-# LANGUAGE DisambiguateRecordFields #-} module Data.Cov.Jac where import Prelude.Extended data Jac a b = Jac { v :: Array Number, nr :: Int }
LATBauerdick/fv.hs
src/Data/Cov/Jac.hs
bsd-3-clause
150
0
9
30
39
25
14
4
0
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE OverloadedStrings #-} module Language.Eiffel.TypeCheck.TypedExpr where import Control.Applicative import Data.DeriveTH import Data.Binary import qualified Data.Text as Text import Data.Text (Text) import qualified Language.Eiffel.Syntax as E (UnPosExpr (..), ROp (..), UnOp (..)) import Language.Eiffel.Syntax hiding (UnPosExpr (..), ROp (..), UnOp (..)) import Language.Eiffel.Position import Language.Eiffel.Util type TClass = ClasBody TExpr type TRoutine = RoutineWithBody TExpr type TStmt = PosAbsStmt TExpr type UnPosTStmt = AbsStmt TExpr type TExpr = Pos UnPosTExpr data EqOp = Eq | Neq | TildeEq | TildeNeq deriving (Show, Eq) eqOp (RelOp E.Eq _) = Eq eqOp (RelOp E.Neq _) = Neq eqOp (RelOp E.TildeEq _) = TildeEq eqOp (RelOp E.TildeNeq _) = TildeNeq eqOp r = error $ "eqOp: " ++ show r binEqOp Eq = RelOp E.Eq NoType binEqOp Neq = RelOp E.Neq NoType binEqOp TildeEq = RelOp E.TildeEq NoType binEqOp TildeNeq = RelOp E.TildeNeq NoType data UnPosTExpr = Call TExpr Text [TExpr] Typ | Access TExpr Text Typ | Agent TExpr Text [TExpr] Typ | Old TExpr | Var Text Typ | EqExpr EqOp TExpr TExpr | CreateExpr Typ Text [TExpr] | Attached (Maybe Typ) TExpr (Maybe Text) | StaticCall Typ Text [TExpr] Typ | Tuple [TExpr] | ResultVar Typ | CurrentVar Typ | Box Typ TExpr | Unbox Typ TExpr | Cast Typ TExpr | LitType Typ | LitArray [TExpr] | LitChar Char | LitString Text | LitInt Integer | LitBool Bool | LitVoid Typ | LitDouble Double deriving (Show, Eq) $( derive makeBinary ''EqOp ) $( derive makeBinary ''UnPosTExpr ) untype :: TClass -> Clas untype = classMapExprs untypeFeat untypeClause untypeConstant untypeClause :: Clause TExpr -> Clause Expr untypeClause (Clause label e) = Clause label (untypeExpr e) untypeContract (Contract inhrt clauses) = Contract inhrt (map untypeClause clauses) untypeConstant (Constant froz decl expr) = Constant froz decl (untypeExpr expr) untypeFeat :: TRoutine -> Routine untypeFeat tfeat = tfeat { routineImpl = untypeImpl (routineImpl tfeat) , routineReq = untypeContract (routineReq tfeat) , routineEns = untypeContract (routineEns tfeat) , routineRescue = map untypeStmt `fmap` routineRescue tfeat } untypeImpl :: RoutineBody TExpr -> RoutineBody Expr untypeImpl body = body {routineBody = untypeStmt (routineBody body)} untypeStmt :: TStmt -> Stmt untypeStmt = fmap untypeStmt' untypeStmt' :: UnPosTStmt -> UnPosStmt untypeStmt' (Assign l e) = Assign (untypeExpr l) (untypeExpr e) untypeStmt' (CallStmt e) = CallStmt (untypeExpr e) untypeStmt' (Block ss) = Block (map untypeStmt ss) untypeStmt' BuiltIn = BuiltIn untypeStmt' (Check cs) = Check (map untypeClause cs) untypeStmt' (Loop from inv untl body var) = Loop (untypeStmt from) (map untypeClause inv) (untypeExpr untl) (untypeStmt body) (untypeExpr <$> var) untypeStmt' (If e body elseIfs elsePart) = let untypeElseIf (ElseIfPart cond s) = ElseIfPart (untypeExpr cond) (untypeStmt s) in If (untypeExpr e) (untypeStmt body) (map untypeElseIf elseIfs) (fmap untypeStmt elsePart) untypeStmt' (Create typeMb targ name es) = Create typeMb (untypeExpr targ) name (map untypeExpr es) untypeStmt' s = error $ "untypeStmt': " ++ show s untypeExpr :: TExpr -> Expr untypeExpr = fmap untypeExpr' untypeExpr' :: UnPosTExpr -> E.UnPosExpr untypeExpr' (Call trg name args _r) = E.QualCall (untypeExpr trg) name (map untypeExpr args) untypeExpr' (Access trg name _r) = E.QualCall (untypeExpr trg) name [] untypeExpr' (Var s _t) = E.VarOrCall s untypeExpr' (CurrentVar _t) = E.CurrentVar untypeExpr' (Old e) = E.UnOpExpr E.Old (untypeExpr e) untypeExpr' (Cast _ e) = contents $ untypeExpr e untypeExpr' (ResultVar _t) = E.ResultVar untypeExpr' (EqExpr op e1 e2) = E.BinOpExpr (binEqOp op) (untypeExpr e1) (untypeExpr e2) untypeExpr' (Attached typ e asName) = E.Attached typ (untypeExpr e) asName untypeExpr' (Box _ e) = contents $ untypeExpr e untypeExpr' (Unbox _ e) = contents $ untypeExpr e untypeExpr' (LitArray es) = E.LitArray (map untypeExpr es) untypeExpr' (LitChar c) = E.LitChar c untypeExpr' (LitString s) = E.LitString s untypeExpr' (LitInt i) = E.LitInt i untypeExpr' (LitBool b) = E.LitBool b untypeExpr' (LitVoid _) = E.LitVoid untypeExpr' (LitDouble d) = E.LitDouble d untypeExpr' (Tuple es) = E.Tuple (map untypeExpr es) untypeExpr' (Agent trg name args _) = E.Agent $ takePos trg $ E.QualCall (untypeExpr trg) name (map untypeExpr args) untypeExpr' (CreateExpr t fname args) = E.CreateExpr t fname $ map untypeExpr args untypeExpr' s = error $ "untypeExpr': " ++ show s texpr :: TExpr -> Typ texpr = texprTyp . contents texprTyp :: UnPosTExpr -> Typ texprTyp (CreateExpr t _ _) = t texprTyp (Agent _ _ _ t) = t texprTyp (Var _ t) = t texprTyp (Cast t _) = t texprTyp (ResultVar t) = t texprTyp (CurrentVar t) = t texprTyp (Call _ _ _ t) = t texprTyp (Access _ _ t) = t texprTyp (EqExpr{}) = boolType texprTyp (Box _ te) = texpr te texprTyp (Unbox t _) = t texprTyp (Old e) = texprTyp (contents e) texprTyp (StaticCall _ _ _ t) = t texprTyp (LitChar _) = charType texprTyp (Attached{}) = boolType texprTyp (LitString _) = stringType texprTyp (LitType t) = ClassType "TYPE" [t] texprTyp (LitInt _) = intType texprTyp (LitBool _) = boolType texprTyp (LitDouble _) = realType texprTyp (LitVoid t) = t
scottgw/eiffel-typecheck
Language/Eiffel/TypeCheck/TypedExpr.hs
bsd-3-clause
5,551
0
11
1,138
2,165
1,110
1,055
153
1
{-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedLabels #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TupleSections #-} module Main (main) where import Prelude (error) import Control.Applicative ((<*>), pure) import Control.Monad ((=<<), (>>=), mapM_, unless) import Data.Bool (Bool(True), otherwise) import Data.Eq (Eq((/=))) import Data.Function (($), (.), id) import Data.Functor ((<$>), fmap) import Data.Foldable (foldr) import Data.List (elem, lookup, map, words) import Data.Maybe (Maybe(Just, Nothing), catMaybes) import Data.Monoid ((<>)) import Data.String (IsString(fromString), String) import Data.Version (showVersion) import System.Environment ( getArgs , getEnvironment , getExecutablePath , getProgName , lookupEnv ) import System.IO (FilePath, IO) import qualified Data.HashMap.Strict as HashMap (lookup) --import Data.List.Split (splitOn) --import Data.Text (Text) import qualified Data.Text as Text (unpack) import qualified Data.Text.IO as Text (putStrLn) import qualified Database.SQLite.Simple as SQLite (execute_, withConnection) import System.Directory ( XdgDirectory(XdgConfig) , canonicalizePath -- , createDirectory , createDirectoryIfMissing , doesDirectoryExist , doesFileExist -- , executable -- , findFileWith -- , getPermissions , getXdgDirectory , setCurrentDirectory ) import System.FilePath ( (</>) , dropTrailingPathSeparator , takeFileName ) import System.Posix.Process (executeFile) import YX.Initialize (initializeProject, readCachedYxConfig) import YX.Main import YX.Paths ( EnvironmentName , TypeOfStuff(CachedStuff, EnvironmentStuff, YxStuff) , yxExeStuff , yxShellStuff , yxStuffPath , yxStuffFile ) import YX.ProcessEnvironmentVariables () -- Force build. import YX.Shell (Shell(Bash), findShell, shellExePaths) import YX.Type.CommandType (CommandType(Command)) import YX.Type.ConfigFile (Executable(Executable){-, ProjectConfig-}) import qualified YX.Type.ConfigFile as Environment (Environment(_bin)) import qualified YX.Type.ConfigFile as ProjectConfig ( Executable(_command, {-_environment,-} _type) , defaultEnvironment , getEnvironment ) import YX.Type.DbConnection (DbConnection(DbConnection)) import YX.Type.Shell () -- Force build. import Paths_yx (version) main :: IO () main = do getProgName >>= \case "yx" -> yxMain other -> getArgs >>= yxExec other where yxExec alias args = do lookupEnv "YX_VERSION" >>= \case Nothing -> error "Not in an YX environment." Just _ -> pure () envName <- lookupEnv "YX_ENVIRONMENT" >>= \case Nothing -> error "YX environment variables are corrupted." Just x -> pure x root <- lookupEnv "YX_PROJECT_ROOT" >>= \case Nothing -> error "YX environment variables are corrupted." Just x -> pure x projCfg <- readCachedYxConfig $ yxStuffFile root CachedStuff "config.bin" projEnv <- case ProjectConfig.getEnvironment projCfg $ fromString envName of Nothing -> error "YX configuration corrupted." Just e -> pure e case HashMap.lookup (fromString alias) (Environment._bin projEnv) of Nothing -> errInvalidAlias alias Just Executable{..} | _type /= Command -> errInvalidAlias alias | otherwise -> case words (Text.unpack _command) of [] -> error $ alias <> ": Invalid configuration of this alias." cmd : cmdArgs -> executeFile cmd True (cmdArgs <> args) Nothing errInvalidAlias cmd = error $ cmd <> ": YX called with invalid alias." yxMain :: IO () yxMain = do dbFile <- getYxDatabaseFile yxExe <- getExecutablePath getArgs >>= \case "cd" : pattern : _ -> doCd dbFile yxExe pattern ["ls"] -> doLs dbFile Nothing "ls" : pattern : _ -> doLs dbFile $ Just pattern _ -> error "Unknown argument or option." doCd :: FilePath -> FilePath -> String -> IO () doCd dbFile yxExe pattern = SQLite.withConnection dbFile $ \c -> do let conn = DbConnection c findProjects conn (modifyPattern pattern) >>= \case [] -> do isADirectory <- doesDirectoryExist pattern if isADirectory then newProject conn pattern >>= runProjEnv Nothing else error "No such project found, try \"yx ls PATTERN\"." [p] -> runProjEnv Nothing p ps -> printProjects ps where runProjEnv = runProjectEnvironment yxExe doLs :: FilePath -> Maybe String -> IO () doLs dbFile possiblePattern = SQLite.withConnection dbFile $ \c -> do let conn = DbConnection c printProjects =<< case possiblePattern of Nothing -> listProjects conn Just pattern -> findProjects conn (modifyPattern pattern) modifyPattern :: IsString s => String -> s modifyPattern pat | '*' `elem` pat = fromString pat | otherwise = fromString $ "*" <> pat <> "*" printProjects :: [Project] -> IO () printProjects = mapM_ printProject where printProject Project{..} = Text.putStrLn $ _name <> ": " <> _path runProjectEnvironment :: FilePath -> Maybe EnvironmentName -> Project -> IO () runProjectEnvironment yxExe possiblyEnvName project@Project{..} = do projectCfg <- initializeProject yxExe root (projEnvName, _projEnv) <- getProjEnv projectCfg setCurrentDirectory root env <- modifyEnvVariables project projEnvName <*> getEnvironment shell <- findShell (lookup "PATH" env) (lookup "SHELL" env) defaultShells executeFile shell True ["--rcfile", bashrc projEnvName] (Just env) where -- We currently support only bash, so it makes sense to have it as default. defaultShells = shellExePaths Bash bashrc projEnvName = yxShellStuff root projEnvName Bash </> "bashrc" root = Text.unpack _path getProjEnv cfg = case possiblyEnvName of Just envName -> case lookupWhenProvided envName of Just env -> pure env Nothing -> error $ envName <> ": No such environment found." Nothing -> case ProjectConfig.defaultEnvironment cfg of Just (n, e) -> pure (Text.unpack n, e) Nothing -> error "Unable to find default environment. Exaclty one\ \ environment has to have 'is-default: true', but no such\ \ environment was found." where lookupWhenProvided n = (n, ) <$> ProjectConfig.getEnvironment cfg (fromString n) newProject :: DbConnection -> FilePath -> IO Project newProject conn relativeDir = do -- Function canonicalizePath preserves trailing path separator. dir <- dropTrailingPathSeparator <$> canonicalizePath relativeDir let project = Project { _id = 0 -- Ignored during INSERT. , _name = fromString $ takeFileName dir , _path = fromString dir } addProject conn project pure project modifyEnvVariables :: Project -> EnvironmentName -> IO ([(String, String)] -> [(String, String)]) modifyEnvVariables project projEnvName = (. go) <$> addYxEnvVariables project where go = (getRidOfStackEnvVariables .) . map $ \case (n@"PATH", path) -> (n, updatePathEnvVariable project projEnvName path) -- TODO: Correct implementation witouth hardcoded environment. ev -> ev updatePathEnvVariable :: Project -> EnvironmentName -> String -> String updatePathEnvVariable project environment path = yxBinDir <> ":" <> path where yxBinDir = yxExeStuff root environment root = Text.unpack $ _path project getRidOfStackEnvVariables :: [(String, String)] -> [(String, String)] getRidOfStackEnvVariables = (catMaybes .) . map $ \case -- These variables are exported by stack and occur when we are already in a -- "stack exec" environment. For the purposes of isolation we need to get -- rid of them. Keeping them means that e.g. changing GHC version would -- fail due to trying to open incorrect package DB. ("STACK_EXE", _) -> Nothing ("GHC_VERSION", _) -> Nothing ("GHC_PACKAGE_PATH", _) -> Nothing ("CABAL_INSTALL_VERSION", _) -> Nothing ("HASKELL_PACKAGE_SANDBOX", _) -> Nothing ("HASKELL_PACKAGE_SANDBOXES", _) -> Nothing ("HASKELL_DIST_DIR", _) -> Nothing e -> Just e addYxEnvVariables :: Project -> IO ([(String, String)] -> [(String, String)]) addYxEnvVariables Project{..} = do yxExe <- getExecutablePath yxInvokedName <- getProgName pure . foldr (.) id $ catMaybes [ add "YX_ENVIRONMENT_DIR" $ Just projectEnvironmentDir , add "YX_ENVIRONMENT" $ Just projectEnvironment , add "YX_EXE" $ Just yxExe , add "YX_INVOKED_AS" $ Just yxInvokedName , add "YX_PROJECT" . Just $ Text.unpack _name , add "YX_PROJECT_ROOT" $ Just projectRoot , add "YX_STUFF" $ Just yxStuffDir , add "YX_VERSION" . Just $ showVersion version ] where projectRoot = Text.unpack _path yxStuffDir = yxStuffPath (Just projectRoot) YxStuff projectEnvironment = "default" projectEnvironmentDir = yxStuffPath (Just projectRoot) . EnvironmentStuff $ Just projectEnvironment add :: String -> Maybe String -> Maybe ([(String, String)] -> [(String, String)]) add n = fmap $ (:) . (n,) getYxConfigDir :: IO FilePath getYxConfigDir = do dir <- getXdgDirectory XdgConfig "yx" createDirectoryIfMissing True dir pure dir getYxDatabaseFile :: IO FilePath getYxDatabaseFile = do dbFile <- (</> "data.db") <$> getYxConfigDir haveDbFile <- doesFileExist dbFile unless haveDbFile $ SQLite.withConnection dbFile $ \conn -> SQLite.execute_ conn "CREATE TABLE Project\ \(id INTEGER PRIMARY KEY AUTOINCREMENT,\ \ name TEXT UNIQUE NOT NULL,\ \ path TEXT UNIQUE NOT NULL\ \);" pure dbFile
trskop/yx
src/Main.hs
bsd-3-clause
10,161
0
18
2,499
2,601
1,386
1,215
218
8
-- Source: https://github.com/bsl/GLFW-b-demo module Util where -------------------------------------------------------------------------------- import Control.Concurrent.STM (TQueue, atomically, writeTQueue) import Control.Monad (when) import Control.Monad.RWS.Strict (liftIO) import Control.Monad.Trans.Maybe (MaybeT (..), runMaybeT) import Data.List (intercalate) import Data.Maybe (catMaybes) import qualified Graphics.UI.GLFW as GLFW import Text.PrettyPrint -------------------------------------------------------------------------------- data Event = EventError !GLFW.Error !String | EventWindowPos !GLFW.Window !Int !Int | EventWindowSize !GLFW.Window !Int !Int | EventWindowClose !GLFW.Window | EventWindowRefresh !GLFW.Window | EventWindowFocus !GLFW.Window !GLFW.FocusState | EventWindowIconify !GLFW.Window !GLFW.IconifyState | EventFramebufferSize !GLFW.Window !Int !Int | EventMouseButton !GLFW.Window !GLFW.MouseButton !GLFW.MouseButtonState !GLFW.ModifierKeys | EventCursorPos !GLFW.Window !Double !Double | EventCursorEnter !GLFW.Window !GLFW.CursorState | EventScroll !GLFW.Window !Double !Double | EventKey !GLFW.Window !GLFW.Key !Int !GLFW.KeyState !GLFW.ModifierKeys | EventChar !GLFW.Window !Char deriving Show -------------------------------------------------------------------------------- -- GLFW-b is made to be very close to the C API, so creating a window is pretty -- clunky by Haskell standards. A higher-level API would have some function -- like withWindow. withWindow :: Int -> Int -> String -> (GLFW.Window -> IO ()) -> IO () withWindow width height title f = do GLFW.setErrorCallback $ Just simpleErrorCallback r <- GLFW.init when r $ do m <- GLFW.createWindow width height title Nothing Nothing case m of (Just win) -> do GLFW.makeContextCurrent m f win GLFW.setErrorCallback $ Just simpleErrorCallback GLFW.destroyWindow win Nothing -> return () GLFW.terminate where simpleErrorCallback e s = putStrLn $ unwords [show e, show s] -------------------------------------------------------------------------------- -- Each callback does just one thing: write an appropriate Event to the events -- TQueue. errorCallback :: TQueue Event -> GLFW.Error -> String -> IO () windowPosCallback :: TQueue Event -> GLFW.Window -> Int -> Int -> IO () windowSizeCallback :: TQueue Event -> GLFW.Window -> Int -> Int -> IO () windowCloseCallback :: TQueue Event -> GLFW.Window -> IO () windowRefreshCallback :: TQueue Event -> GLFW.Window -> IO () windowFocusCallback :: TQueue Event -> GLFW.Window -> GLFW.FocusState -> IO () windowIconifyCallback :: TQueue Event -> GLFW.Window -> GLFW.IconifyState -> IO () framebufferSizeCallback :: TQueue Event -> GLFW.Window -> Int -> Int -> IO () mouseButtonCallback :: TQueue Event -> GLFW.Window -> GLFW.MouseButton -> GLFW.MouseButtonState -> GLFW.ModifierKeys -> IO () cursorPosCallback :: TQueue Event -> GLFW.Window -> Double -> Double -> IO () cursorEnterCallback :: TQueue Event -> GLFW.Window -> GLFW.CursorState -> IO () scrollCallback :: TQueue Event -> GLFW.Window -> Double -> Double -> IO () keyCallback :: TQueue Event -> GLFW.Window -> GLFW.Key -> Int -> GLFW.KeyState -> GLFW.ModifierKeys -> IO () charCallback :: TQueue Event -> GLFW.Window -> Char -> IO () errorCallback tc e s = atomically $ writeTQueue tc $ EventError e s windowPosCallback tc win x y = atomically $ writeTQueue tc $ EventWindowPos win x y windowSizeCallback tc win w h = atomically $ writeTQueue tc $ EventWindowSize win w h windowCloseCallback tc win = atomically $ writeTQueue tc $ EventWindowClose win windowRefreshCallback tc win = atomically $ writeTQueue tc $ EventWindowRefresh win windowFocusCallback tc win fa = atomically $ writeTQueue tc $ EventWindowFocus win fa windowIconifyCallback tc win ia = atomically $ writeTQueue tc $ EventWindowIconify win ia framebufferSizeCallback tc win w h = atomically $ writeTQueue tc $ EventFramebufferSize win w h mouseButtonCallback tc win mb mba mk = atomically $ writeTQueue tc $ EventMouseButton win mb mba mk cursorPosCallback tc win x y = atomically $ writeTQueue tc $ EventCursorPos win x y cursorEnterCallback tc win ca = atomically $ writeTQueue tc $ EventCursorEnter win ca scrollCallback tc win x y = atomically $ writeTQueue tc $ EventScroll win x y keyCallback tc win k sc ka mk = atomically $ writeTQueue tc $ EventKey win k sc ka mk charCallback tc win c = atomically $ writeTQueue tc $ EventChar win c getCursorKeyDirections :: GLFW.Window -> IO (Double, Double) getCursorKeyDirections win = do x0 <- isPress `fmap` GLFW.getKey win GLFW.Key'Up x1 <- isPress `fmap` GLFW.getKey win GLFW.Key'Down y0 <- isPress `fmap` GLFW.getKey win GLFW.Key'Left y1 <- isPress `fmap` GLFW.getKey win GLFW.Key'Right let x0n = if x0 then (-1) else 0 x1n = if x1 then 1 else 0 y0n = if y0 then (-1) else 0 y1n = if y1 then 1 else 0 return (x0n + x1n, y0n + y1n) getJoystickDirections :: GLFW.Joystick -> IO (Double, Double) getJoystickDirections js = do maxes <- GLFW.getJoystickAxes js return $ case maxes of (Just (x:y:_)) -> (-y, x) _ -> ( 0, 0) isPress :: GLFW.KeyState -> Bool isPress GLFW.KeyState'Pressed = True isPress GLFW.KeyState'Repeating = True isPress _ = False keyIsPressed :: GLFW.Window -> GLFW.Key -> IO Bool keyIsPressed win key = isPress `fmap` GLFW.getKey win key -------------------------------------------------------------------------------- printInstructions :: IO () printInstructions = putStrLn $ render $ nest 4 ( text "------------------------------------------------------------" $+$ text "'?': Print these instructions" $+$ text "'i': Print GLFW information" $+$ text "" $+$ text "* Mouse cursor, keyboard cursor keys, and/or joystick" $+$ text " control rotation." $+$ text "* Mouse scroll wheel controls distance from scene." $+$ text "------------------------------------------------------------" ) printInformation :: GLFW.Window -> IO () printInformation win = do version <- GLFW.getVersion versionString <- GLFW.getVersionString monitorInfos <- runMaybeT getMonitorInfos joystickNames <- getJoystickNames clientAPI <- GLFW.getWindowClientAPI win cv0 <- GLFW.getWindowContextVersionMajor win cv1 <- GLFW.getWindowContextVersionMinor win cv2 <- GLFW.getWindowContextVersionRevision win robustness <- GLFW.getWindowContextRobustness win forwardCompat <- GLFW.getWindowOpenGLForwardCompat win debug <- GLFW.getWindowOpenGLDebugContext win profile <- GLFW.getWindowOpenGLProfile win putStrLn $ render $ nest 4 ( text "------------------------------------------------------------" $+$ text "GLFW C library:" $+$ nest 4 ( text "Version:" <+> renderVersion version $+$ text "Version string:" <+> renderVersionString versionString ) $+$ text "Monitors:" $+$ nest 4 ( renderMonitorInfos monitorInfos ) $+$ text "Joysticks:" $+$ nest 4 ( renderJoystickNames joystickNames ) $+$ text "OpenGL context:" $+$ nest 4 ( text "Client API:" <+> renderClientAPI clientAPI $+$ text "Version:" <+> renderContextVersion cv0 cv1 cv2 $+$ text "Robustness:" <+> renderContextRobustness robustness $+$ text "Forward compatibility:" <+> renderForwardCompat forwardCompat $+$ text "Debug:" <+> renderDebug debug $+$ text "Profile:" <+> renderProfile profile ) $+$ text "------------------------------------------------------------" ) where renderVersion (GLFW.Version v0 v1 v2) = text $ intercalate "." $ map show [v0, v1, v2] renderVersionString = text . show renderMonitorInfos = maybe (text "(error)") (vcat . map renderMonitorInfo) renderMonitorInfo (name, (x,y), (w,h), vms) = text (show name) $+$ nest 4 ( location <+> size $+$ fsep (map renderVideoMode vms) ) where location = int x <> text "," <> int y size = int w <> text "x" <> int h <> text "mm" renderVideoMode (GLFW.VideoMode w h r g b rr) = brackets $ res <+> rgb <+> hz where res = int w <> text "x" <> int h rgb = int r <> text "x" <> int g <> text "x" <> int b hz = int rr <> text "Hz" renderJoystickNames pairs = vcat $ map (\(js, name) -> text (show js) <+> text (show name)) pairs renderContextVersion v0 v1 v2 = hcat [int v0, text ".", int v1, text ".", int v2] renderClientAPI = text . show renderContextRobustness = text . show renderForwardCompat = text . show renderDebug = text . show renderProfile = text . show type MonitorInfo = (String, (Int,Int), (Int,Int), [GLFW.VideoMode]) getMonitorInfos :: MaybeT IO [MonitorInfo] getMonitorInfos = getMonitors >>= mapM getMonitorInfo where getMonitors :: MaybeT IO [GLFW.Monitor] getMonitors = MaybeT GLFW.getMonitors getMonitorInfo :: GLFW.Monitor -> MaybeT IO MonitorInfo getMonitorInfo mon = do name <- getMonitorName mon vms <- getVideoModes mon MaybeT $ do pos <- liftIO $ GLFW.getMonitorPos mon size <- liftIO $ GLFW.getMonitorPhysicalSize mon return $ Just (name, pos, size, vms) getMonitorName :: GLFW.Monitor -> MaybeT IO String getMonitorName mon = MaybeT $ GLFW.getMonitorName mon getVideoModes :: GLFW.Monitor -> MaybeT IO [GLFW.VideoMode] getVideoModes mon = MaybeT $ GLFW.getVideoModes mon getJoystickNames :: IO [(GLFW.Joystick, String)] getJoystickNames = catMaybes `fmap` mapM getJoystick joysticks where getJoystick js = fmap (maybe Nothing (\name -> Just (js, name))) (GLFW.getJoystickName js) -------------------------------------------------------------------------------- showModifierKeys :: GLFW.ModifierKeys -> String showModifierKeys mk = "[mod keys: " ++ keys ++ "]" where keys = if null xs then "none" else unwords xs xs = catMaybes ys ys = [ if GLFW.modifierKeysShift mk then Just "shift" else Nothing , if GLFW.modifierKeysControl mk then Just "control" else Nothing , if GLFW.modifierKeysAlt mk then Just "alt" else Nothing , if GLFW.modifierKeysSuper mk then Just "super" else Nothing ] curb :: Ord a => a -> a -> a -> a curb l h x | x < l = l | x > h = h | otherwise = x -------------------------------------------------------------------------------- joysticks :: [GLFW.Joystick] joysticks = [ GLFW.Joystick'1 , GLFW.Joystick'2 , GLFW.Joystick'3 , GLFW.Joystick'4 , GLFW.Joystick'5 , GLFW.Joystick'6 , GLFW.Joystick'7 , GLFW.Joystick'8 , GLFW.Joystick'9 , GLFW.Joystick'10 , GLFW.Joystick'11 , GLFW.Joystick'12 , GLFW.Joystick'13 , GLFW.Joystick'14 , GLFW.Joystick'15 , GLFW.Joystick'16 ]
cmahon/opengl-examples
library/Util.hs
bsd-3-clause
12,796
0
25
4,063
3,313
1,638
1,675
298
6
module Core where import Control.DeepSeq import GHC.Generics import Control.Monad.Catch import Control.Monad.Fix import Control.Monad.IO.Class import Data.Proxy import Control.Wire import Prelude hiding ((.), id) import Game.GoreAndAsh import Game.GoreAndAsh.GLFW import Game.GoreAndAsh.LambdaCube -- | Application monad is monad stack build from given list of modules over base monad (IO) type AppStack = ModuleStack [GLFWT, LambdaCubeT] IO newtype AppState = AppState (ModuleState AppStack) deriving (Generic) instance NFData AppState -- | Wrapper around type family newtype AppMonad a = AppMonad (AppStack a) deriving (Functor, Applicative, Monad, MonadFix, MonadIO, MonadThrow, MonadCatch, MonadLambdaCube, MonadGLFW) instance GameModule AppMonad AppState where type ModuleState AppMonad = AppState runModule (AppMonad m) (AppState s) = do (a, s') <- runModule m s return (a, AppState s') newModuleState = AppState <$> newModuleState withModule _ = withModule (Proxy :: Proxy AppStack) cleanupModule (AppState s) = cleanupModule s -- | Arrow that is build over the monad stack type AppWire a b = GameWire AppMonad a b -- | Helper to run initalization step for wire -- TODO: move to core package withInit :: (c -> GameMonadT AppMonad a) -> (a -> AppWire c b) -> AppWire c b withInit initStep nextStep = mkGen $ \s c -> do a <- initStep c (mb, nextStep') <- stepWire (nextStep a) s (Right c) return (mb, nextStep') -- | Inhibits if gets Nothing nothingInhibit :: AppWire (Maybe a) a nothingInhibit = mkPure_ $ \ma -> case ma of Nothing -> Left () Just a -> Right a
Teaspot-Studio/model-gridizer
src/Core.hs
bsd-3-clause
1,626
0
12
298
488
264
224
-1
-1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TupleSections #-} module Gen.State ( getDB , getPackageInfos , listAllModuleSorted , packageModulesIface ) where import Control.Monad import Control.Monad.Trans.State import Data.Function (on) import Data.List (intercalate, isSuffixOf, sort, sortBy) import Data.Map (Map) import qualified Data.Map as M import Data.Text (Text) import qualified Data.Text as T import Distribution.InstalledPackageInfo import Distribution.ModuleName import Distribution.Package import System.Directory import System.Directory.Tree import System.FilePath import qualified System.Process as S import qualified System.Process.Text as T data State = State { dbs :: [FilePath] , packages :: [InstalledPackageInfo] , zpackages :: [InstalledPackageInfo] } -- | This function returns the list of folder containing the list of installed packages -- [ "$HOME/.stack/programs/x86_64-osx/ghc-7.10.2/lib/ghc-7.10.2/package.conf.d" -- , "$HOME/.stack/snapshots/x86_64-osx/nightly-2015-11-29/7.10.2/pkgdb" -- , "$HOME/dev/project/.stack-work/install/x86_64-osx/nightly-2015-11-29/7.10.2/pkgdb" -- ] getDB :: IO [FilePath] getDB = do (exitcode, tout, terr) <- S.readProcessWithExitCode "stack" ["exec", "--", "ghc-pkg", "list"] "" let dbs = lines tout packages = map init $ filter (\t -> (not.null) t && head t == '/') dbs -- mapM print packages return packages getPackageInfos :: FilePath -> IO [InstalledPackageInfo] getPackageInfos dbpath = do packageFiles <- filter (isSuffixOf ".conf") <$> getDirectoryContents dbpath mbinfos <- mapM getPackageInfo packageFiles infos <- flip filterM mbinfos $ \pr -> case pr of ParseFailed err -> print ("error", err) >> return False ParseOk [] _ -> return True ParseOk warns _ -> print ("warning", warns) >> return True return $ map (\(ParseOk _ a) -> a) infos where getPackageInfo f = parseInstalledPackageInfo <$> readFile (dbpath </> f) packageName :: InstalledPackageInfo -> String packageName = unPackageName . pkgName . sourcePackageId type ModuleNames = [String] packageModules :: InstalledPackageInfo -> [ModuleNames] packageModules ipi = (map (components . exposedName) . exposedModules $ ipi) ++ map components (hiddenModules ipi) packageModulesIface :: InstalledPackageInfo -> [(String, FilePath)] packageModulesIface ipi = for (packageModules ipi) $ \mod -> ( intercalate "." mod , libdir </> (intercalate "/" mod ++ ".hi") ) where libdir = head (libraryDirs ipi) listAllModuleSorted :: [InstalledPackageInfo] -> IO [ExposedModule] listAllModuleSorted ipis = do let a = sortBy (compare `on` snd) $ concatMap _modules ipis _modules ipis = map (( (\(PackageIdentifier n _) -> unPackageName n) ( sourcePackageId ipis ),) . intercalate "." . components . exposedName) ( exposedModules ipis ) b = concatMap exposedModules ipis mapM_ print a return b -- x :: IO () -- x = do -- fileNames <- return [] -- files <- mapM readFile fileNames -- let contents = map parseInstalledPackageInfo files -- return () buildHoogle :: IO [Text] buildHoogle = do (exitcode, tout, terr) <- T.readProcessWithExitCode "git" ["clone", "", "ghc-pkg", "list"] "" let lines = T.lines tout packages = map T.init $ filter (\t -> (not.T.null) t && T.head t == '/') lines mapM_ print packages return packages demodb :: FilePath demodb = "/Users/rvion/.stack/programs/x86_64-osx/ghc-7.10.2/lib/ghc-7.10.2/package.conf.d" for :: [a] -> (a -> b) -> [b] for = flip map --------------------- -- So far I'll try with the string variant until text is needed. -- Not sure about module name spec, though. -- getDBText :: IO [Text] -- getDBText = do -- (exitcode, tout, terr) <- T.readProcessWithExitCode "stack" -- ["exec", "--", "ghc-pkg", "list"] "" -- let -- dbs = T.lines tout -- packages = map T.init $ filter (\t -> (not.T.null) t && (T.head t) == '/') dbs -- mapM print packages -- return packages ---------------------
rvion/ride
jetpack-gen/src/Gen/State.hs
bsd-3-clause
4,341
1
20
1,026
1,026
560
466
79
3
{-# LANGUAGE OverloadedStrings #-} module Main where import Prelude hiding (FilePath) import Control.Applicative import Control.Monad import Control.Exception import Control.Conditional (ifM) import Data.String (fromString) import Data.Trees.MTree import Data.Bitraversable import qualified Data.Text as T import qualified Data.Text.IO as T import System.Environment import System.Exit import System.Cmd import Filesystem import Filesystem.Path import Filesystem.Path.CurrentOS import ID3.Type.Tag import ID3.ReadTag import System.Posix.Process type Unpacker = FilePath -> FilePath -> IO ExitCode zipUnpacker :: Unpacker zipUnpacker file dir = rawSystem "unzip" [encodeString file, "-d", encodeString dir] rarUnpacker :: Unpacker rarUnpacker file dir = rawSystem "unrar" ["x" , encodeString file, encodeString dir] unpack :: FilePath -> FilePath -> IO ExitCode unpack file dir = let ext = maybe (error "cannot get file extension") id $ extension file in case ext of "rar" -> rarUnpacker file dir "zip" -> zipUnpacker file dir _ -> error "unknown file type" mkTempDir :: IO FilePath mkTempDir = do tmp <- fromString . ("tmp_dir_" ++) . show <$> getProcessID createDirectory False tmp return tmp -- readTag sucks because of weird dependencies tryReadTag :: FilePath -> IO (Maybe ID3Tag) tryReadTag f = withFile f ReadMode hReadTag data Track = Track { artist :: Maybe T.Text , album :: Maybe T.Text , title :: Maybe T.Text } deriving (Show) readTree :: FilePath -> IO (Tree FilePath FilePath) readTree p = liftM (Node p) $ listDirectory p >>= mapM readChild where readChild c = ifM (isDirectory c) (readTree c) (return $ Leaf c c) -- file temp process :: FilePath -> FilePath -> IO () process file dir = do putStrLn $ "Temp path: " ++ encodeString dir putStrLn $ "File: " ++ encodeString file isFile file >>= flip unless (error "No such file") unpack file dir >>= \ec -> unless (ec == ExitSuccess) (error "Unpack failed") readTree dir >>= bitraverse return tryReadTag >>= print main :: IO () main = do file <- decodeString . head <$> getArgs bracket mkTempDir removeTree (process file)
ratatosk/tripping-ironman
Main.hs
bsd-3-clause
2,220
0
12
453
703
362
341
58
3
{-# LANGUAGE CPP #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE MultiWayIf #-} module Main where import Graphics.BothGL import Data.Bits import Data.ByteString (ByteString) import Data.ByteString.Char8 (unpack) import Data.FileEmbed (embedFile) import Data.Coerce import Control.Applicative import Control.Concurrent import Control.Concurrent.MVar import Control.Monad hiding (sequence_) import Data.Foldable (minimumBy) import Data.Ord import Control.Monad.Trans.Maybe #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) import GHCJS.DOM import GHCJS.DOM.Document import GHCJS.DOM.Element import GHCJS.DOM.EventTarget import GHCJS.DOM.EventTargetClosures import GHCJS.DOM.Types hiding (Event) import GHCJS.DOM.UIEvent import GHCJS.DOM.WebGLRenderingContextBase import GHCJS.DOM.HTMLCanvasElement import qualified JavaScript.Web.Canvas.Internal as C import GHCJS.Foreign import GHCJS.Types #else import Control.Exception import Control.Exception.Lens import System.Exit import Control.Monad hiding (forM_) import Control.Monad.IO.Class import Graphics.GL.Core41 import Graphics.GL import SDL.Raw import Data.StateVar import Foreign import Foreign.C import Control.Lens #endif main :: IO () main = do #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) initHTML context <- initGL "webgl0" runReaderT context render #else initSDL render initSDL :: IO () -> IO () initSDL render = runInBoundThread $ withCString "gl01" $ \windowName -> do SDL.Raw.init SDL_INIT_EVERYTHING >>= err -- contextMajorVersion $= 3 -- contextMinorVersion $= 3 -- contextProfileMask $= SDL_GL_CONTEXT_PROFILE_CORE -- redSize $= 5 -- greenSize $= 5 -- blueSize $= 5 -- depthSize $= 16 -- doubleBuffer $= True let w = 640 h = 480 flags = SDL_WINDOW_OPENGL .|. SDL_WINDOW_SHOWN .|. SDL_WINDOW_RESIZABLE .|. SDL_WINDOW_FULLSCREEN window <- createWindow windowName SDL_WINDOWPOS_CENTERED SDL_WINDOWPOS_CENTERED w h flags >>= errOnNull -- start OpenGL cxt <- glCreateContext window >>= errOnNull glMakeCurrent window cxt >>= err handling id print render `finally` do glDeleteContext cxt destroyWindow window quit exitSuccess -- | Treat negative return codes as prompting an error check. err :: MonadIO m => CInt -> m () err e | e < 0 = liftIO $ do msg <- getError >>= peekCString clearError when (msg /= "") $ error $ msg | otherwise = return () -- | get\/set @SDL_GL_CONTEXT_MAJOR_VERSION@, OpenGL context major version; see <https://wiki.libsdl.org/SDL_GLattr#OpenGL Remarks> for details contextMajorVersion :: StateVar Int contextMajorVersion = attr SDL_GL_CONTEXT_MAJOR_VERSION -- | get\/set @SDL_GL_CONTEXT_MINOR_VERSION@, OpenGL context major version; see <https://wiki.libsdl.org/SDL_GLattr#OpenGL Remarks> for details contextMinorVersion :: StateVar Int contextMinorVersion = attr SDL_GL_CONTEXT_MINOR_VERSION contextProfileMask :: StateVar Int contextProfileMask = attr SDL_GL_CONTEXT_PROFILE_MASK errOnNull :: MonadIO m => Ptr a -> m (Ptr a) errOnNull p | p == nullPtr = liftIO $ do msg <- getError >>= peekCString clearError error $ if null msg then "Something went wrong, but SDL won't tell me what." else msg | otherwise = return p -- | Use a GLattr as a variable attr :: GLattr -> StateVar Int attr a = StateVar (getAttr a) (setAttr a) boolAttr :: GLattr -> StateVar Bool boolAttr = mapStateVar fromEnum toEnum . attr getAttr :: GLattr -> IO Int getAttr a = alloca $ \p -> do glGetAttribute a p >>= err fromIntegral <$> peek p setAttr :: GLattr -> Int -> IO () setAttr a i = glSetAttribute a (fromIntegral i) >>= err #endif render :: GL gl => gl () render = do Just shaderProg <- initShaders inputs <- initShaderInputs shaderProg buffers <- initBuffers clearColor 0 0 0 1 -- enable context DEPTH_TEST drawScene shaderProg inputs buffers return () data Inputs = Inputs { vertexPosition :: AttributeLocation } data BufferInfo = BufferInfo { buffer :: Buffer , itemSize :: GLint , attrType :: GLenum -- skip normalized, stride, offset , mode :: GLenum , firstI :: GLint , numItems :: GLsizei } data Buffers = Buffers { triangles :: BufferInfo , squares :: BufferInfo } #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) initHTML :: IO () initHTML = do Just doc <- currentDocument Just body <- getBody doc setInnerHTML body . Just $ "<canvas id=\"webgl0\" width=\"200\" height=\"200\" style=\"border: 1px solid\"></canvas>" initGL :: String -> IO WebGL2RenderingContext initGL name = do Just doc <- currentDocument Just canvas' <- getElementById doc name let canvas = coerce canvas' context <- coerce <$> getContext canvas "webgl" -- TODO error handling w <- getWidth canvas h <- getHeight canvas viewport context 0 0 (fromIntegral w) (fromIntegral h) return context #endif initShaders :: GL gl => gl (Maybe Program) initShaders = do Just fragmentShader <- createShader GL_FRAGMENT_SHADER shaderSource fragmentShader fragmentShaderSource Just compileShader fragmentShader -- TODO better error handling vertexShader <- createShader GL_VERTEX_SHADER shaderSource vertexShader vertexShaderSource compileShader vertexShader shaderProgram <- createProgram attachShader shaderProgram fragmentShader attachShader shaderProgram vertexShader linkProgram shaderProgram return shaderProgram vertexShaderSource :: ByteString -- TODO Lazy vs Strict vertexShaderSource = $(embedFile "src/triangle.vert") fragmentShaderSource :: ByteString fragmentShaderSource = unpack $(embedFile "src/triangle.frag") initShaderInputs :: GL gl => Program -> gl Inputs initShaderInputs shaderProgram = do let shaderProgram' = Just shaderProgram useProgram shaderProgram Just pos <- getAttribLocation shaderProgram' "aVertexPosition" enableVertexAttribArray pos return $ Inputs (fromIntegral pos) #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) foreign import javascript unsafe "new Float32Array([-0.5, 0.4, 0, -0.9, -0.4, 0, -0.1, -0.4, 0])" triangleArray :: JSVal foreign import javascript unsafe "new Float32Array([0.9, 0.4, 0, 0.1, 0.4, 0, 0.9, -0.4, 0, 0.1, -0.4, 0])" squareArray :: JSVal -- TODO XXX FIXME Vector? #endif initBuffers :: GL gl => gl Buffers initBuffers = do Just triBuf <- createBuffer bindBuffer ARRAY_BUFFER (Just triBuf) bufferData ARRAY_BUFFER triangleArray STATIC_DRAW let tri = BufferInfo triBuf 3 FLOAT TRIANGLES 0 3 Just sqBuf <- createBuffer bindBuffer ARRAY_BUFFER (Just sqBuf) bufferData ARRAY_BUFFER (Just $ ArrayBuffer squareArray) STATIC_DRAW let sq = BufferInfo sqBuf 3 FLOAT TRIANGLE_STRIP 0 4 return $ Buffers tri sq -- TODO move attr location into BufferInfo drawBuffer :: GL gl => Program -> GLuint -> BufferInfo -> gl () drawBuffer prog attr BufferInfo{..} = do bindBuffer ARRAY_BUFFER (Just buffer) vertexAttribPointer attr itemSize attrType False 0 0 drawArrays mode firstI numItems drawScene :: GL gl => Program -> Inputs -> Buffers -> gl () drawScene prog is bs = do clear $ COLOR_BUFFER_BIT .|. DEPTH_BUFFER_BIT drawBuffer prog (vertexPosition is) (triangles bs) drawBuffer prog (vertexPosition is) (squares bs)
bergey/bothgl
examples/webgl-01-triangle/src/Main.hs
bsd-3-clause
7,546
5
10
1,507
1,173
583
590
145
2
module Callback.Key where #include "Utils.cpp" import Control.Arrow ((&&&)) import Control.Monad (when) import Control.Applicative ((<$>)) import qualified Data.IORef as R import System.Exit (exitSuccess) import qualified Graphics.UI.GLFW as GLFW import Gamgine.Control ((?)) import qualified AppData as AP import qualified Gamgine.State.KeyInfo as KI import qualified Gamgine.State.InputInfo as II import qualified Callback.Common as CC import qualified Convert.ToFileData as TF import qualified Utils as U IMPORT_LENS_AS_LE newKeyCallback :: AP.AppDataRef -> GLFW.KeyCallback newKeyCallback appDataRef = callback where callback win GLFW.Key'Escape _ GLFW.KeyState'Pressed _ = quit win callback win GLFW.Key'Q _ GLFW.KeyState'Pressed _ = quit win callback _ GLFW.Key'S _ GLFW.KeyState'Pressed _ = do appMode <- AP.appMode <$> R.readIORef appDataRef when (appMode == AP.EditMode) $ do (gdata, saveTo) <- (AP.gameData &&& AP.saveLevelsTo) <$> R.readIORef appDataRef writeFile saveTo (show . TF.toFileData $ gdata) putStrLn $ "layers: Levels data written to file '" ++ saveTo ++ "'" callback win key _ keyState mods = do mpos <- CC.mousePosition win appDataRef case keyState of GLFW.KeyState'Pressed -> do let keyInfo = KI.KeyInfo key II.Pressed mpos mods R.modifyIORef appDataRef (AP.handleKeyEvent keyInfo) GLFW.KeyState'Released -> do let keyInfo = KI.KeyInfo key II.Released mpos mods R.modifyIORef appDataRef (AP.handleKeyEvent keyInfo) _ -> return () quit win = GLFW.destroyWindow win >> GLFW.terminate >> exitSuccess
dan-t/layers
src/Callback/Key.hs
bsd-3-clause
1,774
0
18
449
491
263
228
-1
-1
{-# LANGUAGE ViewPatterns, TupleSections, RecordWildCards, ScopedTypeVariables, PatternGuards, DeriveDataTypeable #-} module Output.Items(writeItems, lookupItem, listItems) where import Control.Monad import Data.List.Extra import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy.Char8 as LBS import qualified Data.ByteString.Lazy.UTF8 as UTF8 import Codec.Compression.GZip as GZip import Input.Item import General.Util import General.Store import General.Conduit outputItem :: (TargetId, Target) -> [String] outputItem (i, Target{..}) = [show i ,if null targetURL then "." else targetURL ,maybe "." (joinPair " ") targetPackage ,maybe "." (joinPair " ") targetModule ,if null targetType then "." else targetType ,targetItem] ++ replace [""] ["."] (lines targetDocs) inputItem :: [String] -> (TargetId, Target) inputItem (i:url:pkg:modu:typ:self:docs) = (read i ,Target (if url == "." then "" else url) (f pkg) (f modu) (if typ == "." then "" else typ) self (unlines docs)) where f "." = Nothing f x = Just (word1 x) data Items = Items deriving Typeable -- write all the URLs, docs and enough info to pretty print it to a result -- and replace each with an identifier (index in the space) - big reduction in memory writeItems :: StoreWrite -> (Conduit (Maybe Target, Item) IO (Maybe TargetId, Item) -> IO a) -> IO a writeItems store act = do storeWriteType store Items $ storeWriteParts store $ act $ void $ (\f -> mapAccumMC f 0) $ \pos (target, item) -> case target of Nothing -> return (pos, (Nothing, item)) Just target -> do let bs = BS.concat $ LBS.toChunks $ GZip.compress $ UTF8.fromString $ unlines $ outputItem (TargetId pos, target) liftIO $ do storeWriteBS store $ intToBS $ BS.length bs storeWriteBS store bs let pos2 = pos + fromIntegral (intSize + BS.length bs) return (pos2, (Just $ TargetId pos, item)) listItems :: StoreRead -> [Target] listItems store = unfoldr f $ storeReadBS $ storeReadType Items store where f x | BS.null x = Nothing | (n,x) <- BS.splitAt intSize x , n <- intFromBS n , (this,x) <- BS.splitAt n x = Just (snd $ inputItem $ lines $ UTF8.toString $ GZip.decompress $ LBS.fromChunks [this], x) lookupItem :: StoreRead -> (TargetId -> Target) lookupItem store = let x = storeReadBS $ storeReadType Items store in \(TargetId i) -> let i2 = fromIntegral i n = intFromBS $ BS.take intSize $ BS.drop i2 x in snd $ inputItem $ lines $ UTF8.toString $ GZip.decompress $ LBS.fromChunks $ return $ BS.take n $ BS.drop (i2 + intSize) x
BartAdv/hoogle
src/Output/Items.hs
bsd-3-clause
2,787
14
25
698
853
468
385
54
4
{-# LANGUAGE OverloadedStrings #-} module Snap.Utilities.Configuration.Lookup ( cfgLookup, cfgLookupWithDefault, stringValue, listValue ) where import qualified Data.Configurator as C import qualified Data.Configurator.Types as CT import Data.List (groupBy, intercalate, find, sortBy) import Data.HashMap.Strict (toList) import Data.Text (Text, isPrefixOf, splitOn, pack, unpack) import Snap.Utilities.Configuration.Types ------------------------------------------------------------------------------ -- | Look up a value. cfgLookup :: Text -> (CT.Value -> a) -> [ConfigPair] -> Maybe a cfgLookup key transformer = fmap (transformer . snd) . (found key) -- | Look up a value and fall back to a default. cfgLookupWithDefault :: Text -> a -> (CT.Value -> a) -> [ConfigPair] -> a cfgLookupWithDefault key def transformer = maybe def (transformer . snd) . (found key) -- | Internal: find a ConfigPair matching the key. found :: Text -> [ConfigPair] -> Maybe ConfigPair found key = find (\(k, _) -> k == key) -- | Show a Configurator value as a String. stringValue :: CT.Value -> String stringValue (CT.String x) = unpack x stringValue (CT.List x) = intercalate " " $ map show x stringValue x = show x -- | Show a Configurator value as a list. listValue :: CT.Value -> [String] listValue (CT.List x) = map stringValue x listValue (CT.String x) = map unpack . splitOn "," $ x listValue x = listValue . CT.String . pack . show $ x
anchor/snap-configuration-utilities
lib/Snap/Utilities/Configuration/Lookup.hs
bsd-3-clause
1,441
6
10
233
448
247
201
26
1
{-| Copyright : (c) Dave Laing, 2017 License : BSD3 Maintainer : [email protected] Stability : experimental Portability : non-portable -} module Fragment.Case.Helpers ( tmAlt , tmCase ) where import Data.Foldable (toList) import Data.List (elemIndex) import Bound (abstract) import Control.Lens (review) import Control.Lens.Wrapped (_Unwrapped) import qualified Data.List.NonEmpty as N import Ast.Pattern import Ast.Term import Fragment.Case.Ast.Term tmAlt :: (Eq a, TmAstBound ki ty pt tm, TmAstTransversable ki ty pt tm) => Pattern pt a -> Term ki ty pt tm a -> Alt ki ty pt (TmAst ki ty pt tm) (TmAstVar a) tmAlt p tm = Alt (review _TmPattern p) s where vs = fmap TmAstTmVar . toList $ p s = abstract (`elemIndex` vs) . review _Unwrapped $ tm tmCase :: AsTmCase ki ty pt tm => Term ki ty pt tm a -> [Alt ki ty pt (TmAst ki ty pt tm) (TmAstVar a)] -> Term ki ty pt tm a tmCase tm alts = case N.nonEmpty alts of Nothing -> tm Just xs -> review _TmCase (tm, xs)
dalaing/type-systems
src/Fragment/Case/Helpers.hs
bsd-3-clause
1,012
0
11
214
373
199
174
21
2
----------------------------------------------------------------------------- -- | -- Module : XMonad.Layout.IndependentScreens -- Copyright : (c) 2009 Daniel Wagner -- License : BSD3 -- -- Maintainer : <[email protected]> -- Stability : unstable -- Portability : unportable -- -- Utility functions for simulating independent sets of workspaces on -- each screen (like dwm's workspace model), using internal tags to -- distinguish workspaces associated with each screen. ----------------------------------------------------------------------------- module XMonad.Layout.IndependentScreens ( -- * Usage -- $usage VirtualWorkspace, PhysicalWorkspace, workspaces', withScreens, onCurrentScreen, marshallPP, countScreens, -- * Converting between virtual and physical workspaces -- $converting marshall, unmarshall, unmarshallS, unmarshallW, marshallWindowSpace, unmarshallWindowSpace ) where -- for the screen stuff import Control.Applicative((<*), liftA2) import Control.Arrow hiding ((|||)) import Control.Monad import Data.List import Graphics.X11.Xinerama import XMonad import XMonad.StackSet hiding (filter, workspaces) import XMonad.Hooks.DynamicLog -- $usage -- You can use this module with the following in your @~\/.xmonad\/xmonad.hs@: -- -- > import XMonad.Layout.IndependentScreens -- -- You can define your workspaces by calling @withScreens@: -- -- > myConfig = defaultConfig { workspaces = withScreens 2 ["web", "email", "irc"] } -- -- This will create \"physical\" workspaces with distinct internal names for -- each (screen, virtual workspace) pair. -- -- Then edit any keybindings that use the list of workspaces or refer -- to specific workspace names. In the default configuration, only -- the keybindings for changing workspace do this: -- -- > [((m .|. modm, k), windows $ f i) -- > | (i, k) <- zip (XMonad.workspaces conf) [xK_1 .. xK_9] -- > , (f, m) <- [(W.greedyView, 0), (W.shift, shiftMask)]] -- -- This should change to -- -- > [((m .|. modm, k), windows $ onCurrentScreen f i) -- > | (i, k) <- zip (workspaces' conf) [xK_1 .. xK_9] -- > , (f, m) <- [(W.greedyView, 0), (W.shift, shiftMask)]] -- -- In particular, the analogue of @XMonad.workspaces@ is -- @workspaces'@, and you can use @onCurrentScreen@ to convert functions -- of virtual workspaces to functions of physical workspaces, which work -- by marshalling the virtual workspace name and the currently focused -- screen into a physical workspace name. type VirtualWorkspace = WorkspaceId type PhysicalWorkspace = WorkspaceId -- $converting -- You shouldn't need to use the functions below very much. They are used -- internally. However, in some cases, they may be useful, and so are exported -- just in case. In general, the \"marshall\" functions convert the convenient -- form (like \"web\") you would like to use in your configuration file to the -- inconvenient form (like \"2_web\") that xmonad uses internally. Similarly, -- the \"unmarshall\" functions convert in the other direction. marshall :: ScreenId -> VirtualWorkspace -> PhysicalWorkspace marshall (S sc) vws = show sc ++ '_':vws unmarshall :: PhysicalWorkspace -> (ScreenId, VirtualWorkspace) unmarshallS :: PhysicalWorkspace -> ScreenId unmarshallW :: PhysicalWorkspace -> VirtualWorkspace unmarshall = ((S . read) *** drop 1) . break (=='_') unmarshallS = fst . unmarshall unmarshallW = snd . unmarshall workspaces' :: XConfig l -> [VirtualWorkspace] workspaces' = nub . map (snd . unmarshall) . workspaces withScreens :: ScreenId -- ^ The number of screens to make workspaces for -> [VirtualWorkspace] -- ^ The desired virtual workspace names -> [PhysicalWorkspace] -- ^ A list of all internal physical workspace names withScreens n vws = [marshall sc pws | pws <- vws, sc <- [0..n-1]] onCurrentScreen :: (VirtualWorkspace -> WindowSet -> a) -> (PhysicalWorkspace -> WindowSet -> a) onCurrentScreen f vws = screen . current >>= f . flip marshall vws -- | In case you don't know statically how many screens there will be, you can call this in main before starting xmonad. For example, part of my config reads -- -- > main = do -- > nScreens <- countScreens -- > xmonad $ defaultConfig { -- > ... -- > workspaces = withScreens nScreens (workspaces defaultConfig), -- > ... -- > } -- countScreens :: (MonadIO m, Integral i) => m i countScreens = liftM genericLength . liftIO $ openDisplay "" >>= liftA2 (<*) getScreenInfo closeDisplay -- | This turns a naive pretty-printer into one that is aware of the -- independent screens. That is, you can write your pretty printer to behave -- the way you want on virtual workspaces; this function will convert that -- pretty-printer into one that first filters out physical workspaces on other -- screens, then converts all the physical workspaces on this screen to their -- virtual names. -- -- For example, if you have handles @hLeft@ and @hRight@ for bars on the left and right screens, respectively, and @pp@ is a pretty-printer function that takes a handle, you could write -- -- > logHook = let log screen handle = dynamicLogWithPP . marshallPP screen . pp $ handle -- > in log 0 hLeft >> log 1 hRight marshallPP :: ScreenId -> PP -> PP marshallPP s pp = pp { ppCurrent = ppCurrent pp . snd . unmarshall, ppVisible = ppVisible pp . snd . unmarshall, ppHidden = ppHidden pp . snd . unmarshall, ppHiddenNoWindows = ppHiddenNoWindows pp . snd . unmarshall, ppUrgent = ppUrgent pp . snd . unmarshall, ppSort = fmap (marshallSort s) (ppSort pp) } marshallSort :: ScreenId -> ([WindowSpace] -> [WindowSpace]) -> ([WindowSpace] -> [WindowSpace]) marshallSort s vSort = pScreens . vSort . vScreens where onScreen ws = unmarshallS (tag ws) == s vScreens = map unmarshallWindowSpace . filter onScreen pScreens = map (marshallWindowSpace s) -- | Convert the tag of the 'WindowSpace' from a 'VirtualWorkspace' to a 'PhysicalWorkspace'. marshallWindowSpace :: ScreenId -> WindowSpace -> WindowSpace -- | Convert the tag of the 'WindowSpace' from a 'PhysicalWorkspace' to a 'VirtualWorkspace'. unmarshallWindowSpace :: WindowSpace -> WindowSpace marshallWindowSpace s ws = ws { tag = marshall s (tag ws) } unmarshallWindowSpace ws = ws { tag = unmarshallW (tag ws) }
MasseR/xmonadcontrib
XMonad/Layout/IndependentScreens.hs
bsd-3-clause
6,463
0
10
1,253
865
512
353
53
1
{-# LANGUAGE OverloadedStrings, DeriveGeneric #-} import System.Environment import Text.XML.HXT.Core import Data.Aeson import Data.Aeson.Encode.Pretty import GHC.Generics import qualified Data.ByteString.Lazy as B import Data.Monoid import Data.Ord import qualified Data.Text as T -- A very simple structure for the anime data Anime = Anime { title :: String, status :: String } deriving (Show, Generic) type AnimeList = [Anime] -- Create JSON type automatically instance ToJSON Anime -- Picklers, needed to read from XML xpAnime :: PU Anime xpAnime = xpElem "anime" $ xpFilterCont (hasName "series_title" <+> hasName "my_status") $ xpWrap ( uncurry Anime , \s -> (title s, status s) ) $ xpPair ( xpElem "series_title" $ xpText ) ( xpElem "my_status" $ xpText) xpAnimeList :: PU AnimeList xpAnimeList = xpElem "myanimelist" $ xpFilterCont (hasName "anime") $ xpList $ xpAnime -- Pretty printing for output JSON : fields are sorted by keys comp :: T.Text -> T.Text -> Ordering comp = keyOrder ["title","status"] `mappend` comparing T.length myConfig = Config {confIndent = 2, confCompare = comp} main :: IO () main = do [src] <- getArgs [a] <- runX ( xunpickleDocument xpAnimeList [ withRemoveWS yes ] src) let file = "anime.json" writeFile file "var data =" B.appendFile file $ encodePretty' myConfig a appendFile file ";" return ()
alexDarcy/myanimelist-backup
MyAnimeList.hs
bsd-3-clause
1,429
0
12
300
410
219
191
43
1
{-# LANGUAGE FlexibleContexts, FlexibleInstances, DefaultSignatures , ViewPatterns, RankNTypes, TypeOperators, DataKinds, KindSignatures, PolyKinds , MultiParamTypeClasses, TypeFamilies, FunctionalDependencies #-} module System.Console.YAOP ( module System.Console.YAOP.Selector , module System.Console.YAOP.TH , module System.Console.YAOP.Argument , module System.Console.YAOP.Types , (<>) -- from Data.Monoid , (<=:) , short , long , metavar , help , setter , set , setConst , action , tweak , append , prepend , appendMap , (=:) , Configurable (..) , ParsingConf (..) , defaultParsingConf , withOptions , getOptions , parseOptions , parseOptions' ) where import System.Environment import System.IO.Unsafe import System.Exit import System.Console.GetOpt import System.Console.YAOP.Selector import System.Console.YAOP.Argument import System.Console.YAOP.TH import System.Console.YAOP.Types import Control.Monad.Writer import Data.Tagged import Data.Typeable import Data.Default import Data.Maybe import Data.List import qualified Data.Map as M import GHC.TypeLits data OptBuilder arg a = OptBuilder { obShort :: [Char] , obLong :: [String] , obMetavar :: Maybe String , obDescr :: Maybe String , obSetter :: (arg -> a -> IO a) } newtype OptBuilding arg a = OptBuilding (OptBuilder arg a -> OptBuilder arg a) instance Monoid (OptBuilding arg a) where mempty = OptBuilding id mappend (OptBuilding f) (OptBuilding g) = OptBuilding (f . g) short :: Char -> OptBuilding arg a short f = OptBuilding (\b -> b {obShort = f : obShort b}) long :: String -> OptBuilding arg a long f = OptBuilding (\b -> b {obLong = f : obLong b}) metavar :: String -> OptBuilding arg a metavar v = OptBuilding (\b -> b {obMetavar = Just v}) help :: String -> OptBuilding arg a help d = OptBuilding (\b -> b {obDescr = Just d}) setter :: (arg -> a -> IO a) -> OptBuilding arg a setter s = OptBuilding (\b -> b {obSetter = s}) set :: OptBuilding a a set = setter (\arg _ -> return arg) setConst :: a -> OptBuilding () a setConst c = setter (\() _ -> return c) action :: IO a -> OptBuilding () a action act = setter (\() _ -> act) tweak :: (arg -> a -> a) -> OptBuilding arg a tweak f = setter (\a acc -> return (f a acc)) append :: (Monoid a, Argument arg, Singleton arg a) => OptBuilding arg a append = setter (\a acc -> return $ acc <> singleton a) prepend :: (Monoid a, Argument arg, Singleton arg a) => OptBuilding arg a prepend = setter (\a acc -> return $ singleton a <> acc) appendMap :: (Monoid a, Argument arg) => (arg -> IO a) -> OptBuilding arg a appendMap f = setter (\a acc -> f a >>= \x -> return $ acc <> x) infix 0 <=: (<=:) :: Argument arg => ((t -> IO t) -> a -> IO a) -> OptBuilding arg t -> OptM a () (<=:) sel builder = sel =: pushOption builder where defOptBuilder = OptBuilder [] [] Nothing Nothing (error "Parser does not have an action") pushOption (OptBuilding builder) = let (OptBuilder short long metavar help setter) = builder defOptBuilder in tell [ ParseOpt $ Option short long (argDescr setter metavar) (fromMaybe "(no description)" help) ] -- | Apply selector to options combinator (=:) :: (MonadWriter [Opt t] (OptM t)) => ((t -> IO t) -> a -> IO a) -- ^ selector -> OptM t () -- ^ options -> OptM a () (=:) f optm = tell . map (fmap f) $ runOptM optm newtype Conf a = Conf { unConf :: a } class Configurable a where defConf :: a default defConf :: (Default a) => a defConf = def signature :: a -> String default signature :: (Typeable a) => a -> String signature = (++ "]") . ("[" ++) . show . typeOf parseOpts :: OptM a () instance (Configurable a) => Configurable (Conf a) where defConf = Conf defConf signature (Conf a) = signature a parseOpts = (\f x -> f (unConf x) >>= return . Conf) =: parseOpts instance Configurable [String] where defConf = [] signature _ = "ARGS" parseOpts = tell [ ParseArg $ ArgParse Many (\str l -> return $ l ++ [str] ) ] instance (Configurable a, Configurable b) => Configurable (a, b) where defConf = (defConf, defConf) signature (a, b) = intercalate " " [signature a, signature b] parseOpts = do firstM =: parseOpts secondM =: parseOpts instance (Configurable a, Configurable b, Configurable c) => Configurable (a, b, c) where defConf = (defConf, defConf, defConf) signature (a, b, c) = intercalate " " [signature a, signature b, signature c] parseOpts = do (\f (x, y, z) -> f x >>= \q -> return (q, y, z)) =: parseOpts (\f (x, y, z) -> f y >>= \q -> return (x, q, z)) =: parseOpts (\f (x, y, z) -> f z >>= \q -> return (x, y, q)) =: parseOpts instance (Configurable a, Configurable b, Configurable c, Configurable d) => Configurable (a, b, c, d) where defConf = (defConf, defConf, defConf, defConf) signature (a, b, c, d) = intercalate " " [signature a, signature b, signature c, signature d] parseOpts = do (\f (x, y, z, i) -> f x >>= \q -> return (q, y, z, i)) =: parseOpts (\f (x, y, z, i) -> f y >>= \q -> return (x, q, z, i)) =: parseOpts (\f (x, y, z, i) -> f z >>= \q -> return (x, y, q, i)) =: parseOpts (\f (x, y, z, i) -> f i >>= \q -> return (x, y, z, q)) =: parseOpts instance ( Configurable a, Configurable b, Configurable c , Configurable d, Configurable e) => Configurable (a, b, c, d, e) where defConf = (defConf, defConf, defConf, defConf, defConf) signature (a, b, c, d, e) = intercalate " " [signature a, signature b, signature c, signature d, signature e] parseOpts = do (\f (x, y, z, i, j) -> f x >>= \q -> return (q, y, z, i, j)) =: parseOpts (\f (x, y, z, i, j) -> f y >>= \q -> return (x, q, z, i, j)) =: parseOpts (\f (x, y, z, i, j) -> f z >>= \q -> return (x, y, q, i, j)) =: parseOpts (\f (x, y, z, i, j) -> f i >>= \q -> return (x, y, z, q, j)) =: parseOpts (\f (x, y, z, i, j) -> f j >>= \q -> return (x, y, z, i, q)) =: parseOpts {- parseArgs :: [String] -> [ArgParse (t -> IO t)] -> [(t -> IO t)] parseArgs args parsers = let (reqBeginning, rest1) = break (not . isRequired) parsers (reqEnding, optionalPs) = second reverse . break (not . isRequired) $ reverse rest1 in undefined where isRequired (ArgParse OneReq _) = True consumeReq (x:xs) ((ArgParse OneReq fn):ps) = let (actions, rest) = consumeReq xs ps in (fn x : actions, rest) consumeReq [] (p:ps) = error "Required parameter is not specified" consumeReq xs [] = ([], xs) -} data ParsingConf = ParsingConf { pcProgName :: String -- ^ Usage message header , pcHelpFlag :: Maybe String -- ^ Name of help message flag, default: @\"help\"@ , pcHelpExtraInfo :: String -- ^ Extra help information , pcPermuteArgs :: Bool -- ^ @True@ means `System.Console.GetOpt`'s @Permute@, @False@ means @RequireOrder@ } -- | Default option parsing configuration defaultParsingConf :: ParsingConf defaultParsingConf = ParsingConf { pcProgName = unsafePerformIO getProgName , pcHelpFlag = Just "help" , pcHelpExtraInfo = "" , pcPermuteArgs = True } withOptions :: Configurable t => (t -> IO b) -> IO b withOptions act = getOptions >>= act getOptions :: (Configurable t) => IO t getOptions = parseOptions' defaultParsingConf =<< getArgs parseOptions :: (Configurable t) => [String] -- ^ raw arguments -> IO t parseOptions = parseOptions' defaultParsingConf -- | Run parser, return configured options environment and arguments parseOptions' :: (Configurable t) => ParsingConf -- ^ parsing configuration -> [String] -- ^ raw arguments -> IO t parseOptions' conf rawArgs = do let initial = defConf usageStr sign = flip usageInfo optdescr . init . unlines $ [ "USAGE: " ++ pcProgName conf ++ " " ++ sign , "" , pcHelpExtraInfo conf ] showHelp opts = do putStrLn $ usageStr (signature initial) exitWith ExitSuccess >>= \_ -> return opts helpdescr = case pcHelpFlag conf of Just flag -> [ Option [] [flag] (NoArg showHelp) "print this help message and exit." ] Nothing -> [] parsers = runOptM parseOpts optdescr = helpdescr ++ concatMap (\x -> case x of {ParseOpt d -> [d]; _ -> []} ) parsers --argparsers = concatMap (\x -> case x of {(Arg p) -> [p]; _ -> []} ) parsers let (actions, _args, msgs) = getOpt Permute optdescr rawArgs --argActions = parseArgs args argparsers groupedByShort = M.fromListWith (++) $ catMaybes $ map (\o@(Option (listToMaybe -> s) _ _ _) -> fmap (\x -> ('-':x:[], [o])) s) optdescr groupedByLong = M.fromListWith (++) $ catMaybes $ map (\o@(Option _ (listToMaybe -> l) _ _) -> fmap (\x -> ("--"++x, [o])) l) optdescr duplicates = M.keys . M.filter (>1) . M.map length $ (M.unionWith (++) groupedByShort groupedByLong) unless (null duplicates) $ error $ "Parsing error. Duplicate flags defined: " ++ intercalate ", " duplicates mapM_ (error . flip (++) (usageStr (signature initial))) msgs opts <- foldl' (>>=) (return initial) (actions) -- ++ argActions) return opts
esmolanka/yaop
System/Console/YAOP.hs
bsd-3-clause
9,945
0
19
2,878
3,453
1,898
1,555
199
3
{-# LANGUAGE AllowAmbiguousTypes #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} -- | All high-level logic of Toil. It operates in 'LocalToilM' and -- 'GlobalToilM'. module Pos.Chain.Txp.Toil.Logic ( verifyToil , applyToil , rollbackToil , normalizeToil , processTx ) where import Universum hiding (id) import Control.Monad.Except (ExceptT, mapExceptT, throwError) import Serokell.Data.Memory.Units (Byte) import Pos.Binary.Class (biSize) import Pos.Chain.Genesis (GenesisWStakeholders) import Pos.Chain.Txp.Configuration (TxpConfiguration (..), memPoolLimitTx) import Pos.Chain.Txp.Toil.Failure (ToilVerFailure (..)) import Pos.Chain.Txp.Toil.Monad (GlobalToilM, LocalToilM, UtxoM, hasTx, memPoolSize, putTxWithUndo, utxoMToGlobalToilM, utxoMToLocalToilM) import Pos.Chain.Txp.Toil.Stakes (applyTxsToStakes, rollbackTxsStakes) import Pos.Chain.Txp.Toil.Types (TxFee (..)) import Pos.Chain.Txp.Toil.Utxo (VerifyTxUtxoRes (..)) import qualified Pos.Chain.Txp.Toil.Utxo as Utxo import Pos.Chain.Txp.Topsort (topsortTxs) import Pos.Chain.Txp.Tx (Tx (..), TxId, TxOut (..), TxValidationRules, txOutAddress) import Pos.Chain.Txp.TxAux (TxAux (..), checkTxAux) import Pos.Chain.Txp.TxOutAux (toaOut) import Pos.Chain.Txp.Undo (TxUndo, TxpUndo) import Pos.Chain.Update.BlockVersionData (BlockVersionData (..), isBootstrapEraBVD) import Pos.Core (AddrAttributes (..), AddrStakeDistribution (..), Address, EpochIndex, addrAttributesUnwrapped, isRedeemAddress) import Pos.Core.Common (integerToCoin) import qualified Pos.Core.Common as Fee (TxFeePolicy (..), calculateTxSizeLinear) import Pos.Core.NetworkMagic (makeNetworkMagic) import Pos.Crypto (ProtocolMagic, WithHash (..), hash) import Pos.Util (liftEither) ---------------------------------------------------------------------------- -- Global ---------------------------------------------------------------------------- -- CHECK: @verifyToil -- | Verify transactions correctness with respect to Utxo applying -- them one-by-one. -- Note: transactions must be topsorted to pass check. -- Warning: this function may apply some transactions and fail -- eventually. -- -- If the 'Bool' argument is 'True', all data (script versions, -- witnesses, addresses, attributes) must be known. Otherwise unknown -- data is just ignored. verifyToil :: ProtocolMagic -> TxValidationRules -> BlockVersionData -> Set Address -> EpochIndex -> Bool -> [TxAux] -> ExceptT ToilVerFailure UtxoM TxpUndo verifyToil pm txValRules bvd lockedAssets curEpoch verifyAllIsKnown = mapM (verifyAndApplyTx pm txValRules bvd lockedAssets curEpoch verifyAllIsKnown . withTxId) -- | Apply transactions from one block. They must be valid (for -- example, it implies topological sort). applyToil :: GenesisWStakeholders -> [(TxAux, TxUndo)] -> GlobalToilM () applyToil _ [] = pass applyToil bootStakeholders txun = do applyTxsToStakes bootStakeholders txun utxoMToGlobalToilM $ mapM_ (applyTxToUtxo' . withTxId . fst) txun -- | Rollback transactions from one block. rollbackToil :: GenesisWStakeholders -> [(TxAux, TxUndo)] -> GlobalToilM () rollbackToil bootStakeholders txun = do rollbackTxsStakes bootStakeholders txun utxoMToGlobalToilM $ mapM_ Utxo.rollbackTxUtxo $ reverse txun ---------------------------------------------------------------------------- -- Local ---------------------------------------------------------------------------- -- | Verify one transaction and also add it to mem pool and apply to utxo -- if transaction is valid. processTx :: ProtocolMagic -> TxValidationRules -> TxpConfiguration -> BlockVersionData -> EpochIndex -> (TxId, TxAux) -> ExceptT ToilVerFailure LocalToilM TxUndo processTx pm txValRules txpConfig bvd curEpoch tx@(id, aux) = do whenM (lift $ hasTx id) $ throwError ToilKnown whenM ((>= memPoolLimitTx txpConfig) <$> lift memPoolSize) $ throwError (ToilOverwhelmed $ memPoolLimitTx txpConfig) undo <- mapExceptT utxoMToLocalToilM $ verifyAndApplyTx pm txValRules bvd (tcAssetLockedSrcAddrs txpConfig) curEpoch True tx undo <$ lift (putTxWithUndo id aux undo) -- | Get rid of invalid transactions. -- All valid transactions will be added to mem pool and applied to utxo. normalizeToil :: ProtocolMagic -> TxValidationRules -> TxpConfiguration -> BlockVersionData -> EpochIndex -> [(TxId, TxAux)] -> LocalToilM () normalizeToil pm txValRules txpConfig bvd curEpoch txs = mapM_ normalize ordered where -- If there is a cycle in the tx list, topsortTxs returns Nothing. -- Why is that not an error? And if its not an error, why bother -- top-sorting them anyway? ordered = fromMaybe txs $ topsortTxs wHash txs wHash (i, txAux) = WithHash (taTx txAux) i normalize :: (TxId, TxAux) -> LocalToilM () normalize = void . runExceptT . processTx pm txValRules txpConfig bvd curEpoch ---------------------------------------------------------------------------- -- Verify and Apply logic ---------------------------------------------------------------------------- -- Note: it doesn't consider/affect stakes! That's because we don't -- care about stakes for local txp. verifyAndApplyTx :: ProtocolMagic -> TxValidationRules -> BlockVersionData -> Set Address -> EpochIndex -> Bool -> (TxId, TxAux) -> ExceptT ToilVerFailure UtxoM TxUndo verifyAndApplyTx pm txValRules adoptedBVD lockedAssets curEpoch verifyVersions tx@(_, txAux) = do whenLeft (checkTxAux txValRules txAux) (throwError . ToilInconsistentTxAux) let ctx = Utxo.VTxContext verifyVersions (makeNetworkMagic pm) vtur@VerifyTxUtxoRes {..} <- Utxo.verifyTxUtxo pm ctx lockedAssets txAux liftEither $ verifyGState adoptedBVD curEpoch txAux vtur lift $ applyTxToUtxo' tx pure vturUndo isRedeemTx :: TxUndo -> Bool isRedeemTx resolvedOuts = all isRedeemAddress inputAddresses where inputAddresses = fmap (txOutAddress . toaOut) . catMaybes . toList $ resolvedOuts verifyGState :: BlockVersionData -> EpochIndex -> TxAux -> VerifyTxUtxoRes -> Either ToilVerFailure () verifyGState bvd@BlockVersionData {..} curEpoch txAux vtur = do verifyBootEra bvd curEpoch txAux let txFeeMB = vturFee vtur let txSize = biSize txAux let limit = bvdMaxTxSize unless (isRedeemTx $ vturUndo vtur) $ whenJust txFeeMB $ \txFee -> verifyTxFeePolicy txFee bvdTxFeePolicy txSize when (txSize > limit) $ throwError $ ToilTooLargeTx txSize limit verifyBootEra :: BlockVersionData -> EpochIndex -> TxAux -> Either ToilVerFailure () verifyBootEra bvd curEpoch TxAux {..} = do when (isBootstrapEraBVD bvd curEpoch) $ whenNotNull notBootstrapDistrAddresses $ throwError . ToilNonBootstrapDistr where notBootstrapDistrAddresses :: [Address] notBootstrapDistrAddresses = filter (not . isBootstrapEraDistr) $ map txOutAddress $ toList $ _txOutputs taTx isBootstrapEraDistr :: Address -> Bool isBootstrapEraDistr (addrAttributesUnwrapped -> AddrAttributes {..}) = case aaStakeDistribution of BootstrapEraDistr -> True _ -> False verifyTxFeePolicy :: TxFee -> Fee.TxFeePolicy -> Byte -> Either ToilVerFailure () verifyTxFeePolicy (TxFee txFee) policy txSize = case policy of Fee.TxFeePolicyTxSizeLinear txSizeLinear -> do let -- We use 'ceiling' to convert from a fixed-precision fractional -- to coin amount. The actual fee is always a non-negative integer -- amount of coins, so if @min_fee <= fee@ holds (the ideal check), -- then @ceiling min_fee <= fee@ holds too. -- The reason we can't compare fractionals directly is that the -- minimal fee may need to appear in an error message (as a reason -- for rejecting the transaction). mTxMinFee = integerToCoin . ceiling $ Fee.calculateTxSizeLinear txSizeLinear txSize -- The policy must be designed in a way that makes this impossible, -- but in case the result of its evaluation is negative or exceeds -- maximum coin value, we throw an error. txMinFee <- case mTxMinFee of Left reason -> throwError $ ToilInvalidMinFee policy reason txSize Right a -> return a unless (txMinFee <= txFee) $ throwError $ ToilInsufficientFee policy (TxFee txFee) (TxFee txMinFee) txSize Fee.TxFeePolicyUnknown _ _ -> -- The minimal transaction fee policy exists, but the current -- version of the node doesn't know how to handle it. There are -- three possible options mentioned in [CSLREQ-157]: -- 1. Reject all new-coming transactions (b/c we can't calculate -- fee for them) -- 2. Use latest policy of known type -- 3. Discard the check -- Implementation-wise, the 1st option corresponds to throwing an -- error here (reject), the 3rd option -- doing nothing (accept), and -- the 2nd option would require some engineering feats to -- retrieve previous 'TxFeePolicy' and check against it. return () ---------------------------------------------------------------------------- -- Helpers ---------------------------------------------------------------------------- withTxId :: TxAux -> (TxId, TxAux) withTxId aux = (hash (taTx aux), aux) applyTxToUtxo' :: (TxId, TxAux) -> UtxoM () applyTxToUtxo' (i, TxAux tx _) = Utxo.applyTxToUtxo (WithHash tx i)
input-output-hk/pos-haskell-prototype
chain/src/Pos/Chain/Txp/Toil/Logic.hs
mit
10,144
0
15
2,360
1,893
1,041
852
-1
-1
{-# LANGUAGE OverloadedStrings #-} -- | A utility type for saving memory in the presence of many duplicate ByteStrings, etc. If you have data that may be -- a redundant duplicate, try pinning it to a pin board, and use the result of that operation instead. -- -- Without a pin board: -- -- x ───── "38dce848c8c829c62" -- y ───── "38dce848c8c829c62" -- z ───── "d2518f260535b927b" -- -- With a pin board: -- -- x ───── "38dce848c8c829c62" ┄┄┄┄┄┐ -- y ────────┘ board -- z ───── "d2518f260535b927b" ┄┄┄┄┄┘ -- -- ... and after x is garbage collected: -- -- "38dce848c8c829c62" ┄┄┄┄┄┐ -- y ────────┘ board -- z ───── "d2518f260535b927b" ┄┄┄┄┄┘ -- -- ... and after y is garbage collected: -- -- board -- z ───── "d2518f260535b927b" ┄┄┄┄┄┘ module Unison.Util.PinBoard ( PinBoard, new, pin, -- * For debugging debugDump, debugSize, ) where import Control.Concurrent.MVar import Data.Foldable (find, foldlM) import Data.Functor.Compose import Data.Hashable (Hashable, hash) import qualified Data.IntMap as IntMap import Data.IntMap.Strict (IntMap) import qualified Data.Text as Text import qualified Data.Text.IO as Text import Data.Tuple (swap) import System.Mem.Weak (Weak, deRefWeak, mkWeakPtr) import Unison.Prelude -- | A "pin board" is a place to pin values; semantically, it's a set, but differs in a few ways: -- -- * Pinned values aren't kept alive by the pin board, they might be garbage collected at any time. -- * If you try to pin a value that's already pinned (per its Eq instance), the pinned one will be returned -- instead. -- * It has a small API: just 'new' and 'pin'. newtype PinBoard a = PinBoard (MVar (IntMap (Bucket a))) new :: MonadIO m => m (PinBoard a) new = liftIO (PinBoard <$> newMVar IntMap.empty) pin :: forall a m. (Eq a, Hashable a, MonadIO m) => PinBoard a -> a -> m a pin (PinBoard boardVar) x = liftIO do modifyMVar boardVar \board -> swap <$> getCompose (IntMap.alterF alter n board) where -- Pin to pin board at a hash key: either there's nothing there (ifMiss), or there's a nonempty bucket (ifHit). alter :: Maybe (Bucket a) -> Compose IO ((,) a) (Maybe (Bucket a)) alter = Compose . maybe ifMiss ifHit -- Pin a new value: create a new singleton bucket. ifMiss :: IO (a, Maybe (Bucket a)) ifMiss = (x,) . Just <$> newBucket x finalizer -- Possibly pin a new value: if it already exists in the bucket, return that one instead. Otherwise, insert it. ifHit :: Bucket a -> IO (a, Maybe (Bucket a)) ifHit bucket = bucketFind bucket x >>= \case -- Hash collision: the bucket has things in it, but none are the given value. Insert. Nothing -> (x,) . Just <$> bucketAdd bucket x finalizer -- The thing being inserted already exists; return it. Just y -> pure (y, Just bucket) -- When each thing pinned here is garbage collected, compact its bucket. finalizer :: IO () finalizer = modifyMVar_ boardVar (IntMap.alterF (maybe (pure Nothing) bucketCompact) n) n :: Int n = hash x debugDump :: MonadIO m => (a -> Text) -> PinBoard a -> m () debugDump f (PinBoard boardVar) = liftIO do board <- readMVar boardVar contents <- (traverse . traverse) bucketToList (IntMap.toList board) Text.putStrLn (Text.unlines ("PinBoard" : map row contents)) where row (n, xs) = Text.pack (show n) <> " => " <> Text.pack (show (map f xs)) debugSize :: PinBoard a -> IO Int debugSize (PinBoard boardVar) = do board <- readMVar boardVar foldlM step 0 board where step :: Int -> Bucket a -> IO Int step acc = bucketToList >=> \xs -> pure (acc + length xs) -- | A bucket of weak pointers to different values that all share a hash. newtype Bucket a = Bucket [Weak a] -- Invariant: non-empty list -- | A singleton bucket. newBucket :: a -> IO () -> IO (Bucket a) newBucket = bucketAdd (Bucket []) -- | Add a value to a bucket. bucketAdd :: Bucket a -> a -> IO () -> IO (Bucket a) bucketAdd (Bucket weaks) x finalizer = do weak <- mkWeakPtr x (Just finalizer) pure (Bucket (weak : weaks)) -- | Drop all garbage-collected values from a bucket. If none remain, returns Nothing. bucketCompact :: Bucket a -> IO (Maybe (Bucket a)) bucketCompact (Bucket weaks) = bucketFromList <$> mapMaybeM (\w -> (w <$) <$> deRefWeak w) weaks -- | Look up a value in a bucket per its Eq instance. bucketFind :: Eq a => Bucket a -> a -> IO (Maybe a) bucketFind bucket x = find (== x) <$> bucketToList bucket bucketFromList :: [Weak a] -> Maybe (Bucket a) bucketFromList = \case [] -> Nothing weaks -> Just (Bucket weaks) bucketToList :: Bucket a -> IO [a] bucketToList (Bucket weaks) = mapMaybeM deRefWeak weaks
unisonweb/platform
parser-typechecker/src/Unison/Util/PinBoard.hs
mit
5,021
0
14
1,155
1,236
655
581
-1
-1
module Pos.DB.Ssc.Logic ( module Pos.DB.Ssc.Logic.Global , module Pos.DB.Ssc.Logic.Local , module Pos.DB.Ssc.Logic.VAR ) where import Pos.DB.Ssc.Logic.Global import Pos.DB.Ssc.Logic.Local import Pos.DB.Ssc.Logic.VAR
input-output-hk/pos-haskell-prototype
db/src/Pos/DB/Ssc/Logic.hs
mit
275
0
5
78
61
46
15
7
0
{-# LANGUAGE OverloadedStrings, TupleSections #-} module Parse where import Prelude hiding (takeWhile) import Control.Applicative import Control.Monad import Data.Text (Text) import qualified Data.Text as Text import ParseUtil import Internal parseConfig :: Text -> Either String Config parseConfig input = join $ parse (config <* endOfInput) input config :: Parser (Either String Config) config = do mx <- defaultSection xs <- many section return $ join $ mkConfig `fmap` sequence (maybe xs (:xs) mx) -- | A section header like [name], followed by options and comments section :: Parser (Either String (Section, ConfigSection)) section = do (name, renderedName) <- sectionHeader l <- sectionBody return $ (name,) `fmap` mkSection_ renderedName l defaultSection :: Parser (Maybe (Either String (Section, ConfigSection))) defaultSection = do l <- sectionBody case l of [] -> return Nothing _ -> return $ Just $ (defaultSectionName,) `fmap` mkSection_ (toText defaultSectionName) l mkSection_ :: Text -> [SectionBodyLine] -> Either String ConfigSection mkSection_ renderedName l = mkSection options comments blankLines renderedName where (options, comments, blankLines) = foldr go ([], [], []) $ zip l [0..] go (OptionLine key desc, i) (as, bs, cs) = ((key, (i, desc)) : as , bs, cs) go (CommentLine x, i) (as, bs, cs) = ( as, (i, x) : bs, cs) go (BlankLine x, i) (as, bs, cs) = ( as, bs, (i, x) : cs) sectionHeader :: Parser (Section, Text) sectionHeader = do pre <- blanks name <- char '[' *> sectionName <* char ']' post <- blanks endOfLine <|> endOfInput return (Section name, Text.concat [pre, "[", name, "]", post]) sectionName :: Parser Text sectionName = takeWhile1 sectionClass sectionClass :: Char -> Bool sectionClass c = (not . elem c) "\n\r[]" sectionBody :: Parser [SectionBodyLine] sectionBody = many sectionBodyLine data SectionBodyLine = OptionLine Key ConfigOption | CommentLine Comment | BlankLine Text sectionBodyLine :: Parser SectionBodyLine sectionBodyLine = try (uncurry OptionLine <$> option) <|> try (CommentLine <$> comment) <|> try (BlankLine <$> blankLine) -- | A key–value pair option :: Parser (Key, ConfigOption) option = mk <$> blanks <*> key <*> blanks <*> separator <*> blanks <*> takeLine where key = takeWhile1 keyClass separator = string "=" <|> string ":" mk pre_key _key pre_sep sep post_sep _value = (Key _key, ConfigOption renderedKey (Value _value)) where renderedKey = Text.concat [pre_key, _key, pre_sep, sep, post_sep] keyClass :: Char -> Bool keyClass c = (not . elem c) "\n\r\t =:[]#" comment :: Parser Comment comment = mk <$> blanks <*> string "#" <*> takeLine where mk a b c = Comment $ Text.concat [a, b, c] blankLine :: Parser Text blankLine = -- two rules are needed, otherwise the parser would always succeed blanks <* endOfLine <|> blanks1 <* endOfInput blanks :: Parser Text blanks = takeWhile isHorizontalSpace blanks1 :: Parser Text blanks1 = takeWhile1 isHorizontalSpace takeLine :: Parser Text takeLine = takeWhile (not . isEndOfLine) <* (endOfLine <|> endOfInput)
sol/config-ng
src/Parse.hs
mit
3,297
0
13
742
1,111
594
517
70
3
-- | Haskell AST utilities to work with @import@ section. module Importify.Syntax.Import ( getImportModuleName , importNamesWithTables , importSlice , isImportImplicit , switchHidingImports ) where import Universum import qualified Data.List.NonEmpty as NE import Language.Haskell.Exts (Extension (DisableExtension), ImportDecl (..), ImportSpecList (..), KnownExtension (ImplicitPrelude), Module (..), ModuleName, ModuleName (..), ModulePragma (LanguagePragma), Name (Ident), SrcSpan (..), SrcSpanInfo (..), combSpanInfo, noSrcSpan, prettyExtension) import Language.Haskell.Names (NameInfo (Import)) import Language.Haskell.Names.GlobalSymbolTable (Table) import Importify.Syntax.Module (isInsideExport) import Importify.Syntax.Scoped (InScoped, pullScopedInfo) -- | Returns module name for 'ImportDecl' with annotation erased. getImportModuleName :: ImportDecl l -> ModuleName () getImportModuleName ImportDecl{..} = () <$ importModule -- | Returns 'True' iff import has next form: -- @ -- import Module.Name -- import Module.Name as Other.Name -- import Module.Name hiding (smth) -- @ isImportImplicit :: ImportDecl l -> Bool isImportImplicit ImportDecl{ importQualified = True } = False isImportImplicit ImportDecl{ importSpecs = Nothing } = True isImportImplicit ImportDecl{ importSpecs = Just (ImportSpecList _ True _) } = True isImportImplicit _ = False -- | This function returns name of import disregard to its -- qualification, how this module should be referenced, i.e. like this: -- @ -- import <whatever> A ⇒ A -- import <whatever> B as X ⇒ X -- @ importReferenceName :: ImportDecl l -> ModuleName () importReferenceName ImportDecl{ importAs = Nothing, .. } = () <$ importModule importReferenceName ImportDecl{ importAs = Just name } = () <$ name -- | Keep only hiding imports making them non-hiding. This function -- needed to collect unused hiding imports because @importTable@ doesn't -- track information about hiding imports. switchHidingImports :: Module SrcSpanInfo -> Module SrcSpanInfo switchHidingImports (Module ml mhead mpragmas mimports mdecls) = Module ml mhead ( LanguagePragma noSrcSpan [ Ident noSrcSpan $ prettyExtension $ DisableExtension ImplicitPrelude ] : mpragmas) (mapMaybe unhide mimports) mdecls where unhide :: ImportDecl SrcSpanInfo -> Maybe (ImportDecl SrcSpanInfo) unhide decl = do ImportSpecList l isHiding imports <- importSpecs decl guard isHiding guard $ not $ isInsideExport mhead (importReferenceName decl) pure $ decl { importSpecs = Just $ ImportSpecList l False imports } switchHidingImports m = m -- | Collect mapping from import name to to list of symbols it exports. importNamesWithTables :: [InScoped ImportDecl] -> [(ModuleName (), Table)] importNamesWithTables = map (getImportModuleName &&& getImportedSymbols) where getImportedSymbols :: InScoped ImportDecl -> Table getImportedSymbols = fromImportInfo . pullScopedInfo fromImportInfo :: NameInfo l -> Table fromImportInfo (Import dict) = dict fromImportInfo _ = mempty -- | Returns pair of line numbers — first and last line of import section -- if any import is in list. importSlice :: [ImportDecl SrcSpanInfo] -> Maybe (Int, Int) importSlice [] = Nothing importSlice [ImportDecl{..}] = Just $ startAndEndLines importAnn importSlice (x:y:xs) = Just $ startAndEndLines $ combSpanInfo (importAnn x) (importAnn $ NE.last (y :| xs)) startAndEndLines :: SrcSpanInfo -> (Int, Int) startAndEndLines (SrcSpanInfo SrcSpan{..} _) = (srcSpanStartLine, srcSpanEndLine)
serokell/importify
src/Importify/Syntax/Import.hs
mit
4,637
0
13
1,625
842
466
376
-1
-1
---------------------------------------------------- -- -- -- HyLoRes.Core.Rule.Metadata: -- -- Miscelaneous rule data/info, that probably -- -- should go in Rules.Base but didn't work due to -- -- mutually recursive modules and the 'deriving' -- -- clause.... -- -- -- ---------------------------------------------------- {- Copyright (C) HyLoRes 2002-2007 - See AUTHORS file This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -} module HyLoRes.Core.Rule.Metadata( RuleId(..), PremiseType(..), opposite, Subsumption(..) ) where import Data.Ix data RuleId = R_ResP -- Resolution on propositions | R_ResN -- Resolution on nominals | R_ResB -- Resolution on boxes -- | R_Box -- ([r]) rule | R_BoxX -- Crossed version of the ([r]) rule (past modality) -- | R_Dia -- (<r>) rule (using nom function) -- | R_Down -- Down arrow elimination -- | R_Disj -- Disjunction elimination | R_Conj -- Conjunction elimination -- == -- | R_ParUnit -- Unit full clause paramodulation --- | R_ParP -- Labelled paramodulation on positive propositions | R_ParNegP -- Labelled paramodulation on negative propositions --- | R_ParB -- Labelled paramodulation on boxes (but replacing all -- nominals occurring in the formula) | R_ParEq -- Labelled paramodulation on equalities | R_ParNeq -- Labelled paramodulation on inequalities --- | R_ParR -- Labelled paramodulation on the relations deriving (Eq, Ord, Ix, Bounded, Show) data PremiseType = Main | Side deriving (Show) opposite :: PremiseType -> PremiseType opposite Main = Side opposite Side = Main -- Ways in which a premise may get subsumed: data Subsumption = None -- no subsumption at all, | IsSubset -- using the standard redundancy criteria | ByParUnit -- ParUnit-rule was applied | Semantic -- the clause is redundant because of "semantic" -- reasons (the other premise and/or the consequent -- carry the same information) deriving ( Eq, Show, Read )
nevrenato/HyLoRes_Source
src/HyLoRes/Core/Rule/Metadata.hs
gpl-2.0
3,210
0
6
1,092
229
156
73
29
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.Redshift.CreateCluster -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Creates a new cluster. To create the cluster in virtual private cloud -- (VPC), you must provide cluster subnet group name. If you don\'t provide -- a cluster subnet group name or the cluster security group parameter, -- Amazon Redshift creates a non-VPC cluster, it associates the default -- cluster security group with the cluster. For more information about -- managing clusters, go to -- <http://docs.aws.amazon.com/redshift/latest/mgmt/working-with-clusters.html Amazon Redshift Clusters> -- in the /Amazon Redshift Cluster Management Guide/ . -- -- /See:/ <http://docs.aws.amazon.com/redshift/latest/APIReference/API_CreateCluster.html AWS API Reference> for CreateCluster. module Network.AWS.Redshift.CreateCluster ( -- * Creating a Request createCluster , CreateCluster -- * Request Lenses , ccPubliclyAccessible , ccHSMConfigurationIdentifier , ccClusterSecurityGroups , ccAutomatedSnapshotRetentionPeriod , ccEncrypted , ccClusterSubnetGroupName , ccHSMClientCertificateIdentifier , ccNumberOfNodes , ccElasticIP , ccPreferredMaintenanceWindow , ccKMSKeyId , ccAvailabilityZone , ccVPCSecurityGroupIds , ccClusterType , ccClusterVersion , ccAllowVersionUpgrade , ccClusterParameterGroupName , ccTags , ccPort , ccDBName , ccClusterIdentifier , ccNodeType , ccMasterUsername , ccMasterUserPassword -- * Destructuring the Response , createClusterResponse , CreateClusterResponse -- * Response Lenses , ccrsCluster , ccrsResponseStatus ) where import Network.AWS.Prelude import Network.AWS.Redshift.Types import Network.AWS.Redshift.Types.Product import Network.AWS.Request import Network.AWS.Response -- | -- -- /See:/ 'createCluster' smart constructor. data CreateCluster = CreateCluster' { _ccPubliclyAccessible :: !(Maybe Bool) , _ccHSMConfigurationIdentifier :: !(Maybe Text) , _ccClusterSecurityGroups :: !(Maybe [Text]) , _ccAutomatedSnapshotRetentionPeriod :: !(Maybe Int) , _ccEncrypted :: !(Maybe Bool) , _ccClusterSubnetGroupName :: !(Maybe Text) , _ccHSMClientCertificateIdentifier :: !(Maybe Text) , _ccNumberOfNodes :: !(Maybe Int) , _ccElasticIP :: !(Maybe Text) , _ccPreferredMaintenanceWindow :: !(Maybe Text) , _ccKMSKeyId :: !(Maybe Text) , _ccAvailabilityZone :: !(Maybe Text) , _ccVPCSecurityGroupIds :: !(Maybe [Text]) , _ccClusterType :: !(Maybe Text) , _ccClusterVersion :: !(Maybe Text) , _ccAllowVersionUpgrade :: !(Maybe Bool) , _ccClusterParameterGroupName :: !(Maybe Text) , _ccTags :: !(Maybe [Tag]) , _ccPort :: !(Maybe Int) , _ccDBName :: !(Maybe Text) , _ccClusterIdentifier :: !Text , _ccNodeType :: !Text , _ccMasterUsername :: !Text , _ccMasterUserPassword :: !Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'CreateCluster' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ccPubliclyAccessible' -- -- * 'ccHSMConfigurationIdentifier' -- -- * 'ccClusterSecurityGroups' -- -- * 'ccAutomatedSnapshotRetentionPeriod' -- -- * 'ccEncrypted' -- -- * 'ccClusterSubnetGroupName' -- -- * 'ccHSMClientCertificateIdentifier' -- -- * 'ccNumberOfNodes' -- -- * 'ccElasticIP' -- -- * 'ccPreferredMaintenanceWindow' -- -- * 'ccKMSKeyId' -- -- * 'ccAvailabilityZone' -- -- * 'ccVPCSecurityGroupIds' -- -- * 'ccClusterType' -- -- * 'ccClusterVersion' -- -- * 'ccAllowVersionUpgrade' -- -- * 'ccClusterParameterGroupName' -- -- * 'ccTags' -- -- * 'ccPort' -- -- * 'ccDBName' -- -- * 'ccClusterIdentifier' -- -- * 'ccNodeType' -- -- * 'ccMasterUsername' -- -- * 'ccMasterUserPassword' createCluster :: Text -- ^ 'ccClusterIdentifier' -> Text -- ^ 'ccNodeType' -> Text -- ^ 'ccMasterUsername' -> Text -- ^ 'ccMasterUserPassword' -> CreateCluster createCluster pClusterIdentifier_ pNodeType_ pMasterUsername_ pMasterUserPassword_ = CreateCluster' { _ccPubliclyAccessible = Nothing , _ccHSMConfigurationIdentifier = Nothing , _ccClusterSecurityGroups = Nothing , _ccAutomatedSnapshotRetentionPeriod = Nothing , _ccEncrypted = Nothing , _ccClusterSubnetGroupName = Nothing , _ccHSMClientCertificateIdentifier = Nothing , _ccNumberOfNodes = Nothing , _ccElasticIP = Nothing , _ccPreferredMaintenanceWindow = Nothing , _ccKMSKeyId = Nothing , _ccAvailabilityZone = Nothing , _ccVPCSecurityGroupIds = Nothing , _ccClusterType = Nothing , _ccClusterVersion = Nothing , _ccAllowVersionUpgrade = Nothing , _ccClusterParameterGroupName = Nothing , _ccTags = Nothing , _ccPort = Nothing , _ccDBName = Nothing , _ccClusterIdentifier = pClusterIdentifier_ , _ccNodeType = pNodeType_ , _ccMasterUsername = pMasterUsername_ , _ccMasterUserPassword = pMasterUserPassword_ } -- | If 'true', the cluster can be accessed from a public network. ccPubliclyAccessible :: Lens' CreateCluster (Maybe Bool) ccPubliclyAccessible = lens _ccPubliclyAccessible (\ s a -> s{_ccPubliclyAccessible = a}); -- | Specifies the name of the HSM configuration that contains the -- information the Amazon Redshift cluster can use to retrieve and store -- keys in an HSM. ccHSMConfigurationIdentifier :: Lens' CreateCluster (Maybe Text) ccHSMConfigurationIdentifier = lens _ccHSMConfigurationIdentifier (\ s a -> s{_ccHSMConfigurationIdentifier = a}); -- | A list of security groups to be associated with this cluster. -- -- Default: The default cluster security group for Amazon Redshift. ccClusterSecurityGroups :: Lens' CreateCluster [Text] ccClusterSecurityGroups = lens _ccClusterSecurityGroups (\ s a -> s{_ccClusterSecurityGroups = a}) . _Default . _Coerce; -- | The number of days that automated snapshots are retained. If the value -- is 0, automated snapshots are disabled. Even if automated snapshots are -- disabled, you can still create manual snapshots when you want with -- CreateClusterSnapshot. -- -- Default: '1' -- -- Constraints: Must be a value from 0 to 35. ccAutomatedSnapshotRetentionPeriod :: Lens' CreateCluster (Maybe Int) ccAutomatedSnapshotRetentionPeriod = lens _ccAutomatedSnapshotRetentionPeriod (\ s a -> s{_ccAutomatedSnapshotRetentionPeriod = a}); -- | If 'true', the data in the cluster is encrypted at rest. -- -- Default: false ccEncrypted :: Lens' CreateCluster (Maybe Bool) ccEncrypted = lens _ccEncrypted (\ s a -> s{_ccEncrypted = a}); -- | The name of a cluster subnet group to be associated with this cluster. -- -- If this parameter is not provided the resulting cluster will be deployed -- outside virtual private cloud (VPC). ccClusterSubnetGroupName :: Lens' CreateCluster (Maybe Text) ccClusterSubnetGroupName = lens _ccClusterSubnetGroupName (\ s a -> s{_ccClusterSubnetGroupName = a}); -- | Specifies the name of the HSM client certificate the Amazon Redshift -- cluster uses to retrieve the data encryption keys stored in an HSM. ccHSMClientCertificateIdentifier :: Lens' CreateCluster (Maybe Text) ccHSMClientCertificateIdentifier = lens _ccHSMClientCertificateIdentifier (\ s a -> s{_ccHSMClientCertificateIdentifier = a}); -- | The number of compute nodes in the cluster. This parameter is required -- when the __ClusterType__ parameter is specified as 'multi-node'. -- -- For information about determining how many nodes you need, go to -- <http://docs.aws.amazon.com/redshift/latest/mgmt/working-with-clusters.html#how-many-nodes Working with Clusters> -- in the /Amazon Redshift Cluster Management Guide/. -- -- If you don\'t specify this parameter, you get a single-node cluster. -- When requesting a multi-node cluster, you must specify the number of -- nodes that you want in the cluster. -- -- Default: '1' -- -- Constraints: Value must be at least 1 and no more than 100. ccNumberOfNodes :: Lens' CreateCluster (Maybe Int) ccNumberOfNodes = lens _ccNumberOfNodes (\ s a -> s{_ccNumberOfNodes = a}); -- | The Elastic IP (EIP) address for the cluster. -- -- Constraints: The cluster must be provisioned in EC2-VPC and -- publicly-accessible through an Internet gateway. For more information -- about provisioning clusters in EC2-VPC, go to -- <http://docs.aws.amazon.com/redshift/latest/mgmt/working-with-clusters.html#cluster-platforms Supported Platforms to Launch Your Cluster> -- in the Amazon Redshift Cluster Management Guide. ccElasticIP :: Lens' CreateCluster (Maybe Text) ccElasticIP = lens _ccElasticIP (\ s a -> s{_ccElasticIP = a}); -- | The weekly time range (in UTC) during which automated cluster -- maintenance can occur. -- -- Format: 'ddd:hh24:mi-ddd:hh24:mi' -- -- Default: A 30-minute window selected at random from an 8-hour block of -- time per region, occurring on a random day of the week. For more -- information about the time blocks for each region, see -- <http://docs.aws.amazon.com/redshift/latest/mgmt/working-with-clusters.html#rs-maintenance-windows Maintenance Windows> -- in Amazon Redshift Cluster Management Guide. -- -- Valid Days: Mon | Tue | Wed | Thu | Fri | Sat | Sun -- -- Constraints: Minimum 30-minute window. ccPreferredMaintenanceWindow :: Lens' CreateCluster (Maybe Text) ccPreferredMaintenanceWindow = lens _ccPreferredMaintenanceWindow (\ s a -> s{_ccPreferredMaintenanceWindow = a}); -- | The AWS Key Management Service (KMS) key ID of the encryption key that -- you want to use to encrypt data in the cluster. ccKMSKeyId :: Lens' CreateCluster (Maybe Text) ccKMSKeyId = lens _ccKMSKeyId (\ s a -> s{_ccKMSKeyId = a}); -- | The EC2 Availability Zone (AZ) in which you want Amazon Redshift to -- provision the cluster. For example, if you have several EC2 instances -- running in a specific Availability Zone, then you might want the cluster -- to be provisioned in the same zone in order to decrease network latency. -- -- Default: A random, system-chosen Availability Zone in the region that is -- specified by the endpoint. -- -- Example: 'us-east-1d' -- -- Constraint: The specified Availability Zone must be in the same region -- as the current endpoint. ccAvailabilityZone :: Lens' CreateCluster (Maybe Text) ccAvailabilityZone = lens _ccAvailabilityZone (\ s a -> s{_ccAvailabilityZone = a}); -- | A list of Virtual Private Cloud (VPC) security groups to be associated -- with the cluster. -- -- Default: The default VPC security group is associated with the cluster. ccVPCSecurityGroupIds :: Lens' CreateCluster [Text] ccVPCSecurityGroupIds = lens _ccVPCSecurityGroupIds (\ s a -> s{_ccVPCSecurityGroupIds = a}) . _Default . _Coerce; -- | The type of the cluster. When cluster type is specified as -- -- - 'single-node', the __NumberOfNodes__ parameter is not required. -- - 'multi-node', the __NumberOfNodes__ parameter is required. -- -- Valid Values: 'multi-node' | 'single-node' -- -- Default: 'multi-node' ccClusterType :: Lens' CreateCluster (Maybe Text) ccClusterType = lens _ccClusterType (\ s a -> s{_ccClusterType = a}); -- | The version of the Amazon Redshift engine software that you want to -- deploy on the cluster. -- -- The version selected runs on all the nodes in the cluster. -- -- Constraints: Only version 1.0 is currently available. -- -- Example: '1.0' ccClusterVersion :: Lens' CreateCluster (Maybe Text) ccClusterVersion = lens _ccClusterVersion (\ s a -> s{_ccClusterVersion = a}); -- | If 'true', major version upgrades can be applied during the maintenance -- window to the Amazon Redshift engine that is running on the cluster. -- -- When a new major version of the Amazon Redshift engine is released, you -- can request that the service automatically apply upgrades during the -- maintenance window to the Amazon Redshift engine that is running on your -- cluster. -- -- Default: 'true' ccAllowVersionUpgrade :: Lens' CreateCluster (Maybe Bool) ccAllowVersionUpgrade = lens _ccAllowVersionUpgrade (\ s a -> s{_ccAllowVersionUpgrade = a}); -- | The name of the parameter group to be associated with this cluster. -- -- Default: The default Amazon Redshift cluster parameter group. For -- information about the default parameter group, go to -- <http://docs.aws.amazon.com/redshift/latest/mgmt/working-with-parameter-groups.html Working with Amazon Redshift Parameter Groups> -- -- Constraints: -- -- - Must be 1 to 255 alphanumeric characters or hyphens. -- - First character must be a letter. -- - Cannot end with a hyphen or contain two consecutive hyphens. ccClusterParameterGroupName :: Lens' CreateCluster (Maybe Text) ccClusterParameterGroupName = lens _ccClusterParameterGroupName (\ s a -> s{_ccClusterParameterGroupName = a}); -- | A list of tag instances. ccTags :: Lens' CreateCluster [Tag] ccTags = lens _ccTags (\ s a -> s{_ccTags = a}) . _Default . _Coerce; -- | The port number on which the cluster accepts incoming connections. -- -- The cluster is accessible only via the JDBC and ODBC connection strings. -- Part of the connection string requires the port on which the cluster -- will listen for incoming connections. -- -- Default: '5439' -- -- Valid Values: '1150-65535' ccPort :: Lens' CreateCluster (Maybe Int) ccPort = lens _ccPort (\ s a -> s{_ccPort = a}); -- | The name of the first database to be created when the cluster is -- created. -- -- To create additional databases after the cluster is created, connect to -- the cluster with a SQL client and use SQL commands to create a database. -- For more information, go to -- <http://docs.aws.amazon.com/redshift/latest/dg/t_creating_database.html Create a Database> -- in the Amazon Redshift Database Developer Guide. -- -- Default: 'dev' -- -- Constraints: -- -- - Must contain 1 to 64 alphanumeric characters. -- - Must contain only lowercase letters. -- - Cannot be a word that is reserved by the service. A list of reserved -- words can be found in -- <http://docs.aws.amazon.com/redshift/latest/dg/r_pg_keywords.html Reserved Words> -- in the Amazon Redshift Database Developer Guide. ccDBName :: Lens' CreateCluster (Maybe Text) ccDBName = lens _ccDBName (\ s a -> s{_ccDBName = a}); -- | A unique identifier for the cluster. You use this identifier to refer to -- the cluster for any subsequent cluster operations such as deleting or -- modifying. The identifier also appears in the Amazon Redshift console. -- -- Constraints: -- -- - Must contain from 1 to 63 alphanumeric characters or hyphens. -- - Alphabetic characters must be lowercase. -- - First character must be a letter. -- - Cannot end with a hyphen or contain two consecutive hyphens. -- - Must be unique for all clusters within an AWS account. -- -- Example: 'myexamplecluster' ccClusterIdentifier :: Lens' CreateCluster Text ccClusterIdentifier = lens _ccClusterIdentifier (\ s a -> s{_ccClusterIdentifier = a}); -- | The node type to be provisioned for the cluster. For information about -- node types, go to -- <http://docs.aws.amazon.com/redshift/latest/mgmt/working-with-clusters.html#how-many-nodes Working with Clusters> -- in the /Amazon Redshift Cluster Management Guide/. -- -- Valid Values: 'ds1.xlarge' | 'ds1.8xlarge' | 'ds2.xlarge' | -- 'ds2.8xlarge' | 'dc1.large' | 'dc1.8xlarge'. ccNodeType :: Lens' CreateCluster Text ccNodeType = lens _ccNodeType (\ s a -> s{_ccNodeType = a}); -- | The user name associated with the master user account for the cluster -- that is being created. -- -- Constraints: -- -- - Must be 1 - 128 alphanumeric characters. -- - First character must be a letter. -- - Cannot be a reserved word. A list of reserved words can be found in -- <http://docs.aws.amazon.com/redshift/latest/dg/r_pg_keywords.html Reserved Words> -- in the Amazon Redshift Database Developer Guide. ccMasterUsername :: Lens' CreateCluster Text ccMasterUsername = lens _ccMasterUsername (\ s a -> s{_ccMasterUsername = a}); -- | The password associated with the master user account for the cluster -- that is being created. -- -- Constraints: -- -- - Must be between 8 and 64 characters in length. -- - Must contain at least one uppercase letter. -- - Must contain at least one lowercase letter. -- - Must contain one number. -- - Can be any printable ASCII character (ASCII code 33 to 126) except -- \' (single quote), \" (double quote), \\, \/, \', or space. ccMasterUserPassword :: Lens' CreateCluster Text ccMasterUserPassword = lens _ccMasterUserPassword (\ s a -> s{_ccMasterUserPassword = a}); instance AWSRequest CreateCluster where type Rs CreateCluster = CreateClusterResponse request = postQuery redshift response = receiveXMLWrapper "CreateClusterResult" (\ s h x -> CreateClusterResponse' <$> (x .@? "Cluster") <*> (pure (fromEnum s))) instance ToHeaders CreateCluster where toHeaders = const mempty instance ToPath CreateCluster where toPath = const "/" instance ToQuery CreateCluster where toQuery CreateCluster'{..} = mconcat ["Action" =: ("CreateCluster" :: ByteString), "Version" =: ("2012-12-01" :: ByteString), "PubliclyAccessible" =: _ccPubliclyAccessible, "HsmConfigurationIdentifier" =: _ccHSMConfigurationIdentifier, "ClusterSecurityGroups" =: toQuery (toQueryList "ClusterSecurityGroupName" <$> _ccClusterSecurityGroups), "AutomatedSnapshotRetentionPeriod" =: _ccAutomatedSnapshotRetentionPeriod, "Encrypted" =: _ccEncrypted, "ClusterSubnetGroupName" =: _ccClusterSubnetGroupName, "HsmClientCertificateIdentifier" =: _ccHSMClientCertificateIdentifier, "NumberOfNodes" =: _ccNumberOfNodes, "ElasticIp" =: _ccElasticIP, "PreferredMaintenanceWindow" =: _ccPreferredMaintenanceWindow, "KmsKeyId" =: _ccKMSKeyId, "AvailabilityZone" =: _ccAvailabilityZone, "VpcSecurityGroupIds" =: toQuery (toQueryList "VpcSecurityGroupId" <$> _ccVPCSecurityGroupIds), "ClusterType" =: _ccClusterType, "ClusterVersion" =: _ccClusterVersion, "AllowVersionUpgrade" =: _ccAllowVersionUpgrade, "ClusterParameterGroupName" =: _ccClusterParameterGroupName, "Tags" =: toQuery (toQueryList "Tag" <$> _ccTags), "Port" =: _ccPort, "DBName" =: _ccDBName, "ClusterIdentifier" =: _ccClusterIdentifier, "NodeType" =: _ccNodeType, "MasterUsername" =: _ccMasterUsername, "MasterUserPassword" =: _ccMasterUserPassword] -- | /See:/ 'createClusterResponse' smart constructor. data CreateClusterResponse = CreateClusterResponse' { _ccrsCluster :: !(Maybe Cluster) , _ccrsResponseStatus :: !Int } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'CreateClusterResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ccrsCluster' -- -- * 'ccrsResponseStatus' createClusterResponse :: Int -- ^ 'ccrsResponseStatus' -> CreateClusterResponse createClusterResponse pResponseStatus_ = CreateClusterResponse' { _ccrsCluster = Nothing , _ccrsResponseStatus = pResponseStatus_ } -- | Undocumented member. ccrsCluster :: Lens' CreateClusterResponse (Maybe Cluster) ccrsCluster = lens _ccrsCluster (\ s a -> s{_ccrsCluster = a}); -- | The response status code. ccrsResponseStatus :: Lens' CreateClusterResponse Int ccrsResponseStatus = lens _ccrsResponseStatus (\ s a -> s{_ccrsResponseStatus = a});
fmapfmapfmap/amazonka
amazonka-redshift/gen/Network/AWS/Redshift/CreateCluster.hs
mpl-2.0
21,017
0
13
4,327
2,536
1,558
978
270
1
-- | -- Module : Test.MiniUnit -- Copyright : (c) 2004 Oleg Kiselyov, Alistair Bayley -- License : BSD-style -- Maintainer : [email protected], [email protected] -- Stability : experimental -- Portability : portable -- -- This is just a simple one-module unit test framework, with the same -- API as "Test.HUnit" (albeit with a lot of stuff missing). -- We use it because it works in 'Control.Exception.MonadIO.CaughtMonadIO' -- instead of IO -- (and also because I couldn't convert "Test.HUnit" -- to use 'Control.Exception.MonadIO.CaughtMonadIO'). {-# LANGUAGE CPP #-} module Test.MiniUnit ( -- ** Primary API runTestTT, assertFailure, assertBool, assertString, assertEqual -- ** Exposed for self-testing only; see "Test.MiniUnitTest" , TestResult(..), throwUserError, runSingleTest, reportResults ) where import Control.Exception.MonadIO import Control.Exception import Control.Monad import Control.Monad.Trans (liftIO) import System.IO.Error (ioeGetErrorString) import System.IO import Data.List import Data.IORef data TestResult = TestSuccess | TestFailure String | TestException String deriving (Show, Eq) -- We'll use HUnit's trick of throwing an IOError when an assertion fails. -- This will terminate the test case, obviously, but we catch the exception -- and record that it haa failed so that we can continue with other -- test cases. -- Unlike HUnit, we catch all exceptions; any that are not thrown by -- failed assertions are recorded as test errors (as opposed to test failures), -- and the testing continues... -- When an assertion fails, we throw an IOException with a special -- text prefix, which the exception handler will detect. assertFailure :: CaughtMonadIO m => String -> m () assertFailure msg = throwUserError (exceptionPrefix ++ msg) exceptionPrefix = "MiniUnit:" hugsPrefix = "IO Error: User error\nReason: " nhc98Prefix = "I/O error (user-defined), call to function `userError':\n " ghcPrefix = "" -- We don't use this; it's just documentation... dropPrefix p s = if isPrefixOf p s then drop (length p) s else s trimCompilerPrefixes = dropPrefix hugsPrefix . dropPrefix nhc98Prefix throwUserError :: CaughtMonadIO m => String -> m () throwUserError msg = liftIO (throwIO (userError msg)) runSingleTest :: CaughtMonadIO m => m () -> m TestResult runSingleTest action = do let iohandler :: CaughtMonadIO m =>IOException -> m TestResult iohandler e = let errText = trimCompilerPrefixes (ioeGetErrorString e) in if isPrefixOf exceptionPrefix errText then return (TestFailure (dropPrefix exceptionPrefix errText)) else return (TestException (show e)) errhandler :: CaughtMonadIO m => SomeException -> m TestResult errhandler e = return (TestException (show e)) (action >> return TestSuccess) `gcatch` iohandler `gcatch` errhandler -- Predicates for list filtering isSuccess TestSuccess = True isSuccess _ = False isFailure (TestFailure _) = True isFailure _ = False isError (TestException _) = True isError _ = False -- Make function composition look more like Unix pipes. -- This first definition requires a Point-Free Style. -- I prefer the PFS, as you can use it in (for example) predicate -- functions passed as arguments (see filter example below). infixl 9 |> (|>) = flip (.) -- This second definition affords a more pointed style... -- We can use this operator to inject an argument into a pipe -- defined using |>; it has lower precedence, so will bind last. -- e.g. ... = mylist |>> zip [1..] |> filter (snd |> pred) |> map show |> concat infixl 8 |>> (|>>) = flip ($) --reportFilter pred = zip [1..] |> filter (snd |> pred) |> map testReporter |> concat testReporter (n, TestSuccess) = "" testReporter (n, TestException s) = "Test " ++ show n ++ " failed with exception:\n" ++ s ++ "\n" testReporter (n, TestFailure s) = "Test " ++ show n ++ " failed with message:\n" ++ s ++ "\n" reportResults list = let s = list |>> filter isSuccess |> length e = list |>> filter isError |> length f = list |>> filter isFailure |> length in "Test cases: " ++ show (length list) ++ " Failures: " ++ show f ++ " Errors: " ++ show e -- ++ reportFilter isFailure list -- ++ reportFilter isError list -- 2 defns for same result; which is better? --contains pred = filter pred |> null |> not contains p l = maybe False (const True) (find p l) -- | Return 0 if everything is rosy, -- 1 if there were assertion failures (but no exceptions), -- 2 if there were any exceptions. -- You could use this return code as the return code from -- your program, if you're driving from the command line. runTestTT :: CaughtMonadIO m => String -> [m ()] -> m Int runTestTT desc list = do liftIO (putStrLn "") when (desc /= "") (liftIO (putStr (desc ++ " - "))) liftIO (putStrLn ("Test case count: " ++ show (length list))) r <- mapM (\(n, t) -> liftIO (putStr "." >> hFlush stdout) >> runSingleTestTT n t) (zip [1..] list) liftIO (putStrLn "") liftIO (putStrLn (reportResults r)) if contains isError r then return 2 else if contains isFailure r then return 1 else return 0 -- Could use this instead of runSingleTest - it will output -- failures and exceptions as they occur, rather than all -- at the end. runSingleTestTT :: CaughtMonadIO m => Int -> m () -> m TestResult runSingleTestTT n test = do r <- runSingleTest test case r of TestSuccess -> return r TestFailure _ -> liftIO (putStrLn ('\n':(testReporter (n ,r)))) >> return r TestException _ -> liftIO (putStrLn ('\n':(testReporter (n, r)))) >> return r --------------------------------------------- -- That's the basic framework; now for some sugar... -- ... stolen straight from Dean Herrington's HUnit code. -- Shall we steal his infix operators, too? assertBool :: CaughtMonadIO m => String -> Bool -> m () assertBool msg b = unless b (assertFailure msg) assertString :: CaughtMonadIO m => String -> m () assertString s = unless (null s) (assertFailure s) assertEqual :: (Eq a, Show a, CaughtMonadIO m) => String -- ^ message preface -> a -- ^ expected -> a -- ^ actual -> m () assertEqual preface expected actual = do let msg = (if null preface then "" else preface ++ "\n") ++ "expect: " ++ show expected ++ "\nactual: " ++ show actual unless (actual == expected) (assertFailure msg) --p @? msg = assertBool msg p
paulrzcz/takusen-oracle
Test/MiniUnit.hs
bsd-3-clause
6,608
0
18
1,448
1,446
755
691
96
3
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE LambdaCase #-} -- | Definitions used by various garbage collection algorithms. module Stg.Machine.GarbageCollection.Common ( splitHeapWith, GarbageCollectionAlgorithm(..), Addresses(addrs), UpdateAddrs(..), ) where import Data.Map (Map) import Data.Sequence (Seq, ViewL (..), (<|)) import qualified Data.Sequence as Seq import Data.Set (Set) import qualified Data.Set as S import Data.Text import Stg.Machine.Types -- | Split the heap contained in a machine state in three parts: the dead -- objects that can safely be discarded, a maping from old to new addresses if -- definitions were moved, and the final state with a cleaned up heap. splitHeapWith :: GarbageCollectionAlgorithm -> StgState -> (Set MemAddr, Map MemAddr MemAddr, StgState) splitHeapWith (GarbageCollectionAlgorithm _name gc) = gc -- | A garbage collection algorithm is a specific way to get rid of unused heap -- objects. data GarbageCollectionAlgorithm = GarbageCollectionAlgorithm Text (StgState -> (Set MemAddr, Map MemAddr MemAddr, StgState)) -- ^ @<Algorithm name> (<state> -> (<dead addresses>, <moved addresses>, <new state>)@ -- | Collect all mentioned addresses in a machine element. -- -- Note that none of the types in "Stg.Language" contain addresses, since an -- address is not something present in the STG __language__, only in the execution -- contest the language is put in in the "Stg.Machine" modules. class Addresses a where -- | All contained addresses in the order they appear, but without -- duplicates. addrs :: a -> Seq MemAddr addrs = nubSeq . addrs' -- | All contained addresses in the order they appear, with duplicates. addrs' :: a -> Seq MemAddr {-# MINIMAL addrs' #-} nubSeq :: Ord a => Seq a -> Seq a nubSeq = go mempty where go cache entries = case Seq.viewl entries of EmptyL -> mempty x :< xs | S.member x cache -> go cache xs | otherwise -> x <| go (S.insert x cache) xs instance (Foldable f, Addresses a) => Addresses (f a) where addrs' = foldMap addrs' instance Addresses Code where addrs' = \case Eval _expr locals -> addrs' locals Enter addr -> addrs' addr ReturnCon _con args -> addrs' args ReturnInt _int -> mempty instance Addresses StackFrame where addrs' = \case ArgumentFrame vals -> addrs' vals ReturnFrame _alts locals -> addrs' locals UpdateFrame addr -> addrs' addr instance Addresses MemAddr where addrs' addr = Seq.singleton addr instance Addresses Globals where addrs' (Globals globals) = addrs' globals instance Addresses Locals where addrs' (Locals locals) = addrs' locals instance Addresses Closure where addrs' (Closure _lf free) = addrs' free instance Addresses HeapObject where addrs' = \case HClosure closure -> addrs' closure Blackhole _bhTick -> mempty instance Addresses Value where addrs' = \case Addr addr -> addrs' addr PrimInt _i -> mempty -- | Update all contained addresses in a certain value. Useful for moving -- garbage collectors. class UpdateAddrs a where updateAddrs :: (MemAddr -> MemAddr) -> a -> a instance UpdateAddrs Code where updateAddrs upd = \case Eval expr locals -> Eval expr (updateAddrs upd locals) Enter addr -> Enter (updateAddrs upd addr) ReturnCon constr args -> ReturnCon constr (updateAddrs upd args) r@ReturnInt{} -> r instance UpdateAddrs Locals where updateAddrs upd (Locals locals) = Locals (updateAddrs upd locals) instance UpdateAddrs Globals where updateAddrs upd (Globals locals) = Globals (updateAddrs upd locals) instance UpdateAddrs Value where updateAddrs upd = \case Addr addr -> Addr (updateAddrs upd addr) p@PrimInt{} -> p instance UpdateAddrs MemAddr where updateAddrs = id instance (Functor f, UpdateAddrs a) => UpdateAddrs (f a) where updateAddrs upd = fmap (updateAddrs upd) instance UpdateAddrs StackFrame where updateAddrs upd = \case ArgumentFrame arg -> ArgumentFrame (updateAddrs upd arg) ReturnFrame alts locals -> ReturnFrame alts (updateAddrs upd locals) UpdateFrame addr -> UpdateFrame (updateAddrs upd addr)
quchen/stg
src/Stg/Machine/GarbageCollection/Common.hs
bsd-3-clause
4,458
0
15
1,113
1,074
549
525
91
2
-- | Test maps, sums and enumerations. import Timing import Randomish import System.Environment import qualified Vector as V import qualified Vectorised as Z import qualified Data.Vector.Unboxed as V main :: IO () main = do args <- getArgs case args of [alg, len] -> run alg (read len) _ -> usage usage = putStr $ unlines [ "usage: sumsq <alg> <length>" , " alg one of " ++ show ["vectorised", "vector"] ] run alg num = do (result, tElapsed) <- runAlg alg num putStr $ prettyTime tElapsed print result runAlg "vectorised" num = time $ let result = Z.sumSq num in result `seq` return result runAlg "vector" num = time $ let result = V.sumSq num in result `seq` return result
mainland/dph
dph-examples/examples/smoke/prims/SumSquares/dph/Main.hs
bsd-3-clause
742
28
11
188
271
143
128
26
2
-- | -- Statistics for per-module compilations -- -- (c) The GRASP/AQUA Project, Glasgow University, 1993-1998 -- {-# LANGUAGE FlexibleContexts #-} module HscStats ( ppSourceStats ) where import GhcPrelude import Bag import HsSyn import Outputable import SrcLoc import Util import Data.Char import Data.Foldable (foldl') -- | Source Statistics ppSourceStats :: Bool -> Located (HsModule GhcPs) -> SDoc ppSourceStats short (L _ (HsModule _ exports imports ldecls _ _)) = (if short then hcat else vcat) (map pp_val [("ExportAll ", export_all), -- 1 if no export list ("ExportDecls ", export_ds), ("ExportModules ", export_ms), ("Imports ", imp_no), (" ImpSafe ", imp_safe), (" ImpQual ", imp_qual), (" ImpAs ", imp_as), (" ImpAll ", imp_all), (" ImpPartial ", imp_partial), (" ImpHiding ", imp_hiding), ("FixityDecls ", fixity_sigs), ("DefaultDecls ", default_ds), ("TypeDecls ", type_ds), ("DataDecls ", data_ds), ("NewTypeDecls ", newt_ds), ("TypeFamilyDecls ", type_fam_ds), ("DataConstrs ", data_constrs), ("DataDerivings ", data_derivs), ("ClassDecls ", class_ds), ("ClassMethods ", class_method_ds), ("DefaultMethods ", default_method_ds), ("InstDecls ", inst_ds), ("InstMethods ", inst_method_ds), ("InstType ", inst_type_ds), ("InstData ", inst_data_ds), ("TypeSigs ", bind_tys), ("ClassOpSigs ", generic_sigs), ("ValBinds ", val_bind_ds), ("FunBinds ", fn_bind_ds), ("PatSynBinds ", patsyn_ds), ("InlineMeths ", method_inlines), ("InlineBinds ", bind_inlines), ("SpecialisedMeths ", method_specs), ("SpecialisedBinds ", bind_specs) ]) where decls = map unLoc ldecls pp_val (_, 0) = empty pp_val (str, n) | not short = hcat [text str, int n] | otherwise = hcat [text (trim str), equals, int n, semi] trim ls = takeWhile (not.isSpace) (dropWhile isSpace ls) (fixity_sigs, bind_tys, bind_specs, bind_inlines, generic_sigs) = count_sigs [d | SigD d <- decls] -- NB: this omits fixity decls on local bindings and -- in class decls. ToDo tycl_decls = [d | TyClD d <- decls] (class_ds, type_ds, data_ds, newt_ds, type_fam_ds) = countTyClDecls tycl_decls inst_decls = [d | InstD d <- decls] inst_ds = length inst_decls default_ds = count (\ x -> case x of { DefD{} -> True; _ -> False}) decls val_decls = [d | ValD d <- decls] real_exports = case exports of { Nothing -> []; Just (L _ es) -> es } n_exports = length real_exports export_ms = count (\ e -> case unLoc e of { IEModuleContents{} -> True;_ -> False}) real_exports export_ds = n_exports - export_ms export_all = case exports of { Nothing -> 1; _ -> 0 } (val_bind_ds, fn_bind_ds, patsyn_ds) = sum3 (map count_bind val_decls) (imp_no, imp_safe, imp_qual, imp_as, imp_all, imp_partial, imp_hiding) = sum7 (map import_info imports) (data_constrs, data_derivs) = sum2 (map data_info tycl_decls) (class_method_ds, default_method_ds) = sum2 (map class_info tycl_decls) (inst_method_ds, method_specs, method_inlines, inst_type_ds, inst_data_ds) = sum5 (map inst_info inst_decls) count_bind (PatBind { pat_lhs = L _ (VarPat _) }) = (1,0,0) count_bind (PatBind {}) = (0,1,0) count_bind (FunBind {}) = (0,1,0) count_bind (PatSynBind {}) = (0,0,1) count_bind b = pprPanic "count_bind: Unhandled binder" (ppr b) count_sigs sigs = sum5 (map sig_info sigs) sig_info (FixSig {}) = (1,0,0,0,0) sig_info (TypeSig {}) = (0,1,0,0,0) sig_info (SpecSig {}) = (0,0,1,0,0) sig_info (InlineSig {}) = (0,0,0,1,0) sig_info (ClassOpSig {}) = (0,0,0,0,1) sig_info _ = (0,0,0,0,0) import_info (L _ (ImportDecl { ideclSafe = safe, ideclQualified = qual , ideclAs = as, ideclHiding = spec })) = add7 (1, safe_info safe, qual_info qual, as_info as, 0,0,0) (spec_info spec) safe_info = qual_info qual_info False = 0 qual_info True = 1 as_info Nothing = 0 as_info (Just _) = 1 spec_info Nothing = (0,0,0,0,1,0,0) spec_info (Just (False, _)) = (0,0,0,0,0,1,0) spec_info (Just (True, _)) = (0,0,0,0,0,0,1) data_info (DataDecl { tcdDataDefn = HsDataDefn { dd_cons = cs , dd_derivs = L _ derivs}}) = ( length cs , foldl' (\s dc -> length (deriv_clause_tys $ unLoc dc) + s) 0 derivs ) data_info _ = (0,0) class_info decl@(ClassDecl {}) = (classops, addpr (sum3 (map count_bind methods))) where methods = map unLoc $ bagToList (tcdMeths decl) (_, classops, _, _, _) = count_sigs (map unLoc (tcdSigs decl)) class_info _ = (0,0) inst_info (TyFamInstD {}) = (0,0,0,1,0) inst_info (DataFamInstD {}) = (0,0,0,0,1) inst_info (ClsInstD { cid_inst = ClsInstDecl {cid_binds = inst_meths , cid_sigs = inst_sigs , cid_tyfam_insts = ats , cid_datafam_insts = adts } }) = case count_sigs (map unLoc inst_sigs) of (_,_,ss,is,_) -> (addpr (sum3 (map count_bind methods)), ss, is, length ats, length adts) where methods = map unLoc $ bagToList inst_meths -- TODO: use Sum monoid addpr :: (Int,Int,Int) -> Int sum2 :: [(Int, Int)] -> (Int, Int) sum3 :: [(Int, Int, Int)] -> (Int, Int, Int) sum5 :: [(Int, Int, Int, Int, Int)] -> (Int, Int, Int, Int, Int) sum7 :: [(Int, Int, Int, Int, Int, Int, Int)] -> (Int, Int, Int, Int, Int, Int, Int) add7 :: (Int, Int, Int, Int, Int, Int, Int) -> (Int, Int, Int, Int, Int, Int, Int) -> (Int, Int, Int, Int, Int, Int, Int) addpr (x,y,z) = x+y+z sum2 = foldr add2 (0,0) where add2 (x1,x2) (y1,y2) = (x1+y1,x2+y2) sum3 = foldr add3 (0,0,0) where add3 (x1,x2,x3) (y1,y2,y3) = (x1+y1,x2+y2,x3+y3) sum5 = foldr add5 (0,0,0,0,0) where add5 (x1,x2,x3,x4,x5) (y1,y2,y3,y4,y5) = (x1+y1,x2+y2,x3+y3,x4+y4,x5+y5) sum7 = foldr add7 (0,0,0,0,0,0,0) add7 (x1,x2,x3,x4,x5,x6,x7) (y1,y2,y3,y4,y5,y6,y7) = (x1+y1,x2+y2,x3+y3,x4+y4,x5+y5,x6+y6,x7+y7)
ezyang/ghc
compiler/main/HscStats.hs
bsd-3-clause
7,090
0
15
2,431
2,597
1,516
1,081
140
24
{-# OPTIONS_GHC -fno-implicit-prelude #-} ----------------------------------------------------------------------------- -- | -- Module : Foreign.C.String -- Copyright : (c) The FFI task force 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : [email protected] -- Stability : provisional -- Portability : portable -- -- Utilities for primitive marshalling of C strings. -- -- The marshalling converts each Haskell character, representing a Unicode -- code point, to one or more bytes in a manner that, by default, is -- determined by the current locale. As a consequence, no guarantees -- can be made about the relative length of a Haskell string and its -- corresponding C string, and therefore all the marshalling routines -- include memory allocation. The translation between Unicode and the -- encoding of the current locale may be lossy. -- ----------------------------------------------------------------------------- module Foreign.C.String ( -- representation of strings in C -- * C strings CString, -- = Ptr CChar CStringLen, -- = (Ptr CChar, Int) -- ** Using a locale-dependent encoding -- | Currently these functions are identical to their @CAString@ counterparts; -- eventually they will use an encoding determined by the current locale. -- conversion of C strings into Haskell strings -- peekCString, -- :: CString -> IO String peekCStringLen, -- :: CStringLen -> IO String -- conversion of Haskell strings into C strings -- newCString, -- :: String -> IO CString newCStringLen, -- :: String -> IO CStringLen -- conversion of Haskell strings into C strings using temporary storage -- withCString, -- :: String -> (CString -> IO a) -> IO a withCStringLen, -- :: String -> (CStringLen -> IO a) -> IO a charIsRepresentable, -- :: Char -> IO Bool -- ** Using 8-bit characters -- | These variants of the above functions are for use with C libraries -- that are ignorant of Unicode. These functions should be used with -- care, as a loss of information can occur. castCharToCChar, -- :: Char -> CChar castCCharToChar, -- :: CChar -> Char peekCAString, -- :: CString -> IO String peekCAStringLen, -- :: CStringLen -> IO String newCAString, -- :: String -> IO CString newCAStringLen, -- :: String -> IO CStringLen withCAString, -- :: String -> (CString -> IO a) -> IO a withCAStringLen, -- :: String -> (CStringLen -> IO a) -> IO a -- * C wide strings -- | These variants of the above functions are for use with C libraries -- that encode Unicode using the C @wchar_t@ type in a system-dependent -- way. The only encodings supported are -- -- * UTF-32 (the C compiler defines @__STDC_ISO_10646__@), or -- -- * UTF-16 (as used on Windows systems). CWString, -- = Ptr CWchar CWStringLen, -- = (Ptr CWchar, Int) peekCWString, -- :: CWString -> IO String peekCWStringLen, -- :: CWStringLen -> IO String newCWString, -- :: String -> IO CWString newCWStringLen, -- :: String -> IO CWStringLen withCWString, -- :: String -> (CWString -> IO a) -> IO a withCWStringLen, -- :: String -> (CWStringLen -> IO a) -> IO a ) where import Foreign.Marshal.Array import Foreign.C.Types import Foreign.Ptr import Foreign.Storable import Data.Word #ifdef __GLASGOW_HASKELL__ import GHC.List import GHC.Real import GHC.Num import GHC.IOBase import GHC.Base #else import Data.Char ( chr, ord ) #define unsafeChr chr #endif ----------------------------------------------------------------------------- -- Strings -- representation of strings in C -- ------------------------------ -- | A C string is a reference to an array of C characters terminated by NUL. type CString = Ptr CChar -- | A string with explicit length information in bytes instead of a -- terminating NUL (allowing NUL characters in the middle of the string). type CStringLen = (Ptr CChar, Int) -- exported functions -- ------------------ -- -- * the following routines apply the default conversion when converting the -- C-land character encoding into the Haskell-land character encoding -- | Marshal a NUL terminated C string into a Haskell string. -- peekCString :: CString -> IO String peekCString = peekCAString -- | Marshal a C string with explicit length into a Haskell string. -- peekCStringLen :: CStringLen -> IO String peekCStringLen = peekCAStringLen -- | Marshal a Haskell string into a NUL terminated C string. -- -- * the Haskell string may /not/ contain any NUL characters -- -- * new storage is allocated for the C string and must be -- explicitly freed using 'Foreign.Marshal.Alloc.free' or -- 'Foreign.Marshal.Alloc.finalizerFree'. -- newCString :: String -> IO CString newCString = newCAString -- | Marshal a Haskell string into a C string (ie, character array) with -- explicit length information. -- -- * new storage is allocated for the C string and must be -- explicitly freed using 'Foreign.Marshal.Alloc.free' or -- 'Foreign.Marshal.Alloc.finalizerFree'. -- newCStringLen :: String -> IO CStringLen newCStringLen = newCAStringLen -- | Marshal a Haskell string into a NUL terminated C string using temporary -- storage. -- -- * the Haskell string may /not/ contain any NUL characters -- -- * the memory is freed when the subcomputation terminates (either -- normally or via an exception), so the pointer to the temporary -- storage must /not/ be used after this. -- withCString :: String -> (CString -> IO a) -> IO a withCString = withCAString -- | Marshal a Haskell string into a C string (ie, character array) -- in temporary storage, with explicit length information. -- -- * the memory is freed when the subcomputation terminates (either -- normally or via an exception), so the pointer to the temporary -- storage must /not/ be used after this. -- withCStringLen :: String -> (CStringLen -> IO a) -> IO a withCStringLen = withCAStringLen -- | Determines whether a character can be accurately encoded in a 'CString'. -- Unrepresentable characters are converted to @\'?\'@. -- -- Currently only Latin-1 characters are representable. charIsRepresentable :: Char -> IO Bool charIsRepresentable c = return (ord c < 256) -- single byte characters -- ---------------------- -- -- ** NOTE: These routines don't handle conversions! ** -- | Convert a C byte, representing a Latin-1 character, to the corresponding -- Haskell character. castCCharToChar :: CChar -> Char castCCharToChar ch = unsafeChr (fromIntegral (fromIntegral ch :: Word8)) -- | Convert a Haskell character to a C character. -- This function is only safe on the first 256 characters. castCharToCChar :: Char -> CChar castCharToCChar ch = fromIntegral (ord ch) -- | Marshal a NUL terminated C string into a Haskell string. -- peekCAString :: CString -> IO String #ifndef __GLASGOW_HASKELL__ peekCAString cp = do cs <- peekArray0 nUL cp return (cCharsToChars cs) #else peekCAString cp = do l <- lengthArray0 nUL cp if l <= 0 then return "" else loop "" (l-1) where loop s i = do xval <- peekElemOff cp i let val = castCCharToChar xval val `seq` if i <= 0 then return (val:s) else loop (val:s) (i-1) #endif -- | Marshal a C string with explicit length into a Haskell string. -- peekCAStringLen :: CStringLen -> IO String #ifndef __GLASGOW_HASKELL__ peekCAStringLen (cp, len) = do cs <- peekArray len cp return (cCharsToChars cs) #else peekCAStringLen (cp, len) | len <= 0 = return "" -- being (too?) nice. | otherwise = loop [] (len-1) where loop acc i = do xval <- peekElemOff cp i let val = castCCharToChar xval -- blow away the coercion ASAP. if (val `seq` (i == 0)) then return (val:acc) else loop (val:acc) (i-1) #endif -- | Marshal a Haskell string into a NUL terminated C string. -- -- * the Haskell string may /not/ contain any NUL characters -- -- * new storage is allocated for the C string and must be -- explicitly freed using 'Foreign.Marshal.Alloc.free' or -- 'Foreign.Marshal.Alloc.finalizerFree'. -- newCAString :: String -> IO CString #ifndef __GLASGOW_HASKELL__ newCAString = newArray0 nUL . charsToCChars #else newCAString str = do ptr <- mallocArray0 (length str) let go [] n = pokeElemOff ptr n nUL go (c:cs) n = do pokeElemOff ptr n (castCharToCChar c); go cs (n+1) go str 0 return ptr #endif -- | Marshal a Haskell string into a C string (ie, character array) with -- explicit length information. -- -- * new storage is allocated for the C string and must be -- explicitly freed using 'Foreign.Marshal.Alloc.free' or -- 'Foreign.Marshal.Alloc.finalizerFree'. -- newCAStringLen :: String -> IO CStringLen #ifndef __GLASGOW_HASKELL__ newCAStringLen str = do a <- newArray (charsToCChars str) return (pairLength str a) #else newCAStringLen str = do ptr <- mallocArray0 len let go [] n = n `seq` return () -- make it strict in n go (c:cs) n = do pokeElemOff ptr n (castCharToCChar c); go cs (n+1) go str 0 return (ptr, len) where len = length str #endif -- | Marshal a Haskell string into a NUL terminated C string using temporary -- storage. -- -- * the Haskell string may /not/ contain any NUL characters -- -- * the memory is freed when the subcomputation terminates (either -- normally or via an exception), so the pointer to the temporary -- storage must /not/ be used after this. -- withCAString :: String -> (CString -> IO a) -> IO a #ifndef __GLASGOW_HASKELL__ withCAString = withArray0 nUL . charsToCChars #else withCAString str f = allocaArray0 (length str) $ \ptr -> let go [] n = pokeElemOff ptr n nUL go (c:cs) n = do pokeElemOff ptr n (castCharToCChar c); go cs (n+1) in do go str 0 f ptr #endif -- | Marshal a Haskell string into a C string (ie, character array) -- in temporary storage, with explicit length information. -- -- * the memory is freed when the subcomputation terminates (either -- normally or via an exception), so the pointer to the temporary -- storage must /not/ be used after this. -- withCAStringLen :: String -> (CStringLen -> IO a) -> IO a #ifndef __GLASGOW_HASKELL__ withCAStringLen str act = withArray (charsToCChars str) $ act . pairLength str #else withCAStringLen str f = allocaArray len $ \ptr -> let go [] n = n `seq` return () -- make it strict in n go (c:cs) n = do pokeElemOff ptr n (castCharToCChar c); go cs (n+1) in do go str 0 f (ptr,len) where len = length str #endif -- auxiliary definitions -- ---------------------- -- C's end of string character -- nUL :: CChar nUL = 0 -- pair a C string with the length of the given Haskell string -- pairLength :: String -> a -> (a, Int) pairLength = flip (,) . length #ifndef __GLASGOW_HASKELL__ -- cast [CChar] to [Char] -- cCharsToChars :: [CChar] -> [Char] cCharsToChars xs = map castCCharToChar xs -- cast [Char] to [CChar] -- charsToCChars :: [Char] -> [CChar] charsToCChars xs = map castCharToCChar xs #endif ----------------------------------------------------------------------------- -- Wide strings -- representation of wide strings in C -- ----------------------------------- -- | A C wide string is a reference to an array of C wide characters -- terminated by NUL. type CWString = Ptr CWchar -- | A wide character string with explicit length information in bytes -- instead of a terminating NUL (allowing NUL characters in the middle -- of the string). type CWStringLen = (Ptr CWchar, Int) -- | Marshal a NUL terminated C wide string into a Haskell string. -- peekCWString :: CWString -> IO String peekCWString cp = do cs <- peekArray0 wNUL cp return (cWcharsToChars cs) -- | Marshal a C wide string with explicit length into a Haskell string. -- peekCWStringLen :: CWStringLen -> IO String peekCWStringLen (cp, len) = do cs <- peekArray len cp return (cWcharsToChars cs) -- | Marshal a Haskell string into a NUL terminated C wide string. -- -- * the Haskell string may /not/ contain any NUL characters -- -- * new storage is allocated for the C wide string and must -- be explicitly freed using 'Foreign.Marshal.Alloc.free' or -- 'Foreign.Marshal.Alloc.finalizerFree'. -- newCWString :: String -> IO CWString newCWString = newArray0 wNUL . charsToCWchars -- | Marshal a Haskell string into a C wide string (ie, wide character array) -- with explicit length information. -- -- * new storage is allocated for the C wide string and must -- be explicitly freed using 'Foreign.Marshal.Alloc.free' or -- 'Foreign.Marshal.Alloc.finalizerFree'. -- newCWStringLen :: String -> IO CWStringLen newCWStringLen str = do a <- newArray (charsToCWchars str) return (pairLength str a) -- | Marshal a Haskell string into a NUL terminated C wide string using -- temporary storage. -- -- * the Haskell string may /not/ contain any NUL characters -- -- * the memory is freed when the subcomputation terminates (either -- normally or via an exception), so the pointer to the temporary -- storage must /not/ be used after this. -- withCWString :: String -> (CWString -> IO a) -> IO a withCWString = withArray0 wNUL . charsToCWchars -- | Marshal a Haskell string into a NUL terminated C wide string using -- temporary storage. -- -- * the Haskell string may /not/ contain any NUL characters -- -- * the memory is freed when the subcomputation terminates (either -- normally or via an exception), so the pointer to the temporary -- storage must /not/ be used after this. -- withCWStringLen :: String -> (CWStringLen -> IO a) -> IO a withCWStringLen str act = withArray (charsToCWchars str) $ act . pairLength str -- auxiliary definitions -- ---------------------- wNUL :: CWchar wNUL = 0 cWcharsToChars :: [CWchar] -> [Char] charsToCWchars :: [Char] -> [CWchar] #ifdef mingw32_HOST_OS -- On Windows, wchar_t is 16 bits wide and CWString uses the UTF-16 encoding. -- coding errors generate Chars in the surrogate range cWcharsToChars = map chr . fromUTF16 . map fromIntegral where fromUTF16 (c1:c2:wcs) | 0xd800 <= c1 && c1 <= 0xdbff && 0xdc00 <= c2 && c2 <= 0xdfff = ((c1 - 0xd800)*0x400 + (c2 - 0xdc00) + 0x10000) : fromUTF16 wcs fromUTF16 (c:wcs) = c : fromUTF16 wcs fromUTF16 [] = [] charsToCWchars = foldr utf16Char [] . map ord where utf16Char c wcs | c < 0x10000 = fromIntegral c : wcs | otherwise = let c' = c - 0x10000 in fromIntegral (c' `div` 0x400 + 0xd800) : fromIntegral (c' `mod` 0x400 + 0xdc00) : wcs #else /* !mingw32_HOST_OS */ cWcharsToChars xs = map castCWcharToChar xs charsToCWchars xs = map castCharToCWchar xs -- These conversions only make sense if __STDC_ISO_10646__ is defined -- (meaning that wchar_t is ISO 10646, aka Unicode) castCWcharToChar :: CWchar -> Char castCWcharToChar ch = chr (fromIntegral ch ) castCharToCWchar :: Char -> CWchar castCharToCWchar ch = fromIntegral (ord ch) #endif /* !mingw32_HOST_OS */
alekar/hugs
packages/base/Foreign/C/String.hs
bsd-3-clause
15,152
0
16
3,132
1,579
938
641
109
1
module PL where import PL.Type import PL.Struktur import PL.Interpretation import PL.Semantik
Erdwolf/autotool-bonn
src/PL.hs
gpl-2.0
102
0
4
19
24
15
9
5
0
{-# LANGUAGE DataKinds #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE ImpredicativeTypes #-} {-# LANGUAGE ScopedTypeVariables#-} module Main where import OpenCog.AtomSpace import OpenCog.Lojban import Control.Concurrent import Control.Monad import Control.Monad.IO.Class import Control.Exception import System.Process main :: IO () main = do (parser,printer) <- initParserPrinter "lojban.xml" mainloop parser printer --camxesPath = "/home/roman/OpenCog/Lojban/ilmentufa" mainloop parser printer = do putStrLn "Please Input some Lojban to Translate" input <- getLine {-let args = "run_camxes.js -std -m N \"" ++ input ++ "\"" camxesres <- readCreateProcess (shell $ "node " ++ args){cwd = Just camxesPath ,std_out = CreatePipe} "" putStrLn camxesres-} let res = parser input case res of Just x -> printAtom x Nothing -> putStrLn "Parseing Failed." mainloop parser printer {-case res of Left _ -> mainloop parser printer Right atom -> do (res2 :: Either SomeException String) <- try $ printer atom print res2 mainloop parser printer -}
ruiting/opencog
opencog/nlp/lojban/HaskellLib/app/Main.hs
agpl-3.0
1,259
0
10
325
160
84
76
26
2
module Text.Blaze.Html.Renderer.Utf8 ( renderHtmlBuilder , renderHtml , renderHtmlToByteStringIO ) where import Blaze.ByteString.Builder (Builder) import Data.ByteString (ByteString) import Text.Blaze.Html (Html) import qualified Data.ByteString.Lazy as BL import qualified Text.Blaze.Renderer.Utf8 as R renderHtmlBuilder :: Html -> Builder renderHtmlBuilder = R.renderMarkupBuilder renderHtml :: Html -> BL.ByteString renderHtml = R.renderMarkup renderHtmlToByteStringIO :: (ByteString -> IO ()) -> Html -> IO () renderHtmlToByteStringIO = R.renderMarkupToByteStringIO
iblech/blaze-html
src/Text/Blaze/Html/Renderer/Utf8.hs
bsd-3-clause
590
0
9
79
142
87
55
15
1
{-# LANGUAGE UnicodeSyntax #-} {-# LANGUAGE Arrows #-} {-# LANGUAGE ExplicitForAll #-} {-# LANGUAGE KindSignatures #-} module Simple1 where foo ∷ ∀ a. Eq (a ∷ ★) ⇒ a → IO () foo _ = do i ← return () return i bar x = proc x → id ⤙ x + 1 baz x = proc x → id ⤛ x + 1 bar' x = proc x → x + 1 ⤚ id baz' x = proc x → x + 1 ⤜ id main ∷ IO () main = putStrLn "Hello World!"
siddhanathan/yi
yi-mode-haskell/test/test_data/Simple1Unicode.hs
gpl-2.0
406
12
9
103
178
88
90
-1
-1
yes = foo ((x y), z)
mpickering/hlint-refactor
tests/examples/Bracket11.hs
bsd-3-clause
20
0
8
5
21
11
10
1
1
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="el-GR"> <title>Alert Filters | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
kingthorin/zap-extensions
addOns/alertFilters/src/main/javahelp/org/zaproxy/zap/extension/alertFilters/resources/help_el_GR/helpset_el_GR.hs
apache-2.0
974
78
66
159
413
209
204
-1
-1
{-# LANGUAGE DeriveDataTypeable, PatternGuards, FlexibleInstances, MultiParamTypeClasses, CPP #-} ----------------------------------------------------------------------------- -- | -- Module : XMonad.Hooks.ManageDocks -- Copyright : (c) Joachim Breitner <[email protected]> -- License : BSD -- -- Maintainer : Joachim Breitner <[email protected]> -- Stability : unstable -- Portability : unportable -- -- This module provides tools to automatically manage 'dock' type programs, -- such as gnome-panel, kicker, dzen, and xmobar. module XMonad.Hooks.ManageDocks ( -- * Usage -- $usage manageDocks, checkDock, AvoidStruts, avoidStruts, avoidStrutsOn, docksEventHook, ToggleStruts(..), SetStruts(..), module XMonad.Util.Types, #ifdef TESTING r2c, c2r, RectC(..), #endif -- for XMonad.Actions.FloatSnap calcGap ) where ----------------------------------------------------------------------------- import XMonad import Foreign.C.Types (CLong) import XMonad.Layout.LayoutModifier import XMonad.Util.Types import XMonad.Util.WindowProperties (getProp32s) import XMonad.Util.XUtils (fi) import Data.Monoid (All(..), mempty) import qualified Data.Set as S -- $usage -- To use this module, add the following import to @~\/.xmonad\/xmonad.hs@: -- -- > import XMonad.Hooks.ManageDocks -- -- The first component is a 'ManageHook' which recognizes these -- windows and de-manages them, so that xmonad does not try to tile -- them. To enable it: -- -- > manageHook = ... <+> manageDocks -- -- The second component is a layout modifier that prevents windows -- from overlapping these dock windows. It is intended to replace -- xmonad's so-called \"gap\" support. First, you must add it to your -- list of layouts: -- -- > layoutHook = avoidStruts (tall ||| mirror tall ||| ...) -- > where tall = Tall 1 (3/100) (1/2) -- -- The third component is an event hook that causes new docks to appear -- immediately, instead of waiting for the next focus change. -- -- > handleEventHook = ... <+> docksEventHook -- -- 'AvoidStruts' also supports toggling the dock gaps; add a keybinding -- similar to: -- -- > ,((modm, xK_b ), sendMessage ToggleStruts) -- -- If you have multiple docks, you can toggle their gaps individually. -- For example, to toggle only the top gap: -- -- > ,((modm .|. controlMask, xK_t), sendMessage $ ToggleStrut U) -- -- Similarly, you can use 'D', 'L', and 'R' to individually toggle -- gaps on the bottom, left, or right. -- -- If you want certain docks to be avoided but others to be covered by -- default, you can manually specify the sides of the screen on which -- docks should be avoided, using 'avoidStrutsOn'. For example: -- -- > layoutHook = avoidStrutsOn [U,L] (tall ||| mirror tall ||| ...) -- -- /Important note/: if you are switching from manual gaps -- (defaultGaps in your config) to avoidStruts (recommended, since -- manual gaps will probably be phased out soon), be sure to switch -- off all your gaps (with mod-b) /before/ reloading your config with -- avoidStruts! Toggling struts with a 'ToggleStruts' message will -- not work unless your gaps are set to zero. -- -- For detailed instructions on editing your key bindings, see -- "XMonad.Doc.Extending#Editing_key_bindings". -- -- | Detects if the given window is of type DOCK and if so, reveals -- it, but does not manage it. manageDocks :: ManageHook manageDocks = checkDock --> (doIgnore <+> clearGapCache) where clearGapCache = do liftX (broadcastMessage ClearGapCache) mempty -- | Checks if a window is a DOCK or DESKTOP window checkDock :: Query Bool checkDock = ask >>= \w -> liftX $ do dock <- getAtom "_NET_WM_WINDOW_TYPE_DOCK" desk <- getAtom "_NET_WM_WINDOW_TYPE_DESKTOP" mbr <- getProp32s "_NET_WM_WINDOW_TYPE" w case mbr of Just rs -> return $ any (`elem` [dock,desk]) (map fromIntegral rs) _ -> return False -- | Whenever a new dock appears, refresh the layout immediately to avoid the -- new dock. docksEventHook :: Event -> X All docksEventHook (MapNotifyEvent {ev_window = w}) = do whenX ((not `fmap` (isClient w)) <&&> runQuery checkDock w) $ do broadcastMessage ClearGapCache refresh return (All True) docksEventHook _ = return (All True) -- | Gets the STRUT config, if present, in xmonad gap order getStrut :: Window -> X [Strut] getStrut w = do msp <- getProp32s "_NET_WM_STRUT_PARTIAL" w case msp of Just sp -> return $ parseStrutPartial sp Nothing -> fmap (maybe [] parseStrut) $ getProp32s "_NET_WM_STRUT" w where parseStrut xs@[_, _, _, _] = parseStrutPartial . take 12 $ xs ++ cycle [minBound, maxBound] parseStrut _ = [] parseStrutPartial [l, r, t, b, ly1, ly2, ry1, ry2, tx1, tx2, bx1, bx2] = filter (\(_, n, _, _) -> n /= 0) [(L, l, ly1, ly2), (R, r, ry1, ry2), (U, t, tx1, tx2), (D, b, bx1, bx2)] parseStrutPartial _ = [] -- | Goes through the list of windows and find the gap so that all -- STRUT settings are satisfied. calcGap :: S.Set Direction2D -> X (Rectangle -> Rectangle) calcGap ss = withDisplay $ \dpy -> do rootw <- asks theRoot -- We don't keep track of dock like windows, so we find all of them here (_,_,wins) <- io $ queryTree dpy rootw struts <- (filter careAbout . concat) `fmap` mapM getStrut wins -- we grab the window attributes of the root window rather than checking -- the width of the screen because xlib caches this info and it tends to -- be incorrect after RAndR wa <- io $ getWindowAttributes dpy rootw let screen = r2c $ Rectangle (fi $ wa_x wa) (fi $ wa_y wa) (fi $ wa_width wa) (fi $ wa_height wa) return $ \r -> c2r $ foldr (reduce screen) (r2c r) struts where careAbout (s,_,_,_) = s `S.member` ss -- | Adjust layout automagically: don't cover up any docks, status -- bars, etc. avoidStruts :: LayoutClass l a => l a -> ModifiedLayout AvoidStruts l a avoidStruts = avoidStrutsOn [U,D,L,R] -- | Adjust layout automagically: don't cover up docks, status bars, -- etc. on the indicated sides of the screen. Valid sides are U -- (top), D (bottom), R (right), or L (left). avoidStrutsOn :: LayoutClass l a => [Direction2D] -> l a -> ModifiedLayout AvoidStruts l a avoidStrutsOn ss = ModifiedLayout $ AvoidStruts (S.fromList ss) Nothing data AvoidStruts a = AvoidStruts { avoidStrutsDirection :: S.Set Direction2D, avoidStrutsRectCache :: Maybe (S.Set Direction2D, Rectangle, Rectangle ) } deriving ( Read, Show ) -- | Message type which can be sent to an 'AvoidStruts' layout -- modifier to alter its behavior. data ToggleStruts = ToggleStruts | ToggleStrut Direction2D deriving (Read,Show,Typeable) instance Message ToggleStruts -- | message sent to ensure that caching the gaps won't give a wrong result -- because a new dock has been added data ClearGapCache = ClearGapCache deriving (Read,Show,Typeable) instance Message ClearGapCache -- | SetStruts is a message constructor used to set or unset specific struts, -- regardless of whether or not the struts were originally set. Here are some -- example bindings: -- -- Show all gaps: -- -- > ,((modm .|. shiftMask ,xK_b),sendMessage $ SetStruts [minBound .. maxBound] []) -- -- Hide all gaps: -- -- > ,((modm .|. controlMask,xK_b),sendMessage $ SetStruts [] [minBound .. maxBound]) -- -- Show only upper and left gaps: -- -- > ,((modm .|. controlMask .|. shiftMask,xK_b),sendMessage $ SetStruts [U,L] [minBound .. maxBound]) -- -- Hide the bottom keeping whatever the other values were: -- -- > ,((modm .|. controlMask .|. shiftMask,xK_g),sendMessage $ SetStruts [] [D]) data SetStruts = SetStruts { addedStruts :: [Direction2D] , removedStruts :: [Direction2D] -- ^ These are removed from the currently set struts before 'addedStruts' are added. } deriving (Read,Show,Typeable) instance Message SetStruts instance LayoutModifier AvoidStruts a where modifyLayoutWithUpdate as@(AvoidStruts ss cache) w r = do nr <- case cache of Just (ss', r', nr) | ss' == ss, r' == r -> return nr _ -> do nr <- fmap ($ r) (calcGap ss) setWorkarea nr return nr arranged <- runLayout w nr let newCache = Just (ss, r, nr) return (arranged, if newCache == cache then Nothing else Just as{ avoidStrutsRectCache = newCache } ) pureMess as@(AvoidStruts { avoidStrutsDirection = ss }) m | Just ToggleStruts <- fromMessage m = Just $ as { avoidStrutsDirection = toggleAll ss } | Just (ToggleStrut s) <- fromMessage m = Just $ as { avoidStrutsDirection = toggleOne s ss } | Just (SetStruts n k) <- fromMessage m , let newSS = S.fromList n `S.union` (ss S.\\ S.fromList k) , newSS /= ss = Just $ as { avoidStrutsDirection = newSS } | Just ClearGapCache <- fromMessage m = Just $ as { avoidStrutsRectCache = Nothing } | otherwise = Nothing where toggleAll x | S.null x = S.fromList [minBound .. maxBound] | otherwise = S.empty toggleOne x xs | x `S.member` xs = S.delete x xs | otherwise = x `S.insert` xs setWorkarea :: Rectangle -> X () setWorkarea (Rectangle x y w h) = withDisplay $ \dpy -> do a <- getAtom "_NET_WORKAREA" c <- getAtom "CARDINAL" r <- asks theRoot io $ changeProperty32 dpy r a c propModeReplace [fi x, fi y, fi w, fi h] -- | (Direction, height\/width, initial pixel, final pixel). type Strut = (Direction2D, CLong, CLong, CLong) -- | (Initial x pixel, initial y pixel, -- final x pixel, final y pixel). newtype RectC = RectC (CLong, CLong, CLong, CLong) deriving (Eq,Show) -- | Invertible conversion. r2c :: Rectangle -> RectC r2c (Rectangle x y w h) = RectC (fi x, fi y, fi x + fi w - 1, fi y + fi h - 1) -- | Invertible conversion. c2r :: RectC -> Rectangle c2r (RectC (x1, y1, x2, y2)) = Rectangle (fi x1) (fi y1) (fi $ x2 - x1 + 1) (fi $ y2 - y1 + 1) reduce :: RectC -> Strut -> RectC -> RectC reduce (RectC (sx0, sy0, sx1, sy1)) (s, n, l, h) (RectC (x0, y0, x1, y1)) = RectC $ case s of L | p (y0, y1) && qh x1 -> (mx x0 sx0, y0 , x1 , y1 ) R | p (y0, y1) && qv sx1 x0 -> (x0 , y0 , mn x1 sx1, y1 ) U | p (x0, x1) && qh y1 -> (x0 , mx y0 sy0, x1 , y1 ) D | p (x0, x1) && qv sy1 y0 -> (x0 , y0 , x1 , mn y1 sy1) _ -> (x0 , y0 , x1 , y1 ) where mx a b = max a (b + n) mn a b = min a (b - n) p r = r `overlaps` (l, h) -- Filter out struts that cover the entire rectangle: qh d1 = n <= d1 qv sd1 d0 = sd1 - n >= d0 -- | Do the two ranges overlap? -- -- Precondition for every input range @(x, y)@: @x '<=' y@. -- -- A range @(x, y)@ is assumed to include every pixel from @x@ to @y@. overlaps :: Ord a => (a, a) -> (a, a) -> Bool (a, b) `overlaps` (x, y) = inRange (a, b) x || inRange (a, b) y || inRange (x, y) a where inRange (i, j) k = i <= k && k <= j
pjones/xmonad-test
vendor/xmonad-contrib/XMonad/Hooks/ManageDocks.hs
bsd-2-clause
11,313
0
17
2,765
2,678
1,469
1,209
133
5
module FunDep4 where class A e a | a->e where a :: a->a; e :: a->e class B a where b :: a->a class (A e a,B a) => C e a instance (A e a,B a) => C e a f :: C e a => a->a f x = a (b x)
forste/haReFork
tools/base/tests/FunDep4.hs
bsd-3-clause
187
0
7
58
145
75
70
-1
-1
-- Based on https://github.com/idris-lang/Idris-dev/blob/v0.9.10/libs/effects/Effects.idr {-# LANGUAGE TypeInType, ScopedTypeVariables, TypeOperators, TypeApplications, GADTs, TypeFamilies, AllowAmbiguousTypes #-} module T12442 where import Data.Kind data family Sing (a :: k) data TyFun :: Type -> Type -> Type type a ~> b = TyFun a b -> Type infixr 0 ~> type family (a :: k1 ~> k2) @@ (b :: k1) :: k2 data TyCon1 :: (Type -> Type) -> (Type ~> Type) type instance (TyCon1 t) @@ x = t x data TyCon2 :: (Type -> Type -> Type) -> (Type ~> Type ~> Type) type instance (TyCon2 t) @@ x = (TyCon1 (t x)) data TyCon3 :: (Type -> Type -> Type -> Type) -> (Type ~> Type ~> Type ~> Type) type instance (TyCon3 t) @@ x = (TyCon2 (t x)) type Effect = Type ~> Type ~> Type ~> Type data EFFECT :: Type where MkEff :: Type -> Effect -> EFFECT data EffElem :: (Type ~> Type ~> Type ~> Type) -> Type -> [EFFECT] -> Type where Here :: EffElem x a (MkEff a x ': xs) data instance Sing (elem :: EffElem x a xs) where SHere :: Sing Here type family UpdateResTy b t (xs :: [EFFECT]) (elem :: EffElem e a xs) (thing :: e @@ a @@ b @@ t) :: [EFFECT] where UpdateResTy b _ (MkEff a e ': xs) Here n = MkEff b e ': xs data EffM :: (Type ~> Type) -> [EFFECT] -> [EFFECT] -> Type -> Type effect :: forall e a b t xs prf eff m. Sing (prf :: EffElem e a xs) -> Sing (eff :: e @@ a @@ b @@ t) -> EffM m xs (UpdateResTy b t xs prf eff) t effect = undefined data State :: Type -> Type -> Type -> Type where Get :: State a a a data instance Sing (e :: State a b c) where SGet :: Sing Get type STATE t = MkEff t (TyCon3 State) get_ :: forall m x. EffM m '[STATE x] '[STATE x] x get_ = effect @(TyCon3 State) SHere SGet
olsner/ghc
testsuite/tests/dependent/should_compile/T12442.hs
bsd-3-clause
1,774
3
13
441
755
424
331
-1
-1
-- | Configuration of compiler behaviour that is universal to all backends. module Futhark.Compiler.Config ( FutharkConfig (..), newFutharkConfig, Verbosity (..), ) where import Futhark.IR import Futhark.Pipeline -- | The compiler configuration. This only contains options related -- to core compiler functionality, such as reading the initial program -- and running passes. Options related to code generation are handled -- elsewhere. data FutharkConfig = FutharkConfig { futharkVerbose :: (Verbosity, Maybe FilePath), -- | Warn if True. futharkWarn :: Bool, -- | If true, error on any warnings. futharkWerror :: Bool, -- | If True, ignore @unsafe@. futharkSafe :: Bool, -- | Additional functions that should be exposed as entry points. futharkEntryPoints :: [Name], -- | If false, disable type-checking futharkTypeCheck :: Bool } -- | The default compiler configuration. newFutharkConfig :: FutharkConfig newFutharkConfig = FutharkConfig { futharkVerbose = (NotVerbose, Nothing), futharkWarn = True, futharkWerror = False, futharkSafe = False, futharkEntryPoints = [], futharkTypeCheck = True }
diku-dk/futhark
src/Futhark/Compiler/Config.hs
isc
1,198
0
10
256
161
108
53
22
1
{-# LANGUAGE OverloadedStrings #-} module Main where import Control.Applicative (optional, (<$>)) import Control.Monad.IO.Class import Data.List import Data.Maybe (fromMaybe, isJust, fromJust) import Data.Monoid import Data.Either import Data.Text (Text) import Data.Text.Lazy (unpack) import Data.Char import System.Environment import DataTypes import Happstack.Lite import Parsers import Paths_lambek_monad import Text.XHtml.Strict import TP import XHTML import Evaluator import Control.Concurrent import Control.Concurrent.MVar -- for development import System.Exit data Resources = Resources { lexicon :: String , css_style :: Html , proofs :: [BinTree DecoratedSequent] , sentence :: String , model :: String , readings :: [String] , error_msg :: Maybe String , baseDir :: String , day :: String , dayNotes :: String , modelPref :: String } day1Example = "John loves Mary => s" day2Example = "JLH COMMA the bluesman from Tennessee appeared_in TBB => <ci>s" day3Example = "John does not believe Hesperus is Phosphorus => <p>s" day4Example = "Spain will_beat Germany and Nigeria will_beat Canada => <pr>s" day5Example = "Nigeria will_beat motherfucking Canada => <ci><pr>s" main = do args <- getArgs p <- return $ case args of [] -> 8000 (p : _) -> read p serve (Just defaultServerConfig{port = p}) homePage loadResources :: String -> String -> String -> String -> String -> String -> String -> IO Resources loadResources lexiconFile modelFile baseDir example day notesFile modelPrefFile = do lexFile <- getDataFileName lexiconFile cssFile <- getDataFileName "data/style.css" modelFile <- getDataFileName modelFile notesFile <- getDataFileName notesFile lex <- readFile lexFile -- >> \s -> return $ parseLexicon s m <- readFile modelFile css <- readFile cssFile >>= \s -> return $ primHtml s notes <- readFile notesFile return $ Resources lex css [] example m [] Nothing baseDir day notes modelPrefFile pageTemplate :: Resources -> Html pageTemplate res = header << style << css_style res +++ body << navigation +++ titleArea res +++ notesArea res +++ inputAreaTemplate res +++ hr +++ proofsAreaTemplate res titleArea res = h1 (primHtml $ day res) inputAreaTemplate :: Resources -> Html inputAreaTemplate res = cont << (lexiconForm res +++ modelForm res +++ sentenceForm res) where cont = form ! [ theclass "input" , action "." -- (baseDir res) , enctype "multipart/form-data" , Text.XHtml.Strict.method "POST" ] lexiconForm :: Resources -> Html lexiconForm res = h1 (primHtml "Lexicon") +++ textarea ! [ theclass "mono_textarea" , name "lexicon" , rows "20" , cols "80" ] << primHtml (Main.lexicon res) sentenceForm :: Resources -> Html sentenceForm res = h1 (primHtml "Sentence to parse") +++ textarea ! [ theclass "mono_textarea" , thetype "text" , name "sentence" , rows "1" , cols "80"] << primHtml (sentence res) +++ input ! [ thetype "submit" , name "submit" , theclass "mybutton" , value "Parse" ] notesArea :: Resources -> Html notesArea res = h1 (primHtml "Notes") +++ thediv ! [ theclass "notesArea" ] << primHtml (dayNotes res) modelForm :: Resources -> Html modelForm res = h1 (primHtml "Model") +++ textarea ! [ theclass "mono_textarea" , name "model" , rows "20" , cols "80" ] << primHtml (model res) proofsAreaTemplate :: Resources -> Html proofsAreaTemplate res | isJust (error_msg res) = (h1 << primHtml "Error:") +++ pre << primHtml (fromJust $ error_msg res) | otherwise = proofsTitle +++ ps where proofsTitle = h3 << (primHtml $ (show $ length $ Main.proofs res) ++ " proof(s) for \"" ++ (cleanUpSentence $ sentence res) ++"\"" ) ps = mconcat $ map f $ zip3 (Main.proofs res) (readings res) [1..] cleanUpSentence s = reverse $ dropWhile isSpace $ reverse $ takeWhile (/= '=') s f (p,i,n) = thediv ! [ theclass "proofgroup" ] << (h3 ! [ theclass "prooftitle" ] << (primHtml $ "Proof " ++ show n)) +++ (lterm p +++ reading i +++ proof p) where proof p = thediv ! [ theclass "proof" ] << proof2html p lterm p = thediv ! [ theclass "reading" ] << paragraph << (lambda2html . betaReduce . monadReduce . etaReduce . term . snd . getVal) p reading i = thediv ! [ theclass "model_evaluation_result" ] << pre << primHtml i navigation :: Html navigation = thediv ! [Text.XHtml.Strict.identifier "navcontainer"] << ulist << (li << anchor ! [href "../day1/"] << primHtml "Day 1" +++ li << anchor ! [href "../day2/"] << primHtml "Day 2" +++ li << anchor ! [href "../day3/"] << primHtml "Day 3" +++ li << anchor ! [href "../day4/"] << primHtml "Day 4" +++ li << anchor ! [href "../day5/"] << primHtml "Day 5") homePage :: ServerPart Response homePage = msum [ dir "day1" day1 , dir "day2" day2 , dir "day3" day3 , dir "day4" day4 , dir "day5" day5 , day1 ] where day lexiconFile modelFile baseDir example day notesFile modelPrefFile= do res <- liftIO $ loadResources lexiconFile modelFile baseDir example day notesFile modelPrefFile msum [viewForm res, processForm res] day1 = day "data/day1_lexicon" "data/day1_model" "day1/" day1Example "Day 1" "data/day1_notes.html" "data/model_prefix" day2 = day "data/day2_lexicon" "data/day2_model" "day2/" day2Example "Day 2" "data/day2_notes.html" "data/model_prefix" day3 = day "data/day3_lexicon" "data/day3_model" "day3/" day3Example "Day 3" "data/day3_notes.html" "data/model_prefix" day4 = day "data/day4_lexicon" "data/day4_model" "day4/" day4Example "Day 4" "data/day4_notes.html" "data/model_prefix_with_db" day5 = day "data/day5_lexicon" "data/day5_model" "day5/" day5Example "Day 5" "data/day5_notes.html" "data/model_prefix_with_db" viewForm :: Resources -> ServerPart Response viewForm res = do Happstack.Lite.method GET ok $ toResponse $ pageTemplate res processForm :: Resources -> ServerPart Response processForm res = do Happstack.Lite.method [GET,POST] raw_lex <- lookText "lexicon" sent <- lookText "sentence" m <- lookText "model" lex <- return $ parseLexicon $ unpack raw_lex -- we verify the lexicon if Main.isLeft lex then ok $ toResponse $ pageTemplate res{ Main.lexicon = unpack raw_lex, Main.proofs = [], sentence= unpack sent, model = unpack m, readings = [], error_msg = Just $ fromLeft lex} else do seq <- return $ parseSequent (unpack sent) $ fromRight lex -- we verify the sequent if Main.isLeft seq then ok $ toResponse $ pageTemplate res{ Main.lexicon = unpack raw_lex, Main.proofs = [], sentence= unpack sent, model = unpack m, readings = [], error_msg = Just $ fromLeft seq} else do ps <- return $ evaluateState (toDecoratedWithConstants (fromRight seq) >>= \(ds,m) -> TP.proofs ds >>= \p -> return $ replaceWithConstants p m) startState ps <- return $ nubByShortest (lambdaTermLength . term . snd . getVal) (\x y -> simplifiedEquivalentDecoratedSequent (getVal x) (getVal y)) $ map sanitizeVars ps rs <- mapM (\p -> liftIO $ performEvaluation (unpack m) (modelPref res) (term $ snd $ getVal p)) ps ok $ toResponse $ pageTemplate res{ Main.lexicon = unpack raw_lex, Main.proofs = ps, sentence= unpack sent, model = unpack m, readings = rs} -- |This function performs the evaluation in a different thread, hopefully overcoming the problems with hint performEvaluation :: String -> String -> LambdaTerm -> IO String performEvaluation model modelPrefFile term = do storage <- newEmptyMVar forkIO $ do s <- evaluate model modelPrefFile term putMVar storage s readMVar storage fromLeft :: Either a b -> a fromLeft (Left a) = a fromRight :: Either a b -> b fromRight (Right b) = b lambdaTermLength :: LambdaTerm -> Int lambdaTermLength (V _) = 1 lambdaTermLength (C _) = 1 lambdaTermLength (Lambda x t) = lambdaTermLength x + lambdaTermLength t lambdaTermLength (App f x) = lambdaTermLength f + lambdaTermLength x lambdaTermLength (Eta _ t) = 1 + lambdaTermLength t lambdaTermLength (Bind _ m k) = lambdaTermLength m + lambdaTermLength k lambdaTermLength (Pair a b) = lambdaTermLength a + lambdaTermLength b lambdaTermLength (FirstProjection a) = 1 + lambdaTermLength a lambdaTermLength (SecondProjection a) = 1 + lambdaTermLength a nubByShortest :: Eq a => (a -> Int) -> (a -> a -> Bool) -> [a] -> [a] nubByShortest len eq l = aux l [] where aux [] acc = acc aux (a : as) acc = case find (eq a) acc of Nothing -> aux as (a : acc) Just a' -> case len a < len a' of False -> aux as acc True -> aux as (a : delete a' acc) isLeft :: Either a b -> Bool isLeft (Left _) = True isLeft _ = False
gianlucagiorgolo/lambek-monad
Main.hs
mit
10,062
0
26
3,102
2,911
1,468
1,443
-1
-1
module ParseSpec (spec) where import Test.Hspec import Test.QuickCheck import Parse (parse) import LambdaWithSynonyms instance Arbitrary Expr' where arbitrary = do n <- choose (0, 3) :: Gen Int case n of 0 -> do name <- possibleNames return $ V' name 1 -> do name <- possibleSynonyms return $ S' name 2 -> do name <- possibleNames expr <- arbitrary return $ L' name expr _ -> do expr <- arbitrary expr' <- arbitrary name <- possibleNames return $ Ap' (L' name expr) expr' where possibleNames = elements ['a'..'z'] possibleSynonyms = elements $ ['A'..'Z'] ++ ['0'..'9'] replace :: Char -> Char -> String -> String replace x y = fmap (\c -> if c == x then y else c) spec :: SpecWith () spec = describe "Parsing" $ do it "should be able to parse a shown arbitrary expression back to the same form" $ property $ \expr -> parse (show expr) === Right (expr :: Expr') it "should accept \\ instead of λ, cause, come-on.. who can really type that?" $ property $ \expr -> let shown = replace 'λ' '\\' $ show expr in parse shown === Right (expr :: Expr')
hughfdjackson/abattoir
test/ParseSpec.hs
mit
1,236
0
16
384
406
201
205
31
2
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE CPP #-} module Yesod.Content ( -- * Content Content (..) , emptyContent , ToContent (..) -- * Mime types -- ** Data type , ContentType , typeHtml , typePlain , typeJson , typeXml , typeAtom , typeRss , typeJpeg , typePng , typeGif , typeSvg , typeJavascript , typeCss , typeFlv , typeOgv , typeOctet -- * Utilities , simpleContentType -- * Evaluation strategy , DontFullyEvaluate (..) -- * Representations , ChooseRep , HasReps (..) , defChooseRep -- ** Specific content types , RepHtml (..) , RepJson (..) , RepHtmlJson (..) , RepPlain (..) , RepXml (..) -- * Utilities , formatW3 , formatRFC1123 , formatRFC822 ) where import Data.Maybe (mapMaybe) import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as L import Data.Text.Lazy (Text, pack) import qualified Data.Text as T import Data.Time import System.Locale import qualified Data.Text.Encoding import qualified Data.Text.Lazy.Encoding import Blaze.ByteString.Builder (Builder, fromByteString, fromLazyByteString) import Data.Monoid (mempty) import Text.Hamlet (Html) import Text.Blaze.Html.Renderer.Utf8 (renderHtmlBuilder) import Data.String (IsString (fromString)) import Network.Wai (FilePart) import Data.Conduit (Source, ResourceT, Flush) data Content = ContentBuilder !Builder !(Maybe Int) -- ^ The content and optional content length. | ContentSource !(Source (ResourceT IO) (Flush Builder)) | ContentFile !FilePath !(Maybe FilePart) | ContentDontEvaluate !Content -- | Zero-length enumerator. emptyContent :: Content emptyContent = ContentBuilder mempty $ Just 0 instance IsString Content where fromString = toContent -- | Anything which can be converted into 'Content'. Most of the time, you will -- want to use the 'ContentBuilder' constructor. An easier approach will be to use -- a pre-defined 'toContent' function, such as converting your data into a lazy -- bytestring and then calling 'toContent' on that. -- -- Please note that the built-in instances for lazy data structures ('String', -- lazy 'L.ByteString', lazy 'Text' and 'Html') will not automatically include -- the content length for the 'ContentBuilder' constructor. class ToContent a where toContent :: a -> Content instance ToContent Builder where toContent = flip ContentBuilder Nothing instance ToContent B.ByteString where toContent bs = ContentBuilder (fromByteString bs) $ Just $ B.length bs instance ToContent L.ByteString where toContent = flip ContentBuilder Nothing . fromLazyByteString instance ToContent T.Text where toContent = toContent . Data.Text.Encoding.encodeUtf8 instance ToContent Text where toContent = toContent . Data.Text.Lazy.Encoding.encodeUtf8 instance ToContent String where toContent = toContent . pack instance ToContent Html where toContent bs = ContentBuilder (renderHtmlBuilder bs) Nothing -- | A function which gives targetted representations of content based on the -- content-types the user accepts. type ChooseRep = [ContentType] -- ^ list of content-types user accepts, ordered by preference -> IO (ContentType, Content) -- | Any type which can be converted to representations. class HasReps a where chooseRep :: a -> ChooseRep -- | A helper method for generating 'HasReps' instances. -- -- This function should be given a list of pairs of content type and conversion -- functions. If none of the content types match, the first pair is used. defChooseRep :: [(ContentType, a -> IO Content)] -> a -> ChooseRep defChooseRep reps a ts = do let (ct, c) = case mapMaybe helper ts of (x:_) -> x [] -> case reps of [] -> error "Empty reps to defChooseRep" (x:_) -> x c' <- c a return (ct, c') where helper ct = do c <- lookup ct reps return (ct, c) instance HasReps ChooseRep where chooseRep = id instance HasReps () where chooseRep = defChooseRep [(typePlain, const $ return $ toContent B.empty)] instance HasReps (ContentType, Content) where chooseRep = const . return instance HasReps [(ContentType, Content)] where chooseRep a cts = return $ case filter (\(ct, _) -> go ct `elem` map go cts) a of ((ct, c):_) -> (ct, c) _ -> case a of (x:_) -> x _ -> error "chooseRep [(ContentType, Content)] of empty" where go = simpleContentType newtype RepHtml = RepHtml Content instance HasReps RepHtml where chooseRep (RepHtml c) _ = return (typeHtml, c) newtype RepJson = RepJson Content instance HasReps RepJson where chooseRep (RepJson c) _ = return (typeJson, c) data RepHtmlJson = RepHtmlJson Content Content instance HasReps RepHtmlJson where chooseRep (RepHtmlJson html json) = chooseRep [ (typeHtml, html) , (typeJson, json) ] newtype RepPlain = RepPlain Content instance HasReps RepPlain where chooseRep (RepPlain c) _ = return (typePlain, c) newtype RepXml = RepXml Content instance HasReps RepXml where chooseRep (RepXml c) _ = return (typeXml, c) type ContentType = B.ByteString -- FIXME Text? typeHtml :: ContentType typeHtml = "text/html; charset=utf-8" typePlain :: ContentType typePlain = "text/plain; charset=utf-8" typeJson :: ContentType typeJson = "application/json; charset=utf-8" typeXml :: ContentType typeXml = "text/xml" typeAtom :: ContentType typeAtom = "application/atom+xml" typeRss :: ContentType typeRss = "application/rss+xml" typeJpeg :: ContentType typeJpeg = "image/jpeg" typePng :: ContentType typePng = "image/png" typeGif :: ContentType typeGif = "image/gif" typeSvg :: ContentType typeSvg = "image/svg+xml" typeJavascript :: ContentType typeJavascript = "text/javascript; charset=utf-8" typeCss :: ContentType typeCss = "text/css; charset=utf-8" typeFlv :: ContentType typeFlv = "video/x-flv" typeOgv :: ContentType typeOgv = "video/ogg" typeOctet :: ContentType typeOctet = "application/octet-stream" -- | Removes \"extra\" information at the end of a content type string. In -- particular, removes everything after the semicolon, if present. -- -- For example, \"text/html; charset=utf-8\" is commonly used to specify the -- character encoding for HTML data. This function would return \"text/html\". simpleContentType :: ContentType -> ContentType simpleContentType = fst . B.breakByte 59 -- 59 == ; -- | Format a 'UTCTime' in W3 format. formatW3 :: UTCTime -> T.Text formatW3 = T.pack . formatTime defaultTimeLocale "%FT%X-00:00" -- | Format as per RFC 1123. formatRFC1123 :: UTCTime -> T.Text formatRFC1123 = T.pack . formatTime defaultTimeLocale "%a, %d %b %Y %X %Z" -- | Format as per RFC 822. formatRFC822 :: UTCTime -> T.Text formatRFC822 = T.pack . formatTime defaultTimeLocale "%a, %d %b %Y %H:%M:%S %z" -- | Prevents a response body from being fully evaluated before sending the -- request. -- -- Since 1.1.0 newtype DontFullyEvaluate a = DontFullyEvaluate a instance HasReps a => HasReps (DontFullyEvaluate a) where chooseRep (DontFullyEvaluate a) = fmap (fmap (fmap ContentDontEvaluate)) $ chooseRep a instance ToContent a => ToContent (DontFullyEvaluate a) where toContent (DontFullyEvaluate a) = ContentDontEvaluate $ toContent a
piyush-kurur/yesod
yesod-core/Yesod/Content.hs
mit
7,602
0
17
1,608
1,646
936
710
184
3
{-# language DeriveTraversable #-} {-# language GeneralizedNewtypeDeriving #-} module Unison.Util.EnumContainers ( EnumMap , EnumSet , EnumKey(..) , mapFromList , setFromList , setToList , mapSingleton , setSingleton , mapInsert , unionWith , keys , restrictKeys , withoutKeys , member , lookup , lookupWithDefault , mapWithKey , foldMapWithKey , mapToList , (!) , findMin ) where import Prelude hiding (lookup) import Data.Bifunctor import Data.Word (Word64,Word16) import qualified Data.IntSet as IS import qualified Data.IntMap.Strict as IM class EnumKey k where keyToInt :: k -> Int intToKey :: Int -> k instance EnumKey Word64 where keyToInt e = fromIntegral e intToKey i = fromIntegral i instance EnumKey Word16 where keyToInt e = fromIntegral e intToKey i = fromIntegral i newtype EnumMap k a = EM (IM.IntMap a) deriving ( Monoid , Semigroup , Functor , Foldable , Traversable , Show , Eq , Ord ) newtype EnumSet k = ES IS.IntSet deriving ( Monoid , Semigroup , Show , Eq , Ord ) mapFromList :: EnumKey k => [(k, a)] -> EnumMap k a mapFromList = EM . IM.fromList . fmap (first keyToInt) setFromList :: EnumKey k => [k] -> EnumSet k setFromList = ES . IS.fromList . fmap keyToInt setToList :: EnumKey k => EnumSet k -> [k] setToList (ES s) = intToKey <$> IS.toList s mapSingleton :: EnumKey k => k -> a -> EnumMap k a mapSingleton e a = EM $ IM.singleton (keyToInt e) a setSingleton :: EnumKey k => k -> EnumSet k setSingleton e = ES . IS.singleton $ keyToInt e mapInsert :: EnumKey k => k -> a -> EnumMap k a -> EnumMap k a mapInsert e x (EM m) = EM $ IM.insert (keyToInt e) x m unionWith :: EnumKey k => EnumKey k => (a -> a -> a) -> EnumMap k a -> EnumMap k a -> EnumMap k a unionWith f (EM l) (EM r) = EM $ IM.unionWith f l r keys :: EnumKey k => EnumMap k a -> [k] keys (EM m) = fmap intToKey . IM.keys $ m restrictKeys :: EnumKey k => EnumMap k a -> EnumSet k -> EnumMap k a restrictKeys (EM m) (ES s) = EM $ IM.restrictKeys m s withoutKeys :: EnumKey k => EnumMap k a -> EnumSet k -> EnumMap k a withoutKeys (EM m) (ES s) = EM $ IM.withoutKeys m s member :: EnumKey k => k -> EnumSet k -> Bool member e (ES s) = IS.member (keyToInt e) s lookup :: EnumKey k => k -> EnumMap k a -> Maybe a lookup e (EM m) = IM.lookup (keyToInt e) m lookupWithDefault :: EnumKey k => a -> k -> EnumMap k a -> a lookupWithDefault d e (EM m) = IM.findWithDefault d (keyToInt e) m mapWithKey :: EnumKey k => (k -> a -> b) -> EnumMap k a -> EnumMap k b mapWithKey f (EM m) = EM $ IM.mapWithKey (f . intToKey) m foldMapWithKey :: EnumKey k => Monoid m => (k -> a -> m) -> EnumMap k a -> m foldMapWithKey f (EM m) = IM.foldMapWithKey (f . intToKey) m mapToList :: EnumKey k => EnumMap k a -> [(k, a)] mapToList (EM m) = first intToKey <$> IM.toList m (!) :: EnumKey k => EnumMap k a -> k -> a EM m ! e = m IM.! keyToInt e findMin :: EnumKey k => EnumSet k -> k findMin (ES s) = intToKey $ IS.findMin s
unisonweb/platform
parser-typechecker/src/Unison/Util/EnumContainers.hs
mit
3,041
0
10
727
1,344
682
662
-1
-1
module Graphics.UI.GLFW.Netwire.Input.Types(WindowHandle, ModifierKeys, KeyState, Scancode, Key, MouseCursorPosition, GLFWEventData(..), JoystickState(..) ) where import qualified Graphics.UI.GLFW as GLFW type WindowHandle = GLFW.Window type ModifierKeys = GLFW.ModifierKeys type KeyState = GLFW.KeyState type Scancode = Int type Key = GLFW.Key type MouseCursorPosition = (Double,Double) data GLFWEventData = MouseButtonEvent Int Bool ModifierKeys | KeyEvent Key Scancode KeyState ModifierKeys | MouseMoveEvent (Double,Double) | FocusChangeEvent Bool | MouseEnterEvent Bool | ScrollWheelEvent (Double,Double) | CharEvent Char | CloseButtonEvent Bool deriving(Eq,Ord) data JoystickState = JoystickUnplugged | JoystickState String [Bool] [Double] deriving(Eq,Ord)
barendventer/netwire-glfw-b
src/Graphics/UI/GLFW/Netwire/Input/Types.hs
mit
1,262
0
7
582
213
134
79
26
0
module MonadUtils ( breakM , takeWhileM ) where breakM :: (Eq a, Monad m) => (a -> m Bool) -> [a] -> m ([a], [a]) breakM _ xs@[] = return (xs, xs) breakM predM l@(x:xs) = do val <- predM x case val of True -> return ([], l) _ -> do (ys, zs) <- breakM predM xs return (x:ys, zs) takeWhileM :: Monad m => (a -> m Bool) -> [a] -> m [a] takeWhileM _ xs@[] = return xs takeWhileM predM l@(x:xs) = do val <- predM x case val of False -> return [] _ -> do ys <- takeWhileM predM xs return (x:ys)
arekfu/project_euler
common/MonadUtils.hs
mit
603
0
14
221
322
165
157
21
2
{- HAAP: Haskell Automated Assessment Platform This module provides documentation analysis functions by resorting to the _SourceGraph_ library (<https://hackage.haskell.org/package/SourceGraph>). -} {-# LANGUAGE OverloadedStrings, ViewPatterns, ScopedTypeVariables, DeriveGeneric #-} module HAAP.Code.Analysis.SourceGraph where import HAAP.IO import HAAP.Core import HAAP.Code.Haskell import HAAP.Log import Data.Default import qualified Data.Text as Text import Data.Traversable import Data.List import Data.Csv import Data.Set (Set(..)) import qualified Data.Set as Set import Data.Map (Map(..)) import qualified Data.Map as Map import Data.Maybe import qualified Data.Map as Map import Data.Graph.Inductive.Graph import Data.Graph.Inductive.Query.BCC import Data.Graph.Inductive.Query.DFS import Data.Graph.Inductive.Basic import Data.Graph.Analysis import Data.Graph.Analysis.Algorithms import Data.Graph.Analysis.Utils import Data.Graph.Analysis.Types (graph) import Control.Monad.IO.Class import Control.DeepSeq import Control.Monad --import Control.Exception import Control.Arrow(first) import Language.Haskell.Exts as H import System.FilePath import Safe import GHC.Generics (Generic) -- sourcegraph import Language.Haskell.SourceGraph.Analyse.Module import Language.Haskell.SourceGraph.Analyse.Everything import Language.Haskell.SourceGraph.Parsing import Language.Haskell.SourceGraph.Parsing.Types as SG import Language.Haskell.SourceGraph.Analyse.GraphRepr import Language.Haskell.SourceGraph.Analyse.Utils data SGReport = SGReport { maxModuleCC :: Int -- maximum cyclomatic complexity , globalCC :: Int -- global cyclomatic complexity , numInterModuleCalls :: Int -- number of inter-module function calls } deriving (Show,Generic) instance NFData SGReport where instance DefaultOrdered SGReport where headerOrder _ = header ["maxModuleCC","globalCC","numInterModuleCalls"] instance ToNamedRecord SGReport where toNamedRecord (SGReport x x2 y) = namedRecord ["maxModuleCC" .= x,"globalCC" .= x2,"numInterModuleCalls" .= y] instance FromNamedRecord SGReport where parseNamedRecord m = SGReport <$> m .: "maxModuleCC" <*> m .: "globalCC" <*> m .: "numInterModuleCalls" instance Default SGReport where def = SGReport (-1) (-1) (-1) -- * tool --runCComplexity :: HaapMonad m => IOArgs -> [FilePath] -> Haap p args db m CComplexity --runCComplexity ioargs files = do -- files' <- forM files $ \file -> orLogMaybe $ do -- logEvent $ "parsing complexity for " ++ file -- mn <- parseModuleFileName file -- return (file,mn) -- runCComplexity' ioargs (catMaybes files') -- --runCComplexity' :: HaapMonad m => IOArgs -> [(FilePath,String)] -> Haap p args db m CComplexity --runCComplexity' ioargs files = do -- ccs <- liftM catMaybes $ mapM (orLogMaybe . cComplexity ioargs) files -- let cc = if (length ccs > 0) then maximumDef 0 ccs else (-1) -- return $ CComplexity cc -- --cComplexity :: HaapMonad m => IOArgs -> (FilePath,String) -> Haap p args db m Int --cComplexity ioargs (m,s) = do -- runShWith (const ioargs) $ do -- shCommandWith_ (ioargs) "SourceGraph" [m] -- x <- shCommandWith (ioargs) "egrep" ["-w","<p>The cyclomatic complexity of "++s++" is:",takeDirectory m++"/SourceGraph/"++s++".html"] -- let ax = drop (37 + (length s)) $ Text.unpack $ resStdout x -- liftIO $ evaluate $ force $ readNote "cComplexity" $ take (length ax - 6) ax -- * library data SourceGraphArgs = SourceGraphArgs { ignoreNode :: Entity -> Bool -- graph nodes to ignore for the analysis , ignoreEdge :: CallType -> Bool -- graph edges to ignore for the analysis , rootEntities :: Maybe (Set EntityName) -- analyze only the code slice starting from the given names } type SGraph = GraphData Entity CallType isNormalCall :: CallType -> Bool isNormalCall NormalCall = True isNormalCall _ = False isNormalEntity :: Entity -> Bool isNormalEntity e = eType e == NormalEntity runSourceGraph :: (MonadIO m,HaapStack t m) => SourceGraphArgs -> [FilePath] -> Haap t m (SGReport,Set Entity) runSourceGraph args files = orLogDefault def $ do (_,ms) <- liftIO $ parseHaskellFiles files let (cg,slices) = codeGraph args ms let mgs = moduleGraphs args ms let mccs = map (cyclomaticComplexity . fst) $ Map.elems mgs let gcc = cyclomaticComplexity cg let mcalls = moduleCalls cg return (SGReport (maximumDef 0 mccs) gcc mcalls,slices) codeGraph :: SourceGraphArgs -> ParsedModules -> (SGraph,Set Entity) codeGraph args ms = (g',es) where mns = Map.keys ms g = filterGraph args $ graphData $ collapsedHData $ codeToGraph mns ms (g',es) = sliceGraph args g moduleGraphs :: SourceGraphArgs -> ParsedModules -> Map ModName (SGraph,Set Entity) moduleGraphs args = Map.map (moduleGraph args) moduleGraph :: SourceGraphArgs -> ParsedModule -> (SGraph,Set Entity) moduleGraph args m = g where (_,(n,_,fd)) = moduleToGraph m g = sliceGraph args $ filterGraph args $ graphData $ collapsedHData fd cyclomaticComplexityGr :: DynGraph gr => gr a b -> Int cyclomaticComplexityGr gd = e - n + 2*p where p = length $ componentsOf gd n = noNodes gd e = length $ labEdges gd moduleCalls :: SGraph -> Int moduleCalls cg = length es where g = graph cg es = filter isInterModuleCall $ edges g isInterModuleCall (x,y) = case (lab g x,lab g y) of (Just x',Just y') -> inModule x' /= inModule y' otherwise -> False filterGraph :: SourceGraphArgs -> SGraph -> SGraph filterGraph args g = updateGraph (filteredges . filternodes) g where filternodes = labfilter $ not . ignoreNode args filteredges = efilter $ \(_,_,e) -> not $ ignoreEdge args e -- * slicing sliceGraph :: SourceGraphArgs -> SGraph -> (SGraph,Set Entity) sliceGraph args sg = case rootEntities args of Nothing -> (sg,Set.empty) Just starts -> (sg',Set.fromList $ map snd lslice) where g = graph sg lnodes = labNodes g start_lnodes = filter (flip Set.member starts . SG.name . snd) lnodes slice = accessibleFrom g (map fst start_lnodes) lslice = map (\i -> (i,fromJust $ lab g i)) slice sg' = updateGraph (subgraph (map fst lslice)) sg runSlice :: (MonadIO m,HaapStack t m) => [FilePath] -> (String -> Bool) -> (String -> Bool) -> Haap t m ([Decl SrcSpanInfo],Int,Int) runSlice file = runSliceWith file Nothing (Just []) runSliceWith :: (MonadIO m,HaapStack t m) => [FilePath] -> Maybe [Extension] -> Maybe [H.Fixity] -> (String -> Bool) -> (String -> Bool) -> Haap t m ([Decl SrcSpanInfo],Int,Int) runSliceWith files ext fix isSlice excludeSlice = orLogDefault (def,-1,-1) $ do -- sourcegraph (_,ms) <- liftIO $ parseHaskellFiles files let (map SG.name -> slicednames,cc,noloops) = sliceEntities ms (isSlice . SG.name) (excludeSlice . SG.name) -- haskell-src-exts modules <- mapM (\f -> parseHaskellFileWith f ext fix) files let slices = sliceModules modules slicednames return (slices,cc,noloops) sliceModules :: [H.Module SrcSpanInfo] -> [String] -> [H.Decl SrcSpanInfo] sliceModules modules slicednames = decls' where decls = getTopDecls modules getDecl d = case getTopName d of { Nothing -> Nothing ; Just n -> if elem (nameString n) slicednames then Just d else Nothing } decls' = catMaybes $ map getDecl decls sliceEntities :: ParsedModules -> (Entity -> Bool) -> (Entity -> Bool) -> ([Entity],Int,Int) sliceEntities ms isSlice excludeSlice = (map snd lslice,cc,length loops) where start_lnodes = filter (isSlice . snd) lnodes mns = Map.keys ms g::AGr Entity CallType = efilter (\(_,_,e) -> e == NormalCall) $ graph $ graphData $ collapsedHData $ codeToGraph mns ms lnodes = labNodes g slice = accessibleFrom g (map fst start_lnodes) lslice = filter (not . excludeSlice . snd) $ map (\i -> (i,fromJust $ lab g i)) slice subg = subgraph (map fst lslice) g cc = cyclomaticComplexityGr subg loops = subloops subg subloops :: DynGraph gr => gr a b -> [gr a b] subloops g = cycs where sccs = scc g cycs = filter hasCycle $ map (flip subgraph g) sccs hasCycle g = if noNodes g == 1 then hasLoop g else True
hpacheco/HAAP
src/HAAP/Code/Analysis/SourceGraph.hs
mit
8,361
0
15
1,680
2,361
1,281
1,080
141
3
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} module Keter.Types.Common ( module Keter.Types.Common , FilePath , Text , ByteString , Set , Map , Exception , SomeException ) where import Control.Exception (Exception, SomeException) import Data.Aeson (FromJSON, Object, ToJSON, Value (Bool), object, withBool, withObject, (.!=), (.:?), (.=)) import Data.ByteString (ByteString) import Data.CaseInsensitive (CI, original) import Data.Map (Map) import Data.Set (Set) import qualified Data.Set as Set import Data.Text (Text, pack, unpack) import Data.Typeable (Typeable) import Data.Vector (Vector) import qualified Data.Vector as V import qualified Data.Yaml import Data.Yaml.FilePath import qualified Language.Haskell.TH.Syntax as TH import Network.Socket (AddrInfo, SockAddr) import System.Exit (ExitCode) import System.FilePath (FilePath, takeBaseName) -- | Name of the application. Should just be the basename of the application -- file. type Appname = Text data Plugin = Plugin { pluginGetEnv :: Appname -> Object -> IO [(Text, Text)] } type Plugins = [Plugin] -- | Used for versioning data types. class ToCurrent a where type Previous a toCurrent :: Previous a -> a instance ToCurrent a => ToCurrent (Maybe a) where type Previous (Maybe a) = Maybe (Previous a) toCurrent = fmap toCurrent -- | A port for an individual app to listen on. type Port = Int -- | A virtual host we want to serve content from. type Host = CI Text type HostBS = CI ByteString getAppname :: FilePath -> Text getAppname = pack . takeBaseName data LogMessage = ProcessCreated FilePath | InvalidBundle FilePath SomeException | ProcessDidNotStart FilePath | ExceptionThrown Text SomeException | RemovingPort Int | UnpackingBundle FilePath | TerminatingApp Text | FinishedReloading Text | TerminatingOldProcess AppId | RemovingOldFolder FilePath | ReceivedInotifyEvent Text | ProcessWaiting FilePath | OtherMessage Text | ErrorStartingBundle Text SomeException | SanityChecksPassed | ReservingHosts AppId (Set Host) | ForgetingReservations AppId (Set Host) | ActivatingApp AppId (Set Host) | DeactivatingApp AppId (Set Host) | ReactivatingApp AppId (Set Host) (Set Host) | WatchedFile Text FilePath | ReloadFrom (Maybe String) String | Terminating String | LaunchInitial | LaunchCli | StartWatching | StartListening | BindCli AddrInfo | ReceivedCliConnection SockAddr | KillingApp Port Text instance Show LogMessage where show (ProcessCreated f) = "Created process: " ++ f show (ReloadFrom app input) = "Reloading from: " ++ show app ++ " to " ++ show input show (Terminating app) = "Terminating " ++ show app show (InvalidBundle f e) = concat [ "Unable to parse bundle file '" , f , "': " , show e ] show (ProcessDidNotStart fp) = concat [ "Could not start process within timeout period: " , fp ] show (ExceptionThrown t e) = concat [ unpack t , ": " , show e ] show (RemovingPort p) = "Port in use, removing from port pool: " ++ show p show (UnpackingBundle b) = concat [ "Unpacking bundle '" , b , "'" ] show (TerminatingApp t) = "Shutting down app: " ++ unpack t show (FinishedReloading t) = "App finished reloading: " ++ unpack t show (TerminatingOldProcess (AINamed t)) = "Sending old process TERM signal: " ++ unpack t show (TerminatingOldProcess AIBuiltin) = "Sending old process TERM signal: builtin" show (RemovingOldFolder fp) = "Removing unneeded folder: " ++ fp show (ReceivedInotifyEvent t) = "Received unknown INotify event: " ++ unpack t show (ProcessWaiting f) = "Process restarting too quickly, waiting before trying again: " ++ f show (OtherMessage t) = unpack t show (ErrorStartingBundle name e) = concat [ "Error occured when launching bundle " , unpack name , ": " , show e ] show SanityChecksPassed = "Sanity checks passed" show (ReservingHosts app hosts) = "Reserving hosts for app " ++ show app ++ ": " ++ unwords (map (unpack . original) $ Set.toList hosts) show (ForgetingReservations app hosts) = "Forgetting host reservations for app " ++ show app ++ ": " ++ unwords (map (unpack . original) $ Set.toList hosts) show (ActivatingApp app hosts) = "Activating app " ++ show app ++ " with hosts: " ++ unwords (map (unpack . original) $ Set.toList hosts) show (DeactivatingApp app hosts) = "Deactivating app " ++ show app ++ " with hosts: " ++ unwords (map (unpack . original) $ Set.toList hosts) show (ReactivatingApp app old new) = concat [ "Reactivating app " , show app , ". Old hosts: " , unwords (map (unpack . original) $ Set.toList old) , ". New hosts: " , unwords (map (unpack . original) $ Set.toList new) , "." ] show (WatchedFile action fp) = concat [ "Watched file " , unpack action , ": " , fp ] show LaunchInitial = "Launching initial" show (KillingApp port txt) = "Killing " <> unpack txt <> " running on port: " <> show port show LaunchCli = "Launching cli" show StartWatching = "Started watching" show StartListening = "Started listening" show (BindCli addr) = "Bound cli to " <> show addr show (ReceivedCliConnection peer) = "CLI Connection from " <> show peer data KeterException = CannotParsePostgres FilePath | ExitCodeFailure FilePath ExitCode | NoPortsAvailable | InvalidConfigFile Data.Yaml.ParseException | InvalidKeterConfigFile !FilePath !Data.Yaml.ParseException | CannotReserveHosts !AppId !(Map Host AppId) | FileNotExecutable !FilePath | ExecutableNotFound !FilePath | EnsureAliveShouldBeBiggerThenZero { keterExceptionGot:: !Int } deriving (Show, Typeable) instance Exception KeterException logEx :: TH.Q TH.Exp logEx = do let showLoc TH.Loc { TH.loc_module = m, TH.loc_start = (l, c) } = concat [ m , ":" , show l , ":" , show c ] loc <- fmap showLoc TH.qLocation [|(. ExceptionThrown (pack $(TH.lift loc)))|] data AppId = AIBuiltin | AINamed !Appname deriving (Eq, Ord) instance Show AppId where show AIBuiltin = "/builtin/" show (AINamed t) = unpack t data SSLConfig = SSLFalse | SSLTrue | SSL !FilePath !(Vector FilePath) !FilePath deriving (Show, Eq, Ord) instance ParseYamlFile SSLConfig where parseYamlFile _ v@(Bool _) = withBool "ssl" ( \b -> return (if b then SSLTrue else SSLFalse) ) v parseYamlFile basedir v = withObject "ssl" ( \o -> do mcert <- lookupBaseMaybe basedir o "certificate" mkey <- lookupBaseMaybe basedir o "key" case (mcert, mkey) of (Just cert, Just key) -> do chainCerts <- o .:? "chain-certificates" >>= maybe (return V.empty) (parseYamlFile basedir) return $ SSL cert chainCerts key _ -> return SSLFalse ) v instance ToJSON SSLConfig where toJSON SSLTrue = Bool True toJSON SSLFalse = Bool False toJSON (SSL c cc k) = object [ "certificate" .= c , "chain-certificates" .= cc , "key" .= k ] instance FromJSON SSLConfig where parseJSON v@(Bool _) = withBool "ssl" ( \b -> return (if b then SSLTrue else SSLFalse) ) v parseJSON v = withObject "ssl" ( \o -> do mcert <- o .:? "certificate" mkey <- o .:? "key" case (mcert, mkey) of (Just cert, Just key) -> do chainCerts <- o .:? "chain-certificates" .!= V.empty return $ SSL cert chainCerts key _ -> return SSLFalse -- fail "Must provide both certificate and key files" ) v
snoyberg/keter
Keter/Types/Common.hs
mit
8,876
0
21
2,932
2,259
1,197
1,062
222
1
{-# LANGUAGE OverloadedStrings #-} module Y2020.M11.D09.Exercise where {-- The previous exercise had you parse the European Union's member states then add that to the AllianceMap of the world. That was easy, because those data were available as wikidata.org JSON. Not so for the United Nations (which we will do today) and the Organization of American States (tomorrow). These alliances are in wikitext, and, what's even more FUNZORX is that these wikitext documents don't have an uniform format. YAY! FUNZORX! Today's #haskell problem. Let's parse in the member nations of the United Nations and add that ... 'alliance' (?) to our AllianceMap. I'll provide the seed alliance map. You provide the UN and add it to that map. hint: we may (?) have parsed in nation flags (?) before (?) from wikitext? post-hint: oh. It's not {{flagicon|<country>}}, now it's {{flag|<country>}} The Funzorx continuezorx. :/ --} import Y2020.M10.D12.Exercise -- ALL the way back when for Country. import Y2020.M10.D30.Solution (Alliance(Alliance), AllianceMap, dear, moderns) import qualified Y2020.M10.D30.Solution as A -- look for flaggie stuff here import Y2020.M11.D05.Solution (todoPrep) -- for the updated alliance-parse import Y2020.M11.D06.Solution (addEU, euDir, eu) import qualified Data.Map as Map seedAllianceMap :: FilePath -> FilePath -> IO AllianceMap seedAllianceMap allieses eus = todoPrep allieses >>= flip addEU eus {-- >>> seedAllianceMap (dear ++ moderns) (euDir ++ eu) ... >>> let am = it >>> Map.size am 43 --} unDir :: FilePath unDir = "Y2020/M11/D09/" un :: FilePath un = "un.wtxt" unFlag :: String -> Maybe Country unFlag line = undefined -- unFlag is the same flagicon, but for "{{flag|", ... so it's different. :/ exUnFlagPass, exUnFlagFail :: String exUnFlagPass = "|{{flag|China}}" exUnFlagFail = "|1971, replaced the [[Republic of China]]" {-- >>> unFlag exUnFlagPass Just "China" >>> unFlag exUnFlagFail Nothing --} -- and with that --^ we can do this --v unitedNationsParser :: FilePath -> IO Alliance unitedNationsParser file = undefined addUN :: AllianceMap -> FilePath -> IO AllianceMap addUN am uns = undefined
geophf/1HaskellADay
exercises/HAD/Y2020/M11/D09/Exercise.hs
mit
2,158
0
7
353
238
145
93
23
1
module Rebase.GHC.ConsoleHandler ( module GHC.ConsoleHandler ) where import GHC.ConsoleHandler
nikita-volkov/rebase
library/Rebase/GHC/ConsoleHandler.hs
mit
98
0
5
12
20
13
7
4
0
{-# LANGUAGE FunctionalDependencies #-} module Query.Transformers ( Grouping, groupedAs, groupedBs, unwrapGrouped, RightGrouped(), unRightGrouped, unsafeLiftGrouped, groupRight, unGroupRight, RightCollapsed(), unRightCollapsed, unsafeLiftRightCollapsed, collapseRight, fullCollapseRight, unCollapseRight, WeakCollapsed(), unWeakCollapsed, fromRightCollapsed, dataLeftJoin, fullDataLeftJoin ) where import Control.Category import Data.List.NonEmpty (NonEmpty) import qualified Data.List.NonEmpty as NE import Data.Map.Strict as M import Import class Grouping t a b | t -> a b where groupedAs :: t -> [a] groupedBs :: t -> [b] unwrapGrouped :: t -> [(a, b)] unwrapGrouped = uncurry zip . (groupedAs &&& groupedBs) newtype RightGrouped a b = RightGrouped { unRightGrouped :: [NonEmpty (a, b)] } deriving (Show, Eq) instance Grouping (RightGrouped a b) (NonEmpty a) (NonEmpty b) where groupedAs = fmap (fmap fst) . unRightGrouped groupedBs = fmap (fmap snd) . unRightGrouped unsafeLiftGrouped :: ([NonEmpty (a, b)] -> [NonEmpty (c, d)]) -> RightGrouped a b -> RightGrouped c d unsafeLiftGrouped f = RightGrouped . f . unRightGrouped groupRight :: Eq a => [(a, b)] -> RightGrouped a b groupRight = RightGrouped <$> NE.groupBy (\a b -> fst a == fst b) unGroupRight :: RightGrouped a b -> [(a, b)] unGroupRight (RightGrouped xs) = mconcat $ NE.toList <$> xs newtype RightCollapsed a b = RightCollapsed { unRightCollapsed :: [(a, NonEmpty b)] } deriving (Show, Eq) instance Grouping (RightCollapsed a b) a (NonEmpty b) where groupedAs = fmap fst . unRightCollapsed groupedBs = fmap snd . unRightCollapsed unsafeLiftRightCollapsed :: ([(a, NonEmpty b)] -> [(c, NonEmpty d)]) -> RightCollapsed a b -> RightCollapsed c d unsafeLiftRightCollapsed f = RightCollapsed . f . unRightCollapsed collapseRight :: RightGrouped a b -> RightCollapsed a b collapseRight (RightGrouped xs) = RightCollapsed $ (first NE.head . NE.unzip) <$> xs fullCollapseRight :: Eq a => [(a, b)] -> RightCollapsed a b fullCollapseRight = collapseRight . groupRight unCollapseRight :: RightCollapsed a b -> RightGrouped a b unCollapseRight (RightCollapsed xs) = RightGrouped $ (\(a, bs) -> NE.zip (NE.repeat a) bs) <$> xs newtype WeakCollapsed a b = WeakCollapsed { unWeakCollapsed :: [(a, [b])] } deriving (Show, Eq) instance Grouping (WeakCollapsed a b) a [b] where groupedAs = fmap fst . unWeakCollapsed groupedBs = fmap snd . unWeakCollapsed fromRightCollapsed :: RightCollapsed a b -> WeakCollapsed a b fromRightCollapsed = WeakCollapsed . fmap (second NE.toList) . unRightCollapsed dataLeftJoin :: (Ord a) => RightCollapsed a b -> [a] -> WeakCollapsed a b dataLeftJoin (RightCollapsed xs) as = WeakCollapsed $ lookupTuple xsMap <$> as where xsMap = M.fromList $ second NE.toList <$> xs lookupTuple cMap x = (,) x $ fromMaybe [] $ M.lookup x cMap fullDataLeftJoin :: Ord a => [a] -> [(a, b)] -> WeakCollapsed a b fullDataLeftJoin as = flip dataLeftJoin as . collapseRight . groupRight --unsafeFastLeftJoin :: RightCollapsed a b -> [a] -> LeftJoined a b]
ForestPhoenix/FPSurvey
Query/Transformers.hs
mit
3,249
0
12
674
1,111
606
505
-1
-1
{-# LANGUAGE OverloadedStrings, QuasiQuotes #-} module Y2017.M11.D22.Exercise where {-- You send me an article id, I send you the full text of the article. Simple as that. ... of course, it's never as simple as that, is it. The article needs to be cleaned of special characters. Also, some articles have this annoying "Source: http://" whatever at the bottom of their text that needs to be removed. So, you know: do that. --} import Data.Aeson import Data.Aeson.Encode.Pretty import Data.Time import Database.PostgreSQL.Simple import Database.PostgreSQL.Simple.SqlQQ import Database.PostgreSQL.Simple.FromRow -- below imports available via 1HaskellADay git repository import Control.Scan.Config import Store.SQL.Connection import Y2017.M11.D01.Exercise -- for special chars data FullText = FT { ftidx :: Integer, fttitle, ftfullText :: String, ftauthor :: Maybe String, ftdate :: Day } deriving (Eq, Show) instance FromRow FullText where fromRow = undefined -- we also want to output our results as JSON instance ToJSON FullText where toJSON ft = undefined -- from an id get the article's full text fullTextStmt :: Query fullTextStmt = [sql|SELECT id,author,full_text FROM article where id=?|] -- returns a cleaned full text of article x fullText :: Connection -> Integer -> IO [FullText] fullText conn idx = undefined -- now, we need to remove special characters and remove the 'Source:'-thingie removeSourceThingie :: SpecialCharTable -> String -> String removeSourceThingie fulltext = undefined -- With that, we need to transform a FullText value to a cleaned-up verson of -- the same cleanup :: SpecialCharTable -> FullText -> FullText cleanup dict (FT a b c d e) = undefined -- And we are g2g! AM I RIGHT OR AM I RIGHT? main' :: [String] -> IO () main' args = undefined
geophf/1HaskellADay
exercises/HAD/Y2017/M11/D22/Exercise.hs
mit
1,871
0
9
369
279
168
111
30
1
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DuplicateRecordFields #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE NoImplicitPrelude #-} module System.Etc.Internal.Errors where import RIO import qualified Data.Aeson as JSON import System.Etc.Internal.Spec.Types -- | Thrown when calling the 'getConfig' or 'getConfigWith' functions on a key -- that does not exist in the configuration spec newtype InvalidConfigKeyPath = InvalidConfigKeyPath { inputKeys :: [Text] -- ^ Input Keys } deriving (Generic, Show, Read, Eq) instance Exception InvalidConfigKeyPath -- | Thrown when there is a type mismatch in a JSON parser given via -- 'getConfigWith' data ConfigValueParserFailed = ConfigValueParserFailed { inputKeys :: ![Text] -- ^ Input Keys , parserErrorMessage :: !Text -- ^ Parser Error Message } deriving (Generic, Show, Read, Eq) instance Exception ConfigValueParserFailed -- | Thrown when the 'resolveFile' function finds a key on a configuration -- file that is not specified in the given configuration spec data UnknownConfigKeyFound = UnknownConfigKeyFound { parentKeys :: ![Text] -- ^ Parent Keys , keyName :: !Text -- ^ Key Name , siblingKeys :: ![Text] -- ^ Sibling Keys (other keys in the same level) } deriving (Generic, Show, Read, Eq) instance Exception UnknownConfigKeyFound -- | Thrown when there is a type mismatch on a configuration entry, -- specifically, when there is a raw value instead of a sub-config in a -- configuration file data SubConfigEntryExpected = SubConfigEntryExpected { keyName :: !Text -- ^ Key Name , configValue :: !JSON.Value -- ^ Config Value } deriving (Generic, Show, Read, Eq) instance Exception SubConfigEntryExpected -- | This error is thrown when a type mismatch is found in a raw value when -- calling 'resolveFile' data ConfigValueTypeMismatchFound = ConfigValueTypeMismatchFound { keyName :: !Text -- ^ Key Name , configValueEntry :: !JSON.Value -- ^ Config Value , configValueEntryType :: !ConfigValueType -- ^ Config Value Type } deriving (Generic, Show, Read, Eq) instance Exception ConfigValueTypeMismatchFound -- | Thrown when a specified configuration file is not found in the system newtype ConfigurationFileNotFound = ConfigurationFileNotFound { configFilepath :: Text -- ^ Config FilePath } deriving (Generic, Show, Read, Eq) instance Exception ConfigurationFileNotFound -- | Thrown when an input configuration file contains an unsupported file -- extension newtype UnsupportedFileExtensionGiven = UnsupportedFileExtensionGiven { configFilepath :: Text -- ^ Config FilePath } deriving (Generic, Show, Read, Eq) instance Exception UnsupportedFileExtensionGiven -- | Thrown when an input configuration file contains invalid syntax data ConfigInvalidSyntaxFound = ConfigInvalidSyntaxFound { configFilepath :: !Text -- ^ Config FilePath , parserErrorMessage :: !Text -- ^ Parser Error Message } deriving (Generic, Show, Read, Eq) instance Exception ConfigInvalidSyntaxFound -- | Thrown when an configuration spec file contains invalid syntax data SpecInvalidSyntaxFound = SpecInvalidSyntaxFound { specFilepath :: !(Maybe Text) -- ^ Spec FilePath , parseErrorMessage :: !Text -- ^ Parser Error Message } deriving (Generic, Show, Read, Eq) instance Exception SpecInvalidSyntaxFound
roman/Haskell-etc
etc/src/System/Etc/Internal/Errors.hs
mit
3,462
0
11
682
511
300
211
84
0
{-# LANGUAGE TypeFamilies, MultiParamTypeClasses, OverloadedStrings, FlexibleInstances, FlexibleContexts, ScopedTypeVariables, TupleSections #-} module Config ( Conf , parseConfig , readMimeTypesFile , gititConfigFromConf , cfg_port , cfg_repository_path , cfg_repository_type , cfg_static_dir , cfg_max_upload_size , foundationSettingsFromConf , FoundationSettings , appRoot ) where import Data.Text (Text) import qualified Data.Text as T import qualified Data.Map as M import qualified Data.ByteString.Char8 as B import Data.Yaml import Control.Exception (catch, SomeException) import Yesod import Network.Gitit2 import Data.Monoid (mappend) import Data.Maybe (fromMaybe) import Error data Conf = Conf { cfg_port :: Int , cfg_approot :: Maybe Text , cfg_repository_path :: FilePath , cfg_repository_type :: Text , cfg_page_extension :: FilePath , cfg_default_format :: Text , cfg_static_dir :: FilePath , cfg_mime_types_file :: Maybe FilePath , cfg_use_mathjax :: Bool , cfg_feed_days :: Integer , cfg_feed_minutes :: Integer , cfg_pandoc_user_data :: Maybe FilePath , cfg_use_cache :: Bool , cfg_cache_dir :: FilePath , cfg_front_page :: Text , cfg_help_page :: Text , cfg_max_upload_size :: String , cfg_latex_engine :: Maybe FilePath } data FoundationSettings = FoundationSettings { appRoot:: Text } deriving (Show) foundationSettingsFromConf :: Conf -> FoundationSettings foundationSettingsFromConf conf = FoundationSettings (fromMaybe defaultApproot (cfg_approot conf)) where defaultApproot = "http://localhost:" `mappend` T.pack (show (cfg_port conf)) parseElem :: FromJSON a => [Object] -> Text -> Parser (Maybe a) parseElem os text = foldr f (return Nothing) os where f o pm = do maybeParsedO <- o .:? text case maybeParsedO of Nothing -> pm _ -> return maybeParsedO parseConfig :: [Object] -> Parser Conf parseConfig os = Conf <$> os `parseElem` "port" .!= 50000 <*> os `parseElem` "approot" <*> os `parseElem` "repository_path" .!= "wikidata" <*> os `parseElem` "repository_type" .!= "git" <*> os `parseElem` "page_extension" .!= ".page" <*> os `parseElem` "default_format" .!= "markdown" <*> os `parseElem` "static_dir" .!= "static" <*> os `parseElem` "mime_types_file" <*> os `parseElem` "use_mathjax" .!= False <*> os `parseElem` "feed_days" .!= 14 <*> os `parseElem` "feed_minutes" .!= 15 <*> os `parseElem` "pandoc_user_data" <*> os `parseElem` "use_cache" .!= False <*> os `parseElem` "cache_dir" .!= "cache" <*> os `parseElem` "front_page" .!= "Front Page" <*> os `parseElem` "help_page" .!= "Help" <*> os `parseElem` "max_upload_size" .!= "1M" <*> os `parseElem` "latex_engine" -- | Ready collection of common mime types. (Copied from -- Happstack.Server.HTTP.FileServe.) mimeTypes :: M.Map String ContentType mimeTypes = M.fromList [("xml","application/xml") ,("xsl","application/xml") ,("js","text/javascript; charset=UTF-8") ,("html","text/html; charset=UTF-8") ,("htm","text/html; charset=UTF-8") ,("css","text/css; charset=UTF-8") ,("gif","image/gif") ,("jpg","image/jpeg") ,("png","image/png") ,("txt","text/plain; charset=UTF-8") ,("doc","application/msword") ,("exe","application/octet-stream") ,("pdf","application/pdf") ,("zip","application/zip") ,("gz","application/x-gzip") ,("ps","application/postscript") ,("rtf","application/rtf") ,("wav","application/x-wav") ,("hs","text/plain; charset=UTF-8")] -- | Read a file associating mime types with extensions, and return a -- map from extensions tstypes. Each line of the file consists of a -- mime type, followed by space, followed by a list of zersor more -- extensions, separated by spaces. Example: text/plain txt text readMimeTypesFile :: FilePath -> IO (M.Map String ContentType) readMimeTypesFile f = catch ((foldr (gs. words) M.empty . lines) `fmap` readFile f) handleMimeTypesFileNotFound where gs[] m = m -- skip blank lines gs(x:xs) m = foldr (\ext -> M.insert ext $ B.pack x) m xs handleMimeTypesFileNotFound :: SomeException -> IO (M.Map String ContentType) handleMimeTypesFileNotFound e = do warn $ "Could not parse mime types file.\n" ++ show e return mimeTypes gititConfigFromConf :: Conf -> IO GititConfig gititConfigFromConf conf = do mimes <- case cfg_mime_types_file conf of Nothing -> return mimeTypes Just f -> readMimeTypesFile f format <- case readPageFormat (cfg_default_format conf) of Just f -> return f Nothing -> err 11 $ "Unknown default format: " ++ T.unpack (cfg_default_format conf) let gconfig = GititConfig{ mime_types = mimes , default_format = format , repository_path = cfg_repository_path conf , page_extension = cfg_page_extension conf , static_path = cfg_static_dir conf , use_mathjax = cfg_use_mathjax conf , feed_days = cfg_feed_days conf , feed_minutes = cfg_feed_minutes conf , pandoc_user_data = cfg_pandoc_user_data conf , use_cache = cfg_use_cache conf , cache_dir = cfg_cache_dir conf , front_page = cfg_front_page conf , help_page = cfg_help_page conf , latex_engine = cfg_latex_engine conf } return gconfig
thkoch2001/gitit2
src/Config.hs
gpl-2.0
6,347
0
54
2,036
1,331
754
577
134
3
{-| Implementation of the runtime configuration details. -} {- Copyright (C) 2011, 2012, 2013 Google Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -} module Ganeti.Runtime ( GanetiDaemon(..) , MiscGroup(..) , GanetiGroup(..) , RuntimeEnts , daemonName , daemonOnlyOnMaster , daemonLogBase , daemonUser , daemonGroup , ExtraLogReason(..) , daemonLogFile , daemonsExtraLogbase , daemonsExtraLogFile , daemonPidFile , getEnts , verifyDaemonUser ) where import Control.Exception import Control.Monad import qualified Data.Map as M import System.Exit import System.FilePath import System.IO import System.IO.Error import System.Posix.Types import System.Posix.User import Text.Printf import qualified Ganeti.ConstantUtils as ConstantUtils import qualified Ganeti.Path as Path import Ganeti.BasicTypes import AutoConf data GanetiDaemon = GanetiMasterd | GanetiNoded | GanetiRapi | GanetiConfd | GanetiLuxid | GanetiMond deriving (Show, Enum, Bounded, Eq, Ord) data MiscGroup = DaemonsGroup | AdminGroup deriving (Show, Enum, Bounded, Eq, Ord) data GanetiGroup = DaemonGroup GanetiDaemon | ExtraGroup MiscGroup deriving (Show, Eq, Ord) type RuntimeEnts = (M.Map GanetiDaemon UserID, M.Map GanetiGroup GroupID) -- | Returns the daemon name for a given daemon. daemonName :: GanetiDaemon -> String daemonName GanetiMasterd = "ganeti-masterd" daemonName GanetiNoded = "ganeti-noded" daemonName GanetiRapi = "ganeti-rapi" daemonName GanetiConfd = "ganeti-confd" daemonName GanetiLuxid = "ganeti-luxid" daemonName GanetiMond = "ganeti-mond" -- | Returns whether the daemon only runs on the master node. daemonOnlyOnMaster :: GanetiDaemon -> Bool daemonOnlyOnMaster GanetiMasterd = True daemonOnlyOnMaster GanetiNoded = False daemonOnlyOnMaster GanetiRapi = False daemonOnlyOnMaster GanetiConfd = False daemonOnlyOnMaster GanetiLuxid = True daemonOnlyOnMaster GanetiMond = False -- | Returns the log file base for a daemon. daemonLogBase :: GanetiDaemon -> String daemonLogBase GanetiMasterd = "master-daemon" daemonLogBase GanetiNoded = "node-daemon" daemonLogBase GanetiRapi = "rapi-daemon" daemonLogBase GanetiConfd = "conf-daemon" daemonLogBase GanetiLuxid = "luxi-daemon" daemonLogBase GanetiMond = "monitoring-daemon" -- | Returns the configured user name for a daemon. daemonUser :: GanetiDaemon -> String daemonUser GanetiMasterd = AutoConf.masterdUser daemonUser GanetiNoded = AutoConf.nodedUser daemonUser GanetiRapi = AutoConf.rapiUser daemonUser GanetiConfd = AutoConf.confdUser daemonUser GanetiLuxid = AutoConf.luxidUser daemonUser GanetiMond = AutoConf.mondUser -- | Returns the configured group for a daemon. daemonGroup :: GanetiGroup -> String daemonGroup (DaemonGroup GanetiMasterd) = AutoConf.masterdGroup daemonGroup (DaemonGroup GanetiNoded) = AutoConf.nodedGroup daemonGroup (DaemonGroup GanetiRapi) = AutoConf.rapiGroup daemonGroup (DaemonGroup GanetiConfd) = AutoConf.confdGroup daemonGroup (DaemonGroup GanetiLuxid) = AutoConf.luxidGroup daemonGroup (DaemonGroup GanetiMond) = AutoConf.mondGroup daemonGroup (ExtraGroup DaemonsGroup) = AutoConf.daemonsGroup daemonGroup (ExtraGroup AdminGroup) = AutoConf.adminGroup data ExtraLogReason = AccessLog | ErrorLog -- | Some daemons might require more than one logfile. Specifically, -- right now only the Haskell http library "snap", used by the -- monitoring daemon, requires multiple log files. daemonsExtraLogbase :: GanetiDaemon -> ExtraLogReason -> String daemonsExtraLogbase daemon AccessLog = daemonLogBase daemon ++ "-access" daemonsExtraLogbase daemon ErrorLog = daemonLogBase daemon ++ "-error" -- | Returns the log file for a daemon. daemonLogFile :: GanetiDaemon -> IO FilePath daemonLogFile daemon = do logDir <- Path.logDir return $ logDir </> daemonLogBase daemon <.> "log" -- | Returns the extra log files for a daemon. daemonsExtraLogFile :: GanetiDaemon -> ExtraLogReason -> IO FilePath daemonsExtraLogFile daemon logreason = do logDir <- Path.logDir return $ logDir </> daemonsExtraLogbase daemon logreason <.> "log" -- | Returns the pid file name for a daemon. daemonPidFile :: GanetiDaemon -> IO FilePath daemonPidFile daemon = do runDir <- Path.runDir return $ runDir </> daemonName daemon <.> "pid" -- | All groups list. A bit hacking, as we can't enforce it's complete -- at compile time. allGroups :: [GanetiGroup] allGroups = map DaemonGroup [minBound..maxBound] ++ map ExtraGroup [minBound..maxBound] ignoreDoesNotExistErrors :: IO a -> IO (Result a) ignoreDoesNotExistErrors value = do result <- tryJust (\e -> if isDoesNotExistError e then Just (show e) else Nothing) value return $ eitherToResult result -- | Computes the group/user maps. getEnts :: IO (Result RuntimeEnts) getEnts = do users <- mapM (\daemon -> do entry <- ignoreDoesNotExistErrors . getUserEntryForName . daemonUser $ daemon return (entry >>= \e -> return (daemon, userID e)) ) [minBound..maxBound] groups <- mapM (\group -> do entry <- ignoreDoesNotExistErrors . getGroupEntryForName . daemonGroup $ group return (entry >>= \e -> return (group, groupID e)) ) allGroups return $ do -- 'Result' monad users' <- sequence users groups' <- sequence groups let usermap = M.fromList users' groupmap = M.fromList groups' return (usermap, groupmap) -- | Checks whether a daemon runs as the right user. verifyDaemonUser :: GanetiDaemon -> RuntimeEnts -> IO () verifyDaemonUser daemon ents = do myuid <- getEffectiveUserID -- note: we use directly ! as lookup failues shouldn't happen, due -- to the above map construction checkUidMatch (daemonName daemon) ((M.!) (fst ents) daemon) myuid -- | Check that two UIDs are matching or otherwise exit. checkUidMatch :: String -> UserID -> UserID -> IO () checkUidMatch name expected actual = when (expected /= actual) $ do hPrintf stderr "%s started using wrong user ID (%d), \ \expected %d\n" name (fromIntegral actual::Int) (fromIntegral expected::Int) :: IO () exitWith $ ExitFailure ConstantUtils.exitFailure
vladimir-ipatov/ganeti
src/Ganeti/Runtime.hs
gpl-2.0
7,260
0
19
1,604
1,399
737
662
139
2
{-# LANGUAGE Arrows, FlexibleContexts, FlexibleInstances, MultiParamTypeClasses, NoMonomorphismRestriction, RankNTypes, TypeOperators, UndecidableInstances #-} {- A puzzle from Raymond Smullyan's "The Lady or the Tiger?", OUP, 1982. - Copyright : (C)opyright 2011 peteg42 at gmail dot com - License : GPL (see COPYING for details) - - ghc -Wall -O -main-is MetaPuzzle3.main -rtsopts -prof -package ADHOC MetaPuzzle3.hs - ghci -package ADHOC MetaPuzzle3.hs - -} module MetaPuzzle3 where ------------------------------------------------------------------- -- Dependencies ------------------------------------------------------------------- import Prelude hiding ( id, (.) ) import ADHOC import ADHOC.NonDet import ADHOC.ModelChecker.CTL as CTL import ADHOC.ModelChecker.CounterExamples import ADHOC.Knowledge ------------------------------------------------------------------- -- The puzzle. ------------------------------------------------------------------- {- p93: 3. A Knight-Knave Metapuzzle. My book /What is the name of this book?/ contains a host of puzzles about an island on which every inhabitant is either a knight or a knave; knights always tell the truth and knaves always lie. Here is a knight-knave metapuzzle. A logician once visited this island and came across two inhabitants, A and B. He asked A, "Are both of you knights?" A answered either yes or no. The logician thought for a while but did not yet have enough information to determine what they were. The logician then asked A, "Are you two of the same type?" (Same type means both knights or both knaves.) A answered either yes or no, and the logician then knew what type each was. What type is each? -} -- | An inhabitant is either a knight or a knave. type Inhabitant b = b is_a_knightA, is_a_knaveA :: ArrowComb (~>) => B (~>) ~> B (~>) is_a_knightA = id is_a_knaveA = notA -- | The system state: the type of the two inhabitants. type State b = (Inhabitant b, Inhabitant b) inhabitant_a, inhabitant_b :: State b -> Inhabitant b inhabitant_a = fst inhabitant_b = snd logician :: AgentID logician = "logician" a_is_a_knight, b_is_a_knight :: ProbeID a_is_a_knight = "A is a knight" b_is_a_knight = "B is a knight" {- We need to model the temporal dimension here. As we don't care about the epistemic states of inhabitants A and B, we model only the logician as an agent. -} -- | The questions are answered in succeeding instants. answersA = proc s -> do -- A tells the truth iff he is a knight. a_tells_the_truth <- is_a_knightA -< inhabitant_a s -- FIXME cheesy: we should probably have 3 states, not just 2: a1, a2, finished. (| muxAC (isInitialState -< ()) ( -- 1 (to A): Are both of you knights? (returnA -< a_tells_the_truth) `iffAC` ((is_a_knightA -< inhabitant_a s) `andAC` (is_a_knightA -< inhabitant_b s))) ( -- 2 (to A): Are you two of the same type? (returnA -< a_tells_the_truth) `iffAC` ((is_a_knightA -< inhabitant_a s) `iffAC` (is_a_knightA -< inhabitant_b s))) |) -- | At each instant the logician decides whether he knows the types -- of A and B. logicianA = agent logician $ kTest $ (logician `knows_hat` a_is_a_knight) /\ (logician `knows_hat` b_is_a_knight) top = proc () -> do -- All states are initially plausible. s <- nondetLatchAC trueA -< () probeA a_is_a_knight <<< is_a_knightA -< inhabitant_a s probeA b_is_a_knight <<< is_a_knightA -< inhabitant_b s -- Pipe the answers to the logician. logicianA <<< answersA -< s ------------------------------------------------------------------- -- Synthesis and model checking. ------------------------------------------------------------------- -- Clock won't work here, we need to remember what was said. Just (kautos, m, lout) = singleSPRSynth MinNone top ctlM = mkCTLModel m -- We want the initial state(s) where the dialogue went to plan. -- -- The logician initially doesn't know, then does. dialogue_result = showWitness ctlM (neg (prop lout) /\ ex (prop lout)) test_mc = isOK (CTL.mc ctlM ((neg (prop lout) /\ ex (prop lout)) --> (neg (probe a_is_a_knight) /\ neg (probe b_is_a_knight)))) test_mc_non_trivial = not (isOK (CTL.mc ctlM (neg (neg (prop lout) /\ ex (prop lout))))) -- Answer: A and B are both knaves. -- The answer is not canonical in this straightforward way:. test_mc_canonical_naive = not (isOK (CTL.mc ctlM (ag (prop lout --> (neg (probe a_is_a_knight) /\ neg (probe b_is_a_knight)))))) canonical_naive_counterexample = showCounterExample ctlM (ag (prop lout --> (neg (probe a_is_a_knight) /\ neg (probe b_is_a_knight)))) -- ... because the logician would know A is a knight and B is a knave -- in the initial state if he gets the answer "no".
peteg/ADHOC
Apps/Smullyan/TheLadyOrTheTiger/MetaPuzzle3.hs
gpl-2.0
4,806
4
18
890
764
421
343
-1
-1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_HADDOCK show-extensions #-} -- | -- Module : Yi.Mode.JavaScript -- License : GPL-2 -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable -- -- Module defining the 'Mode' for JavaScript. 'javaScriptMode' uses -- the parser defined at "Yi.Syntax.JavaScript". module Yi.Mode.JavaScript (javaScriptMode, hooks) where import Control.Applicative import Control.Lens import Control.Monad.Writer.Lazy (execWriter) import Data.Binary import Data.DList as D (toList) import Data.Default import Data.Foldable as F (toList) import Data.List (nub) import Data.Maybe (isJust) import Data.Monoid import qualified Data.Text as T import Data.Typeable import System.FilePath.Posix (takeBaseName) import Yi.Buffer import Yi.Core (withSyntax) import Yi.Types (YiVariable) import Yi.Editor (withEditor, withOtherWindow, getEditorDyn, stringToNewBuffer , findBuffer, switchToBufferE, withCurrentBuffer, withGivenBuffer) import Yi.Event (Key(..), Event(..)) import Yi.File (fwriteE) import Yi.IncrementalParse (scanner) import Yi.Interact (choice) import Yi.Keymap (YiM, Action(..), topKeymapA) import Yi.Keymap.Keys (ctrlCh, (?>>), (?>>!), important) import Yi.Lexer.Alex (AlexState, Tok, lexScanner, commonLexer, CharScanner) import Yi.Lexer.JavaScript (alexScanToken, TT, initState, HlState, Token) import Yi.Modes (anyExtension) import Yi.Monad import qualified Yi.Rope as R import Yi.String import Yi.Syntax (ExtHL(..), mkHighlighter, Scanner) import Yi.Syntax.JavaScript (Tree, parse, getStrokes) import Yi.Syntax.Tree (getLastPath) import Yi.Verifier.JavaScript (verify) javaScriptAbstract :: Mode syntax javaScriptAbstract = emptyMode { modeApplies = anyExtension ["js"] , modeName = "javascript" , modeToggleCommentSelection = Just (toggleCommentB "//") } javaScriptMode :: Mode (Tree TT) javaScriptMode = javaScriptAbstract { modeIndent = jsSimpleIndent , modeHL = ExtHL $ mkHighlighter (scanner parse . jsLexer) , modeGetStrokes = getStrokes } jsSimpleIndent :: Tree TT -> IndentBehaviour -> BufferM () jsSimpleIndent t behave = do indLevel <- shiftWidth <$> indentSettingsB prevInd <- getNextNonBlankLineB Backward >>= indentOfB solPnt <- pointAt moveToSol let path = getLastPath (F.toList t) solPnt case path of Nothing -> indentTo [indLevel, 0] Just _ -> indentTo [prevInd, prevInd + indLevel, prevInd - indLevel] where -- Given a list of possible columns to indent to, removes any -- duplicates from it and cycles between the resulting -- indentations. indentTo :: [Int] -> BufferM () indentTo = cycleIndentsB behave . nub jsLexer :: CharScanner -> Scanner (AlexState HlState) (Tok Token) jsLexer = lexScanner (commonLexer alexScanToken initState) -------------------------------------------------------------------------------- -- tta :: Yi.Lexer.Alex.Tok Token -> Maybe (Yi.Syntax.Span String) -- tta = sequenceA . tokToSpan . (fmap Main.tokenToText) -- | Hooks for the JavaScript mode. hooks :: Mode (Tree TT) -> Mode (Tree TT) hooks mode = mode { modeKeymap = topKeymapA %~ important (choice m) , modeFollow = YiA . jsCompile } where m = [ ctrlCh 'c' ?>> ctrlCh 'l' ?>>! withSyntax modeFollow , Event KEnter [] ?>>! newlineAndIndentB ] newtype JSBuffer = JSBuffer (Maybe BufferRef) deriving (Default, Typeable, Binary) instance YiVariable JSBuffer -- | The "compiler." jsCompile :: Tree TT -> YiM () jsCompile tree = do fwriteE Just filename <- withCurrentBuffer $ gets file buf <- getJSBuffer withOtherWindow $ withEditor $ switchToBufferE buf jsErrors filename buf (D.toList $ execWriter $ verify tree) -- | Returns the JS verifier buffer, creating it if necessary. getJSBuffer :: YiM BufferRef getJSBuffer = withOtherWindow $ do JSBuffer mb <- withEditor getEditorDyn case mb of Nothing -> mkJSBuffer Just b -> do stillExists <- isJust <$> findBuffer b if stillExists then return b else mkJSBuffer -- | Creates a new empty buffer and returns it. mkJSBuffer :: YiM BufferRef mkJSBuffer = stringToNewBuffer (MemBuffer "js") mempty -- | Given a filename, a BufferRef and a list of errors, prints the -- errors in that buffer. jsErrors :: Show a => String -> BufferRef -> [a] -> YiM () jsErrors fname buf errs = let problems = T.unlines $ map item errs item x = "* " <> showT x str = if null errs then "No problems found!" else "Problems in " <> R.fromString (takeBaseName fname) <> ":\n" <> R.fromText problems in withGivenBuffer buf (replaceBufferContent str)
atsukotakahashi/wi
src/library/Yi/Mode/JavaScript.hs
gpl-2.0
5,302
1
15
1,390
1,218
675
543
104
3
module Lamdu.GUI.Expr.EventMap ( add, makeBaseEvents , Options(..), defaultOptions , extractCursor , addLetEventMap , makeLiteralNumberEventMap , makeLiteralCharEventMap , makeLiteralEventMap , allowedSearchTerm, isAlphaNumericName, recordOpener , parenKeysEvent , closeParenEvent ) where import qualified Control.Lens as Lens import qualified Data.Char as Char import qualified Data.Text as Text import qualified GUI.Momentu.Direction as Dir import GUI.Momentu.EventMap (EventMap) import qualified GUI.Momentu.EventMap as E import qualified GUI.Momentu.I18N as MomentuTexts import GUI.Momentu.ModKey (noMods) import qualified GUI.Momentu.ModKey as ModKey import qualified GUI.Momentu.State as GuiState import GUI.Momentu.Widget (EventContext) import qualified GUI.Momentu.Widget as Widget import qualified GUI.Momentu.Widgets.Menu.Search as SearchMenu import qualified Lamdu.CharClassification as Chars import qualified Lamdu.Config as Config import Lamdu.GUI.Monad (GuiM) import qualified Lamdu.GUI.Monad as GuiM import qualified Lamdu.GUI.WidgetIds as WidgetIds import qualified Lamdu.I18N.CodeUI as Texts import qualified Lamdu.I18N.Definitions as Texts import Lamdu.Precedence (precedence) import Lamdu.Sugar.Parens (MinOpPrec) import qualified Lamdu.Sugar.Types as Sugar import Lamdu.Prelude data ExprInfo o = ExprInfo { exprInfoActions :: Sugar.NodeActions o , exprInfoMinOpPrec :: MinOpPrec , exprInfoIsSelected :: Bool } newtype Options = Options { addOperatorSetHoleState :: Maybe Sugar.EntityId } defaultOptions :: Options defaultOptions = Options { addOperatorSetHoleState = Nothing } exprInfoFromPl :: Monad i => GuiM env i o (Sugar.Payload v o0 -> ExprInfo o0) exprInfoFromPl = GuiState.isSubCursor <&> \isSubCursor pl -> let isSelected = WidgetIds.fromExprPayload pl & isSubCursor in ExprInfo { exprInfoActions = pl ^. Sugar.plActions , exprInfoMinOpPrec = -- Expression with parentheses intercepts all operations from inside it, -- But if it is itself selected then we're out of the parentheses, -- and its parents may take some operators. if pl ^. Sugar.plParenInfo . Sugar.piNeedParens && not isSelected then 0 else pl ^. Sugar.plParenInfo . Sugar.piMinOpPrec , exprInfoIsSelected = isSelected } add :: _ => Options -> Sugar.Payload v o -> GuiM env i o (w o -> w o) add options pl = exprInfoFromPl ?? pl >>= actionsEventMap options <&> Widget.weakerEventsWithContext makeBaseEvents :: _ => Sugar.Payload v o -> GuiM env i o (EventMap (o GuiState.Update)) makeBaseEvents pl = exprInfoFromPl ?? pl >>= baseEvents extractCursor :: Sugar.ExtractDestination -> Widget.Id extractCursor (Sugar.ExtractToLet letId) = WidgetIds.fromEntityId letId extractCursor (Sugar.ExtractToDef defId) = WidgetIds.fromEntityId defId extractEventMap :: _ => m (Sugar.NodeActions o -> EventMap (o GuiState.Update)) extractEventMap = Lens.view id <&> \env actions -> actions ^. Sugar.extract <&> extractCursor & E.keysEventMapMovesCursor (env ^. has . Config.extractKeys) (E.toDoc env [has . MomentuTexts.edit, has . Texts.extract]) addLetEventMap :: _ => o Sugar.EntityId -> GuiM env i o (EventMap (o GuiState.Update)) addLetEventMap addLet = do env <- Lens.view id savePos <- GuiM.mkPrejumpPosSaver savePos >> addLet <&> WidgetIds.fromEntityId & E.keysEventMapMovesCursor (env ^. has . Config.letAddItemKeys) (E.toDoc env [ has . MomentuTexts.edit , has . Texts.letClause , has . Texts.add ]) & pure actionsEventMap :: _ => Options -> ExprInfo o -> GuiM env i o (EventContext -> EventMap (o GuiState.Update)) actionsEventMap options exprInfo = (baseEvents exprInfo <&> const) -- throw away EventContext here <> (transformEventMap ?? options ?? exprInfo) baseEvents :: _ => ExprInfo o -> GuiM env i o (EventMap (o GuiState.Update)) baseEvents exprInfo = mconcat [ detachEventMap ?? exprInfo , extractEventMap ?? actions , mkReplaceParent , actions ^. Sugar.delete & replaceEventMap , actions ^. Sugar.mApply & foldMap applyEventMap , makeLiteralEventMap ?? actions ^. Sugar.setToLiteral ] where actions = exprInfoActions exprInfo mkReplaceParent = Lens.view id <&> \env -> let replaceKeys = env ^. has . Config.replaceParentKeys in actions ^. Sugar.mReplaceParent & foldMap (E.keysEventMapMovesCursor replaceKeys (E.toDoc env [has . MomentuTexts.edit, has . Texts.replaceParent]) . fmap WidgetIds.fromEntityId) -- | Create the hole search term for new apply operators, -- given the extra search term chars from another hole. applyEventMap :: _ => o Sugar.EntityId -> GuiM env i o (EventMap (o GuiState.Update)) applyEventMap action = Lens.view id <&> \env -> action <&> WidgetIds.fromEntityId & E.keysEventMapMovesCursor [noMods ModKey.Key'Space] (E.toDoc env [ has . MomentuTexts.edit , has . Texts.apply ]) transformSearchTerm :: _ => m (ExprInfo o -> EventContext -> EventMap Text) transformSearchTerm = Lens.view id <&> \env exprInfo eventCtx -> let maybeTransformEventMap | exprInfoIsSelected exprInfo = E.charEventMap "Letter" (E.toDoc env [has . MomentuTexts.edit, has . Texts.transform]) transform | otherwise = mempty transform c = do guard (c `notElem` Chars.operator) guard (allowedSearchTerm env (Text.singleton c)) pure (Text.singleton c) searchStrRemainder = eventCtx ^. Widget.ePrevTextRemainder acceptOp = (>= exprInfoMinOpPrec exprInfo) . precedence opDoc = E.toDoc env [has . MomentuTexts.edit, has . Texts.applyOperator] mkOpsGroup ops = E.charGroup Nothing opDoc ops Text.singleton afterDot = Just . Text.singleton in case Text.uncons searchStrRemainder of Nothing -> mkOpsGroup (filter acceptOp Chars.operator) <> maybeTransformEventMap Just ('.', "") | acceptOp '.' -> E.charEventMap "Letter or Operator" opDoc afterDot | otherwise -> mempty Just (firstOp, _) | acceptOp firstOp -> mkOpsGroup Chars.operator <> maybeTransformEventMap | otherwise -> maybeTransformEventMap <&> (searchStrRemainder <>) transformEventMap :: _ => m (Options -> ExprInfo o -> EventContext -> EventMap (o GuiState.Update)) transformEventMap = transformSearchTerm <&> \transform options exprInfo eventCtx -> let x = case exprInfoActions exprInfo ^. Sugar.detach of Sugar.DetachAction detach -> addOperatorSetHoleState options & maybe detachAndOpen widgetId where detachAndOpen = detach <&> WidgetIds.fromEntityId <&> WidgetIds.fragmentHoleId Sugar.FragmentedAlready holeId -> widgetId holeId <&> WidgetIds.fragmentHoleId in transform exprInfo eventCtx <&> SearchMenu.enterWithSearchTerm <&> (x <&>) where widgetId = pure . WidgetIds.fromEntityId parenKeysEvent :: (MonadReader env m, Has Dir.Layout env) => m ([Lens.ALens' env Text] -> o a -> EventMap (o a)) parenKeysEvent = Lens.view id <&> \env texts act -> let parenKeys = case env ^. has of Dir.LeftToRight -> "([" Dir.RightToLeft -> ")]" in E.charGroup (Just "Open Paren") (E.toDoc env texts) parenKeys (const act) detachEventMap :: _ => m (ExprInfo o -> EventMap (o GuiState.Update)) detachEventMap = parenKeysEvent <&> \mkEvent exprInfo -> case exprInfoActions exprInfo ^. Sugar.detach of Sugar.DetachAction act | exprInfoIsSelected exprInfo -> mkEvent [has . MomentuTexts.edit, has . Texts.detach] (mempty <$ act) _ -> mempty replaceEventMap :: _ => Sugar.Delete f -> m (EventMap (f GuiState.Update)) replaceEventMap x = Lens.view id <&> \env -> let mk action docLens = action <&> WidgetIds.fromEntityId & E.keysEventMapMovesCursor (Config.delKeys env) (E.toDoc env [has . MomentuTexts.edit, has . docLens]) in case x of Sugar.SetToHole action -> mk action Texts.setToHole Sugar.Delete action -> mk action MomentuTexts.delete Sugar.CannotDelete -> mempty goToLiteral :: Widget.Id -> GuiState.Update goToLiteral = GuiState.updateCursor . WidgetIds.literalEditOf makeLiteralNumberEventMap :: _ => String -> m ((Sugar.Literal Identity -> o Sugar.EntityId) -> EventMap (o GuiState.Update)) makeLiteralNumberEventMap prefix = makeLiteralCommon (Just "Digit") Chars.digit Texts.literalNumber ?? Sugar.LiteralNum . Identity . read . (prefix <>) . (: []) <&> Lens.mapped . Lens.mapped . Lens.mapped %~ goToLiteral makeLiteralCharEventMap :: _ => Text -> m ((Sugar.Literal Identity -> o Sugar.EntityId) -> EventMap (o GuiState.Update)) makeLiteralCharEventMap searchTerm = case Text.unpack searchTerm of ['\'', c] -> makeLiteralCommon Nothing "'" Texts.literalChar ?? const (Sugar.LiteralChar (Identity c)) <&> Lens.mapped . Lens.mapped . Lens.mapped %~ GuiState.updateCursor _ -> mempty makeLiteralCommon :: _ => Maybe Text -> String -> Lens.ALens' (Texts.CodeUI Text) Text -> m ((Char -> Sugar.Literal Identity) -> (Sugar.Literal Identity -> o Sugar.EntityId) -> EventMap (o Widget.Id)) makeLiteralCommon mGroupDesc chars help = Lens.view id <&> E.toDoc <&> \toDoc f makeLiteral -> E.charGroup mGroupDesc (toDoc [has . MomentuTexts.edit, has . Lens.cloneLens help]) chars (fmap WidgetIds.fromEntityId . makeLiteral . f) makeLiteralEventMap :: _ => m ((Sugar.Literal Identity -> o Sugar.EntityId) -> EventMap (o GuiState.Update)) makeLiteralEventMap = mconcat [ makeLiteralCommon Nothing "\"" Texts.literalText ?? const (Sugar.LiteralText (Identity "")) <&> f , makeLiteralCommon Nothing "#" Texts.literalBytes ?? const (Sugar.LiteralBytes (Identity "")) <&> f , makeLiteralNumberEventMap "" ] where f = Lens.mapped . Lens.mapped . Lens.mapped %~ goToLiteral recordOpener :: (MonadReader env m, Has Dir.Layout env) => m Char recordOpener = Lens.view has <&> \case Dir.LeftToRight -> '{' Dir.RightToLeft -> '}' allowedSearchTerm :: (MonadReader env m, Has Dir.Layout env) => m (Text -> Bool) allowedSearchTerm = recordOpener <&> \r searchTerm -> any (searchTerm &) [ Text.all (`elem` Chars.operator) , isNameOrPrefixed , (`elem` ["\\", Text.singleton r]) , isCharSearchTerm ] isCharSearchTerm :: Text -> Bool isCharSearchTerm t = case Text.uncons t of Just ('\'', x) -> Text.length x == 1 _ -> False isNameOrPrefixed :: Text -> Bool isNameOrPrefixed t = case Text.uncons t of Nothing -> True Just (x, xs) | x `elem` prefixes -> isAlphaNumericName xs Just _ -> isAlphaNumericName t where prefixes :: String prefixes = ".'" isAlphaNumericName :: Text -> Bool isAlphaNumericName suffix = case Text.uncons suffix of Nothing -> True Just (x, xs) -> Char.isAlpha x && Text.all Char.isAlphaNum xs closeParenChars :: (MonadReader env m, Has Dir.Layout env) => m [Char] closeParenChars = Lens.view has <&> \case Dir.LeftToRight -> ")]" Dir.RightToLeft -> "([" closeParenEvent :: (MonadReader env m, Has Dir.Layout env, Functor f) => [Lens.ALens' env Text] -> f Widget.Id -> m (EventMap (f GuiState.Update)) closeParenEvent doc action = E.charGroup (Just "Close Paren") <$> (Lens.view id <&> (`E.toDoc` doc)) <*> closeParenChars ?? const (action <&> GuiState.updateCursor)
lamdu/lamdu
src/Lamdu/GUI/Expr/EventMap.hs
gpl-3.0
12,244
0
20
3,049
3,602
1,864
1,738
-1
-1
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TypeSynonymInstances #-} module MulSYM where import ExpSYM import qualified ExpSYM class MulSYM repr where mul :: repr -> repr -> repr tfm1 :: (ExpSYM repr, MulSYM repr) => repr tfm1 = add (lit 7) (neg (mul (lit 1) (lit 2))) tfm2 :: (ExpSYM repr, MulSYM repr) => repr tfm2 = mul (lit 7) ExpSYM.tf1 -------------------------------------------------------------------------------- -- Instances of @MulSYM@ -------------------------------------------------------------------------------- instance MulSYM Int where mul = (*) instance MulSYM String where mul e0 e1 = "(" ++ e0 ++ " * " ++ e1 ++ ")"
capitanbatata/sandbox
tagless/src/MulSYM.hs
gpl-3.0
675
0
11
125
187
102
85
15
1
module FOOL.AST where -- Simplified FOOL Terms data FOOLTerm = IConst Integer | BConst Bool | Var String | TypedVar String Type | ITE FOOLTerm FOOLTerm FOOLTerm | Tuple [FOOLTerm] | FunApp String [FOOLTerm] | Store FOOLTerm FOOLTerm FOOLTerm | Select FOOLTerm FOOLTerm | Bin BOp FOOLTerm FOOLTerm | Uni UOp FOOLTerm | Quantified QOp [FOOLTerm] FOOLTerm | Let [(FOOLTerm, FOOLTerm)] FOOLTerm -- for parallel assign deriving (Eq, Show) instance Ord FOOLTerm where compare (TypedVar _ t1) (TypedVar _ t2) = compare t1 t2 compare _ _ = EQ data Type = I -- $i | TType String -- $tType | Boolean -- $o | Integer -- $int -- Both map and func are arrow type, but tptp distinguish them | MapType Type Type | FuncType [Type] Type deriving (Eq, Show, Ord) data BOp = And | Or | Imply | Iff | Xor | Exply | Greater | Less | Geq | Leq | Equal | Neq | Add | Subtract | Multiply | Div deriving (Show, Eq, Ord) data UOp = Neg | Not deriving (Show, Eq, Ord) data QOp = Forall | Exists deriving (Show, Eq, Ord)
emptylambda/BLT
src/FOOL/AST.hs
gpl-3.0
1,289
0
8
486
353
206
147
33
0
-- import Control.Wire -- import Render.Render -- import Utils.Helpers (wee) import Control.Category import Control.Monad import Control.Monad.Fix import Data.Traversable import FRP.Netwire import Linear.V3 import Linear.Vector import Physics import Prelude hiding ((.), id) import Render.Backend.GNUPlot import Render.Render fr :: Double fr = 60 main :: IO () main = do clearLogs bCount runTest bCount (roomBodies roomGravity roomBodyList verlet) where roomGravity = V3 0 0 (-2) roomBodyList = [(Body 1 zero, V3 1 1 1)] bCount = length roomBodyList runTest :: Int -> Wire (Timed Double ()) String IO () [Body] -> IO () runTest n w = do clearLogs 10 runBackend (gnuPlotBackend (1/fr) (round (fr*6))) (writeLog n) (w . pure ()) clearLogs :: Int -> IO () clearLogs n = forM_ [0..(n-1)] $ \i -> writeFile ("out/room_b" ++ show i ++ ".dat") "" writeLog :: Int -> [Body] -> IO () writeLog n bodies = forM_ [0..(n-1)] $ \i -> appendFile ("out/room_b" ++ show i ++ ".dat") ((++ "\n") . gnuplot $ bodies !! i) roomBodies :: (MonadFix m, Monoid e, HasTime Double s) => V3D -> [(Body, V3D)] -> Integrator -> Wire s e m () [Body] roomBodies grav bodies igr = sequenceA $ map makeWire bodies where makeWire (b0, v0) = bodyFConstrained wall b0 v0 igr . pure [grav] wall (V3 x _ z) | z < 0 = Just (V3 0 0 1) | z > 1 = Just (V3 0 0 (-1)) | x < 0 = Just (V3 1 0 0) | x > 1.5 = Just (V3 (-1) 0 0) | otherwise = Nothing
mstksg/netwire-experiments
src/Experiment/Room.hs
gpl-3.0
1,597
0
13
452
703
363
340
-1
-1
module Ant where import Data.Array.Repa (Z(..),(:.)(..),(!)) import qualified Data.Array.Repa as R {- Direction 0 3 1 2 -} type Dir = Int type Ant = (Int, Int) type Grid = R.Array R.U R.DIM2 Int -- When n = 1, turn right -- When n = 3, turn left turn :: Dir -> Int -> Dir turn d n = (d + n) `mod` 4 forward :: Ant -> Dir -> Ant forward (a,b) d | d == 0 = (a, b+1) | d == 1 = (a+1, b) | d == 2 = (a, b-1) | d == 3 = (a-1, b) tick :: Ant -> Grid -> IO Grid tick ant world = R.computeP $ R.traverse world id (\_ sh@(Z :. a :. b) -> if ant == (a,b) then turn (world ! sh) 2 else world ! sh) zeroGrid :: Int -> Int -> IO Grid zeroGrid w h = return $ R.fromListUnboxed (Z :. w :. h) (replicate (w*h) 3)
iurdan/haskell-langton
src/Ant.hs
gpl-3.0
799
0
12
265
398
223
175
20
2
-- Copyright (C) 2013 Michael Zuser [email protected] -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE IncoherentInstances #-} -- | Chain comparisons together -- -- example: -- -- @ -- inRange :: Ord a => (a, a) -> a -> Bool -- inRange (a, b) x = doCmp (a <=. x <=. b) -- @ module KitchenSink.ChainCmp ( CmpChain, doCmp , (==.), (/=.), (<.) , (>.), (<=.), (>=.) ) where import KitchenSink.Combinators import Data.Maybe infixl 4 ==., /=., <., <=., >., >=. -- | A chain of comparisions. newtype CmpChain a = Chain {unChain :: Maybe a} -- | Run a chain of comparisions to get a boolean result. doCmp :: CmpChain a -> Bool doCmp = isJust . unChain class ChainCmp a b where -- | Chaining ('==') (==.) :: a -> b -> CmpChain b -- | Chaining ('/=') (/=.) :: a -> b -> CmpChain b -- | Chaining ('<') (<.) :: a -> b -> CmpChain b -- | Chaining ('<=') (<=.) :: a -> b -> CmpChain b -- | Chaining ('>') (>.) :: a -> b -> CmpChain b -- | Chaining ('>=') (>=.) :: a -> b -> CmpChain b liftS :: (a -> a -> Bool) -> (CmpChain a -> a -> CmpChain a) liftS op x y = Chain $ (? y) . (`op` y) =<< unChain x liftZ :: (a -> a -> Bool) -> (a -> a -> CmpChain a) liftZ op x y = Chain $ (? y) . (`op` y) $ x instance (a ~ b, Ord a) => ChainCmp (CmpChain a) b where (==.) = liftS (==) (/=.) = liftS (/=) (<.) = liftS (<) (<=.) = liftS (<=) (>.) = liftS (>) (>=.) = liftS (>=) instance (a ~ b, Ord a) => ChainCmp a b where (==.) = liftZ (==) (/=.) = liftZ (/=) (<.) = liftZ (<) (<=.) = liftZ (<=) (>.) = liftZ (>) (>=.) = liftZ (>=)
bacchanalia/KitchenSink
KitchenSink/ChainCmp.hs
gpl-3.0
2,360
0
9
581
611
378
233
38
1
{-# LANGUAGE NoImplicitPrelude, TemplateHaskell, OverloadedStrings #-} module Graphics.UI.Bottle.Widgets.FlyNav ( make, makeIO , Config(..) , State , initState ) where import Prelude.Compat import Control.Applicative (liftA2) import Control.Lens (Lens') import qualified Control.Lens as Lens import Control.Lens.Operators import Control.Lens.Tuple import Control.Monad (void) import Data.IORef import Data.Monoid ((<>)) import Data.Vector.Vector2 (Vector2(..)) import qualified Graphics.DrawingCombinators as Draw import Graphics.UI.Bottle.Animation (AnimId) import qualified Graphics.UI.Bottle.Animation as Anim import qualified Graphics.UI.Bottle.Direction as Direction import qualified Graphics.UI.Bottle.EventMap as EventMap import Graphics.UI.Bottle.ModKey (ModKey(..), ctrlMods, shiftMods) import Graphics.UI.Bottle.Rect (Rect(..)) import qualified Graphics.UI.Bottle.Rect as Rect import Graphics.UI.Bottle.Widget (Widget, Size) import qualified Graphics.UI.Bottle.Widget as Widget import Graphics.UI.Bottle.Widgets.StdKeys (DirKeys(..), stdDirKeys) import qualified Graphics.UI.GLFW as GLFW newtype Config = Config { configLayer :: Anim.Layer } data Movement = Movement { _mName :: String , __mModKey :: ModKey , _mDir :: Vector2 Widget.R } Lens.makeLenses ''Movement data ActiveState = ActiveState { _asPos :: Vector2 Widget.R , _asMovements :: [Movement] } type State = Maybe ActiveState modKey :: GLFW.Key -> ModKey modKey = ModKey (ctrlMods <> shiftMods) finishKeys :: [ModKey] finishKeys = [ ModKey shiftMods GLFW.Key'LeftControl , ModKey shiftMods GLFW.Key'RightControl , ModKey ctrlMods GLFW.Key'LeftShift , ModKey ctrlMods GLFW.Key'RightShift ] modifierKeys :: [GLFW.Key] modifierKeys = [ GLFW.Key'LeftControl , GLFW.Key'RightControl , GLFW.Key'LeftShift , GLFW.Key'RightShift ] initState :: State initState = Nothing withEmptyResult :: Functor f => f () -> f Widget.EventResult withEmptyResult = (fmap . const) mempty mkTickHandler :: Functor f => f () -> Widget.EventHandlers f mkTickHandler = EventMap.tickHandler . withEmptyResult mkKeyMap :: Functor f => GLFW.KeyState -> ModKey -> EventMap.Doc -> f () -> Widget.EventHandlers f mkKeyMap isPress key doc = EventMap.keyEventMap (EventMap.KeyEvent isPress key) doc . withEmptyResult speed :: Vector2 Widget.R speed = 8 accel :: Vector2 Widget.R accel = 1.05 targetSize :: Size targetSize = Vector2 25 25 targetColor :: Draw.Color targetColor = Draw.Color 0.9 0.9 0 0.7 highlightColor :: Draw.Color highlightColor = Draw.Color 0.4 0.4 1 0.4 target :: Config -> AnimId -> Vector2 Widget.R -> Anim.Frame target config animId pos = void Draw.circle & Anim.simpleFrame animId & Anim.unitImages %~ Draw.tint targetColor & Anim.scale targetSize & Anim.translate pos & Anim.layers +~ configLayer config cap :: Size -> Vector2 Widget.R -> Vector2 Widget.R cap size = liftA2 max 0 . liftA2 min size highlightRect :: AnimId -> Rect -> Anim.Frame highlightRect animId (Rect pos size) = Anim.unitSquare animId & Anim.unitImages %~ Draw.tint highlightColor & Anim.layers -~ 50 -- TODO: 50?! & Anim.scale size & Anim.translate pos addMovements :: Functor f => Vector2 Widget.R -> [Movement] -> (Maybe ActiveState -> f ()) -> Widget.EventHandlers f addMovements = mconcat [ addMovement "Down" (keysDown stdDirKeys) (Vector2 0 1) , addMovement "Up" (keysUp stdDirKeys) (Vector2 0 (-1)) , addMovement "Right" (keysRight stdDirKeys) (Vector2 1 0) , addMovement "Left" (keysLeft stdDirKeys) (Vector2 (-1) 0) ] addMovement :: Functor f => String -> [GLFW.Key] -> Vector2 Widget.R -> Vector2 Widget.R -> [Movement] -> (Maybe ActiveState -> f ()) -> Widget.EventHandlers f addMovement name keys dir pos movements setState | name `elem` map (^. mName) movements = mempty | otherwise = mconcat [ mkKeyMap GLFW.KeyState'Pressed mk (EventMap.Doc ["Navigation", "FlyNav", name]) . setState . Just $ ActiveState pos (Movement name mk dir : movements) | key <- keys , let mk = modKey key ] -- separate out a single element each time zipped :: [a] -> [(a, [a])] zipped [] = [] zipped (x:xs) = (x, xs) : (Lens.mapped . _2 %~ (x:)) (zipped xs) focalCenter :: Lens' (Widget f) (Vector2 Widget.R) focalCenter = Widget.focalArea . Rect.center make :: Applicative f => Config -> AnimId -> State -> (State -> f ()) -> Widget f -> Widget f make _ _ Nothing setState w = w & Widget.eventMap <>~ addMovements (w ^. focalCenter) [] setState make config animId (Just (ActiveState pos movements)) setState w = w & Widget.animFrame %~ mappend frame & Widget.eventMap .~ eventMap where delta = sum $ map (^. mDir) movements highlight = maybe mempty (highlightRect (animId ++ ["highlight"]) . (^. Widget.enterResultRect)) mEnteredChild frame = target config (animId ++ ["target"]) pos `mappend` highlight mEnteredChild = fmap ($ targetPos) $ w ^. Widget.mEnter targetPos = Direction.Point pos nextState = ActiveState (cap (pos + delta*speed) (w ^. Widget.size)) $ movements & Lens.mapped . mDir *~ accel eventMap = mconcat $ (mkTickHandler . setState . Just) nextState : addMovements pos movements setState : finishMove : [ stopMovement name mk lessMovements | (Movement name mk _, lessMovements) <- zipped movements ] finishMove = mconcat $ map finishOn $ finishKeys ++ map modKey modifierKeys stopMovement name mk newMovements = mkKeyMap GLFW.KeyState'Released mk (EventMap.Doc ["Navigation", "Stop FlyNav", name]) . setState . Just $ ActiveState pos newMovements finishOn mk = EventMap.keyEventMap (EventMap.KeyEvent GLFW.KeyState'Released mk) (EventMap.Doc ["Navigation", "Stop FlyNav"]) $ setState Nothing *> -- TODO: Just cancel FlyNav in any case if the MaybeEnter is -- Nothing... maybe (pure mempty) (^. Widget.enterResultEvent) mEnteredChild makeIO :: Config -> AnimId -> IO (Widget IO -> IO (Widget IO)) makeIO config animId = do flyNavState <- newIORef initState return $ \widget -> do fnState <- readIORef flyNavState return $ make config animId fnState (writeIORef flyNavState) widget
rvion/lamdu
bottlelib/Graphics/UI/Bottle/Widgets/FlyNav.hs
gpl-3.0
6,884
0
16
1,790
2,100
1,122
978
-1
-1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.TagManager.Accounts.Containers.Workspaces.Zones.List -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Lists all GTM Zones of a GTM container workspace. -- -- /See:/ <https://developers.google.com/tag-manager Tag Manager API Reference> for @tagmanager.accounts.containers.workspaces.zones.list@. module Network.Google.Resource.TagManager.Accounts.Containers.Workspaces.Zones.List ( -- * REST Resource AccountsContainersWorkspacesZonesListResource -- * Creating a Request , accountsContainersWorkspacesZonesList , AccountsContainersWorkspacesZonesList -- * Request Lenses , acwzlParent , acwzlXgafv , acwzlUploadProtocol , acwzlAccessToken , acwzlUploadType , acwzlPageToken , acwzlCallback ) where import Network.Google.Prelude import Network.Google.TagManager.Types -- | A resource alias for @tagmanager.accounts.containers.workspaces.zones.list@ method which the -- 'AccountsContainersWorkspacesZonesList' request conforms to. type AccountsContainersWorkspacesZonesListResource = "tagmanager" :> "v2" :> Capture "parent" Text :> "zones" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "pageToken" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] ListZonesResponse -- | Lists all GTM Zones of a GTM container workspace. -- -- /See:/ 'accountsContainersWorkspacesZonesList' smart constructor. data AccountsContainersWorkspacesZonesList = AccountsContainersWorkspacesZonesList' { _acwzlParent :: !Text , _acwzlXgafv :: !(Maybe Xgafv) , _acwzlUploadProtocol :: !(Maybe Text) , _acwzlAccessToken :: !(Maybe Text) , _acwzlUploadType :: !(Maybe Text) , _acwzlPageToken :: !(Maybe Text) , _acwzlCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'AccountsContainersWorkspacesZonesList' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'acwzlParent' -- -- * 'acwzlXgafv' -- -- * 'acwzlUploadProtocol' -- -- * 'acwzlAccessToken' -- -- * 'acwzlUploadType' -- -- * 'acwzlPageToken' -- -- * 'acwzlCallback' accountsContainersWorkspacesZonesList :: Text -- ^ 'acwzlParent' -> AccountsContainersWorkspacesZonesList accountsContainersWorkspacesZonesList pAcwzlParent_ = AccountsContainersWorkspacesZonesList' { _acwzlParent = pAcwzlParent_ , _acwzlXgafv = Nothing , _acwzlUploadProtocol = Nothing , _acwzlAccessToken = Nothing , _acwzlUploadType = Nothing , _acwzlPageToken = Nothing , _acwzlCallback = Nothing } -- | GTM Workspace\'s API relative path. Example: -- accounts\/{account_id}\/containers\/{container_id}\/workspaces\/{workspace_id} acwzlParent :: Lens' AccountsContainersWorkspacesZonesList Text acwzlParent = lens _acwzlParent (\ s a -> s{_acwzlParent = a}) -- | V1 error format. acwzlXgafv :: Lens' AccountsContainersWorkspacesZonesList (Maybe Xgafv) acwzlXgafv = lens _acwzlXgafv (\ s a -> s{_acwzlXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). acwzlUploadProtocol :: Lens' AccountsContainersWorkspacesZonesList (Maybe Text) acwzlUploadProtocol = lens _acwzlUploadProtocol (\ s a -> s{_acwzlUploadProtocol = a}) -- | OAuth access token. acwzlAccessToken :: Lens' AccountsContainersWorkspacesZonesList (Maybe Text) acwzlAccessToken = lens _acwzlAccessToken (\ s a -> s{_acwzlAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). acwzlUploadType :: Lens' AccountsContainersWorkspacesZonesList (Maybe Text) acwzlUploadType = lens _acwzlUploadType (\ s a -> s{_acwzlUploadType = a}) -- | Continuation token for fetching the next page of results. acwzlPageToken :: Lens' AccountsContainersWorkspacesZonesList (Maybe Text) acwzlPageToken = lens _acwzlPageToken (\ s a -> s{_acwzlPageToken = a}) -- | JSONP acwzlCallback :: Lens' AccountsContainersWorkspacesZonesList (Maybe Text) acwzlCallback = lens _acwzlCallback (\ s a -> s{_acwzlCallback = a}) instance GoogleRequest AccountsContainersWorkspacesZonesList where type Rs AccountsContainersWorkspacesZonesList = ListZonesResponse type Scopes AccountsContainersWorkspacesZonesList = '["https://www.googleapis.com/auth/tagmanager.edit.containers", "https://www.googleapis.com/auth/tagmanager.readonly"] requestClient AccountsContainersWorkspacesZonesList'{..} = go _acwzlParent _acwzlXgafv _acwzlUploadProtocol _acwzlAccessToken _acwzlUploadType _acwzlPageToken _acwzlCallback (Just AltJSON) tagManagerService where go = buildClient (Proxy :: Proxy AccountsContainersWorkspacesZonesListResource) mempty
brendanhay/gogol
gogol-tagmanager/gen/Network/Google/Resource/TagManager/Accounts/Containers/Workspaces/Zones/List.hs
mpl-2.0
5,945
0
18
1,309
789
460
329
122
1
{-# LANGUAGE CPP #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE UnicodeSyntax #-} {-| Module : $Header$ Description : functions necessary for deploying the application as a webservice Copyright : (c) Justus Adam, 2015 License : LGPL-3 Maintainer : [email protected] Stability : experimental Portability : POSIX Uses wai and warp to create a deployable web service instance of this software. -} module SchedulePlanner.Server (server, app, ServerOptions(..)) where import Control.Monad.Unicode import Data.ByteString.Lazy (ByteString) import Network.HTTP.Types (Header, imATeaPot418, methodOptions, methodPost, ok200) import Network.Wai (Application, lazyRequestBody, remoteHost, requestMethod, responseLBS) import Network.Wai.Handler.Warp (run) import Prelude.Unicode import SchedulePlanner.Util defaultHeaders :: [Header] defaultHeaders = [ ("Access-Control-Allow-Origin" , "http://justus.science") , ("Access-Control-Allow-Methods", "POST") , ("Access-Control-Allow-Headers", "Content-Type") ] {-| Options used for the "serve" subcommand. -} data ServerOptions = ServerOptions { port :: Int -- ^ default 'defaultServerPort' , logFile :: Maybe FilePath } {-| The 'Application' used for the server instance. -} app :: ServerOptions -> (ByteString -> ByteString) -> Application app _ app' request respond | rMethod == methodPost = logLine ("New POST request from " ++ show (remoteHost request)) ≫ lazyRequestBody request ≫= respond . responseLBS ok200 headers . app' | rMethod == methodOptions = respond $ responseLBS ok200 headers "Bring it!" | otherwise = logLine ("Unhandleable request: " ++ show request) ≫ respond (responseLBS imATeaPot418 [] "What are you doing to an innocent teapot?") where rMethod = requestMethod request headers = defaultHeaders {-| Run the server. -} server :: ServerOptions -> (ByteString -> ByteString) -> IO () server opts@(ServerOptions { port, logFile }) = (≫) serverInit . run port . app opts where serverInit = do logLine $ "Server starting on port " ++ show port logLine $ "Logging: " ++ maybe "disabled" ((++) "enbled, logging to " . show) logFile
JustusAdam/schedule-planner
src/SchedulePlanner/Server.hs
lgpl-3.0
2,486
0
15
638
463
257
206
-1
-1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} module P1 where import Control.Monad.Except import Control.Monad.Reader import Data.Text as T import Data.Text.IO as T import P0 data DbConfig = DbConfig { dbConn :: DbConnection , schema :: Schema } data NetworkConfig = NetConfig { port :: Port , ssl :: SSL } data AppConfig = AppConfig { appDbConfig :: DbConfig , appNetConfig :: NetworkConfig } data DbError = QueryError T.Text | InvalidConnection data NetworkError = Timeout Int | ServerOnFire data AppError = AbbDbError DbError | AppNetError NetworkError -- 3:44 newtype App a = App { unApp :: ReaderT AppConfig (ExceptT AppError IO) a } deriving (Applicative, Functor, Monad, MonadIO, MonadReader AppConfig, MonadError AppError) -- 6:09 getPort :: MonadReader NetworkConfig m => m Port getPort = reader port -- 'reader' is synonym for 'asks' getPort' :: MonadReader NetworkConfig m => m Port getPort' = do cfg <- ask return (port cfg) printM :: MonadIO m => Text -> m () printM = liftIO . T.putStrLn -- 9:53 type Err = Text mightFail :: MonadError Err m => m Int mightFail = undefined couldFail :: MonadError Err m => m Text couldFail = undefined maybeFail :: MonadError Err m => m (Maybe (Int, Text)) maybeFail = ( do a <- mightFail b <- couldFail pure (Just (a, b)) ) `catchError` (\_ -> pure Nothing) -- 10:06 {- -- instance MonadReader AppConfig App ask :: App AppConfig -- instance MonadError AppError App throwError :: AppError -> App a catchError :: App a -> (AppError -> App a) -> App q -- instance MonadIO App liftIO :: IO a -> App a -} -- 11:00 -- No type-safety in following: loadFromDb :: App MyData loadFromDb = undefined sendOverNet :: MyData -> App () sendOverNet = undefined loadAndSend :: App () loadAndSend = loadFromDb >>= sendOverNet -- 12:50 -- this version provide more type-safety : can't touch NetworkConfig or throw Network Errors loadFromDb' :: (MonadReader DbConfig m, MonadError DbError m, MonadIO m) => m MyData loadFromDb' = undefined -- 13:29 sendOverNet' :: (MonadReader NetworkConfig m, MonadError NetworkError m, MonadIO m) => MyData -> m () sendOverNet' = undefined -- but this causes a type error: -- loadAndSend' = loadFromDb' >>= sendOverNet'
haroldcarr/learn-haskell-coq-ml-etc
haskell/topic/program-structure/2015-06-george-wilson-classy-optics/src/P1.hs
unlicense
2,588
0
12
738
579
322
257
65
1
-- Copyright 2017 Google Inc. -- -- 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. {-# LANGUAGE CPP #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} -- | Converts the entities from the common Translate representation to Kythe -- entries. module Language.Haskell.Indexer.Frontend.Kythe ( toKythe ) where import Control.Monad.Identity (Identity) import Control.Monad.Morph (lift, hoist) import Control.Monad.Trans.Maybe import Control.Monad.Trans.Reader import qualified Data.ByteString as BS import Data.Conduit (ConduitT) import Data.Conduit.List (sourceList) import Data.Maybe (fromMaybe, maybeToList) #if !MIN_VERSION_base(4,11,0) import Data.Monoid ((<>)) #endif import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Encoding as T import qualified Data.Text.Lazy as TL import qualified Data.Text.Offset as Offset import Language.Kythe.Schema.Typed import qualified Language.Kythe.Schema.Raw as Raw import Language.Kythe.Schema.Raw.VName import Language.Haskell.Indexer.Translate import Language.Haskell.Indexer.Translate.Render import Language.Haskell.Indexer.Translate.Utils (tickString) -- | Data commonly needed while converting Analysis result to Kythe. data ConversionEnv = ConversionEnv { pkgVName :: !Raw.VName , offsets :: !Offset.OffsetTable , baseVName :: !Raw.VName } -- | The computation context used by the Kythe conversion. type Conversion = Reader ConversionEnv type ConversionT = ReaderT ConversionEnv -- | Converts crossreference data of a file to Kythe schema. -- 'basevn' should have the corpus and language prefilled. toKythe :: Raw.VName -> T.Text -> XRef -> ConduitT () Raw.Entry Identity () toKythe basevn content XRef{..} = do let NameAndEntries pkgvn pkgEntries = makePackageFacts basevn (mtPkgModule xrefModule) NameAndEntries filevn fileEntries = makeFileFacts basevn (analysedOriginalPath xrefFile) encodedContent env = ConversionEnv pkgvn table basevn -- Files are children of the package they belong to. -- This makes more sense for golang, but can't hurt here either. pkgFileEntry = edge filevn ChildOfE pkgvn sourceList (pkgFileEntry : pkgEntries ++ fileEntries) flip runReaderT env $ do stream (makeAnchor (mtSpan xrefModule) DefinesBindingE pkgvn Nothing Nothing) mapM_ (stream . makeDeclFacts) xrefDecls mapM_ (stream . makeDocDeclFacts) xrefDocDecls mapM_ (stream . makeModuleDocDeclFacts) xrefModuleDocDecls mapM_ (stream . makeUsageFacts) xrefCrossRefs mapM_ (stream . makeRelationFacts) xrefRelations mapM_ (stream . makeImportFacts) xrefImports where table = Offset.createOffsetTable (TL.fromStrict content) encodedContent = T.encodeUtf8 content -- | Changes a conversion returning a list of entries into one that streams -- those entries. To be applied at reasonable points in the computation tree, -- where already a decent but not too large amount of entries have accumulated stream :: Conversion [Raw.Entry] -> ConversionT (ConduitT () Raw.Entry Identity) () stream a = do es <- hoist lift a lift (sourceList es) -- | Glorified pair. The entries are not exhaustive for the given VName. data NameAndEntries = NameAndEntries !Raw.VName ![Raw.Entry] -- | Facts for a Kythe package, which corresponds to a Haskell package+module. makePackageFacts :: Raw.VName -> PkgModule -> NameAndEntries makePackageFacts basevn PkgModule{..} = NameAndEntries pkgvn facts where pkgvn = basevn { vnSignature = moduleSig } where moduleSig = getPackage <> ":" <> getModule facts = nodeFacts pkgvn PackageNK [] -- | Creates file node entries. Not in Conversion, since the result is needed -- to construct the ConversionEnv. makeFileFacts :: Raw.VName -> SourcePath -> BS.ByteString -> NameAndEntries makeFileFacts basevn origPath encodedContent = NameAndEntries filevn facts where facts = nodeFacts filevn FileNK [ nodeFact FileTextF encodedContent ] filevn = basevn -- Kythe conventions for file node. { vnLanguage = "" , vnSignature = "" , vnPath = unSourcePath origPath } -- | Makes entries for an anchor referring some existing declaration. makeUsageFacts :: TickReference -> Conversion [Raw.Entry] makeUsageFacts TickReference{..} = do -- TODO(robinpalotai): add more data from backend to translate layer about -- spans of ref vs call. In Kythe a call needs both a ref (with name -- anchor) and ref/call (with anchor spanning also the args). targetVname <- tickVName refTargetTick mbCallContext <- traverse tickVName refHighLevelContext let edgeType = case refKind of Ref -> RefE Call -> RefE TypeDecl -> RefDocE Import -> RefImportsE makeAnchor (Just refSourceSpan) edgeType targetVname Nothing mbCallContext -- | Makes all entries for a declaration. makeDeclFacts :: Decl -> Conversion [Raw.Entry] makeDeclFacts decl@Decl{..} = do declVName <- tickVName declTick -- TODO(robinpalotai): use actual node type (Variable is a catch-all now). -- TODO(robinpalotai): emit type entries. -- TODO(robinpalotai): emit Module childofness if top-level. let declFacts = nodeFacts declVName VariableNK [nodeFact CompleteF Definition] anchorEntries <- makeAnchor (declPreferredUiSpan decl) DefinesBindingE declVName Nothing -- snippet -- TODO(robinpalotai): plumb high-level context to -- Decl entries too in backend. Nothing childOfModule <- if tickUniqueInModule declTick then Just . edge declVName ChildOfE <$> asks pkgVName else return Nothing return (declFacts ++ anchorEntries ++ maybeToList childOfModule) -- | Makes all entries for a doc/uri declaration. makeDocDeclFacts :: DocUriDecl -> Conversion [Raw.Entry] makeDocDeclFacts DocUriDecl{..} = do declVName <- tickVName ddeclTick return $ nodeFacts declVName VariableNK [ nodeFact DocUriF (T.encodeUtf8 ddeclDocUri) , nodeFact CompleteF Definition ] -- | Makes all entries for a module's doc/uri declaration. makeModuleDocDeclFacts :: ModuleDocUriDecl -> Conversion [Raw.Entry] makeModuleDocDeclFacts ModuleDocUriDecl{..} = do vn <- asks baseVName let pm = mtPkgModule mddeclTick NameAndEntries pkgVn pkgEntries = makePackageFacts vn pm docUriFacts = nodeFacts pkgVn PackageNK [ nodeFact DocUriF (T.encodeUtf8 mddeclDocUri), nodeFact CompleteF Definition ] return $ pkgEntries ++ docUriFacts -- | Makes entries for an anchor (either explicit or implicit).. -- -- If snippet span is not provided, the Kythe service will auto-construct one. makeAnchor :: Maybe Span -- ^ Anchor span. If missing, anchor is implicit. -> AnchorEdge -- ^ How it refers its target. -> Raw.VName -- ^ Anchor target. -> Maybe Span -- ^ Snippet span. -> Maybe Raw.VName -- ^ Reference context (like enclosing function). -> Conversion [Raw.Entry] makeAnchor mbSource anchorEdge targetVName mbSnippet mbRefContext = do (vname, spanOrSubkindFacts) <- fromMaybeTPureDef implicits $ do -- TODO(robinpalotai): CPP - spanAndOffs can be Nothing, if a macro -- was expanded, since GHC expands the macro on the same, "long" line -- with columns over the true columns of that line - and so -- OffsetTable will indicate failure. Could workaround and emit anchor -- at the beginning of the line, or more properly (?) generate small -- virtual files for the macro expansion. SpanAndOffs source offs <- spanAndOffs mbSource lift $ do anchorVN <- anchorVName (spanFile source) offs targetVName let spanFacts = makeLocFacts offs return (anchorVN, spanFacts) snippetFacts <- fromMaybeTPureDef [] $ makeSnippetFacts . onlyOffset <$> spanAndOffs mbSnippet let nodeEntries = nodeFacts vname AnchorNK . concat $ [ spanOrSubkindFacts , snippetFacts ] let edgeEntries = edge vname (AnchorEdgeE anchorEdge) targetVName : maybeToList (edge vname ChildOfE <$> mbRefContext) return $! nodeEntries ++ edgeEntries where implicits = ( implicitAnchorVName targetVName , [nodeFact AnchorSubkindF ImplicitAnchor] ) -- | Makes fact about a non-reference edge. makeRelationFacts :: Relation -> Conversion [Raw.Entry] makeRelationFacts (Relation src relKind target) = traverse (\k -> edge <$> tickVName src <*> pure k <*> tickVName target) edgeKinds where edgeKinds = case relKind of ImplementsMethod -> [OverridesE, OverridesRootE] InstantiatesClass -> [ExtendsE] -- Note: In Haskell-terms, class instantiation is not extension -- (or subclassing), but in Kythe terms we can think of the class -- as an interface, and the instance as the implementation. -- So by squinting a bit, we'll hopefully get better functionality -- out of Kythe-related tools that are not aware of Haskell. -- | Makes fact about module imports. makeImportFacts :: ModuleTick -> Conversion [Raw.Entry] makeImportFacts ModuleTick{..} = do vn <- asks baseVName let NameAndEntries pkgvn _ = makePackageFacts vn mtPkgModule makeAnchor mtSpan RefImportsE pkgvn Nothing Nothing -- Helpers below. -- | Makes a location start/end fact pair using the given offset. makeLocFacts :: OffsetRange -> [AnonymousFact] makeLocFacts (OffsetRange s e) = [ nodeFact LocStartF s , nodeFact LocEndF e ] -- | Makes a snippet start/end fact pair using the given offset. makeSnippetFacts :: OffsetRange -> [AnonymousFact] makeSnippetFacts (OffsetRange s e) = [ nodeFact SnippetStartF s , nodeFact SnippetEndF e ] -- | Generates VName for an abstract entity. -- The generated name uniquely identifies the given entitiy. tickVName :: Tick -> Conversion Raw.VName tickVName t = updateSig <$> asks baseVName where updateSig v = v { vnSignature = tickString t } -- | A non-implicit anchor VName. -- In theory the pure location is enough to construct it, but for practical -- debuggability we stick the signature of the target entity to the signature -- of the generated VName. anchorVName :: SourcePath -> OffsetRange -> Raw.VName -> Conversion Raw.VName anchorVName sourcePath (OffsetRange s e) targetVName = update <$> asks baseVName where update v = v { vnPath = unSourcePath sourcePath , vnSignature = vnSignature targetVName <> ":" <> tshow s <> "," <> tshow e } -- | An implicit anchor doesn't have a source location, but we still need to -- make a unique VName for it. So we generate it from the signature of the -- target. -- TODO(robinp): this should still have the current sourcePath set. -- TODO(robinp): could randomize signature to make multiple implicit anchors -- stay distinct. Though not clear if that is useful. implicitAnchorVName :: Raw.VName -> Raw.VName implicitAnchorVName targetVName = targetVName { vnSignature = vnSignature targetVName <> ":ImplicitAnchor" } -- Dealing with spans and offsets. -- | Glorified tuple. data SpanAndOffs = SpanAndOffs !Span !OffsetRange -- | Glorified snd. onlyOffset :: SpanAndOffs -> OffsetRange onlyOffset (SpanAndOffs _ offs) = offs -- | High-level helper to get span info with less boilerplate. spanAndOffs :: Maybe Span -> MaybeT Conversion SpanAndOffs spanAndOffs mbSpan = do aSpan <- hoistMaybe mbSpan offs <- MaybeT (spanToOffsets aSpan) return $! SpanAndOffs aSpan offs -- | A range in bytes. data OffsetRange = OffsetRange !Int !Int -- | Translates char-based span to byte-based offsets, using the table -- constructed for the analysed file in context. spanToOffsets :: Span -> Conversion (Maybe OffsetRange) spanToOffsets (Span (Pos l1 c1 _) (Pos l2 c2 _)) = do t <- asks offsets let start = Offset.lineColToByteOffset t (l1 - 1) (c1 - 1) -- Being just at line end is acceptable for end span. end = case Offset.lineColToByteOffsetDetail t (l2 - 1) (c2 - 1) of Right o -> Just o Left (Offset.OverLineEnd o Offset.JustAtLineEnd) -> Just o Left _ -> Nothing return $! OffsetRange <$> start <*> end -- Boilerplate usually found in upstream libs. -- | Like 'show' but return 'Text' instead 'String'. tshow :: (Show a) => a -> Text tshow = T.pack . show -- | Shorthand for MaybeT . return. hoistMaybe :: (Monad m) => Maybe a -> MaybeT m a hoistMaybe = MaybeT . return -- | Like 'fromMaybe', but for 'MaybeT' and with a pure default. fromMaybeTPureDef :: (Monad m) => a -> MaybeT m a -> m a fromMaybeTPureDef a = fmap (fromMaybe a) . runMaybeT
google/haskell-indexer
haskell-indexer-frontend-kythe/src/Language/Haskell/Indexer/Frontend/Kythe.hs
apache-2.0
13,850
0
17
3,300
2,519
1,321
1,198
214
4
module MaxSequence where import Data.List -- Return the greatest subarray sum within the array of integers passed in. maxSequence :: [Int] -> Int maxSequence = foldl1 max . map (foldl (+) 0) . foldl1 (++) . map inits . tails t1 = [-2, 1, -3, 4, -1, 2, 1, -5, 4] :: [Int]
lisphacker/codewars
MaxSequence.hs
bsd-2-clause
274
0
11
56
113
66
47
5
1
-- Copyright (c) 2012-2017, Christoph Pohl -- BSD License (see http://www.opensource.org/licenses/BSD-3-Clause) ------------------------------------------------------------------------------- -- -- Project Euler Problem 30 -- -- Surprisingly there are only three numbers that can be written as the sum of -- fourth powers of their digits: -- -- 1634 = 1^4 + 6^4 + 3^4 + 4^4 -- 8208 = 8^4 + 2^4 + 0^4 + 8^4 -- 9474 = 9^4 + 4^4 + 7^4 + 4^4 -- -- As 1 = 1^4 is not a sum it is not included. -- -- The sum of these numbers is 1634 + 8208 + 9474 = 19316. -- -- Find the sum of all the numbers that can be written as the sum of fifth -- powers of their digits. module Main where import Data.Digits main :: IO () main = print result -- since 6*9^5 has only six digits, use it as an upper bound result = sum $ filter isFifthPowerSum [1..6*9^5] isFifthPowerSum :: Int -> Bool isFifthPowerSum x | x == 1 = False | x == fifthPowerSum x = True | otherwise = False fifthPowerSum :: Int -> Int fifthPowerSum x = sum [y^5 | y <- digits 10 x]
Psirus/euler
src/euler030.hs
bsd-3-clause
1,066
0
9
235
166
93
73
12
1
-- | -- Module : Main -- Copyright : [2013] Manuel M T Chakravarty & Leon A Chakravarty -- License : BSD3 -- -- Maintainer : Manuel M T Chakravarty <[email protected]> -- Portability : haskell2011 -- -- /Usage/ -- -- Provide the filename as the single command line argument. -- -- Left mouse button — draw with current colour -- Left mouse button + Shift — erase with transparency -- Right mouse button — erase with transparency -- 'W', 'S', 'A', 'D' - enlarge canvas to the top, bottom, left, and right, respectively -- 'W', 'S', 'A', 'D' + Shift - shrink canvas from the top, bottom, left, and right, respectively -- -- Canvas changes are automatically saved. import Codec.BMP import Data.ByteString (ByteString, pack, unpack) import Graphics.Gloss import Graphics.Gloss.Interface.IO.Game import Control.Exception as Exc import Control.Monad import Data.Array import Data.Word import System.Environment import System.Exit import System.IO.Error -- Constants -- --------- -- Frames per second -- fps :: Int fps = 60 -- Minimum time (in seconds) between image writes. -- writeInterval :: Float writeInterval = 0.3 -- How many physical pixel per pixel art block? -- pixelSize :: (Int, Int) pixelSize = (8, 8) -- Number of blocks on the initial canvas of an empty canvas (if not specified on the command line)? -- initialCanvasSize :: (Int, Int) initialCanvasSize = (16, 32) -- Padding to the window border. -- windowPadding :: Float windowPadding = 40 -- Padding between window elements. -- elementPadding :: Float elementPadding = 50 -- The height of the colour indicator strip. -- colourIndicatorHeight :: Float colourIndicatorHeight = fromIntegral (fst pixelSize) * 2 -- The colour of the grid lines. -- gridColor :: Color gridColor = makeColor 0.8 0.8 0.8 1 -- Fully transparent colour. -- transparent :: Color transparent = makeColor 0 0 0 0 -- Nearly (25% opaque) transparent black. -- nearlytransparent :: Color nearlytransparent = makeColor 0 0 0 0.25 -- Half (50% opaque) transparent black. -- halftransparent :: Color halftransparent = makeColor 0 0 0 0.5 -- Application state -- ----------------- -- The colour grid that contains the drawing -- type Canvas = Array (Int, Int) Color -- The subarea of the canvas currently in use. -- type Area = ((Int, Int), (Int, Int)) -- Entire state of the applications -- data State = State { fname :: FilePath -- name of the image file , canvas :: Canvas -- the image canvas , area :: Area -- range of indices of the canvas used , image :: BMP -- BMP image version of the canvas , dirty :: Bool -- 'True' iff there are unsaved changes , timeSinceWrite :: Float -- seconds passed since last write to image file , penDown :: Maybe Color -- 'Just col' iff pen down with the given color , colour :: Color -- colour of the pen } initialState :: FilePath -> Canvas -> BMP -> State initialState name initialCanvas initialImage = State { fname = name , canvas = initialCanvas , area = bounds initialCanvas , image = initialImage , dirty = False , timeSinceWrite = 0 , penDown = Nothing , colour = black } -- Yield the width and height of an area. -- areaSize :: Area -> (Int, Int) areaSize ((minX, minY), (maxX, maxY)) = (maxX - minX + 1, maxY - minY + 1) -- Check whether one area is completely contained in another. -- containedWithin :: Area -> Area -> Bool ((minX1, minY1), (maxX1, maxY1)) `containedWithin` ((minX2, minY2), (maxX2, maxY2)) = minX1 >= minX2 && minY1 >= minY2 && maxX1 <= maxX2 && maxY1 <= maxY2 -- Compute the smallest area containing the two given ones. -- unionArea :: Area -> Area -> Area ((minX1, minY1), (maxX1, maxY1)) `unionArea` ((minX2, minY2), (maxX2, maxY2)) = ((minX1 `min` minX2, minY1 `min` minY2), (maxX1 `max` maxX2, maxY1 `max` maxY2)) -- Vector addition -- vplus :: (Int, Int) -> (Int, Int) -> (Int, Int) (i, j) `vplus` (k, l) = (i + k, j + l) -- Vector subtraction -- vminus :: (Int, Int) -> (Int, Int) -> (Int, Int) (i, j) `vminus` (k, l) = (i - k, j - l) -- UI presentation -- --------------- -- Determine an appropriate window size for the given application state. -- windowSize :: State -> Point windowSize state = (2 * (canvasW + paletteW) + 2 * windowPadding + 2 * elementPadding, (20 + 1.5 * canvasH + 2 * windowPadding) `max` (1.5 * paletteH + 2 * windowPadding)) where (canvasW, canvasH) = canvasSize state (paletteW, paletteH) = zoomedPaletteSize -- Size of the canvas in physical pixel. -- canvasSize :: State -> Point canvasSize state = (fromIntegral (width * fst pixelSize), fromIntegral (height * snd pixelSize)) where (width, height) = areaSize (area state) -- Size of the palette in physical pixel. -- paletteSize :: Point paletteSize = (fromIntegral (16 * fst pixelSize), fromIntegral (16 * snd pixelSize)) -- Size of the palette in physical pixel *scaled* by a factor of two. -- zoomedPaletteSize :: Point zoomedPaletteSize = (fst paletteSize * 2, snd paletteSize * 2) -- Convert window coordinates to a canvas index. -- windowPosToCanvas :: (Float, Float) -> Point -> Maybe (Int, Int) windowPosToCanvas (canvasWidth, canvasHeight) (x, y) | x_shifted < 0 || x_shifted >= canvasWidth || y_shifted < 0 || y_shifted >= canvasHeight = Nothing | otherwise = Just (truncate x_shifted `div` fst pixelSize, truncate y_shifted `div` snd pixelSize) where halfCanvasWidth = canvasWidth / 2 halfCanvasHeight = canvasHeight / 2 x_shifted = x + halfCanvasWidth y_shifted = y + halfCanvasHeight -- Convert a canvas index to widget coordinates. -- canvasToWidgetPos :: (Float, Float) -> (Int, Int) -> Point canvasToWidgetPos (canvasWidth, canvasHeight) (i, j) = (x, y) where x = (fromIntegral i + 0.5) * width - (canvasWidth / 2) y = (fromIntegral j + 0.5) * height - (canvasHeight / 2) width = fromIntegral (fst pixelSize) height = fromIntegral (snd pixelSize) -- Turn the canvas in the application state into a picture (one frame). -- drawCanvas :: State -> Picture drawCanvas state = let (start, end) = area state in Pictures $ map drawPixelBlock [(pos `vminus` start, canvas state!pos) | pos <- range (start, end)] where drawPixelBlock (pos, color) = Translate x y $ Pictures [ rectangleChecker width height , Color color (rectangleSolid width height) , Color gridColor (rectangleWire width height) ] where (x, y) = canvasToWidgetPos (canvasSize state) pos width = fromIntegral (fst pixelSize) height = fromIntegral (snd pixelSize) -- Turn the image in the application state into a picture (one frame). -- drawImage :: State -> Picture drawImage = bitmapOfBMP . image -- Produce the picture of the colour palette. -- drawPalette :: Picture drawPalette = Pictures (map drawPaletteBlock [(i, j) | i <- [0..15], j <- [0..15]]) where drawPaletteBlock :: (Int, Int) -> Picture drawPaletteBlock pos = Translate x y $ Pictures [ rectangleChecker width height , Color (paletteColour pos) (rectangleSolid width height) ] where (x, y) = canvasToWidgetPos paletteSize pos width = fromIntegral (fst pixelSize) height = fromIntegral (snd pixelSize) -- Draw a checker rectangle with a wire frame. -- -- Width and height must be divisible by 2. -- rectangleChecker :: Float -> Float -> Picture rectangleChecker width height = Pictures [ Translate (-w4) (-h4) $ Color (greyN 0.90) (rectangleSolid w2 h2) , Translate (-w4) ( h4) $ Color white (rectangleSolid w2 h2) , Translate ( w4) (-h4) $ Color white (rectangleSolid w2 h2) , Translate ( w4) ( h4) $ Color (greyN 0.90) (rectangleSolid w2 h2) , Translate 0 0 $ Color (greyN 0.95) (Line [(0, -h2), (0, h2)]) , Translate 0 0 $ Color (greyN 0.95) (Line [(-h2, 0), (h2, 0)]) , Translate 0 0 $ Color gridColor (rectangleWire width height) ] where w2 = width / 2 h2 = height / 2 w4 = width / 4 h4 = height / 4 -- Compute the colour of the palette at a particular index position. -- -- 8-bit palette: RRGIBBGT -- -- * RR = 2-bit red -- * GG = 2-bit green -- * BB = 2-bit blue -- * I = 1-bit brightness -- * T = 1-bit transparency -- -- Intensity scales -- -- * 00 = 0% (irrespective of brightness) -- * 01 = brightness ? 40% : (transparency ? 30% : 20%) -- * 10 = brightness ? 70% : (transparency ? 60% : 50%) -- * 11 = brightness ? 100% : (transparency ? 90% : 80%) -- -- Transparency is 50% if brightness == 1. -- -- Special values -- -- * 00010000 = 25% transparent (black) -- * 00000001 = 50% transparent (black) -- * 00010001 = fully transparent (black) -- -- Here, i = 4 MSBs and j = 4 LSBs. -- paletteColour :: (Int, Int) -> Color paletteColour (i, j) = paletteColour' (i, 15 - j) where paletteColour' (1, 0) = nearlytransparent paletteColour' (0, 1) = halftransparent paletteColour' (1, 1) = transparent paletteColour' (i, j) = makeColor (scale red / 100) (scale green / 100) (scale blue / 100) (if transparency == 1 && brightness == 1 then 0.5 else 1) where red = fromIntegral $ ((i `div` 8) `mod` 2) * 2 + (i `div` 4) `mod` 2 green = fromIntegral $ ((i `div` 2) `mod` 2) * 2 + (j `div` 2) `mod` 2 blue = fromIntegral $ ((j `div` 8) `mod` 2) * 2 + (j `div` 4) `mod` 2 brightness = fromIntegral $ (i `mod` 2) transparency = fromIntegral $ (j `mod` 2) scale 0 = 0 scale 1 | brightness == 1 = 40 | transparency == 1 = 30 | otherwise = 20 scale 2 | brightness == 1 = 70 | transparency == 1 = 60 | otherwise = 50 scale 3 | brightness == 1 = 100 | transparency == 1 = 90 | otherwise = 80 {- -- Compute the colour of the palette at a particular index position, but use the transparency of the given colour. -- paletteColourWithTransparencyOf :: Color -> (Int, Int) -> Color paletteColourWithTransparencyOf col idx = makeColor r g b a where (r, g, b, _) = rgbaOfColor $ paletteColour idx (_, _, _, a) = rgbaOfColor col -} {- -- Adjust a colour transparency (alpha value) for the given index position in the transparency palette. -- transparencyColour :: Color -> Int -> Color transparencyColour col i = makeColor r g b (fromIntegral i / 16) where (r, g, b, _a) = rgbaOfColor col -} -- Draw a picture of the entire application window. -- drawWindow :: State -> IO Picture drawWindow state = return $ Pictures [ drawCanvas state , Translate (-40) sizeOffset canvasSizeText -- ^^FIXME: Gloss doesn't seem to center text :( -- , Translate (-imageOffset) 0 (drawImage state) , Translate paletteOffset 0 (Scale 2 2 drawPalette) , Translate paletteOffset (-colourOffset) colourIndicator ] where imageOffset = elementPadding + fst (canvasSize state) / 2 + fromIntegral (fst (bmpDimensions (image state))) / 2 paletteOffset = elementPadding + fst (canvasSize state) / 2 + fst zoomedPaletteSize / 2 colourOffset = 2 * colourIndicatorHeight + snd zoomedPaletteSize / 2 sizeOffset = snd (canvasSize state) / 2 + 20 colourIndicator = Pictures $ [ Translate (fromIntegral i * pixelWidth + pixelWidth / 2) (fromIntegral j * pixelHeight + pixelHeight / 2) $ rectangleChecker pixelWidth pixelHeight | i <- [-16..15], j <- [-1..0] ] ++ [ Color (colour state) (rectangleSolid (fst zoomedPaletteSize) colourIndicatorHeight) , Color gridColor (rectangleWire (fst zoomedPaletteSize) colourIndicatorHeight) ] pixelWidth = fromIntegral $ fst pixelSize pixelHeight = fromIntegral $ snd pixelSize canvasSizeText = let (width, height) = areaSize (area state) in Scale 0.2 0.2 (Text (show width ++ "x" ++ show height)) -- Reading and writing of image files -- ---------------------------------- -- Try to read the image file and to convert it to a canvas. If that fails yield an empty canvas. -- -- The first argument determines whether we clip the input colours to the BigPixel colour palette. -- readImageFile :: Bool -> FilePath -> IO (Canvas, BMP) readImageFile forcePalette fname = do { result <- readBMP fname ; case result of Left err -> do { putStrLn ("BigPixel: error reading '" ++ fname ++ "': " ++ show err) ; putStrLn "Delete the file if you want to replace it." ; exitFailure } Right bmp -> do { let (bmpWidth, bmpHeight) = bmpDimensions bmp canvasWidth = bmpWidth `div` fst pixelSize canvasHeight = bmpHeight `div` snd pixelSize ; unless (bmpWidth `mod` fst pixelSize == 0 && bmpHeight `mod` snd pixelSize == 0) $ do { putStrLn ("BigPixel: '" ++ fname ++ "' doesn't appear to be a BigPixel image") ; putStrLn ("Expected the image size to be a multiple of " ++ show (fst pixelSize) ++ "x" ++ show (snd pixelSize)) } ; let stream = unpack (unpackBMPToRGBA32 bmp) indices = [(i, j) | j <- [0..bmpHeight - 1], i <- [0..bmpWidth - 1]] image = array ((0, 0), (bmpWidth - 1, bmpHeight - 1)) (zip indices [word8ToColor quad | quad <- quads stream]) canvas0 = listArray ((0, 0), (canvasWidth - 1, canvasHeight - 1)) [averageAt image (i, j) | i <- [0..canvasWidth - 1] , j <- [0..canvasHeight - 1]] ; return (canvas0, bmp) } } `Exc.catch` \exc -> if isDoesNotExistErrorType (ioeGetErrorType exc) then return (emptyCanvas, canvasToImage emptyCanvas (bounds emptyCanvas)) else do { putStrLn ("BigPixel: error reading '" ++ fname ++ "': " ++ show exc) ; putStrLn "Delete the file if you want to replace it." ; exitFailure } where maxX = fst initialCanvasSize - 1 maxY = snd initialCanvasSize - 1 emptyCanvas = listArray ((0, 0), (maxX, maxY)) (repeat transparent) quads :: [a] -> [[a]] quads [] = [] quads (x:y:z:v:rest) = [x, y, z, v] : quads rest quads l = [l] averageAt image (i, j) -- = clipColour $ image ! (i * fst pixelSize + fst pixelSize `div` 2, -- j * snd pixelSize + snd pixelSize `div` 2) = (if forcePalette then clipColour else id) $ foldl1 (mixColors 0.5 0.5) [ image ! (i * fst pixelSize + ioff, j * snd pixelSize + joff) | ioff <- [0..fst pixelSize - 1] , joff <- [0..snd pixelSize - 1]] -- Write the contents of the canvas to the image file. -- writeImageFile :: State -> IO () writeImageFile state = writeBMP (fname state) (canvasToImage (canvas state) (area state)) -- Convert the specified area of a canvas array into a BMP image file. -- canvasToImage :: Array (Int, Int) Color -> Area -> BMP canvasToImage canvas area = packRGBA32ToBMP imageWidth imageHeight $ pack (concat [ colorToWord8 (canvas!(minX + x `div` fst pixelSize, minY + y `div` snd pixelSize)) | y <- [0..imageHeight - 1], x <- [0..imageWidth - 1]]) where (canvasWidth, canvasHeight) = areaSize area ((minX, minY), _) = area imageWidth = canvasWidth * fst pixelSize imageHeight = canvasHeight * snd pixelSize -- Convert a Gloss colour to an RGBA value (quad of 'Word8's) for a BMP. -- colorToWord8 :: Color -> [Word8] colorToWord8 col = let (red, green, blue, alpha) = rgbaOfColor col in [toWord8 red, toWord8 green, toWord8 blue, toWord8 alpha] where toWord8 = truncate . (* 255) -- Convert an RGBA value (quad of 'Word8's) for a BMP to a Gloss colour. -- word8ToColor :: [Word8] -> Color word8ToColor [red, green, blue, alpha] = makeColor (fromWord8 red) (fromWord8 green) (fromWord8 blue) (fromWord8 alpha) where fromWord8 = (/ 255) . fromIntegral word8ToColor arg = error ("word8ToColor: not a quad: " ++ show arg) -- Clip a colour to the BigPixel 8-bit colour space -- clipColour :: Color -> Color clipColour col | transparent = makeColor 0 0 0 0 | black = makeColor 0 0 0 1 | otherwise = makeColor red' green' blue' alpha' where (red, green, blue, alpha) = rgbaOfColor col black = averageBrightness [red, green, blue] < 0.15 transparent = alpha < 0.25 alpha' | alpha >= 0.25 && alpha < 0.75 = 0.5 | otherwise = 1 bright = averageBrightness [red, green, blue] >= 0.55 red' = clip red green' = clip green blue' = clip blue averageBrightness cols = sum significantCols / fromIntegral (length significantCols) where significantCols = [col | col <- cols, col >= 0.15] clip c | c < 0.15 = 0 | bright && c < 0.70 = 0.6 | bright && c < 0.90 = 0.8 | bright = 1 | c > 0.45 = 0.5 | c > 0.35 = 0.4 | otherwise = 0.3 -- Event handling -- -------------- -- Process a single event. -- handleEvent :: Event -> State -> IO State -- Drawing and colour selection handleEvent (EventKey (MouseButton LeftButton) Down mods mousePos) state = let newState | ctrl mods == Down = let pickedColour = pick mousePos state in state { penDown = Just pickedColour , colour = pickedColour } | shift mods == Down = state { penDown = Just transparent } | otherwise = state { penDown = Just (colour state) } in return $ draw mousePos newState handleEvent (EventKey (MouseButton RightButton) Down mods mousePos) state = let newState = state { penDown = Just transparent } in return $ draw mousePos newState handleEvent (EventKey (MouseButton LeftButton) Up _mods mousePos) state = return $ selectColour mousePos (state {penDown = Nothing}) handleEvent (EventKey (MouseButton RightButton) Up _mods mousePos) state = return $ state {penDown = Nothing} handleEvent (EventMotion mousePos) state = return $ draw mousePos state -- Alter canvas size handleEvent (EventKey (Char 'w') Down mods _mousePos) state = return $ resize ((0, 0), (0, 1)) state handleEvent (EventKey (Char 'W') Down mods _mousePos) state = return $ resize ((0, 0), (0, -1)) state handleEvent (EventKey (Char 's') Down mods _mousePos) state = return $ resize ((0, -1), (0, 0)) state handleEvent (EventKey (Char 'S') Down mods _mousePos) state = return $ resize ((0, 1), (0, 0)) state handleEvent (EventKey (Char 'a') Down mods _mousePos) state = return $ resize ((-1, 0), (0, 0)) state handleEvent (EventKey (Char 'A') Down mods _mousePos) state = return $ resize ((1, 0), (0, 0)) state handleEvent (EventKey (Char 'd') Down mods _mousePos) state = return $ resize ((0, 0), (1, 0)) state handleEvent (EventKey (Char 'D') Down mods _mousePos) state = return $ resize ((0, 0), (-1, 0)) state -- Unhandled event handleEvent event state = return state -- Draw onto the canvas if mouse position is within canvas boundaries. -- -- (NB: Does image conversion as well; i.e., only use once per frame in the current form.) -- draw :: Point -> State -> State draw mousePos (state@State { penDown = Just col }) = case windowPosToCanvas (canvasSize state) mousePos of Nothing -> state Just idx -> let base = fst (area state) newCanvas = canvas state // [(base `vplus` idx, col)] in state { canvas = newCanvas -- , image = canvasToImage newCanvas ?? , dirty = True } draw _mousePos state = state -- Determine the colour at the given point in the image, or return the current colour if the position is outside the -- image. -- pick :: Point -> State -> Color pick mousePos (state@State { colour = col }) = case windowPosToCanvas (canvasSize state) mousePos of Nothing -> col Just idx -> canvas state ! (base `vplus` idx) where base = fst (area state) -- Select a colour if mouse position is within palette boundaries. -- selectColour :: Point -> State -> State selectColour mousePos state = case windowPosToCanvas paletteSize paletteAdjustedMousePos of Nothing -> state Just idx -> state { colour = paletteColour idx } where paletteOffsetX = elementPadding + fst (canvasSize state) / 2 + fst zoomedPaletteSize / 2 paletteAdjustedMousePos = ((fst mousePos - paletteOffsetX) / 2, snd mousePos / 2) -- Resize the used canvas area. -- -- We only change the actual canvas array if it needs to grow beyond its current size. If it, -- shrinks, we leave it as it is to enable undoing the shrinking by growing it again. -- resize :: Area -> State -> State resize ((dminX, dminY), (dmaxX, dmaxY)) state | newWidth >= 2 && newHeight >= 2 = state { canvas = newCanvas, area = newArea, dirty = True } | otherwise = state where ((minX, minY), (maxX, maxY)) = area state (width, height) = areaSize (area state) (newWidth, newHeight) = areaSize newArea canvasArea = bounds (canvas state) newArea = ((minX + dminX, minY + dminY), (maxX + dmaxX, maxY + dmaxY)) newCanvasArea = canvasArea `unionArea` newArea newCanvas | newArea `containedWithin` canvasArea = canvas state | otherwise = array newCanvasArea [ (pos, if inRange canvasArea pos then canvas state ! pos else transparent) | pos <- range newCanvasArea] -- Advance the application state -- ----------------------------- -- Account for passing time. -- stepState :: Float -> State -> IO State stepState time state = maybeWriteFile $ state {timeSinceWrite = timeSinceWrite state + time} -- Determine whether we should write the image file. -- maybeWriteFile :: State -> IO State maybeWriteFile state@(State {dirty = True, timeSinceWrite = time}) | time > writeInterval = do { writeImageFile state ; return $ state {dirty = False, timeSinceWrite = 0} } maybeWriteFile state = return state -- The program body -- ---------------- -- Kick of the event loop -- main :: IO () main = do { -- Read the image file name from the command line arguments ; args <- getArgs ; let forcePalette = length args == 2 && head args == "--force-palette" ; when (not $ length args == 1 || forcePalette) $ do { putStrLn "BigPixel: needs image file name with suffix '.bmp' as argument,\n optionally preceeded by --force-palette" ; exitFailure } ; let [fname] = if forcePalette then tail args else args ; when (take 4 (reverse fname) /= reverse ".bmp") $ do { putStrLn "BigPixel: image file must have suffix '.bmp'" ; exitFailure } ; when forcePalette $ putStrLn "WARNING: --force-palette needs to be adapted to the latest palette" -- Read the image from the given file, or yield an empty canvas ; (canvas, image) <- readImageFile forcePalette fname -- Initialise the application state ; let state = initialState fname canvas image initialWindowSize = windowSize state -- Enter the event loop ; playIO (InWindow "BigPixel" (round (fst initialWindowSize), round (snd initialWindowSize)) (100, 50)) white fps state drawWindow handleEvent stepState }
mchakravarty/BigPixel
src/BigPixel.hs
bsd-3-clause
25,205
1
23
7,623
6,716
3,666
3,050
385
8
module Main(main) where import System.Environment (getArgs) --import Control.Parallel import GHC.Conc import Data.Int type FibType = Int64 main = do [arg1,arg2] <- getArgs let n = read arg1 :: FibType -- input for nfib t = read arg2 :: FibType -- threshold res = parfib n t putStrLn ("parfib " ++ show n ++ " = " ++ show res) -- parallel version of the code with thresholding parfib :: FibType -> FibType -> FibType parfib n t | n <= t = nfib n | otherwise = n1 `par` (n2 `pseq` n1 + n2 + 1) where n1 = parfib (n-1) t n2 = parfib (n-2) t -- sequential version of the code nfib :: FibType -> FibType nfib 0 = 1 nfib 1 = 1 nfib x = nfib (x-2) + nfib (x-1) + 1
rrnewton/Haskell-CnC
Intel/HCilk/parfib_threshold.hs
bsd-3-clause
762
1
12
240
287
151
136
20
1
{-# LANGUAGE PatternSynonyms #-} -------------------------------------------------------------------------------- -- | -- Module : Graphics.GL.NV.LightMaxExponent -- Copyright : (c) Sven Panne 2019 -- License : BSD3 -- -- Maintainer : Sven Panne <[email protected]> -- Stability : stable -- Portability : portable -- -------------------------------------------------------------------------------- module Graphics.GL.NV.LightMaxExponent ( -- * Extension Support glGetNVLightMaxExponent, gl_NV_light_max_exponent, -- * Enums pattern GL_MAX_SHININESS_NV, pattern GL_MAX_SPOT_EXPONENT_NV ) where import Graphics.GL.ExtensionPredicates import Graphics.GL.Tokens
haskell-opengl/OpenGLRaw
src/Graphics/GL/NV/LightMaxExponent.hs
bsd-3-clause
694
0
5
95
52
39
13
8
0
{-# LANGUAGE RecordWildCards, ImplicitParams, TupleSections #-} module Internal.ITransducer(TxInstance(..), Transducer(..), TxPortRef(..)) where import Internal.CFA import Internal.IType import Internal.IVar data TxPortRef = TxInputRef String | TxLocalRef String String deriving (Eq) data TxInstance = TxInstance { tiTxName :: String , tiInstName :: String , tiInputs :: [Maybe TxPortRef] } data Transducer = Transducer { txName :: String , txInput :: [(Type, String)] , txOutput :: [(Type, String)] , txBody :: Either ([TxPortRef], [TxInstance]) (CFA, [Var]) }
termite2/tsl
Internal/ITransducer.hs
bsd-3-clause
897
0
11
408
178
112
66
17
0
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. {-# LANGUAGE GADTs #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} module Duckling.Numeral.ZH.Rules ( rules ) where import Data.Maybe import Data.String import Data.Text (Text) import Prelude import qualified Data.HashMap.Strict as HashMap import qualified Data.Text as Text import Duckling.Dimensions.Types import Duckling.Numeral.Helpers import Duckling.Numeral.Types (NumeralData (..)) import Duckling.Regex.Types import Duckling.Types import qualified Duckling.Numeral.Types as TNumeral ruleInteger :: Rule ruleInteger = Rule { name = "integer (0..10)" , pattern = [ regex "(〇|零|一|二|两|兩|三|四|五|六|七|八|九|十|壹|貳|參|肆|伍|陸|柒|捌|玖|拾)" ] , prod = \case (Token RegexMatch (GroupMatch (match:_)):_) -> HashMap.lookup match integerMap >>= integer _ -> Nothing } integerMap :: HashMap.HashMap Text Integer integerMap = HashMap.fromList [ ( "〇", 0 ) , ( "零", 0 ) , ( "一", 1 ) , ( "壹", 1 ) , ( "兩", 2 ) , ( "两", 2 ) , ( "二", 2 ) , ( "貳", 2 ) , ( "三", 3 ) , ( "參", 3 ) , ( "四", 4 ) , ( "肆", 4 ) , ( "五", 5 ) , ( "伍", 5 ) , ( "六", 6 ) , ( "陸", 6 ) , ( "七", 7 ) , ( "柒", 7 ) , ( "八", 8 ) , ( "捌", 8 ) , ( "九", 9 ) , ( "玖", 9 ) , ( "十", 10 ) , ( "拾", 10 ) ] tensMap :: HashMap.HashMap Text Integer tensMap = HashMap.fromList [ ( "廿" , 20 ) , ( "卅" , 30 ) , ( "卌" , 40 ) ] ruleTens :: Rule ruleTens = Rule { name = "integer (20,30,40)" , pattern = [ regex "(廿|卅|卌)" ] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (match:_)):_) -> HashMap.lookup (Text.toLower match) tensMap >>= integer _ -> Nothing } ruleCompositeTens :: Rule ruleCompositeTens = Rule { name = "integer 21..49" , pattern = [ oneOf [20,30,40] , regex "[\\s\\-]+" , numberBetween 1 10 ] , prod = \tokens -> case tokens of (Token Numeral NumeralData{TNumeral.value = tens}: _: Token Numeral NumeralData{TNumeral.value = units}: _) -> double $ tens + units _ -> Nothing } ruleNumeralsPrefixWithNegativeOrMinus :: Rule ruleNumeralsPrefixWithNegativeOrMinus = Rule { name = "numbers prefix with -, negative or minus" , pattern = [ regex "-|负|負" , Predicate isPositive ] , prod = \case (_:Token Numeral nd:_) -> double (TNumeral.value nd * (-1)) _ -> Nothing } ruleDecimalWithThousandsSeparator :: Rule ruleDecimalWithThousandsSeparator = Rule { name = "decimal with thousands separator" , pattern = [ regex "(\\d+(,\\d\\d\\d)+\\.\\d+)" ] , prod = \case (Token RegexMatch (GroupMatch (match:_)):_) -> parseDouble (Text.replace "," Text.empty match) >>= double _ -> Nothing } ruleDecimalNumeral :: Rule ruleDecimalNumeral = Rule { name = "decimal number" , pattern = [ regex "(\\d*\\.\\d+)" ] , prod = \case (Token RegexMatch (GroupMatch (match:_)):_) -> parseDecimal True match _ -> Nothing } ruleDotSpelledOut :: Rule ruleDotSpelledOut = Rule { name = "one point 2" , pattern = [ dimension Numeral , regex "點" , Predicate $ not . hasGrain ] , prod = \tokens -> case tokens of (Token Numeral nd1:_:Token Numeral nd2:_) -> double $ TNumeral.value nd1 + decimalsToDouble (TNumeral.value nd2) _ -> Nothing } ruleFraction :: Rule ruleFraction = Rule { name = "fraction" , pattern = [ dimension Numeral , regex "分之|分|份" , dimension Numeral ] , prod = \tokens -> case tokens of (Token Numeral NumeralData{TNumeral.value = v1}: _: Token Numeral NumeralData{TNumeral.value = v2}: _) -> double $ v2 / v1 _ -> Nothing } ruleMixedFraction :: Rule ruleMixedFraction = Rule { name = " mixed fraction" , pattern = [ dimension Numeral , regex "又" , dimension Numeral , regex "分之|分|份" , dimension Numeral ] , prod = \tokens -> case tokens of (Token Numeral NumeralData{TNumeral.value = v1}: _: Token Numeral NumeralData{TNumeral.value = v2}: _: Token Numeral NumeralData{TNumeral.value = v3}: _) -> double $ v3 / v2 + v1 _ -> Nothing } ruleNumeral :: Rule ruleNumeral = Rule { name = "<number>个/個" , pattern = [ dimension Numeral , regex "个|個" ] , prod = \case (token:_) -> Just token _ -> Nothing } ruleHalf :: Rule ruleHalf = Rule { name = "half" , pattern = [ regex "(1|一)?半(半|个|個)?" ] , prod = \case (_:_) -> double 0.5 >>= withMultipliable _ -> Nothing } ruleDozen :: Rule ruleDozen = Rule { name = "a dozen of" , pattern = [ regex "打" ] , prod = \_ -> integer 12 >>= withMultipliable >>= notOkForAnyTime } rulePair :: Rule rulePair = Rule { name = "a pair" , pattern = [ regex "雙|對" ] , prod = \_ -> integer 2 >>= withMultipliable >>= notOkForAnyTime } numeralSuffixList :: [(Text, Maybe Token)] numeralSuffixList = [ ("K", double 1e3 >>= withGrain 3 >>= withMultipliable) , ("M", double 1e6 >>= withGrain 6 >>= withMultipliable) , ("G", double 1e9 >>= withGrain 9 >>= withMultipliable) , ("十|拾", double 1e1 >>= withGrain 1 >>= withMultipliable) , ("百|佰", double 1e2 >>= withGrain 2 >>= withMultipliable) , ("千|仟", double 1e3 >>= withGrain 3 >>= withMultipliable) , ("万|萬", double 1e4 >>= withGrain 4 >>= withMultipliable) , ("亿|億", double 1e8 >>= withGrain 8 >>= withMultipliable) ] ruleNumeralSuffixes :: [Rule] ruleNumeralSuffixes = uncurry constructNumeralSuffixRule <$> numeralSuffixList where constructNumeralSuffixRule :: Text -> Maybe Token -> Rule constructNumeralSuffixRule suffixName production = Rule { name = "number suffix: " `mappend` suffixName , pattern = [ regex $ Text.unpack suffixName ] , prod = const production } ruleMultiply :: Rule ruleMultiply = Rule { name = "compose by multiplication" , pattern = [ dimension Numeral , Predicate isMultipliable ] , prod = \case (token1:token2:_) -> multiply token1 token2 _ -> Nothing } ruleIntegerWithThousandsSeparator :: Rule ruleIntegerWithThousandsSeparator = Rule { name = "integer with thousands separator ," , pattern = [ regex "(\\d{1,3}(,\\d\\d\\d){1,5})" ] , prod = \case (Token RegexMatch (GroupMatch (match:_)): _) -> let fmt = Text.replace "," Text.empty match in parseDouble fmt >>= double _ -> Nothing } ruleNumeralsIntersectNonconsectiveUnit :: Rule ruleNumeralsIntersectNonconsectiveUnit = Rule { name = "integer with nonconsecutive unit modifiers" , pattern = [ Predicate isPositive , regex "零|〇" , Predicate isPositive ] , prod = \case (Token Numeral NumeralData{TNumeral.value = v1}:_: Token Numeral NumeralData{TNumeral.value = v2}:_) -> sumConnectedNumbers v1 v2 (diffIntegerDigits v1 v2) >>= double _ -> Nothing } where sumConnectedNumbers :: Double -> Double -> Int -> Maybe Double sumConnectedNumbers v1 v2 d | d <= 1 = Nothing | otherwise = Just $ v1 + v2 ruleNumeralsIntersectConsecutiveUnit :: Rule ruleNumeralsIntersectConsecutiveUnit = Rule { name = "integer with consecutive unit modifiers" , pattern = [ Predicate isPositive , Predicate isPositive ] , prod = \case (Token Numeral NumeralData{TNumeral.value = v1}: Token Numeral NumeralData{TNumeral.value = v2}:_) -> sumConnectedNumbers v1 v2 (diffIntegerDigits v1 v2) >>= double _ -> Nothing } where sumConnectedNumbers :: Double -> Double -> Int -> Maybe Double sumConnectedNumbers v1 v2 d | d == 1 = Just $ v1 + v2 | otherwise = Nothing ruleHundredPrefix :: Rule ruleHundredPrefix = Rule { name = "one hundred and <integer> (short form)" , pattern = [ regex "百|佰" , numberBetween 1 10 ] , prod = \case (_:Token Numeral NumeralData{TNumeral.value = v}:_) -> double $ 100 + v*10 _ -> Nothing } ruleThousandPrefix :: Rule ruleThousandPrefix = Rule { name = "one thousand and <integer> (short form)" , pattern = [ regex "千|仟" , numberBetween 1 10 ] , prod = \case (_:Token Numeral NumeralData{TNumeral.value = v}:_) -> double $ 1000 + v*100 _ -> Nothing } ruleTenThousandPrefix :: Rule ruleTenThousandPrefix = Rule { name = "ten thousand and <integer> (short form)" , pattern = [ regex "万|萬" , numberBetween 1 10 ] , prod = \case (_:Token Numeral NumeralData{TNumeral.value = v}:_) -> double $ 10000 + v*1000 _ -> Nothing } rules :: [Rule] rules = [ ruleDecimalNumeral , ruleDecimalWithThousandsSeparator , ruleInteger , ruleIntegerWithThousandsSeparator , ruleNumeral , ruleNumeralsIntersectConsecutiveUnit , ruleNumeralsIntersectNonconsectiveUnit , ruleNumeralsPrefixWithNegativeOrMinus , ruleMultiply , ruleTens , ruleCompositeTens , ruleHalf , ruleDotSpelledOut , ruleDozen , rulePair , ruleFraction , ruleMixedFraction , ruleHundredPrefix , ruleThousandPrefix , ruleTenThousandPrefix ] ++ ruleNumeralSuffixes
facebookincubator/duckling
Duckling/Numeral/ZH/Rules.hs
bsd-3-clause
9,563
0
20
2,385
2,837
1,585
1,252
298
2
module Control.Distributed.Task.DataAccess.SimpleDataSource where import qualified Data.ByteString.Lazy.Char8 as BLC import Control.Distributed.Task.Types.TaskTypes (TaskInput) import Control.Distributed.Task.Util.Logging import Control.Distributed.Task.Util.Configuration loadEntries :: FilePath -> IO TaskInput loadEntries filePath = do pseudoDBPath <- getConfiguration >>= return . _pseudoDBPath let path = pseudoDBPath++"/"++filePath in do logInfo $ "accessing pseudo db at: "++path BLC.readFile path >>= return . BLC.lines
michaxm/task-distribution
src/Control/Distributed/Task/DataAccess/SimpleDataSource.hs
bsd-3-clause
547
0
14
70
134
76
58
12
1
-------------------------------------------------------------------------------- {-# LANGUAGE OverloadedStrings #-} import Data.List (intersperse) import Data.Maybe (fromMaybe) import Data.Monoid ((<>)) import Control.Applicative ((<|>)) import Control.Monad (liftM) import Hakyll import Text.Blaze.Html (toHtml, toValue, (!)) import qualified Text.Blaze.Html5 as H import qualified Text.Blaze.Html5.Attributes as A -------------------------------------------------------------------------------- main :: IO () main = hakyll $ do match "images/**" $ do route idRoute compile copyFileCompiler match "css/*" $ do route idRoute compile $ compressCssCompiler match "404.html" $ do route idRoute compile $ pandocCompiler >>= loadAndApplyTemplate "templates/default.html" siteCtx >>= relativizeUrls -------------------------------------------------------------------------- -- Build tags from posts (and used by posts) -- tags <- buildTags "posts/*/index.*" (fromCapture "tags/*.html") categories <- buildMetaCategories "posts/*/index.*" (fromCapture "categories/*.html") let postCtxWithTags = tagsField "tags" tags <> metaCategoriesField "categories" categories <> postCtx match "posts/*/index.*" $ do route $ setExtension "html" compile $ pandocCompiler >>= saveSnapshot "content" >>= loadAndApplyTemplate "templates/post.html" postCtxWithTags >>= loadAndApplyTemplate "templates/default.html" postCtxWithTags >>= relativizeUrls match "pages/*/index.*" $ do route $ setExtension "html" compile $ pandocCompiler >>= loadAndApplyTemplate "templates/page.html" siteCtx >>= loadAndApplyTemplate "templates/default.html" siteCtx -------------------------------------------------------------------------- -- generate home page with most recent 10 posts -- create ["index.html"] $ do route idRoute compile $ do let postTeaserCtx = teaserCtx postCtxWithTags let homeCtx = listField "posts" postTeaserCtx (recentPosts 10) <> siteCtx makeItem "" >>= loadAndApplyTemplate "templates/home.html" homeCtx >>= loadAndApplyTemplate "templates/default.html" homeCtx >>= relativizeUrls -------------------------------------------------------------------------- -- generate archive list of posts -- create ["posts/index.html"] $ do route idRoute compile $ do let listCtx = listField "items" postCtxWithTags orderedPosts <> siteCtx makeItem "" >>= loadAndApplyTemplate "templates/list.html" listCtx >>= loadAndApplyTemplate "templates/default.html" listCtx >>= relativizeUrls -------------------------------------------------------------------------- -- generate tag lists -- tagsRules tags $ \tag pattern -> do let title = "Posts tagged \"" ++ tag ++ "\"" route idRoute compile $ do posts <- recentFirst =<< loadAll pattern let ctx = constField "title" title <> listField "items" postCtxWithTags (return posts) <> siteCtx makeItem "" >>= loadAndApplyTemplate "templates/tag.html" ctx >>= loadAndApplyTemplate "templates/default.html" ctx >>= relativizeUrls -------------------------------------------------------------------------- -- generate category lists -- tagsRules categories $ \category pattern -> do let title = "Posts in \"" ++ category ++ "\"" route idRoute compile $ do posts <- recentFirst =<< loadAll pattern let ctx = constField "title" title <> listField "items" postCtxWithTags (return posts) <> siteCtx makeItem "" >>= loadAndApplyTemplate "templates/tag.html" ctx >>= loadAndApplyTemplate "templates/default.html" ctx >>= relativizeUrls -------------------------------------------------------------------------- -- compile all the templates for use in other rules -- match "templates/*" $ compile templateCompiler -------------------------------------------------------------------------- teaserCtx :: Context String -> Context String teaserCtx = (teaserField "teaser" "content" <>) postCtx :: Context String postCtx = dateField "date" "%B %e, %Y" <> dateField "iso" "%Y-%m-%d" <> siteCtx siteCtx :: Context String siteCtx = constField "site-title" "event -> [thought] -> Stream post" <> constField "site-tagline" "A blog really for myself" <> constField "site-author" "Galex Yen" <> constField "site-author-github" "galexy" <> constField "site-author-linkedin" "galexyen" <> constField "site-copyright" "© 2019 Galex Yen" <> constField "site-disqus-shortname" "event-list-thought-stream-post" <> constField "site-description" "event -> thoughts is a blog by Galex Yen, software engineer, Director of Data Science at Remitly" <> defaultContext orderedPosts :: Compiler [Item String] orderedPosts = do let contentPattern = fromGlob "posts/*/index.*" recentFirst =<< loadAllSnapshots contentPattern "content" recentPosts :: Int -> Compiler [Item String] recentPosts n = take n <$> orderedPosts buildMetaCategories :: MonadMetadata m => Pattern -> (String -> Identifier) -> m Tags buildMetaCategories = buildTagsWith getMetaCategories getMetaCategories :: MonadMetadata m => Identifier -> m [String] getMetaCategories identifier = do metadata <- getMetadata identifier return $ fromMaybe [] $ (lookupStringList "categories" metadata) <|> (map trim . splitAll "," <$> lookupString "categories" metadata) metaCategoriesField :: String -> Tags -> Context a metaCategoriesField = tagsFieldWith getMetaCategories simpleRenderLink (mconcat . intersperse ", ") -------------------------------------------------------------------------------- -- | Render one tag link -- Note: Duplicate from @Hakyll.Web.Tags@ simpleRenderLink :: String -> (Maybe FilePath) -> Maybe H.Html simpleRenderLink _ Nothing = Nothing simpleRenderLink tag (Just filePath) = Just $ H.a ! A.href (toValue $ toUrl filePath) $ toHtml tag
galexy/galexy.github.io
app/Main.hs
bsd-3-clause
7,100
12
25
2,128
1,311
615
696
128
1
{-# LANGUAGE FlexibleContexts, FlexibleInstances, MultiParamTypeClasses #-} module Opaleye.Internal.RunQuery where import Database.PostgreSQL.Simple.Internal (RowParser) import Database.PostgreSQL.Simple.FromField (FieldParser, FromField, fromField, pgArrayFieldParser) import Database.PostgreSQL.Simple.FromRow (fieldWith) import Database.PostgreSQL.Simple.Types (fromPGArray) import Opaleye.Column (Column) import Opaleye.Internal.Column (Nullable) import qualified Opaleye.Internal.PackMap as PackMap import qualified Opaleye.Column as C import qualified Opaleye.Internal.Unpackspec as U import qualified Opaleye.PGTypes as T import qualified Data.Profunctor as P import Data.Profunctor (dimap) import qualified Data.Profunctor.Product as PP import Data.Profunctor.Product (empty, (***!)) import qualified Data.Profunctor.Product.Default as D import qualified Data.CaseInsensitive as CI import qualified Data.Text as ST import qualified Data.Text.Lazy as LT import qualified Data.ByteString as SBS import qualified Data.ByteString.Lazy as LBS import qualified Data.Time as Time import Data.Typeable (Typeable) import Data.UUID (UUID) import GHC.Int (Int64) -- We introduce 'QueryRunnerColumn' which is *not* a Product -- Profunctor because it is the only way I know of to get the instance -- generation to work for non-Nullable and Nullable types at once. data QueryRunnerColumn coltype haskell = QueryRunnerColumn (U.Unpackspec (Column coltype) ()) (FieldParser haskell) data QueryRunner columns haskells = QueryRunner (U.Unpackspec columns ()) (columns -> RowParser haskells) -- We never actually -- look at the columns -- except to see its -- "type" in the case -- of a sum profunctor fieldQueryRunnerColumn :: FromField haskell => QueryRunnerColumn coltype haskell fieldQueryRunnerColumn = QueryRunnerColumn (P.rmap (const ()) U.unpackspecColumn) fromField queryRunner :: QueryRunnerColumn a b -> QueryRunner (Column a) b queryRunner qrc = QueryRunner u (const (fieldWith fp)) where QueryRunnerColumn u fp = qrc queryRunnerColumnNullable :: QueryRunnerColumn a b -> QueryRunnerColumn (Nullable a) (Maybe b) queryRunnerColumnNullable qr = QueryRunnerColumn (P.lmap C.unsafeCoerce u) (fromField' fp) where QueryRunnerColumn u fp = qr fromField' :: FieldParser a -> FieldParser (Maybe a) fromField' _ _ Nothing = pure Nothing fromField' fp' f bs = fmap Just (fp' f bs) -- { Instances for automatic derivation instance QueryRunnerColumnDefault a b => QueryRunnerColumnDefault (Nullable a) (Maybe b) where queryRunnerColumnDefault = queryRunnerColumnNullable queryRunnerColumnDefault instance QueryRunnerColumnDefault a b => D.Default QueryRunner (Column a) b where def = queryRunner queryRunnerColumnDefault -- } -- { Instances that must be provided once for each type. Instances -- for Nullable are derived automatically from these. class QueryRunnerColumnDefault a b where queryRunnerColumnDefault :: QueryRunnerColumn a b instance QueryRunnerColumnDefault T.PGInt4 Int where queryRunnerColumnDefault = fieldQueryRunnerColumn instance QueryRunnerColumnDefault T.PGInt8 Int64 where queryRunnerColumnDefault = fieldQueryRunnerColumn instance QueryRunnerColumnDefault T.PGText String where queryRunnerColumnDefault = fieldQueryRunnerColumn instance QueryRunnerColumnDefault T.PGFloat8 Double where queryRunnerColumnDefault = fieldQueryRunnerColumn instance QueryRunnerColumnDefault T.PGBool Bool where queryRunnerColumnDefault = fieldQueryRunnerColumn instance QueryRunnerColumnDefault T.PGUuid UUID where queryRunnerColumnDefault = fieldQueryRunnerColumn instance QueryRunnerColumnDefault T.PGBytea SBS.ByteString where queryRunnerColumnDefault = fieldQueryRunnerColumn instance QueryRunnerColumnDefault T.PGBytea LBS.ByteString where queryRunnerColumnDefault = fieldQueryRunnerColumn instance QueryRunnerColumnDefault T.PGText ST.Text where queryRunnerColumnDefault = fieldQueryRunnerColumn instance QueryRunnerColumnDefault T.PGText LT.Text where queryRunnerColumnDefault = fieldQueryRunnerColumn instance QueryRunnerColumnDefault T.PGDate Time.Day where queryRunnerColumnDefault = fieldQueryRunnerColumn instance QueryRunnerColumnDefault T.PGTimestamptz Time.UTCTime where queryRunnerColumnDefault = fieldQueryRunnerColumn instance QueryRunnerColumnDefault T.PGTimestamp Time.LocalTime where queryRunnerColumnDefault = fieldQueryRunnerColumn instance QueryRunnerColumnDefault T.PGTime Time.TimeOfDay where queryRunnerColumnDefault = fieldQueryRunnerColumn instance QueryRunnerColumnDefault T.PGCitext (CI.CI ST.Text) where queryRunnerColumnDefault = fieldQueryRunnerColumn instance QueryRunnerColumnDefault T.PGCitext (CI.CI LT.Text) where queryRunnerColumnDefault = fieldQueryRunnerColumn -- No CI String instance since postgresql-simple doesn't define FromField (CI String) arrayColumn :: Column (T.PGArray a) -> Column a arrayColumn = C.unsafeCoerce instance (Typeable b, QueryRunnerColumnDefault a b) => QueryRunnerColumnDefault (T.PGArray a) [b] where queryRunnerColumnDefault = QueryRunnerColumn (P.lmap arrayColumn c) ((fmap . fmap . fmap) fromPGArray (pgArrayFieldParser f)) where QueryRunnerColumn c f = queryRunnerColumnDefault -- } -- Boilerplate instances instance Functor (QueryRunner c) where fmap f (QueryRunner u r) = QueryRunner u ((fmap . fmap) f r) -- TODO: Seems like this one should be simpler! instance Applicative (QueryRunner c) where pure = QueryRunner (P.lmap (const ()) PP.empty) . pure . pure QueryRunner uf rf <*> QueryRunner ux rx = QueryRunner (P.dimap (\x -> (x,x)) (const ()) (uf PP.***! ux)) ((<*>) <$> rf <*> rx) instance P.Profunctor QueryRunner where dimap f g (QueryRunner u r) = QueryRunner (P.lmap f u) (P.dimap f (fmap g) r) instance PP.ProductProfunctor QueryRunner where empty = PP.defaultEmpty (***!) = PP.defaultProfunctorProduct instance PP.SumProfunctor QueryRunner where f +++! g = QueryRunner (P.rmap (const ()) (fu PP.+++! gu)) (PackMap.eitherFunction fr gr) where QueryRunner fu fr = f QueryRunner gu gr = g
silkapp/haskell-opaleye
src/Opaleye/Internal/RunQuery.hs
bsd-3-clause
6,650
0
13
1,354
1,478
805
673
107
2
{-# LANGUAGE BangPatterns #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Data.Binary.Serialise.CBOR.Aeson () where import Data.Aeson import Data.Scientific import qualified Data.Vector as Vec import qualified Data.HashMap.Lazy as HashMap import Data.Binary.Serialise.CBOR.Encoding import Data.Binary.Serialise.CBOR.Decoding import Data.Binary.Serialise.CBOR import Data.Monoid import Control.Applicative instance Serialise Value where encode = encodeValue decode = decodeValue encodeValue :: Value -> Encoding encodeValue (Object vs) = encodeMapLen (fromIntegral $ HashMap.size vs) <> mconcat [ encodeString k <> encodeValue v | (k,v) <- HashMap.toList vs ] encodeValue (Array vs) = encodeListLen (fromIntegral $ Vec.length vs) <> mconcat [ encodeValue v | v <- Vec.toList vs ] encodeValue (String s) = encodeString s encodeValue (Number n) = case floatingOrInteger n of Left d -> encodeDouble d Right i -> encodeInteger i encodeValue (Bool b) = encodeBool b encodeValue Null = encodeNull decodeValue :: Decoder Value decodeValue = do tkty <- peekTokenType case tkty of TypeUInt -> decodeNumberIntegral TypeUInt64 -> decodeNumberIntegral TypeNInt -> decodeNumberIntegral TypeNInt64 -> decodeNumberIntegral TypeInteger -> decodeNumberIntegral TypeFloat64 -> decodeNumberFloating TypeString -> String <$> decodeString TypeListLen -> decodeListLen >>= decodeArray TypeMapLen -> decodeMapLen >>= decodeObject TypeBool -> Bool <$> decodeBool TypeNull -> Null <$ decodeNull _ -> fail $ "unexpected CBOR token type for a JSON value: " ++ show tkty decodeNumberIntegral :: Decoder Value decodeNumberIntegral = Number . fromInteger <$> decodeInteger decodeNumberFloating :: Decoder Value decodeNumberFloating = Number . fromFloatDigits <$> decodeDouble decodeArray :: Int -> Decoder Value decodeArray n0 = do vs <- go n0 [] return $! Array (Vec.fromListN n0 (reverse vs)) where go 0 acc = return acc go n acc = do t <- decodeValue go (n-1) (t : acc) decodeObject :: Int -> Decoder Value decodeObject n0 = do kvs <- go n0 [] return $! Object (HashMap.fromList kvs) where go 0 acc = return acc go n acc = do k <- decodeString v <- decodeValue go (n-1) ((k, v) : acc)
thoughtpolice/binary-serialise-cbor
examples/Aeson.hs
bsd-3-clause
2,555
0
12
705
716
364
352
63
12
{-| module: Bot.Scripting.Core Implements the core IRC-related functionality, like user registration, responding to pings, joining and leaving channels, and so on. -} module Bot.Scripting.Core ( callbacks, -- * Connection connected, disconnected, manageReadyStatus, respondToEndOfMOTD, managePingTimer, pingTimeoutLen, pingTimer, respondToPong, pingTimeout, -- * Queries respondToNAMES, respondToWHOISUSER, respondToWHOWASUSER, namesResponse, whoisResponse, -- * Nick management nickservAddr, acquiredNick, nickservIdent, identPassword, identSuccess, requestOp, -- * Channel management chanservAddr, respondToJoin, respondToPart, respondToKick, unableToJoin, unableToJoinChan, opOnJoin, -- * Other respondToPing, ) where import Bot import Control.Concurrent (killThread) import Data.List (delete, (\\)) import Data.List.Split (splitOn) -- | Event hooks callbacks = [ connected , disconnected , manageReadyStatus , respondToPing , managePingTimer , respondToPong , acquiredNick , identSuccess , respondToJoin , respondToPart , respondToKick , unableToJoin , opOnJoin , respondToNAMES , respondToWHOISUSER , respondToWHOWASUSER ] -- Connection management handle376 = GlobalKey nilCH "handle376" :: GlobalKey CallbackHandle -- | User registration, and set a callback to join channels. connected :: SEvent -> Bot () connected Connected = do putLogInfo "Connected to server." nick <- getGlobal' botNick writeMsg $ CMsg NICK [nick] writeMsg $ CMsg USER [nick, "0", "*" , nick] addCallback respondToEndOfMOTD >>= setGlobal handle376 -- | Remove all the channels from the current channel list. disconnected :: SEvent -> Bot () disconnected Disconnected = do putLogInfo "Disconnected from server." setGlobal currChanList [] signalEvent UnReady -- | Keep track of ready\/unready status. manageReadyStatus Ready = do putLogInfo "Now ready." setGlobal readyStatus True manageReadyStatus UnReady = do putLogInfo "Now unready." setGlobal readyStatus False -- | Join channels on 376 (end of MOTD), and then unhook this callback. respondToEndOfMOTD :: SEvent -> Bot () respondToEndOfMOTD (SNumeric _ 376 _) = do getGlobal handle376 >>= removeCallback chans <- getGlobal' autoJoinList if null chans then return () else joinChannels chans -- | Respond to a server PING with PONG. respondToPing :: SEvent -> Bot () respondToPing (SPing srv) = writeMsg $ CMsg PONG [srv] pingTimerHandle = GlobalKey nilCH "pingTimerHandle" pingTimeoutHandle = GlobalKey nilCH "pingTimeoutHandle" pingN = GlobalKey "" "pingN" :: GlobalKey String -- | How long we should wait without receiving a ping response before -- reconnecting to the server. Pings will be sent at intervals of a third -- of this. pingTimeoutLen = CacheKey 60 "BOT" "pingTimeoutLen" :: PersistentKey Integer -- | Register or unregister the ping timers when we connect/disconnect. -- Every once in a while we'll send a ping to the server, to see if the -- connection is still active. We have a timeout timer, 'pingTimeout', that -- will force a reconnect if it expires. When we receive ping response, we -- reset the timer, so that it's only triggered if we don't receive a timely -- response. managePingTimer :: SEvent -> Bot () managePingTimer Connected = do tm <- getGlobal' pingTimeoutLen runInS tm pingTimeout >>= setGlobal pingTimeoutHandle runInS (div tm 3) pingTimer >>= setGlobal pingTimerHandle managePingTimer Disconnected = do getGlobal pingTimerHandle >>= removeTimer getGlobal pingTimeoutHandle >>= removeTimer -- | Send a ping to the server, every pingTimeoutLen/3 seconds. pingTimer :: Bot () pingTimer = do nick <- getGlobal' botNick writeMsg $ CMsg PING [nick] tm <- getGlobal' pingTimeoutLen runInS (div tm 3) pingTimer >>= setGlobal pingTimerHandle -- | Receive a ping reply from the server and reset the timeout timer. respondToPong :: SEvent -> Bot () respondToPong (SPong _ _) = do getGlobal pingTimeoutHandle >>= removeTimer tm <- getGlobal' pingTimeoutLen runInS tm pingTimeout >>= setGlobal pingTimeoutHandle -- | Disconnect from the server by any means by killing the listener thread. -- This will force a disconnect/reconnect in the main event thread. pingTimeout :: Bot () pingTimeout = do tm <- getGlobal' pingTimeoutLen putLogInfo $ "Ping timeout: " ++ show tm ++ " seconds." getGlobal listenThread >>= liftIO . killThread -- Nick management -- | The password to use to identify the nickname with NickServ. identPassword = CacheKey "" "BOT" "identPassword" -- | The address of the NickServ service on the server. nickservAddr = CacheKey (SServer "") "SERVER" "nickserv" handleNickservNotice = GlobalKey nilCH "handleNickservNotice" :: GlobalKey CallbackHandle -- | On '001', i.e., getting assigned a nick, start listening for a message from NickServ -- in case we have to identify for it. acquiredNick :: SEvent -> Bot () acquiredNick (SNumeric _ 001 _) = addCallback nickservIdent >>= setGlobal handleNickservNotice -- | On the first message from NickServ, whatever it is, identify for our nick. nickservIdent :: SEvent -> Bot () nickservIdent (SNotice sender@(SUser _ _ _) _ _) = do nsAddr <- getGlobal' nickservAddr nsPass <- getGlobal' identPassword if sender /= nsAddr || nsAddr == SServer "" || nsPass == "" then return () else do getGlobal handleNickservNotice >>= removeCallback sendMessage (fromS sender :: User) ("IDENTIFY "++nsPass) -- | When we successfully identify for our nick, we want to request -- op from ChanServ, in case any ops depended on being identified. identSuccess :: SEvent -> Bot () identSuccess (SMode _ (RUser nick) [(True, 'r', [])]) = do ownNick <- getGlobal' botNick when (nick == ownNick) requestOp -- | The address of the ChanServ service on the server. chanservAddr = CacheKey (SServer "") "SERVER" "chanserv" -- | Request op in all channels from ChanServ. requestOp = do cs <- getGlobal' chanservAddr case cs of ss@SUser{} -> sendMessage (fromS ss :: User) "OP" _ -> return () -- Channel management -- | If it's the bot that's joined, update the current channels list. If -- we just joined the last remaining channel on the autojoin list, signal 'Ready'. respondToJoin (SJoin (SUser nick _ _) ch@(RChannel _)) = do ownNick <- getGlobal' botNick if nick /= ownNick then return () else do modGlobal currChanList (++[fromR ch]) putLogInfo ("Joined " ++ show ch) currChans <- getGlobal currChanList autojoin <- getGlobal' autoJoinList when (fromR ch `elem` autojoin && null (autojoin \\ currChans)) $ signalEvent Ready -- | If it's the bot that's parted, update the current channels list. respondToPart (SPart (SUser nick _ _) ch@(RChannel _)) = do ownNick <- getGlobal' botNick if nick /= ownNick then return () else modGlobal currChanList (delete (fromR ch)) >> putLogInfo ("Parted " ++ show ch) -- | If it's the bot that's been kicked, update the current channels list, -- and rejoin the channel after a delay. If this was an autojoin channel, -- signal UnReady. respondToKick e@(SKick (SUser nick _ _) ch@(RChannel _) target reason) = do ownNick <- getGlobal' botNick if target /= ownNick then return () else do modGlobal currChanList (delete (fromR ch)) putLogInfo ("Kicked from " ++ show ch ++" by " ++ nick ++ ": " ++ reason) autojoin <- getGlobal' autoJoinList when (fromR ch `elem` autojoin) $ signalEvent UnReady runInSPriority 5 $ joinChannels [fromR ch] -- | If we're unable to join a channel, we want to record why, and then -- retry joining in 10 seconds. unableToJoinChan chstr n = do putLogWarning $ "Unable to join channel " ++ chstr ++ " - ERR " ++ show n ++ ". Retrying." runInSPriority 10 $ joinChannels [makeChannel chstr] -- | Catch all the cases when we're unable to join a channel. unableToJoin (SNumeric _ n@471 (_:st:_)) = unableToJoinChan st n unableToJoin (SNumeric _ n@473 (_:st:_)) = unableToJoinChan st n unableToJoin (SNumeric _ n@474 (_:st:_)) = unableToJoinChan st n unableToJoin (SNumeric _ n@475 (_:st:_)) = unableToJoinChan st n -- | Try to get op from ChanServ when we join a channel. opOnJoin (SJoin (SUser n _ _) ch@(RChannel _)) = do ownNick <- getGlobal' botNick when (n == ownNick) requestOp -- | NAMES reply - handles both RPL_NAMREPLY (353) and RPL_ENDOFNAMES (366); -- the requester will be called on 353 and unhooked; or if, e.g., the channel -- doesn't exist, the server will only send a 366 and the requester will be -- called on that. respondToNAMES (SNumeric _ 353 [_,_,ch,names]) = do chrs <- getGlobal' statusChars let toUser (x:xs) = if x `elem` chrs then (makeUser xs){statusCharL=[(makeChannel ch, x)]} else makeUser (x:xs) let namesL = map toUser . splitOn " " $ names namesResponse ch namesL respondToNAMES (SNumeric _ 366 [_,_,ch,_]) = namesResponse ch [] -- | Find the requester for the NAMES query, unhook and invoke it. namesResponse :: String -> [User] -> Bot () namesResponse ch cL = do cbs <- consumeGlobal nameCallbacks (\(c, cb) -> "#"++c == ch) mapM_ (($cL) . snd) cbs whoisTempReplies = GlobalKey [] "whoisTempReplies" :: GlobalKey [(String, User)] -- | WHOIS reply - like 'respondToNAMES', this handles RPL_WHOISUSER (311), RPL_WHOISCHANNELS -- (319) and RPL_ENDOFWHOIS (318). We keep a list of intermediate responses which we update -- when we get a 311 and 319, and invoke the callbacks on whatever we've stored when -- a 318 arrives. respondToWHOISUSER (SNumeric _ 311 [_,n,u,h,_,realName]) = modGlobal whoisTempReplies (++[(n, makeUserH n u h)]) respondToWHOISUSER (SNumeric _ 319 [_,n,chanL]) = do chrs <- getGlobal' statusChars let toSC (x:xs) = if x `elem` chrs then (makeChannel xs,x) else (makeChannel $ x:xs,' ') sCL = map toSC . splitOn " " $ chanL modGlobal whoisTempReplies $ map (\(n',u) -> if n'==n then (n', u {statusCharL=sCL}) else (n',u)) respondToWHOISUSER (SNumeric _ 318 [_,n,_]) = do tr <- consumeGlobal whoisTempReplies ((n==).fst) if null tr then whoisResponse n Nothing else mapM_ (\(n,u) -> whoisResponse n (Just u)) tr -- | WHOWAS reply - like 'respondToNAMES', this handles both RPL_WHOWASUSER (314) -- and RPL_ENDOFWHOWAS (369). Handle and . Unlike WHOIS, we're never going to get a -- list of channels, so we don't need to store any intermediate callbacks. respondToWHOWASUSER (SNumeric _ 314 [_,n,u,h,_,realName]) = whoisResponse n . Just $ makeUserH n u h respondToWHOWASUSER (SNumeric _ 369 [_,n,_]) = whoisResponse n Nothing -- | Find the requester for the WHOIS\/WHOWAS query, unhook and invoke it. whoisResponse :: String -> Maybe User -> Bot () whoisResponse n userMb = do putLogDebug $ "Whois response: " ++ show n ++ " - " ++ show userMb cbs <- getGlobal whoisCallbacks let shouldRun = [t | t@(u, cb) <- cbs, u == n] let shouldKeep = [t | t@(u, cb) <- cbs, u /= n] setGlobal whoisCallbacks shouldKeep mapM_ (($userMb) . snd) shouldRun
cyclohexanamine/haskbot
src/Bot/Scripting/Core.hs
bsd-3-clause
11,472
0
17
2,484
2,853
1,464
1,389
177
4
module Main where import Graphics.HsCharts import Graphics.Gloss main :: IO () main = do let disp = InWindow "HsCharts Demo" (windowW, windowH) (50, 50) display disp white $ pictures [ q 0 0 pointChart , q 1 0 lineChart , q 2 0 bubbleChart , q 3 0 logScaleChart , q 0 1 barChart , q 1 1 areaChart , q 2 1 Main.boxPlot , q 3 1 polarChart ] windowW = 1050 windowH = 550 chartW = 200 chartH = 200 chartM = 50 q x y = translate dx dy where dx = (-(fromIntegral windowW / 2)) + (chartM + x * (chartW + chartM)) dy = (fromIntegral windowH / 2) - chartH - chartM - (y * (chartH + chartM)) bgColor = makeColor 0.98 0.98 0.98 1 gridColor = makeColor 0.8 0.8 0.8 1 gridAltColor = makeColor 0.8 0.8 0.8 0.4 pointColor = makeColor 0.15 0.50 0.75 1 pointColor' = makeColor 0.75 0.15 0.15 1 pointColor'' = makeColor 0.15 0.75 0.15 1 barColor = makeColor 0.15 0.50 0.75 0.8 areaColor = makeColor 0.15 0.50 0.75 0.4 ----------------------------------------------------------------------------- lineChart :: Picture lineChart = pictures [ color bgColor $ plotChartBackground xAxis yAxis , color gridColor $ plotGrid xAxis yAxis (0, 0.125) , plotAxes xAxis yAxis , plotAxisScales xAxis yAxis (2, 0.5) , line 1 pointColor , line 1.5 pointColor' , line 3 pointColor'' ] where xAxis = autoScaleAxis Linear chartW xs yAxis = fixedScaleAxis Linear chartH 0 1 xs = [-6,-5.75..6] ys = [sigmoid x | x <- xs] pts x = zip xs (map ((+(0.5 - sigmoid 0 / x)) . (/x)) ys) line x c = color c $ plotLineChart xAxis yAxis (pts x) sigmoid x = 1.0 / (1 + exp (-x)) ----------------------------------------------------------------------------- boxPlot :: Picture boxPlot = pictures [ color bgColor $ plotChartBackground xAxis yAxis , color gridColor $ plotGrid xAxis yAxis (0, 0.25) , plotAxes xAxis yAxis , plotAxisScales xAxis yAxis (0, 0.5) , boxPlots xAxis yAxis 25 barColor (pts ++ pts' ++ pts'' ++ pts''') ] where xAxis = fixedScaleAxis Linear chartW 0.5 4.5 yAxis = fixedScaleAxis Linear chartH (-1) 1 pts = zip (repeat 1) (map sin [0..10]) pts' = zip (repeat 2) (map cos [0, 0.1..2]) pts'' = zip (repeat 3) (map cos [1, 1.1..3]) pts''' = zip (repeat 4) (map cos [1, 1.1..2]) ----------------------------------------------------------------------------- pointChart :: Picture pointChart = pictures [ color bgColor $ plotChartBackground xAxis yAxis , color gridColor $ plotGrid xAxis yAxis (1, 1) , plotAxes xAxis yAxis , plotAxisScales xAxis yAxis (1, 1) , color pointColor $ plotPointChart' (circleSolid 3) xAxis yAxis pts , color pointColor' $ plotPointChart' (eqTriangleSolid 6) xAxis yAxis pts' ] where xAxis = fixedScaleAxis Linear chartW 0 10 yAxis = fixedScaleAxis Linear chartH 0 10 pts = [ (0.5, 0.7), (0.9, 1.3), (1.3, 2.1), (2.3, 3.9) , (3.0, 0.9), (3.2, 4.1), (3.4, 3.8), (3.7, 2.6) , (4.1, 5.2), (4.3, 1.2), (4.5, 2.3), (5.1, 2.5) ] pts' = [ (5.2, 6.1), (5.7, 6.5), (6.1, 8.9), (6.2, 8.4) , (6.3, 7.5), (6.8, 8.2), (7.1, 5.5), (7.6, 8.9) , (8.0, 9.5), (8.3, 6.6), (8.4, 7.5), (8.7, 5.6) , (8.7, 9.6), (9.4, 8.7), (9.9, 9.9) ] ----------------------------------------------------------------------------- bubbleChart :: Picture bubbleChart = pictures [ color bgColor $ plotChartBackground xAxis yAxis , color gridColor $ plotGrid xAxis yAxis (1, 1) , plotAxes xAxis yAxis , plotAxisScales xAxis yAxis (1, 1) , plotBubbleChart xAxis yAxis zAxis $ zip3 xs ys zs ] where xAxis = autoScaleAxis' Linear chartW xs yAxis = autoScaleAxis' Linear chartH xs zAxis = fixedScaleAxis Linear 20 (-1.5) 1 xs = [1..10] ys = [0.5 + maximum xs - (x + sin x) | x <- xs] zs = map cos xs ----------------------------------------------------------------------------- barChart :: Picture barChart = pictures [ color bgColor $ plotChartBackground xAxis yAxis , color gridColor $ plotGrid xAxis yAxis (0, 0.1) , plotAxes xAxis yAxis , plotAxisScales xAxis yAxis (1, 0.1) , color barColor $ plotBarChart xAxis yAxis pts ] where xAxis = autoScaleAxis Linear chartW xs yAxis = fixedScaleAxis Linear chartH 0 1 xs = [0..18] ys = [sin (x / 6) | x <- xs] pts = zip xs ys ----------------------------------------------------------------------------- areaChart :: Picture areaChart = pictures [ color bgColor $ plotChartBackground xAxis yAxis , color gridColor $ plotGrid xAxis yAxis (0, 0.1) , plotAxes xAxis yAxis , plotAxisScales xAxis yAxis (1, 0.2) , color areaColor $ plotAreaChart xAxis yAxis pts , color pointColor $ plotLineChart xAxis yAxis pts ] where xAxis = autoScaleAxis Linear chartW xs yAxis = fixedScaleAxis Linear chartH (-1) 1 xs = [0,0.1..2 * pi] ys = map sin xs pts = zip xs ys ----------------------------------------------------------------------------- polarChart :: Picture polarChart = pictures [ color bgColor $ plotChartBackground tAxis rAxis , color gridColor $ plotPolarGrid tAxis rAxis (pi / 4, pi / 8) , color pointColor $ plotPolarChart line tAxis rAxis pts , color pointColor' $ plotPolarChart line tAxis rAxis pts' ] where tAxis = angularAxis chartW rAxis = radialAxis Linear chartH 0 (pi / 2) xs = map ((2 * pi / 100) * ) [0..100] ys = map (\x -> sin (4 * x) ) xs xs' = map ((4 * pi / 100) * ) [0..100] ys' = map (/ (2.6 * pi)) $ xs' pts = zip xs ys pts' = zip xs' ys' renderPointFn = pictures . map point point (x, y) = translate x y $ circleSolid 2.5 ----------------------------------------------------------------------------- logScaleChart :: Picture logScaleChart = pictures [ color bgColor $ plotChartBackground xAxis yAxis , plotAxes xAxis yAxis , color pointColor $ plotAxisScales xAxis yAxis (1, 10) , translate (chartW + 25) 0 $ color pointColor' $ plotAxisScales xAxis yAxis' (0, 10) , color pointColor $ plotLineChart xAxis yAxis $ zip xs ys , color pointColor' $ plotLineChart xAxis yAxis' $ zip xs ys ] where xAxis = fixedScaleAxis Linear chartW 0 10 yAxis = fixedScaleAxis Linear chartH 0 1024 yAxis' = fixedScaleAxis Log chartH 1 1000 xs = [0.1, 0.25..10] ys = map (2 **) xs
maciej-wichrowski/HsCharts
demo/Main.hs
bsd-3-clause
7,621
0
16
2,729
2,398
1,280
1,118
144
1
{-| Module : Idris.IBC Description : Core representations and code to generate IBC files. Copyright : License : BSD3 Maintainer : The Idris Community. -} {-# LANGUAGE TypeSynonymInstances #-} {-# OPTIONS_GHC -fwarn-incomplete-patterns #-} module Idris.IBC (loadIBC, loadPkgIndex, writeIBC, writePkgIndex, hasValidIBCVersion, IBCPhase(..)) where import Idris.Core.Evaluate import Idris.Core.TT import Idris.Core.Binary import Idris.Core.CaseTree import Idris.AbsSyntax import Idris.Imports import Idris.Error import Idris.DeepSeq import Idris.Delaborate import qualified Idris.Docstrings as D import Idris.Docstrings (Docstring) import Idris.Output import IRTS.System (getIdrisLibDir) import Paths_idris import qualified Cheapskate.Types as CT import Data.Binary import Data.Functor import Data.Vector.Binary import Data.List as L import Data.Maybe (catMaybes) import Data.ByteString.Lazy as B hiding (length, elem, map) import qualified Data.Text as T import qualified Data.Set as S import Control.Monad import Control.DeepSeq import Control.Monad.State.Strict hiding (get, put) import qualified Control.Monad.State.Strict as ST import System.FilePath import System.Directory import Codec.Archive.Zip import Debug.Trace ibcVersion :: Word16 ibcVersion = 145 -- | When IBC is being loaded - we'll load different things (and omit -- different structures/definitions) depending on which phase we're in. data IBCPhase = IBC_Building -- ^ when building the module tree | IBC_REPL Bool -- ^ when loading modules for the REPL Bool = True for top level module deriving (Show, Eq) data IBCFile = IBCFile { ver :: Word16 , sourcefile :: FilePath , ibc_reachablenames :: ![Name] , ibc_imports :: ![(Bool, FilePath)] , ibc_importdirs :: ![FilePath] , ibc_implicits :: ![(Name, [PArg])] , ibc_fixes :: ![FixDecl] , ibc_statics :: ![(Name, [Bool])] , ibc_classes :: ![(Name, ClassInfo)] , ibc_records :: ![(Name, RecordInfo)] , ibc_instances :: ![(Bool, Bool, Name, Name)] , ibc_dsls :: ![(Name, DSL)] , ibc_datatypes :: ![(Name, TypeInfo)] , ibc_optimise :: ![(Name, OptInfo)] , ibc_syntax :: ![Syntax] , ibc_keywords :: ![String] , ibc_objs :: ![(Codegen, FilePath)] , ibc_libs :: ![(Codegen, String)] , ibc_cgflags :: ![(Codegen, String)] , ibc_dynamic_libs :: ![String] , ibc_hdrs :: ![(Codegen, String)] , ibc_totcheckfail :: ![(FC, String)] , ibc_flags :: ![(Name, [FnOpt])] , ibc_fninfo :: ![(Name, FnInfo)] , ibc_cg :: ![(Name, CGInfo)] , ibc_docstrings :: ![(Name, (Docstring D.DocTerm, [(Name, Docstring D.DocTerm)]))] , ibc_moduledocs :: ![(Name, Docstring D.DocTerm)] , ibc_transforms :: ![(Name, (Term, Term))] , ibc_errRev :: ![(Term, Term)] , ibc_coercions :: ![Name] , ibc_lineapps :: ![(FilePath, Int, PTerm)] , ibc_namehints :: ![(Name, Name)] , ibc_metainformation :: ![(Name, MetaInformation)] , ibc_errorhandlers :: ![Name] , ibc_function_errorhandlers :: ![(Name, Name, Name)] -- fn, arg, handler , ibc_metavars :: ![(Name, (Maybe Name, Int, [Name], Bool, Bool))] , ibc_patdefs :: ![(Name, ([([(Name, Term)], Term, Term)], [PTerm]))] , ibc_postulates :: ![Name] , ibc_externs :: ![(Name, Int)] , ibc_parsedSpan :: !(Maybe FC) , ibc_usage :: ![(Name, Int)] , ibc_exports :: ![Name] , ibc_autohints :: ![(Name, Name)] , ibc_deprecated :: ![(Name, String)] , ibc_defs :: ![(Name, Def)] , ibc_total :: ![(Name, Totality)] , ibc_injective :: ![(Name, Injectivity)] , ibc_access :: ![(Name, Accessibility)] , ibc_fragile :: ![(Name, String)] , ibc_constraints :: ![(FC, UConstraint)] } deriving Show {-! deriving instance Binary IBCFile !-} initIBC :: IBCFile initIBC = IBCFile ibcVersion "" [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] Nothing [] [] [] [] [] [] [] [] [] [] hasValidIBCVersion :: FilePath -> Idris Bool hasValidIBCVersion fp = do archiveFile <- runIO $ B.readFile fp case toArchiveOrFail archiveFile of Left _ -> return False Right archive -> do ver <- getEntry 0 "ver" archive return (ver == ibcVersion) loadIBC :: Bool -- ^ True = reexport, False = make everything private -> IBCPhase -> FilePath -> Idris () loadIBC reexport phase fp = do imps <- getImported case lookup fp imps of Nothing -> load True Just p -> if (not p && reexport) then load False else return () where load fullLoad = do logIBC 1 $ "Loading ibc " ++ fp ++ " " ++ show reexport archiveFile <- runIO $ B.readFile fp case toArchiveOrFail archiveFile of Left _ -> do ifail $ fp ++ " isn't loadable, it may have an old ibc format.\n" ++ "Please clean and rebuild it." Right archive -> do if fullLoad then process reexport phase archive fp else unhide phase archive addImported reexport fp -- | Load an entire package from its index file loadPkgIndex :: String -> Idris () loadPkgIndex pkg = do ddir <- runIO getIdrisLibDir addImportDir (ddir </> pkg) fp <- findPkgIndex pkg loadIBC True IBC_Building fp makeEntry :: (Binary b) => String -> [b] -> Maybe Entry makeEntry name val = if L.null val then Nothing else Just $ toEntry name 0 (encode val) entries :: IBCFile -> [Entry] entries i = catMaybes [Just $ toEntry "ver" 0 (encode $ ver i), makeEntry "sourcefile" (sourcefile i), makeEntry "ibc_imports" (ibc_imports i), makeEntry "ibc_importdirs" (ibc_importdirs i), makeEntry "ibc_implicits" (ibc_implicits i), makeEntry "ibc_fixes" (ibc_fixes i), makeEntry "ibc_statics" (ibc_statics i), makeEntry "ibc_classes" (ibc_classes i), makeEntry "ibc_records" (ibc_records i), makeEntry "ibc_instances" (ibc_instances i), makeEntry "ibc_dsls" (ibc_dsls i), makeEntry "ibc_datatypes" (ibc_datatypes i), makeEntry "ibc_optimise" (ibc_optimise i), makeEntry "ibc_syntax" (ibc_syntax i), makeEntry "ibc_keywords" (ibc_keywords i), makeEntry "ibc_objs" (ibc_objs i), makeEntry "ibc_libs" (ibc_libs i), makeEntry "ibc_cgflags" (ibc_cgflags i), makeEntry "ibc_dynamic_libs" (ibc_dynamic_libs i), makeEntry "ibc_hdrs" (ibc_hdrs i), makeEntry "ibc_totcheckfail" (ibc_totcheckfail i), makeEntry "ibc_flags" (ibc_flags i), makeEntry "ibc_fninfo" (ibc_fninfo i), makeEntry "ibc_cg" (ibc_cg i), makeEntry "ibc_docstrings" (ibc_docstrings i), makeEntry "ibc_moduledocs" (ibc_moduledocs i), makeEntry "ibc_transforms" (ibc_transforms i), makeEntry "ibc_errRev" (ibc_errRev i), makeEntry "ibc_coercions" (ibc_coercions i), makeEntry "ibc_lineapps" (ibc_lineapps i), makeEntry "ibc_namehints" (ibc_namehints i), makeEntry "ibc_metainformation" (ibc_metainformation i), makeEntry "ibc_errorhandlers" (ibc_errorhandlers i), makeEntry "ibc_function_errorhandlers" (ibc_function_errorhandlers i), makeEntry "ibc_metavars" (ibc_metavars i), makeEntry "ibc_patdefs" (ibc_patdefs i), makeEntry "ibc_postulates" (ibc_postulates i), makeEntry "ibc_externs" (ibc_externs i), toEntry "ibc_parsedSpan" 0 . encode <$> ibc_parsedSpan i, makeEntry "ibc_usage" (ibc_usage i), makeEntry "ibc_exports" (ibc_exports i), makeEntry "ibc_autohints" (ibc_autohints i), makeEntry "ibc_deprecated" (ibc_deprecated i), makeEntry "ibc_defs" (ibc_defs i), makeEntry "ibc_total" (ibc_total i), makeEntry "ibc_injective" (ibc_injective i), makeEntry "ibc_access" (ibc_access i), makeEntry "ibc_fragile" (ibc_fragile i)] -- TODO: Put this back in shortly after minimising/pruning constraints -- makeEntry "ibc_constraints" (ibc_constraints i)] writeArchive :: FilePath -> IBCFile -> Idris () writeArchive fp i = do let a = L.foldl (\x y -> addEntryToArchive y x) emptyArchive (entries i) runIO $ B.writeFile fp (fromArchive a) writeIBC :: FilePath -> FilePath -> Idris () writeIBC src f = do logIBC 1 $ "Writing ibc " ++ show f i <- getIState -- case (Data.List.map fst (idris_metavars i)) \\ primDefs of -- (_:_) -> ifail "Can't write ibc when there are unsolved metavariables" -- [] -> return () resetNameIdx ibcf <- mkIBC (ibc_write i) (initIBC { sourcefile = src }) idrisCatch (do runIO $ createDirectoryIfMissing True (dropFileName f) writeArchive f ibcf logIBC 1 "Written") (\c -> do logIBC 1 $ "Failed " ++ pshow i c) return () -- | Write a package index containing all the imports in the current -- IState Used for ':search' of an entire package, to ensure -- everything is loaded. writePkgIndex :: FilePath -> Idris () writePkgIndex f = do i <- getIState let imps = map (\ (x, y) -> (True, x)) $ idris_imported i logIBC 1 $ "Writing package index " ++ show f ++ " including\n" ++ show (map snd imps) resetNameIdx let ibcf = initIBC { ibc_imports = imps } idrisCatch (do runIO $ createDirectoryIfMissing True (dropFileName f) writeArchive f ibcf logIBC 1 "Written") (\c -> do logIBC 1 $ "Failed " ++ pshow i c) return () mkIBC :: [IBCWrite] -> IBCFile -> Idris IBCFile mkIBC [] f = return f mkIBC (i:is) f = do ist <- getIState logIBC 5 $ show i ++ " " ++ show (L.length is) f' <- ibc ist i f mkIBC is f' ibc :: IState -> IBCWrite -> IBCFile -> Idris IBCFile ibc i (IBCFix d) f = return f { ibc_fixes = d : ibc_fixes f } ibc i (IBCImp n) f = case lookupCtxtExact n (idris_implicits i) of Just v -> return f { ibc_implicits = (n,v): ibc_implicits f } _ -> ifail "IBC write failed" ibc i (IBCStatic n) f = case lookupCtxtExact n (idris_statics i) of Just v -> return f { ibc_statics = (n,v): ibc_statics f } _ -> ifail "IBC write failed" ibc i (IBCClass n) f = case lookupCtxtExact n (idris_classes i) of Just v -> return f { ibc_classes = (n,v): ibc_classes f } _ -> ifail "IBC write failed" ibc i (IBCRecord n) f = case lookupCtxtExact n (idris_records i) of Just v -> return f { ibc_records = (n,v): ibc_records f } _ -> ifail "IBC write failed" ibc i (IBCInstance int res n ins) f = return f { ibc_instances = (int, res, n, ins) : ibc_instances f } ibc i (IBCDSL n) f = case lookupCtxtExact n (idris_dsls i) of Just v -> return f { ibc_dsls = (n,v): ibc_dsls f } _ -> ifail "IBC write failed" ibc i (IBCData n) f = case lookupCtxtExact n (idris_datatypes i) of Just v -> return f { ibc_datatypes = (n,v): ibc_datatypes f } _ -> ifail "IBC write failed" ibc i (IBCOpt n) f = case lookupCtxtExact n (idris_optimisation i) of Just v -> return f { ibc_optimise = (n,v): ibc_optimise f } _ -> ifail "IBC write failed" ibc i (IBCSyntax n) f = return f { ibc_syntax = n : ibc_syntax f } ibc i (IBCKeyword n) f = return f { ibc_keywords = n : ibc_keywords f } ibc i (IBCImport n) f = return f { ibc_imports = n : ibc_imports f } ibc i (IBCImportDir n) f = return f { ibc_importdirs = n : ibc_importdirs f } ibc i (IBCObj tgt n) f = return f { ibc_objs = (tgt, n) : ibc_objs f } ibc i (IBCLib tgt n) f = return f { ibc_libs = (tgt, n) : ibc_libs f } ibc i (IBCCGFlag tgt n) f = return f { ibc_cgflags = (tgt, n) : ibc_cgflags f } ibc i (IBCDyLib n) f = return f {ibc_dynamic_libs = n : ibc_dynamic_libs f } ibc i (IBCHeader tgt n) f = return f { ibc_hdrs = (tgt, n) : ibc_hdrs f } ibc i (IBCDef n) f = do f' <- case lookupDefExact n (tt_ctxt i) of Just v -> return f { ibc_defs = (n,v) : ibc_defs f } _ -> ifail "IBC write failed" case lookupCtxtExact n (idris_patdefs i) of Just v -> return f' { ibc_patdefs = (n,v) : ibc_patdefs f } _ -> return f' -- Not a pattern definition ibc i (IBCDoc n) f = case lookupCtxtExact n (idris_docstrings i) of Just v -> return f { ibc_docstrings = (n,v) : ibc_docstrings f } _ -> ifail "IBC write failed" ibc i (IBCCG n) f = case lookupCtxtExact n (idris_callgraph i) of Just v -> return f { ibc_cg = (n,v) : ibc_cg f } _ -> ifail "IBC write failed" ibc i (IBCCoercion n) f = return f { ibc_coercions = n : ibc_coercions f } ibc i (IBCAccess n a) f = return f { ibc_access = (n,a) : ibc_access f } ibc i (IBCFlags n a) f = return f { ibc_flags = (n,a) : ibc_flags f } ibc i (IBCFnInfo n a) f = return f { ibc_fninfo = (n,a) : ibc_fninfo f } ibc i (IBCTotal n a) f = return f { ibc_total = (n,a) : ibc_total f } ibc i (IBCInjective n a) f = return f { ibc_injective = (n,a) : ibc_injective f } ibc i (IBCTrans n t) f = return f { ibc_transforms = (n, t) : ibc_transforms f } ibc i (IBCErrRev t) f = return f { ibc_errRev = t : ibc_errRev f } ibc i (IBCLineApp fp l t) f = return f { ibc_lineapps = (fp,l,t) : ibc_lineapps f } ibc i (IBCNameHint (n, ty)) f = return f { ibc_namehints = (n, ty) : ibc_namehints f } ibc i (IBCMetaInformation n m) f = return f { ibc_metainformation = (n,m) : ibc_metainformation f } ibc i (IBCErrorHandler n) f = return f { ibc_errorhandlers = n : ibc_errorhandlers f } ibc i (IBCFunctionErrorHandler fn a n) f = return f { ibc_function_errorhandlers = (fn, a, n) : ibc_function_errorhandlers f } ibc i (IBCMetavar n) f = case lookup n (idris_metavars i) of Nothing -> return f Just t -> return f { ibc_metavars = (n, t) : ibc_metavars f } ibc i (IBCPostulate n) f = return f { ibc_postulates = n : ibc_postulates f } ibc i (IBCExtern n) f = return f { ibc_externs = n : ibc_externs f } ibc i (IBCTotCheckErr fc err) f = return f { ibc_totcheckfail = (fc, err) : ibc_totcheckfail f } ibc i (IBCParsedRegion fc) f = return f { ibc_parsedSpan = Just fc } ibc i (IBCModDocs n) f = case lookupCtxtExact n (idris_moduledocs i) of Just v -> return f { ibc_moduledocs = (n,v) : ibc_moduledocs f } _ -> ifail "IBC write failed" ibc i (IBCUsage n) f = return f { ibc_usage = n : ibc_usage f } ibc i (IBCExport n) f = return f { ibc_exports = n : ibc_exports f } ibc i (IBCAutoHint n h) f = return f { ibc_autohints = (n, h) : ibc_autohints f } ibc i (IBCDeprecate n r) f = return f { ibc_deprecated = (n, r) : ibc_deprecated f } ibc i (IBCFragile n r) f = return f { ibc_fragile = (n,r) : ibc_fragile f } ibc i (IBCConstraint fc u) f = return f { ibc_constraints = (fc, u) : ibc_constraints f } getEntry :: (Binary b, NFData b) => b -> FilePath -> Archive -> Idris b getEntry alt f a = case findEntryByPath f a of Nothing -> return alt Just e -> return $! (force . decode . fromEntry) e unhide :: IBCPhase -> Archive -> Idris () unhide phase ar = do processImports True phase ar processAccess True phase ar process :: Bool -- ^ Reexporting -> IBCPhase -> Archive -> FilePath -> Idris () process reexp phase archive fn = do ver <- getEntry 0 "ver" archive when (ver /= ibcVersion) $ do logIBC 1 "ibc out of date" let e = if ver < ibcVersion then " an earlier " else " a later " ifail $ "Incompatible ibc version.\nThis library was built with" ++ e ++ "version of Idris.\n" ++ "Please clean and rebuild." source <- getEntry "" "sourcefile" archive srcok <- runIO $ doesFileExist source when srcok $ timestampOlder source fn processImportDirs archive processImports reexp phase archive processImplicits archive processInfix archive processStatics archive processClasses archive processRecords archive processInstances archive processDSLs archive processDatatypes archive processOptimise archive processSyntax archive processKeywords archive processObjectFiles archive processLibs archive processCodegenFlags archive processDynamicLibs archive processHeaders archive processPatternDefs archive processFlags archive processFnInfo archive processTotalityCheckError archive processCallgraph archive processDocs archive processModuleDocs archive processCoercions archive processTransforms archive processErrRev archive processLineApps archive processNameHints archive processMetaInformation archive processErrorHandlers archive processFunctionErrorHandlers archive processMetaVars archive processPostulates archive processExterns archive processParsedSpan archive processUsage archive processExports archive processAutoHints archive processDeprecate archive processDefs archive processTotal archive processInjective archive processAccess reexp phase archive processFragile archive processConstraints archive timestampOlder :: FilePath -> FilePath -> Idris () timestampOlder src ibc = do srct <- runIO $ getModificationTime src ibct <- runIO $ getModificationTime ibc if (srct > ibct) then ifail $ unlines [ "Module needs reloading:" , unwords ["\tSRC :", show src] , unwords ["\tModified at:", show srct] , unwords ["\tIBC :", show ibc] , unwords ["\tModified at:", show ibct] ] else return () processPostulates :: Archive -> Idris () processPostulates ar = do ns <- getEntry [] "ibc_postulates" ar updateIState (\i -> i { idris_postulates = idris_postulates i `S.union` S.fromList ns }) processExterns :: Archive -> Idris () processExterns ar = do ns <- getEntry [] "ibc_externs" ar updateIState (\i -> i{ idris_externs = idris_externs i `S.union` S.fromList ns }) processParsedSpan :: Archive -> Idris () processParsedSpan ar = do fc <- getEntry Nothing "ibc_parsedSpan" ar updateIState (\i -> i { idris_parsedSpan = fc }) processUsage :: Archive -> Idris () processUsage ar = do ns <- getEntry [] "ibc_usage" ar updateIState (\i -> i { idris_erasureUsed = ns ++ idris_erasureUsed i }) processExports :: Archive -> Idris () processExports ar = do ns <- getEntry [] "ibc_exports" ar updateIState (\i -> i { idris_exports = ns ++ idris_exports i }) processAutoHints :: Archive -> Idris () processAutoHints ar = do ns <- getEntry [] "ibc_autohints" ar mapM_ (\(n,h) -> addAutoHint n h) ns processDeprecate :: Archive -> Idris () processDeprecate ar = do ns <- getEntry [] "ibc_deprecated" ar mapM_ (\(n,reason) -> addDeprecated n reason) ns processFragile :: Archive -> Idris () processFragile ar = do ns <- getEntry [] "ibc_fragile" ar mapM_ (\(n,reason) -> addFragile n reason) ns processConstraints :: Archive -> Idris () processConstraints ar = do cs <- getEntry [] "ibc_constraints" ar mapM_ (\ (fc, c) -> addConstraints fc (0, [c])) cs processImportDirs :: Archive -> Idris () processImportDirs ar = do fs <- getEntry [] "ibc_importdirs" ar mapM_ addImportDir fs processImports :: Bool -> IBCPhase -> Archive -> Idris () processImports reexp phase ar = do fs <- getEntry [] "ibc_imports" ar mapM_ (\(re, f) -> do i <- getIState ibcsd <- valIBCSubDir i ids <- allImportDirs fp <- findImport ids ibcsd f -- if (f `elem` imported i) -- then logLvl 1 $ "Already read " ++ f putIState (i { imported = f : imported i }) let phase' = case phase of IBC_REPL _ -> IBC_REPL False p -> p case fp of LIDR fn -> do logIBC 1 $ "Failed at " ++ fn ifail "Must be an ibc" IDR fn -> do logIBC 1 $ "Failed at " ++ fn ifail "Must be an ibc" IBC fn src -> loadIBC (reexp && re) phase' fn) fs processImplicits :: Archive -> Idris () processImplicits ar = do imps <- getEntry [] "ibc_implicits" ar mapM_ (\ (n, imp) -> do i <- getIState case lookupDefAccExact n False (tt_ctxt i) of Just (n, Hidden) -> return () Just (n, Private) -> return () _ -> putIState (i { idris_implicits = addDef n imp (idris_implicits i) })) imps processInfix :: Archive -> Idris () processInfix ar = do f <- getEntry [] "ibc_fixes" ar updateIState (\i -> i { idris_infixes = sort $ f ++ idris_infixes i }) processStatics :: Archive -> Idris () processStatics ar = do ss <- getEntry [] "ibc_statics" ar mapM_ (\ (n, s) -> updateIState (\i -> i { idris_statics = addDef n s (idris_statics i) })) ss processClasses :: Archive -> Idris () processClasses ar = do cs <- getEntry [] "ibc_classes" ar mapM_ (\ (n, c) -> do i <- getIState -- Don't lose instances from previous IBCs, which -- could have loaded in any order let is = case lookupCtxtExact n (idris_classes i) of Just (CI _ _ _ _ _ ins _) -> ins _ -> [] let c' = c { class_instances = class_instances c ++ is } putIState (i { idris_classes = addDef n c' (idris_classes i) })) cs processRecords :: Archive -> Idris () processRecords ar = do rs <- getEntry [] "ibc_records" ar mapM_ (\ (n, r) -> updateIState (\i -> i { idris_records = addDef n r (idris_records i) })) rs processInstances :: Archive -> Idris () processInstances ar = do cs <- getEntry [] "ibc_instances" ar mapM_ (\ (i, res, n, ins) -> addInstance i res n ins) cs processDSLs :: Archive -> Idris () processDSLs ar = do cs <- getEntry [] "ibc_dsls" ar mapM_ (\ (n, c) -> updateIState (\i -> i { idris_dsls = addDef n c (idris_dsls i) })) cs processDatatypes :: Archive -> Idris () processDatatypes ar = do cs <- getEntry [] "ibc_datatypes" ar mapM_ (\ (n, c) -> updateIState (\i -> i { idris_datatypes = addDef n c (idris_datatypes i) })) cs processOptimise :: Archive -> Idris () processOptimise ar = do cs <- getEntry [] "ibc_optimise" ar mapM_ (\ (n, c) -> updateIState (\i -> i { idris_optimisation = addDef n c (idris_optimisation i) })) cs processSyntax :: Archive -> Idris () processSyntax ar = do s <- getEntry [] "ibc_syntax" ar updateIState (\i -> i { syntax_rules = updateSyntaxRules s (syntax_rules i) }) processKeywords :: Archive -> Idris () processKeywords ar = do k <- getEntry [] "ibc_keywords" ar updateIState (\i -> i { syntax_keywords = k ++ syntax_keywords i }) processObjectFiles :: Archive -> Idris () processObjectFiles ar = do os <- getEntry [] "ibc_objs" ar mapM_ (\ (cg, obj) -> do dirs <- allImportDirs o <- runIO $ findInPath dirs obj addObjectFile cg o) os processLibs :: Archive -> Idris () processLibs ar = do ls <- getEntry [] "ibc_libs" ar mapM_ (uncurry addLib) ls processCodegenFlags :: Archive -> Idris () processCodegenFlags ar = do ls <- getEntry [] "ibc_cgflags" ar mapM_ (uncurry addFlag) ls processDynamicLibs :: Archive -> Idris () processDynamicLibs ar = do ls <- getEntry [] "ibc_dynamic_libs" ar res <- mapM (addDyLib . return) ls mapM_ checkLoad res where checkLoad (Left _) = return () checkLoad (Right err) = ifail err processHeaders :: Archive -> Idris () processHeaders ar = do hs <- getEntry [] "ibc_hdrs" ar mapM_ (uncurry addHdr) hs processPatternDefs :: Archive -> Idris () processPatternDefs ar = do ds <- getEntry [] "ibc_patdefs" ar mapM_ (\ (n, d) -> updateIState (\i -> i { idris_patdefs = addDef n (force d) (idris_patdefs i) })) ds processDefs :: Archive -> Idris () processDefs ar = do ds <- getEntry [] "ibc_defs" ar mapM_ (\ (n, d) -> do d' <- updateDef d case d' of TyDecl _ _ -> return () _ -> do logIBC 1 $ "SOLVING " ++ show n solveDeferred emptyFC n updateIState (\i -> i { tt_ctxt = addCtxtDef n d' (tt_ctxt i) })) ds where updateDef (CaseOp c t args o s cd) = do o' <- mapM updateOrig o cd' <- updateCD cd return $ CaseOp c t args o' s cd' updateDef t = return t updateOrig (Left t) = liftM Left (update t) updateOrig (Right (l, r)) = do l' <- update l r' <- update r return $ Right (l', r') updateCD (CaseDefs (ts, t) (cs, c) (is, i) (rs, r)) = do c' <- updateSC c r' <- updateSC r return $ CaseDefs (cs, c') (cs, c') (cs, c') (rs, r') updateSC (Case t n alts) = do alts' <- mapM updateAlt alts return (Case t n alts') updateSC (ProjCase t alts) = do alts' <- mapM updateAlt alts return (ProjCase t alts') updateSC (STerm t) = do t' <- update t return (STerm t') updateSC c = return c updateAlt (ConCase n i ns t) = do t' <- updateSC t return (ConCase n i ns t') updateAlt (FnCase n ns t) = do t' <- updateSC t return (FnCase n ns t') updateAlt (ConstCase c t) = do t' <- updateSC t return (ConstCase c t') updateAlt (SucCase n t) = do t' <- updateSC t return (SucCase n t') updateAlt (DefaultCase t) = do t' <- updateSC t return (DefaultCase t') -- We get a lot of repetition in sub terms and can save a fair chunk -- of memory if we make sure they're shared. addTT looks for a term -- and returns it if it exists already, while also keeping stats of -- how many times a subterm is repeated. update t = do tm <- addTT t case tm of Nothing -> update' t Just t' -> return t' update' (P t n ty) = do n' <- getSymbol n return $ P t n' ty update' (App s f a) = liftM2 (App s) (update' f) (update' a) update' (Bind n b sc) = do b' <- updateB b sc' <- update sc return $ Bind n b' sc' where updateB (Let t v) = liftM2 Let (update' t) (update' v) updateB b = do ty' <- update' (binderTy b) return (b { binderTy = ty' }) update' (Proj t i) = do t' <- update' t return $ Proj t' i update' t = return t processDocs :: Archive -> Idris () processDocs ar = do ds <- getEntry [] "ibc_docstrings" ar mapM_ (\(n, a) -> addDocStr n (fst a) (snd a)) ds processModuleDocs :: Archive -> Idris () processModuleDocs ar = do ds <- getEntry [] "ibc_moduledocs" ar mapM_ (\ (n, d) -> updateIState (\i -> i { idris_moduledocs = addDef n d (idris_moduledocs i) })) ds processAccess :: Bool -- ^ Reexporting? -> IBCPhase -> Archive -> Idris () processAccess reexp phase ar = do ds <- getEntry [] "ibc_access" ar mapM_ (\ (n, a_in) -> do let a = if reexp then a_in else Hidden logIBC 3 $ "Setting " ++ show (a, n) ++ " to " ++ show a updateIState (\i -> i { tt_ctxt = setAccess n a (tt_ctxt i) }) if (not reexp) then do logIBC 1 $ "Not exporting " ++ show n setAccessibility n Hidden else logIBC 1 $ "Exporting " ++ show n -- Everything should be available at the REPL from -- things imported publicly when (phase == IBC_REPL True) $ setAccessibility n Public) ds processFlags :: Archive -> Idris () processFlags ar = do ds <- getEntry [] "ibc_flags" ar mapM_ (\ (n, a) -> setFlags n a) ds processFnInfo :: Archive -> Idris () processFnInfo ar = do ds <- getEntry [] "ibc_fninfo" ar mapM_ (\ (n, a) -> setFnInfo n a) ds processTotal :: Archive -> Idris () processTotal ar = do ds <- getEntry [] "ibc_total" ar mapM_ (\ (n, a) -> updateIState (\i -> i { tt_ctxt = setTotal n a (tt_ctxt i) })) ds processInjective :: Archive -> Idris () processInjective ar = do ds <- getEntry [] "ibc_injective" ar mapM_ (\ (n, a) -> updateIState (\i -> i { tt_ctxt = setInjective n a (tt_ctxt i) })) ds processTotalityCheckError :: Archive -> Idris () processTotalityCheckError ar = do es <- getEntry [] "ibc_totcheckfail" ar updateIState (\i -> i { idris_totcheckfail = idris_totcheckfail i ++ es }) processCallgraph :: Archive -> Idris () processCallgraph ar = do ds <- getEntry [] "ibc_cg" ar mapM_ (\ (n, a) -> addToCG n a) ds processCoercions :: Archive -> Idris () processCoercions ar = do ns <- getEntry [] "ibc_coercions" ar mapM_ (\ n -> addCoercion n) ns processTransforms :: Archive -> Idris () processTransforms ar = do ts <- getEntry [] "ibc_transforms" ar mapM_ (\ (n, t) -> addTrans n t) ts processErrRev :: Archive -> Idris () processErrRev ar = do ts <- getEntry [] "ibc_errRev" ar mapM_ addErrRev ts processLineApps :: Archive -> Idris () processLineApps ar = do ls <- getEntry [] "ibc_lineapps" ar mapM_ (\ (f, i, t) -> addInternalApp f i t) ls processNameHints :: Archive -> Idris () processNameHints ar = do ns <- getEntry [] "ibc_namehints" ar mapM_ (\ (n, ty) -> addNameHint n ty) ns processMetaInformation :: Archive -> Idris () processMetaInformation ar = do ds <- getEntry [] "ibc_metainformation" ar mapM_ (\ (n, m) -> updateIState (\i -> i { tt_ctxt = setMetaInformation n m (tt_ctxt i) })) ds processErrorHandlers :: Archive -> Idris () processErrorHandlers ar = do ns <- getEntry [] "ibc_errorhandlers" ar updateIState (\i -> i { idris_errorhandlers = idris_errorhandlers i ++ ns }) processFunctionErrorHandlers :: Archive -> Idris () processFunctionErrorHandlers ar = do ns <- getEntry [] "ibc_function_errorhandlers" ar mapM_ (\ (fn,arg,handler) -> addFunctionErrorHandlers fn arg [handler]) ns processMetaVars :: Archive -> Idris () processMetaVars ar = do ns <- getEntry [] "ibc_metavars" ar updateIState (\i -> i { idris_metavars = L.reverse ns ++ idris_metavars i }) ----- For Cheapskate and docstrings instance Binary a => Binary (D.Docstring a) where put (D.DocString opts lines) = do put opts ; put lines get = do opts <- get lines <- get return (D.DocString opts lines) instance Binary CT.Options where put (CT.Options x1 x2 x3 x4) = do put x1 ; put x2 ; put x3 ; put x4 get = do x1 <- get x2 <- get x3 <- get x4 <- get return (CT.Options x1 x2 x3 x4) instance Binary D.DocTerm where put D.Unchecked = putWord8 0 put (D.Checked t) = putWord8 1 >> put t put (D.Example t) = putWord8 2 >> put t put (D.Failing e) = putWord8 3 >> put e get = do i <- getWord8 case i of 0 -> return D.Unchecked 1 -> fmap D.Checked get 2 -> fmap D.Example get 3 -> fmap D.Failing get _ -> error "Corrupted binary data for DocTerm" instance Binary a => Binary (D.Block a) where put (D.Para lines) = do putWord8 0 ; put lines put (D.Header i lines) = do putWord8 1 ; put i ; put lines put (D.Blockquote bs) = do putWord8 2 ; put bs put (D.List b t xs) = do putWord8 3 ; put b ; put t ; put xs put (D.CodeBlock attr txt src) = do putWord8 4 ; put attr ; put txt ; put src put (D.HtmlBlock txt) = do putWord8 5 ; put txt put D.HRule = putWord8 6 get = do i <- getWord8 case i of 0 -> fmap D.Para get 1 -> liftM2 D.Header get get 2 -> fmap D.Blockquote get 3 -> liftM3 D.List get get get 4 -> liftM3 D.CodeBlock get get get 5 -> liftM D.HtmlBlock get 6 -> return D.HRule _ -> error "Corrupted binary data for Block" instance Binary a => Binary (D.Inline a) where put (D.Str txt) = do putWord8 0 ; put txt put D.Space = putWord8 1 put D.SoftBreak = putWord8 2 put D.LineBreak = putWord8 3 put (D.Emph xs) = putWord8 4 >> put xs put (D.Strong xs) = putWord8 5 >> put xs put (D.Code xs tm) = putWord8 6 >> put xs >> put tm put (D.Link a b c) = putWord8 7 >> put a >> put b >> put c put (D.Image a b c) = putWord8 8 >> put a >> put b >> put c put (D.Entity a) = putWord8 9 >> put a put (D.RawHtml x) = putWord8 10 >> put x get = do i <- getWord8 case i of 0 -> liftM D.Str get 1 -> return D.Space 2 -> return D.SoftBreak 3 -> return D.LineBreak 4 -> liftM D.Emph get 5 -> liftM D.Strong get 6 -> liftM2 D.Code get get 7 -> liftM3 D.Link get get get 8 -> liftM3 D.Image get get get 9 -> liftM D.Entity get 10 -> liftM D.RawHtml get _ -> error "Corrupted binary data for Inline" instance Binary CT.ListType where put (CT.Bullet c) = putWord8 0 >> put c put (CT.Numbered nw i) = putWord8 1 >> put nw >> put i get = do i <- getWord8 case i of 0 -> liftM CT.Bullet get 1 -> liftM2 CT.Numbered get get _ -> error "Corrupted binary data for ListType" instance Binary CT.CodeAttr where put (CT.CodeAttr a b) = put a >> put b get = liftM2 CT.CodeAttr get get instance Binary CT.NumWrapper where put (CT.PeriodFollowing) = putWord8 0 put (CT.ParenFollowing) = putWord8 1 get = do i <- getWord8 case i of 0 -> return CT.PeriodFollowing 1 -> return CT.ParenFollowing _ -> error "Corrupted binary data for NumWrapper" ----- Generated by 'derive' instance Binary SizeChange where put x = case x of Smaller -> putWord8 0 Same -> putWord8 1 Bigger -> putWord8 2 Unknown -> putWord8 3 get = do i <- getWord8 case i of 0 -> return Smaller 1 -> return Same 2 -> return Bigger 3 -> return Unknown _ -> error "Corrupted binary data for SizeChange" instance Binary CGInfo where put (CGInfo x1 x2 x3) = do put x1 -- put x3 -- Already used SCG info for totality check put x3 get = do x1 <- get x3 <- get return (CGInfo x1 [] x3) instance Binary CaseType where put x = case x of Updatable -> putWord8 0 Shared -> putWord8 1 get = do i <- getWord8 case i of 0 -> return Updatable 1 -> return Shared _ -> error "Corrupted binary data for CaseType" instance Binary SC where put x = case x of Case x1 x2 x3 -> do putWord8 0 put x1 put x2 put x3 ProjCase x1 x2 -> do putWord8 1 put x1 put x2 STerm x1 -> do putWord8 2 put x1 UnmatchedCase x1 -> do putWord8 3 put x1 ImpossibleCase -> do putWord8 4 get = do i <- getWord8 case i of 0 -> do x1 <- get x2 <- get x3 <- get return (Case x1 x2 x3) 1 -> do x1 <- get x2 <- get return (ProjCase x1 x2) 2 -> do x1 <- get return (STerm x1) 3 -> do x1 <- get return (UnmatchedCase x1) 4 -> return ImpossibleCase _ -> error "Corrupted binary data for SC" instance Binary CaseAlt where put x = {-# SCC "putCaseAlt" #-} case x of ConCase x1 x2 x3 x4 -> do putWord8 0 put x1 put x2 put x3 put x4 ConstCase x1 x2 -> do putWord8 1 put x1 put x2 DefaultCase x1 -> do putWord8 2 put x1 FnCase x1 x2 x3 -> do putWord8 3 put x1 put x2 put x3 SucCase x1 x2 -> do putWord8 4 put x1 put x2 get = do i <- getWord8 case i of 0 -> do x1 <- get x2 <- get x3 <- get x4 <- get return (ConCase x1 x2 x3 x4) 1 -> do x1 <- get x2 <- get return (ConstCase x1 x2) 2 -> do x1 <- get return (DefaultCase x1) 3 -> do x1 <- get x2 <- get x3 <- get return (FnCase x1 x2 x3) 4 -> do x1 <- get x2 <- get return (SucCase x1 x2) _ -> error "Corrupted binary data for CaseAlt" instance Binary CaseDefs where put (CaseDefs x1 x2 x3 x4) = do -- don't need totality checked or inlined versions put x2 put x4 get = do x2 <- get x4 <- get return (CaseDefs x2 x2 x2 x4) instance Binary CaseInfo where put x@(CaseInfo x1 x2 x3) = do put x1 put x2 put x3 get = do x1 <- get x2 <- get x3 <- get return (CaseInfo x1 x2 x3) instance Binary Def where put x = {-# SCC "putDef" #-} case x of Function x1 x2 -> do putWord8 0 put x1 put x2 TyDecl x1 x2 -> do putWord8 1 put x1 put x2 -- all primitives just get added at the start, don't write Operator x1 x2 x3 -> do return () -- no need to add/load original patterns, because they're not -- used again after totality checking CaseOp x1 x2 x3 _ _ x4 -> do putWord8 3 put x1 put x2 put x3 put x4 get = do i <- getWord8 case i of 0 -> do x1 <- get x2 <- get return (Function x1 x2) 1 -> do x1 <- get x2 <- get return (TyDecl x1 x2) -- Operator isn't written, don't read 3 -> do x1 <- get x2 <- get x3 <- get -- x4 <- get -- x3 <- get always [] x5 <- get return (CaseOp x1 x2 x3 [] [] x5) _ -> error "Corrupted binary data for Def" instance Binary Accessibility where put x = case x of Public -> putWord8 0 Frozen -> putWord8 1 Private -> putWord8 2 Hidden -> putWord8 3 get = do i <- getWord8 case i of 0 -> return Public 1 -> return Frozen 2 -> return Private 3 -> return Hidden _ -> error "Corrupted binary data for Accessibility" safeToEnum :: (Enum a, Bounded a, Integral int) => String -> int -> a safeToEnum label x' = result where x = fromIntegral x' result | x < fromEnum (minBound `asTypeOf` result) || x > fromEnum (maxBound `asTypeOf` result) = error $ label ++ ": corrupted binary representation in IBC" | otherwise = toEnum x instance Binary PReason where put x = case x of Other x1 -> do putWord8 0 put x1 Itself -> putWord8 1 NotCovering -> putWord8 2 NotPositive -> putWord8 3 Mutual x1 -> do putWord8 4 put x1 NotProductive -> putWord8 5 BelieveMe -> putWord8 6 UseUndef x1 -> do putWord8 7 put x1 ExternalIO -> putWord8 8 get = do i <- getWord8 case i of 0 -> do x1 <- get return (Other x1) 1 -> return Itself 2 -> return NotCovering 3 -> return NotPositive 4 -> do x1 <- get return (Mutual x1) 5 -> return NotProductive 6 -> return BelieveMe 7 -> do x1 <- get return (UseUndef x1) 8 -> return ExternalIO _ -> error "Corrupted binary data for PReason" instance Binary Totality where put x = case x of Total x1 -> do putWord8 0 put x1 Partial x1 -> do putWord8 1 put x1 Unchecked -> do putWord8 2 Productive -> do putWord8 3 Generated -> do putWord8 4 get = do i <- getWord8 case i of 0 -> do x1 <- get return (Total x1) 1 -> do x1 <- get return (Partial x1) 2 -> return Unchecked 3 -> return Productive 4 -> return Generated _ -> error "Corrupted binary data for Totality" instance Binary MetaInformation where put x = case x of EmptyMI -> do putWord8 0 DataMI x1 -> do putWord8 1 put x1 get = do i <- getWord8 case i of 0 -> return EmptyMI 1 -> do x1 <- get return (DataMI x1) _ -> error "Corrupted binary data for MetaInformation" instance Binary DataOpt where put x = case x of Codata -> putWord8 0 DefaultEliminator -> putWord8 1 DataErrRev -> putWord8 2 DefaultCaseFun -> putWord8 3 get = do i <- getWord8 case i of 0 -> return Codata 1 -> return DefaultEliminator 2 -> return DataErrRev 3 -> return DefaultCaseFun _ -> error "Corrupted binary data for DataOpt" instance Binary FnOpt where put x = case x of Inlinable -> putWord8 0 TotalFn -> putWord8 1 Dictionary -> putWord8 2 AssertTotal -> putWord8 3 Specialise x -> do putWord8 4 put x Coinductive -> putWord8 5 PartialFn -> putWord8 6 Implicit -> putWord8 7 Reflection -> putWord8 8 ErrorHandler -> putWord8 9 ErrorReverse -> putWord8 10 CoveringFn -> putWord8 11 NoImplicit -> putWord8 12 Constructor -> putWord8 13 CExport x1 -> do putWord8 14 put x1 AutoHint -> putWord8 15 PEGenerated -> putWord8 16 get = do i <- getWord8 case i of 0 -> return Inlinable 1 -> return TotalFn 2 -> return Dictionary 3 -> return AssertTotal 4 -> do x <- get return (Specialise x) 5 -> return Coinductive 6 -> return PartialFn 7 -> return Implicit 8 -> return Reflection 9 -> return ErrorHandler 10 -> return ErrorReverse 11 -> return CoveringFn 12 -> return NoImplicit 13 -> return Constructor 14 -> do x1 <- get return $ CExport x1 15 -> return AutoHint 16 -> return PEGenerated _ -> error "Corrupted binary data for FnOpt" instance Binary Fixity where put x = case x of Infixl x1 -> do putWord8 0 put x1 Infixr x1 -> do putWord8 1 put x1 InfixN x1 -> do putWord8 2 put x1 PrefixN x1 -> do putWord8 3 put x1 get = do i <- getWord8 case i of 0 -> do x1 <- get return (Infixl x1) 1 -> do x1 <- get return (Infixr x1) 2 -> do x1 <- get return (InfixN x1) 3 -> do x1 <- get return (PrefixN x1) _ -> error "Corrupted binary data for Fixity" instance Binary FixDecl where put (Fix x1 x2) = do put x1 put x2 get = do x1 <- get x2 <- get return (Fix x1 x2) instance Binary ArgOpt where put x = case x of HideDisplay -> putWord8 0 InaccessibleArg -> putWord8 1 AlwaysShow -> putWord8 2 UnknownImp -> putWord8 3 get = do i <- getWord8 case i of 0 -> return HideDisplay 1 -> return InaccessibleArg 2 -> return AlwaysShow 3 -> return UnknownImp _ -> error "Corrupted binary data for Static" instance Binary Static where put x = case x of Static -> putWord8 0 Dynamic -> putWord8 1 get = do i <- getWord8 case i of 0 -> return Static 1 -> return Dynamic _ -> error "Corrupted binary data for Static" instance Binary Plicity where put x = case x of Imp x1 x2 x3 x4 _ -> do putWord8 0 put x1 put x2 put x3 put x4 Exp x1 x2 x3 -> do putWord8 1 put x1 put x2 put x3 Constraint x1 x2 -> do putWord8 2 put x1 put x2 TacImp x1 x2 x3 -> do putWord8 3 put x1 put x2 put x3 get = do i <- getWord8 case i of 0 -> do x1 <- get x2 <- get x3 <- get x4 <- get return (Imp x1 x2 x3 x4 False) 1 -> do x1 <- get x2 <- get x3 <- get return (Exp x1 x2 x3) 2 -> do x1 <- get x2 <- get return (Constraint x1 x2) 3 -> do x1 <- get x2 <- get x3 <- get return (TacImp x1 x2 x3) _ -> error "Corrupted binary data for Plicity" instance (Binary t) => Binary (PDecl' t) where put x = case x of PFix x1 x2 x3 -> do putWord8 0 put x1 put x2 put x3 PTy x1 x2 x3 x4 x5 x6 x7 x8 -> do putWord8 1 put x1 put x2 put x3 put x4 put x5 put x6 put x7 put x8 PClauses x1 x2 x3 x4 -> do putWord8 2 put x1 put x2 put x3 put x4 PData x1 x2 x3 x4 x5 x6 -> do putWord8 3 put x1 put x2 put x3 put x4 put x5 put x6 PParams x1 x2 x3 -> do putWord8 4 put x1 put x2 put x3 PNamespace x1 x2 x3 -> do putWord8 5 put x1 put x2 put x3 PRecord x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 -> do putWord8 6 put x1 put x2 put x3 put x4 put x5 put x6 put x7 put x8 put x9 put x10 put x11 put x12 PClass x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 -> do putWord8 7 put x1 put x2 put x3 put x4 put x5 put x6 put x7 put x8 put x9 put x10 put x11 put x12 PInstance x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13 x14 x15 -> do putWord8 8 put x1 put x2 put x3 put x4 put x5 put x6 put x7 put x8 put x9 put x10 put x11 put x12 put x13 put x14 put x15 PDSL x1 x2 -> do putWord8 9 put x1 put x2 PCAF x1 x2 x3 -> do putWord8 10 put x1 put x2 put x3 PMutual x1 x2 -> do putWord8 11 put x1 put x2 PPostulate x1 x2 x3 x4 x5 x6 x7 x8 -> do putWord8 12 put x1 put x2 put x3 put x4 put x5 put x6 put x7 put x8 PSyntax x1 x2 -> do putWord8 13 put x1 put x2 PDirective x1 -> error "Cannot serialize PDirective" PProvider x1 x2 x3 x4 x5 x6 -> do putWord8 15 put x1 put x2 put x3 put x4 put x5 put x6 PTransform x1 x2 x3 x4 -> do putWord8 16 put x1 put x2 put x3 put x4 PRunElabDecl x1 x2 x3 -> do putWord8 17 put x1 put x2 put x3 POpenInterfaces x1 x2 x3 -> do putWord8 18 put x1 put x2 put x3 get = do i <- getWord8 case i of 0 -> do x1 <- get x2 <- get x3 <- get return (PFix x1 x2 x3) 1 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get x7 <- get x8 <- get return (PTy x1 x2 x3 x4 x5 x6 x7 x8) 2 -> do x1 <- get x2 <- get x3 <- get x4 <- get return (PClauses x1 x2 x3 x4) 3 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get return (PData x1 x2 x3 x4 x5 x6) 4 -> do x1 <- get x2 <- get x3 <- get return (PParams x1 x2 x3) 5 -> do x1 <- get x2 <- get x3 <- get return (PNamespace x1 x2 x3) 6 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get x7 <- get x8 <- get x9 <- get x10 <- get x11 <- get x12 <- get return (PRecord x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12) 7 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get x7 <- get x8 <- get x9 <- get x10 <- get x11 <- get x12 <- get return (PClass x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12) 8 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get x7 <- get x8 <- get x9 <- get x10 <- get x11 <- get x12 <- get x13 <- get x14 <- get x15 <- get return (PInstance x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13 x14 x15) 9 -> do x1 <- get x2 <- get return (PDSL x1 x2) 10 -> do x1 <- get x2 <- get x3 <- get return (PCAF x1 x2 x3) 11 -> do x1 <- get x2 <- get return (PMutual x1 x2) 12 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get x7 <- get x8 <- get return (PPostulate x1 x2 x3 x4 x5 x6 x7 x8) 13 -> do x1 <- get x2 <- get return (PSyntax x1 x2) 14 -> do error "Cannot deserialize PDirective" 15 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get return (PProvider x1 x2 x3 x4 x5 x6) 16 -> do x1 <- get x2 <- get x3 <- get x4 <- get return (PTransform x1 x2 x3 x4) 17 -> do x1 <- get x2 <- get x3 <- get return (PRunElabDecl x1 x2 x3) 18 -> do x1 <- get x2 <- get x3 <- get return (POpenInterfaces x1 x2 x3) _ -> error "Corrupted binary data for PDecl'" instance Binary t => Binary (ProvideWhat' t) where put (ProvTerm x1 x2) = do putWord8 0 put x1 put x2 put (ProvPostulate x1) = do putWord8 1 put x1 get = do y <- getWord8 case y of 0 -> do x1 <- get x2 <- get return (ProvTerm x1 x2) 1 -> do x1 <- get return (ProvPostulate x1) _ -> error "Corrupted binary data for ProvideWhat" instance Binary Using where put (UImplicit x1 x2) = do putWord8 0; put x1; put x2 put (UConstraint x1 x2) = do putWord8 1; put x1; put x2 get = do i <- getWord8 case i of 0 -> do x1 <- get; x2 <- get; return (UImplicit x1 x2) 1 -> do x1 <- get; x2 <- get; return (UConstraint x1 x2) _ -> error "Corrupted binary data for Using" instance Binary SyntaxInfo where put (Syn x1 x2 x3 x4 _ _ x5 x6 x7 _ _ x8 _ _ _) = do put x1 put x2 put x3 put x4 put x5 put x6 put x7 put x8 get = do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get x7 <- get x8 <- get return (Syn x1 x2 x3 x4 [] id x5 x6 x7 Nothing 0 x8 0 True True) instance (Binary t) => Binary (PClause' t) where put x = case x of PClause x1 x2 x3 x4 x5 x6 -> do putWord8 0 put x1 put x2 put x3 put x4 put x5 put x6 PWith x1 x2 x3 x4 x5 x6 x7 -> do putWord8 1 put x1 put x2 put x3 put x4 put x5 put x6 put x7 PClauseR x1 x2 x3 x4 -> do putWord8 2 put x1 put x2 put x3 put x4 PWithR x1 x2 x3 x4 x5 -> do putWord8 3 put x1 put x2 put x3 put x4 put x5 get = do i <- getWord8 case i of 0 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get return (PClause x1 x2 x3 x4 x5 x6) 1 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get x7 <- get return (PWith x1 x2 x3 x4 x5 x6 x7) 2 -> do x1 <- get x2 <- get x3 <- get x4 <- get return (PClauseR x1 x2 x3 x4) 3 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get return (PWithR x1 x2 x3 x4 x5) _ -> error "Corrupted binary data for PClause'" instance (Binary t) => Binary (PData' t) where put x = case x of PDatadecl x1 x2 x3 x4 -> do putWord8 0 put x1 put x2 put x3 put x4 PLaterdecl x1 x2 x3 -> do putWord8 1 put x1 put x2 put x3 get = do i <- getWord8 case i of 0 -> do x1 <- get x2 <- get x3 <- get x4 <- get return (PDatadecl x1 x2 x3 x4) 1 -> do x1 <- get x2 <- get x3 <- get return (PLaterdecl x1 x2 x3) _ -> error "Corrupted binary data for PData'" instance Binary PunInfo where put x = case x of TypeOrTerm -> putWord8 0 IsType -> putWord8 1 IsTerm -> putWord8 2 get = do i <- getWord8 case i of 0 -> return TypeOrTerm 1 -> return IsType 2 -> return IsTerm _ -> error "Corrupted binary data for PunInfo" instance Binary PTerm where put x = case x of PQuote x1 -> do putWord8 0 put x1 PRef x1 x2 x3 -> do putWord8 1 put x1 put x2 put x3 PInferRef x1 x2 x3 -> do putWord8 2 put x1 put x2 put x3 PPatvar x1 x2 -> do putWord8 3 put x1 put x2 PLam x1 x2 x3 x4 x5 -> do putWord8 4 put x1 put x2 put x3 put x4 put x5 PPi x1 x2 x3 x4 x5 -> do putWord8 5 put x1 put x2 put x3 put x4 put x5 PLet x1 x2 x3 x4 x5 x6 -> do putWord8 6 put x1 put x2 put x3 put x4 put x5 put x6 PTyped x1 x2 -> do putWord8 7 put x1 put x2 PAppImpl x1 x2 -> error "PAppImpl in final term" PApp x1 x2 x3 -> do putWord8 8 put x1 put x2 put x3 PAppBind x1 x2 x3 -> do putWord8 9 put x1 put x2 put x3 PMatchApp x1 x2 -> do putWord8 10 put x1 put x2 PCase x1 x2 x3 -> do putWord8 11 put x1 put x2 put x3 PTrue x1 x2 -> do putWord8 12 put x1 put x2 PResolveTC x1 -> do putWord8 15 put x1 PRewrite x1 x2 x3 x4 x5 -> do putWord8 17 put x1 put x2 put x3 put x4 put x5 PPair x1 x2 x3 x4 x5 -> do putWord8 18 put x1 put x2 put x3 put x4 put x5 PDPair x1 x2 x3 x4 x5 x6 -> do putWord8 19 put x1 put x2 put x3 put x4 put x5 put x6 PAlternative x1 x2 x3 -> do putWord8 20 put x1 put x2 put x3 PHidden x1 -> do putWord8 21 put x1 PType x1 -> do putWord8 22 put x1 PGoal x1 x2 x3 x4 -> do putWord8 23 put x1 put x2 put x3 put x4 PConstant x1 x2 -> do putWord8 24 put x1 put x2 Placeholder -> putWord8 25 PDoBlock x1 -> do putWord8 26 put x1 PIdiom x1 x2 -> do putWord8 27 put x1 put x2 PReturn x1 -> do putWord8 28 put x1 PMetavar x1 x2 -> do putWord8 29 put x1 put x2 PProof x1 -> do putWord8 30 put x1 PTactics x1 -> do putWord8 31 put x1 PImpossible -> putWord8 33 PCoerced x1 -> do putWord8 34 put x1 PUnifyLog x1 -> do putWord8 35 put x1 PNoImplicits x1 -> do putWord8 36 put x1 PDisamb x1 x2 -> do putWord8 37 put x1 put x2 PUniverse x1 -> do putWord8 38 put x1 PRunElab x1 x2 x3 -> do putWord8 39 put x1 put x2 put x3 PAs x1 x2 x3 -> do putWord8 40 put x1 put x2 put x3 PElabError x1 -> do putWord8 41 put x1 PQuasiquote x1 x2 -> do putWord8 42 put x1 put x2 PUnquote x1 -> do putWord8 43 put x1 PQuoteName x1 x2 x3 -> do putWord8 44 put x1 put x2 put x3 PIfThenElse x1 x2 x3 x4 -> do putWord8 45 put x1 put x2 put x3 put x4 PConstSugar x1 x2 -> do putWord8 46 put x1 put x2 PWithApp x1 x2 x3 -> do putWord8 47 put x1 put x2 put x3 get = do i <- getWord8 case i of 0 -> do x1 <- get return (PQuote x1) 1 -> do x1 <- get x2 <- get x3 <- get return (PRef x1 x2 x3) 2 -> do x1 <- get x2 <- get x3 <- get return (PInferRef x1 x2 x3) 3 -> do x1 <- get x2 <- get return (PPatvar x1 x2) 4 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get return (PLam x1 x2 x3 x4 x5) 5 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get return (PPi x1 x2 x3 x4 x5) 6 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get return (PLet x1 x2 x3 x4 x5 x6) 7 -> do x1 <- get x2 <- get return (PTyped x1 x2) 8 -> do x1 <- get x2 <- get x3 <- get return (PApp x1 x2 x3) 9 -> do x1 <- get x2 <- get x3 <- get return (PAppBind x1 x2 x3) 10 -> do x1 <- get x2 <- get return (PMatchApp x1 x2) 11 -> do x1 <- get x2 <- get x3 <- get return (PCase x1 x2 x3) 12 -> do x1 <- get x2 <- get return (PTrue x1 x2) 15 -> do x1 <- get return (PResolveTC x1) 17 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get return (PRewrite x1 x2 x3 x4 x5) 18 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get return (PPair x1 x2 x3 x4 x5) 19 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get return (PDPair x1 x2 x3 x4 x5 x6) 20 -> do x1 <- get x2 <- get x3 <- get return (PAlternative x1 x2 x3) 21 -> do x1 <- get return (PHidden x1) 22 -> do x1 <- get return (PType x1) 23 -> do x1 <- get x2 <- get x3 <- get x4 <- get return (PGoal x1 x2 x3 x4) 24 -> do x1 <- get x2 <- get return (PConstant x1 x2) 25 -> return Placeholder 26 -> do x1 <- get return (PDoBlock x1) 27 -> do x1 <- get x2 <- get return (PIdiom x1 x2) 28 -> do x1 <- get return (PReturn x1) 29 -> do x1 <- get x2 <- get return (PMetavar x1 x2) 30 -> do x1 <- get return (PProof x1) 31 -> do x1 <- get return (PTactics x1) 33 -> return PImpossible 34 -> do x1 <- get return (PCoerced x1) 35 -> do x1 <- get return (PUnifyLog x1) 36 -> do x1 <- get return (PNoImplicits x1) 37 -> do x1 <- get x2 <- get return (PDisamb x1 x2) 38 -> do x1 <- get return (PUniverse x1) 39 -> do x1 <- get x2 <- get x3 <- get return (PRunElab x1 x2 x3) 40 -> do x1 <- get x2 <- get x3 <- get return (PAs x1 x2 x3) 41 -> do x1 <- get return (PElabError x1) 42 -> do x1 <- get x2 <- get return (PQuasiquote x1 x2) 43 -> do x1 <- get return (PUnquote x1) 44 -> do x1 <- get x2 <- get x3 <- get return (PQuoteName x1 x2 x3) 45 -> do x1 <- get x2 <- get x3 <- get x4 <- get return (PIfThenElse x1 x2 x3 x4) 46 -> do x1 <- get x2 <- get return (PConstSugar x1 x2) 47 -> do x1 <- get x2 <- get x3 <- get return (PWithApp x1 x2 x3) _ -> error "Corrupted binary data for PTerm" instance Binary PAltType where put x = case x of ExactlyOne x1 -> do putWord8 0 put x1 FirstSuccess -> putWord8 1 TryImplicit -> putWord8 2 get = do i <- getWord8 case i of 0 -> do x1 <- get return (ExactlyOne x1) 1 -> return FirstSuccess 2 -> return TryImplicit _ -> error "Corrupted binary data for PAltType" instance (Binary t) => Binary (PTactic' t) where put x = case x of Intro x1 -> do putWord8 0 put x1 Focus x1 -> do putWord8 1 put x1 Refine x1 x2 -> do putWord8 2 put x1 put x2 Rewrite x1 -> do putWord8 3 put x1 LetTac x1 x2 -> do putWord8 4 put x1 put x2 Exact x1 -> do putWord8 5 put x1 Compute -> putWord8 6 Trivial -> putWord8 7 Solve -> putWord8 8 Attack -> putWord8 9 ProofState -> putWord8 10 ProofTerm -> putWord8 11 Undo -> putWord8 12 Try x1 x2 -> do putWord8 13 put x1 put x2 TSeq x1 x2 -> do putWord8 14 put x1 put x2 Qed -> putWord8 15 ApplyTactic x1 -> do putWord8 16 put x1 Reflect x1 -> do putWord8 17 put x1 Fill x1 -> do putWord8 18 put x1 Induction x1 -> do putWord8 19 put x1 ByReflection x1 -> do putWord8 20 put x1 ProofSearch x1 x2 x3 x4 x5 x6 -> do putWord8 21 put x1 put x2 put x3 put x4 put x5 put x6 DoUnify -> putWord8 22 CaseTac x1 -> do putWord8 23 put x1 SourceFC -> putWord8 24 Intros -> putWord8 25 Equiv x1 -> do putWord8 26 put x1 Claim x1 x2 -> do putWord8 27 put x1 put x2 Unfocus -> putWord8 28 MatchRefine x1 -> do putWord8 29 put x1 LetTacTy x1 x2 x3 -> do putWord8 30 put x1 put x2 put x3 TCInstance -> putWord8 31 GoalType x1 x2 -> do putWord8 32 put x1 put x2 TCheck x1 -> do putWord8 33 put x1 TEval x1 -> do putWord8 34 put x1 TDocStr x1 -> do putWord8 35 put x1 TSearch x1 -> do putWord8 36 put x1 Skip -> putWord8 37 TFail x1 -> do putWord8 38 put x1 Abandon -> putWord8 39 get = do i <- getWord8 case i of 0 -> do x1 <- get return (Intro x1) 1 -> do x1 <- get return (Focus x1) 2 -> do x1 <- get x2 <- get return (Refine x1 x2) 3 -> do x1 <- get return (Rewrite x1) 4 -> do x1 <- get x2 <- get return (LetTac x1 x2) 5 -> do x1 <- get return (Exact x1) 6 -> return Compute 7 -> return Trivial 8 -> return Solve 9 -> return Attack 10 -> return ProofState 11 -> return ProofTerm 12 -> return Undo 13 -> do x1 <- get x2 <- get return (Try x1 x2) 14 -> do x1 <- get x2 <- get return (TSeq x1 x2) 15 -> return Qed 16 -> do x1 <- get return (ApplyTactic x1) 17 -> do x1 <- get return (Reflect x1) 18 -> do x1 <- get return (Fill x1) 19 -> do x1 <- get return (Induction x1) 20 -> do x1 <- get return (ByReflection x1) 21 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get return (ProofSearch x1 x2 x3 x4 x5 x6) 22 -> return DoUnify 23 -> do x1 <- get return (CaseTac x1) 24 -> return SourceFC 25 -> return Intros 26 -> do x1 <- get return (Equiv x1) 27 -> do x1 <- get x2 <- get return (Claim x1 x2) 28 -> return Unfocus 29 -> do x1 <- get return (MatchRefine x1) 30 -> do x1 <- get x2 <- get x3 <- get return (LetTacTy x1 x2 x3) 31 -> return TCInstance 32 -> do x1 <- get x2 <- get return (GoalType x1 x2) 33 -> do x1 <- get return (TCheck x1) 34 -> do x1 <- get return (TEval x1) 35 -> do x1 <- get return (TDocStr x1) 36 -> do x1 <- get return (TSearch x1) 37 -> return Skip 38 -> do x1 <- get return (TFail x1) 39 -> return Abandon _ -> error "Corrupted binary data for PTactic'" instance (Binary t) => Binary (PDo' t) where put x = case x of DoExp x1 x2 -> do putWord8 0 put x1 put x2 DoBind x1 x2 x3 x4 -> do putWord8 1 put x1 put x2 put x3 put x4 DoBindP x1 x2 x3 x4 -> do putWord8 2 put x1 put x2 put x3 put x4 DoLet x1 x2 x3 x4 x5 -> do putWord8 3 put x1 put x2 put x3 put x4 put x5 DoLetP x1 x2 x3 -> do putWord8 4 put x1 put x2 put x3 get = do i <- getWord8 case i of 0 -> do x1 <- get x2 <- get return (DoExp x1 x2) 1 -> do x1 <- get x2 <- get x3 <- get x4 <- get return (DoBind x1 x2 x3 x4) 2 -> do x1 <- get x2 <- get x3 <- get x4 <- get return (DoBindP x1 x2 x3 x4) 3 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get return (DoLet x1 x2 x3 x4 x5) 4 -> do x1 <- get x2 <- get x3 <- get return (DoLetP x1 x2 x3) _ -> error "Corrupted binary data for PDo'" instance (Binary t) => Binary (PArg' t) where put x = case x of PImp x1 x2 x3 x4 x5 -> do putWord8 0 put x1 put x2 put x3 put x4 put x5 PExp x1 x2 x3 x4 -> do putWord8 1 put x1 put x2 put x3 put x4 PConstraint x1 x2 x3 x4 -> do putWord8 2 put x1 put x2 put x3 put x4 PTacImplicit x1 x2 x3 x4 x5 -> do putWord8 3 put x1 put x2 put x3 put x4 put x5 get = do i <- getWord8 case i of 0 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get return (PImp x1 x2 x3 x4 x5) 1 -> do x1 <- get x2 <- get x3 <- get x4 <- get return (PExp x1 x2 x3 x4) 2 -> do x1 <- get x2 <- get x3 <- get x4 <- get return (PConstraint x1 x2 x3 x4) 3 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get return (PTacImplicit x1 x2 x3 x4 x5) _ -> error "Corrupted binary data for PArg'" instance Binary ClassInfo where put (CI x1 x2 x3 x4 x5 _ x6) = do put x1 put x2 put x3 put x4 put x5 put x6 get = do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get return (CI x1 x2 x3 x4 x5 [] x6) instance Binary RecordInfo where put (RI x1 x2 x3) = do put x1 put x2 put x3 get = do x1 <- get x2 <- get x3 <- get return (RI x1 x2 x3) instance Binary OptInfo where put (Optimise x1 x2) = do put x1 put x2 get = do x1 <- get x2 <- get return (Optimise x1 x2) instance Binary FnInfo where put (FnInfo x1) = put x1 get = do x1 <- get return (FnInfo x1) instance Binary TypeInfo where put (TI x1 x2 x3 x4 x5) = do put x1 put x2 put x3 put x4 put x5 get = do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get return (TI x1 x2 x3 x4 x5) instance Binary SynContext where put x = case x of PatternSyntax -> putWord8 0 TermSyntax -> putWord8 1 AnySyntax -> putWord8 2 get = do i <- getWord8 case i of 0 -> return PatternSyntax 1 -> return TermSyntax 2 -> return AnySyntax _ -> error "Corrupted binary data for SynContext" instance Binary Syntax where put (Rule x1 x2 x3) = do putWord8 0 put x1 put x2 put x3 put (DeclRule x1 x2) = do putWord8 1 put x1 put x2 get = do i <- getWord8 case i of 0 -> do x1 <- get x2 <- get x3 <- get return (Rule x1 x2 x3) 1 -> do x1 <- get x2 <- get return (DeclRule x1 x2) _ -> error "Corrupted binary data for Syntax" instance (Binary t) => Binary (DSL' t) where put (DSL x1 x2 x3 x4 x5 x6 x7 x8 x9 x10) = do put x1 put x2 put x3 put x4 put x5 put x6 put x7 put x8 put x9 put x10 get = do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get x7 <- get x8 <- get x9 <- get x10 <- get return (DSL x1 x2 x3 x4 x5 x6 x7 x8 x9 x10) instance Binary SSymbol where put x = case x of Keyword x1 -> do putWord8 0 put x1 Symbol x1 -> do putWord8 1 put x1 Expr x1 -> do putWord8 2 put x1 SimpleExpr x1 -> do putWord8 3 put x1 Binding x1 -> do putWord8 4 put x1 get = do i <- getWord8 case i of 0 -> do x1 <- get return (Keyword x1) 1 -> do x1 <- get return (Symbol x1) 2 -> do x1 <- get return (Expr x1) 3 -> do x1 <- get return (SimpleExpr x1) 4 -> do x1 <- get return (Binding x1) _ -> error "Corrupted binary data for SSymbol" instance Binary Codegen where put x = case x of Via ir str -> do putWord8 0 put ir put str Bytecode -> putWord8 1 get = do i <- getWord8 case i of 0 -> do x1 <- get x2 <- get return (Via x1 x2) 1 -> return Bytecode _ -> error "Corrupted binary data for Codegen" instance Binary IRFormat where put x = case x of IBCFormat -> putWord8 0 JSONFormat -> putWord8 1 get = do i <- getWord8 case i of 0 -> return IBCFormat 1 -> return JSONFormat _ -> error "Corrupted binary data for IRFormat"
ozgurakgun/Idris-dev
src/Idris/IBC.hs
bsd-3-clause
100,046
0
21
55,355
27,569
12,662
14,907
2,406
17
{-# LANGUAGE OverloadedStrings #-} module Cauterize.Dynamic.Common ( isNameOf , lu , fieldsToNameMap , fieldsToIndexMap , fieldNameSet , isSynonym , isRange , isArray , isVector , isEnumeration , isRecord , isCombination , isUnion ) where import Cauterize.Dynamic.Types import Control.Exception import Data.Maybe import qualified Data.Text.Lazy as T import qualified Cauterize.Specification as S import qualified Cauterize.CommonTypes as C import qualified Data.Map as M import qualified Data.Set as Set lu :: C.Identifier -> TyMap -> S.Type lu n m = fromMaybe (throw $ InvalidType n) (n `M.lookup` m) fieldsToNameMap :: [S.Field] -> M.Map C.Identifier S.Field fieldsToNameMap fs = M.fromList $ map go fs where go f = (S.fieldName f, f) fieldsToIndexMap :: [S.Field] -> M.Map Integer S.Field fieldsToIndexMap fs = M.fromList $ map go fs where go f = (S.fieldIndex f, f) fieldNameSet :: [S.Field] -> Set.Set C.Identifier fieldNameSet fs = Set.fromList $ map S.fieldName fs isNameOf :: T.Text -> PrimDetails -> Bool isNameOf "u8" (PDu8 _) = True isNameOf "u16" (PDu16 _) = True isNameOf "u32" (PDu32 _) = True isNameOf "u64" (PDu64 _) = True isNameOf "s8" (PDs8 _) = True isNameOf "s16" (PDs16 _) = True isNameOf "s32" (PDs32 _) = True isNameOf "s64" (PDs64 _) = True isNameOf "f32" (PDf32 _) = True isNameOf "f64" (PDf64 _) = True isNameOf "bool" (PDbool _) = True isNameOf _ _ = False isSynonym :: S.Type -> Bool isSynonym (S.Type { S.typeDesc = S.Synonym {} }) = True isSynonym _ = False isRange :: S.Type -> Bool isRange (S.Type { S.typeDesc = S.Range {} }) = True isRange _ = False isArray :: S.Type -> Bool isArray (S.Type { S.typeDesc = S.Array {} }) = True isArray _ = False isVector :: S.Type -> Bool isVector (S.Type { S.typeDesc = S.Vector {} }) = True isVector _ = False isEnumeration :: S.Type -> Bool isEnumeration (S.Type { S.typeDesc = S.Enumeration {} }) = True isEnumeration _ = False isRecord :: S.Type -> Bool isRecord (S.Type { S.typeDesc = S.Record {} }) = True isRecord _ = False isCombination :: S.Type -> Bool isCombination (S.Type { S.typeDesc = S.Combination {} }) = True isCombination _ = False isUnion :: S.Type -> Bool isUnion (S.Type { S.typeDesc = S.Union {} }) = True isUnion _ = False
cauterize-tools/cauterize
src/Cauterize/Dynamic/Common.hs
bsd-3-clause
2,303
0
11
458
922
497
425
71
1
module Type where import qualified Data.IntMap as IM import Data.Maybe import qualified Data.Set as Set import Data.List import Name import FreeEnvironment type Dictionary = FreeEnv String type Type = TypeA () data TypeInstance = TDouble | TBool deriving (Eq, Show) -- TODO replace i by Free ? -- TODO merge tvar poly with (TVar kind i) data TypeA i = TVal TypeInstance | TVar Free i | TPoly Free i | TAppl (TypeA i) (TypeA i) deriving (Eq, Show) normalise :: Type -> Type normalise = snd .normaliseWith IM.empty -- TODO not a save interface unMapped types get number assignd base on size map, which already can be use -- you could use list instead, or only use normalise -- TODO rename match function closer -- TODO it recalculates size every time, could be more efficent. but wont matter in practice normaliseWith :: IM.IntMap Type -> Type -> (IM.IntMap Type, Type) normaliseWith env t@TVal {} = (env,t) normaliseWith env (TPoly (Free f) _) = case IM.lookup f env of Just t@TPoly {} -> (env,t) Just _ -> error "key clash" Nothing -> let t = TPoly (Free $ IM.size env) () in (IM.insert f t env,t) normaliseWith env (TVar (Free f) _) = case IM.lookup f env of Just t@TVar {} -> (env,t) Just _ -> error "keyclash" Nothing -> let t = TVar (Free $ IM.size env) () in (IM.insert f t env,t) normaliseWith env (TAppl t1 t2) = let (env', t1') = normaliseWith env t1 (env'',t2') = normaliseWith env' t2 in (env'', TAppl t1' t2') mkDictonarie :: [Type] -> Dictionary mkDictonarie = mkDictonarieWithReserved IM.empty mkDictonarieWithReserved :: Dictionary -> [Type] -> Dictionary mkDictonarieWithReserved fixedNames ts = fst $ foldl go (fixedNames, letters ) $ concatMap typeVars ts where go :: ( Dictionary, [String] ) -> Free -> ( Dictionary, [String]) go (dic, freeNames) (Free i) = case IM.lookup i dic of Just _ -> (dic, freeNames) Nothing -> let usedNames = map snd $ IM.toList dic name : newFreeNames = dropWhile (\ n -> elem n usedNames) freeNames in (IM.insert i name dic, newFreeNames) pShow :: Type -> String pShow t = pShowWithDic t (mkDictonarie [t]) pShowWithDic :: Type -> Dictionary -> String pShowWithDic = go where go (TPoly f j) dic = '*':go (TVar f j) dic go (TVar (Free i) _) dic = fromMaybe (error "incomplete dictonary; missing name for: " ++ show i) (IM.lookup i dic) go (TAppl t1 t2) dic = let string1 = case t1 of TAppl {} -> "(" ++ go t1 dic ++ ")" _ -> go t1 dic string2 = go t2 dic in string1 ++ " -> " ++ string2 go (TVal v) _ = showTypeInstance v typeVars :: Eq i => TypeA i -> [Free] typeVars = nub . getTvars where getTvars (TVar i _) = [i] getTvars (TAppl i j) = getTvars i ++ getTvars j getTvars (TPoly i _) = [i] getTvars TVal {} = [] typeSize :: TypeA i -> Int typeSize (TAppl t1 t2) = typeSize t1 + typeSize t2 typeSize _ = 1 -- TODO rename it does not map var anymore but anotation mapVar :: (i -> j) -> TypeA i -> TypeA j mapVar f (TAppl t1 t2) = TAppl (mapVar f t1) (mapVar f t2) mapVar f (TPoly i j) = TPoly i $ f j mapVar f (TVar i j) = TVar i $ f j mapVar _ (TVal a) = TVal a mapFree :: (Free -> Free) -> TypeA i -> TypeA i --T mapFree f (TAppl t1 t2) = TAppl (mapFree f t1) (mapFree f t2) mapFree f (TPoly i j) = TPoly (f i) j mapFree f (TVar i j) = TVar (f i) j mapFree _ (TVal a) = TVal a showTypeInstance :: TypeInstance -> String showTypeInstance TDouble = "Double" showTypeInstance TBool = "Bool" dropTypeArg :: Show i => TypeA i -> TypeA i dropTypeArg (TAppl _ t ) = t dropTypeArg t = error $ "cant drop targ with" ++ show t typeFreeVars ::Type -> Set.Set Free typeFreeVars (TVar v _ ) = Set.singleton v typeFreeVars (TAppl t1 t2) = typeFreeVars t1 `Set.union` typeFreeVars t2 typeFreeVars _ = Set.empty accumulateTypes :: TypeA a -> [TypeA a] accumulateTypes (TAppl t1 t2) = t1 : accumulateTypes t2 accumulateTypes t = [t]
kwibus/myLang
src/Type.hs
bsd-3-clause
4,102
1
17
1,051
1,638
833
805
90
5
{-# LANGUAGE PatternGuards, TypeSynonymInstances, FlexibleInstances #-} -- | Duck Operator Tree Parsing -- -- Since the precedence of operators is adjustable, we parse expressions -- involving operators in two passes. This file contains the second pass. -- Partially borrowed from <http://hackage.haskell.org/trac/haskell-prime/attachment/wiki/FixityResolution/resolve.hs> module ParseOps ( Ops(..) , Precedence , Fixity(..) , PrecFix , PrecEnv , sortOps , prettyop ) where import qualified Data.Foldable as Fold import qualified Data.Map as Map import Data.Maybe import Pretty import SrcLoc import Var import Token import ParseMonad type Precedence = Int type PrecFix = (Precedence, Fixity) type PrecEnv = Map.Map Var PrecFix data Ops a = OpAtom !a | OpUn !Var !(Ops a) | OpBin !Var !(Ops a) !(Ops a) deriving (Show) minPrec, defaultPrec :: PrecFix minPrec = (minBound, NonFix) defaultPrec = (100, LeftFix) -- This is just used for pretty printing, so we hard-code the defaults opPrecs :: PrecEnv opPrecs = Map.fromList [ (V v,p) | (p,vl) <- [((90,RightFix), ["."]) ,((80,RightFix), ["^", "^^", "**"]) ,((70,LeftFix), ["*","/"]) ,((60,LeftFix), ["+","-"]) ,((50,RightFix), [":","++"]) ,((40,NonFix), ["==","!=","<","<=",">=",">"]) ,((30,RightFix), ["&&"]) ,((20,RightFix), ["||"]) ,((10,LeftFix), [">>",">>="]) ,((10,RightFix), ["<<=","$"]) ,((2,LeftFix), ["::"]) ,((1,RightFix), ["->"]) ,((0,RightFix), ["\\","="]) ], v <- vl ] opPrec :: Var -> Maybe PrecFix opPrec op = Map.lookup op opPrecs orderPrec :: PrecFix -> PrecFix -> Fixity orderPrec (p1,d1) (p2,d2) = case compare p1 p2 of LT -> RightFix GT -> LeftFix EQ -> if d1 == d2 then d1 else NonFix sortOps :: Show a => PrecEnv -> SrcLoc -> Ops a -> Ops a sortOps precs loc input = out where (out, []) = parse minPrec Nothing toks parse p Nothing (Left l : rest) = parse p (Just (OpAtom l)) rest parse p (Just l) mid@(Right (o,p') : rest) = case orderPrec p p' of NonFix -> err o LeftFix -> (l, mid) RightFix -> parse p (Just $ OpBin o l r) rest' where (r, rest') = parse p' Nothing rest parse p Nothing (Right (o,p') : rest) = parse p (Just (OpUn o r)) rest' where (r, rest') = parse (max p' p) Nothing rest parse _ (Just l) [] = (l, []) parse _ _ _ = error "parseOps" toks = map (fmap (\o -> (o, prec o))) $ otoks input [] otoks (OpAtom a) t = Left a : t otoks (OpUn o r) t = Right o : otoks r t otoks (OpBin o l r) t = otoks l (Right o : otoks r t) prec o = fromMaybe defaultPrec $ Map.lookup o precs err o = parseError loc $ "ambiguous operator expression involving" <+> quoted o prettyop :: (Pretty f, HasVar f, Pretty a) => f -> [a] -> Doc' prettyop f a | Just v <- unVar f , Just (i,d) <- opPrec v = case (v,a,d) of (V "-",[x],_) -> i #> pf <+> x (_,[x,y],LeftFix) -> i #> pguard i x <+> pf <+> y (_,[x,y],NonFix) -> i #> x <+> pf <+> y (_,[x,y],RightFix) -> i #> x <+> pf <+> pguard i y _ -> prettyap f a where pf = pguard (-1) f prettyop f a | Just v <- unVar f , Just n <- tupleLen v , n == length a = 3 #> punctuate ',' a prettyop f a | Just (V "if") <- unVar f , [c,x,y] <- a = 1 #> "if" <+> pretty c <+> "then" <+> pretty x <+> "else" <+> pretty y prettyop f a = prettyap f a instance Pretty a => Pretty (Ops a) where pretty' (OpAtom a) = pretty' a pretty' (OpUn o a) = prettyop o [a] pretty' (OpBin o l r) = prettyop o [l,r] instance Pretty PrecFix where pretty' (p,d) = d <+> p instance Functor Ops where fmap f (OpAtom a) = OpAtom (f a) fmap f (OpUn v o) = OpUn v (fmap f o) fmap f (OpBin v o1 o2) = OpBin v (fmap f o1) (fmap f o2) instance Fold.Foldable Ops where foldr f z (OpAtom a) = f a z foldr f z (OpUn _ r) = Fold.foldr f z r foldr f z (OpBin _ l r) = Fold.foldr f (Fold.foldr f z r) l instance HasVar a => HasVar (Ops a) where unVar (OpAtom a) = unVar a unVar _ = Nothing
girving/duck
duck/ParseOps.hs
bsd-3-clause
4,021
0
14
976
1,933
1,039
894
120
9
{-# LANGUAGE DeriveDataTypeable #-} module Language.Lambda.SimplyTyped.Syntax where import Data.Data data Type a = Base a | Arrow (Type a) (Type a) deriving(Show, Eq, Data, Typeable) data Expr s a c = Var s | App (Expr s a c) (Expr s a c) | Lam s (Type a) (Expr s a c) | Constant c deriving(Show, Eq, Data, Typeable)
jfischoff/LambdaAST
src/Language/Lambda/SimplyTyped/Syntax.hs
bsd-3-clause
401
0
8
143
150
84
66
10
0