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
{-| JWS -} module Network.ACME.JWS ( module Network.ACME.JWS , JWK , Base64Octets(..) ) where import Control.Lens (Identity(..), review, set, view) import Control.Lens.TH (makeLenses) import Control.Monad.Except import Crypto.JOSE import Crypto.JOSE.Types (Base64Octets(..)) import Data.Aeson import qualified Data.ByteString.Char8 as B import Data.ByteString.Lazy (toStrict) import Data.Text as T import Network.ACME.Error import Network.ACME.Object (AcmeJwsNonce, URL, urlToString) type AcmeJws = FlattenedJWS AcmeJwsHeader -- | Enhanced 'JWSHeader' with additional header parameters data AcmeJwsHeader a = AcmeJwsHeader { _acmeJwsHeaderNonce :: AcmeJwsNonce , _acmeJwsHeaderUrl :: URL , _acmeJwsHeader :: JWSHeader a } deriving (Show) makeLenses ''AcmeJwsHeader instance HasParams AcmeJwsHeader where parseParamsFor proxy hp hu = AcmeJwsHeader <$> headerRequiredProtected "nonce" hp hu <*> headerRequiredProtected "url" hp hu <*> parseParamsFor proxy hp hu params h = (True, "nonce" .= view acmeJwsHeaderNonce h) : (True, "url" .= view acmeJwsHeaderUrl h) : params (view acmeJwsHeader h) extensions = const ["nonce", "url"] instance HasJWSHeader AcmeJwsHeader where jwsHeader = acmeJwsHeader newAcmeJwsHeader :: URL -- ^ Request URL -> JWK -- ^ Private key -> JWK -- ^ Public key -> AcmeJwsNonce -- ^ Nonce -> Maybe URL -- ^ Kid -> Either AcmeErr (AcmeJwsHeader Protection) newAcmeJwsHeader vUrl vJwkPrivate vJwkPublic vNonce vKid -- Boulder sais -- 'detail: signature type 'PS512' in JWS header is not supported' = do vBestAlg <- bestAlg return AcmeJwsHeader { _acmeJwsHeader = setAuth $ newJWSHeader (Protected, vBestAlg) , _acmeJwsHeaderNonce = vNonce , _acmeJwsHeaderUrl = vUrl } where bestAlg = case bestJWSAlg vJwkPrivate of Right PS512 -> return RS256 Right x -> return x Left e -> throwError $ AcmeErrJws e setAuth = case vKid of Just k -> set kid (Just $ HeaderParam Protected (T.pack $ urlToString k)) Nothing -> set jwk (Just $ HeaderParam Protected vJwkPublic) -- | Removes private key jwkPublic :: AsPublicKey a => a -> Either AcmeErr a jwkPublic = maybe (Left AcmeErrJwkNoPubkey) return . view asPublicKey {-| Creates a signed JWS object in ACME format. This implies interaction with the ACME server for obtaining a valid nonce for this request. -} acmeNewJwsBody :: (ToJSON a) => Maybe a -> URL -> JWK -> JWK -> AcmeJwsNonce -> Maybe URL -> ExceptT AcmeErr IO AcmeJws acmeNewJwsBody vObj vUrl vJwkPrivate vJwkPublic vNonce vKid = do xh <- either throwError return vHeader withExceptT AcmeErrJws $ signJWS payload (Identity (xh, vJwkPrivate)) where vHeader = newAcmeJwsHeader vUrl vJwkPrivate vJwkPublic vNonce vKid payload = toStrict $ maybe "" encode vObj -- | JSON Web Key (JWK) Thumbprint -- <https://tools.ietf.org/html/rfc7638 RFC 7638> jwkThumbprint :: JWK -> String jwkThumbprint x = B.unpack $ review (base64url . digest) (view thumbprint x :: Digest SHA256) sha256 :: String -> String sha256 x = B.unpack $ review (base64url . digest) (hash (B.pack x) :: Digest SHA256)
hemio-ev/libghc-acme
src/Network/ACME/JWS.hs
lgpl-3.0
3,225
0
16
666
863
461
402
-1
-1
module Main where import MancalaBoard import MancalaAI import System.IO import Data.Char {- this is from last week's lab -} gameOver :: MancalaBoard -> Bool gameOver m = or (map ((all (==0)) . (playerSide m)) allPlayers) welcomeUser :: IO() welcomeUser = do putStr "\n***********************************************\n" putStr "Hello and welcome to Digicala(TM)\n" putStr "To move, please type the number corresponding\n" putStr "to the pit you would like to select for moving,\n" putStr "then press Enter. Please input 1 if you would\n" putStr "like to go first, input 2 if you prefer second.\n" putStr "***********************************************\n\n" hFlush stdout sayGoodbye :: IO() sayGoodbye = do putStr "Thanks for playing, please come back soon!\n" showMove :: MancalaBoard -> Int -> IO() showMove board move = do putStr ((show (getCurPlayer board)) ++ " moved " ++ (show move) ++ "\n") playGame :: MancalaBoard -> Player -> IO() playGame board aiPlayer = do if getCurPlayer board == aiPlayer then do let move = MancalaAI.minimax board aiPlayer 6 True let newBoard = MancalaBoard.move board move if gameOver newBoard then endGame newBoard else do showMove board move putStr (show newBoard) playGame newBoard aiPlayer else do move' <- getLine if not (all isDigit move') then do -- not given integer putStr "Please input an integer.\n" playGame board aiPlayer else do-- given integer let move = read move' :: Int if (move `elem` allowedMoves board) then do -- is valid move let newBoard = MancalaBoard.move board move if gameOver newBoard then endGame newBoard else do showMove board move putStr (show newBoard) playGame newBoard aiPlayer else do-- not a valid move putStr ("Please input an integer from the list " ++ show (allowedMoves board) ++ "\n") playGame board aiPlayer endGame :: MancalaBoard -> IO() endGame board = do putStr (show board) putStr (show (whoWins board) ++ " is(are) the winner(s)! Congrats!\n") main :: IO() main = do welcomeUser turn <- getLine let aiPlayer = MancalaBoard.allPlayers !! ((read turn :: Int) `mod` 2) putStr (show initial) playGame initial aiPlayer sayGoodbye
kbrose/math
Mancala/OnePlayerMancala.hs
unlicense
2,528
0
22
744
667
315
352
64
6
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE ViewPatterns #-} module Language.K3.Analysis.Core where import Control.Arrow import Control.DeepSeq import Control.Monad import Data.Binary import Data.Serialize import Data.Vector.Serialize import Data.Bits import Data.Bits.Extras import Data.Char import Data.List import Data.Maybe import Data.Tree import Data.Word ( Word8 ) import Numeric import Data.IntMap.Strict ( IntMap ) import qualified Data.IntMap.Strict as IntMap import Data.Vector.Binary () import Data.Vector.Unboxed ( Vector, (!?) ) import qualified Data.Vector.Unboxed as Vector import GHC.Generics ( Generic ) import Language.K3.Core.Annotation import Language.K3.Core.Common import Language.K3.Core.Declaration import Language.K3.Core.Expression import Language.K3.Core.Utils import qualified Language.K3.Core.Constructor.Declaration as DC import Data.Text ( Text ) import qualified Data.Text as T import Language.K3.Utils.Pretty import qualified Language.K3.Utils.PrettyText as PT -- | Lambda closures, as a map of lambda expression UIDs to closure variable identifiers. type ClosureEnv = IntMap [Identifier] -- | Metadata for indexing on variables at a given scope data IndexedScope = IndexedScope { scids :: ![Identifier], scsz :: !Int } deriving (Eq, Ord, Read, Show, Generic) -- | Binding point scopes, as a map of binding point expression UIDS to current scope -- including the new binding. type ScopeEnv = IntMap IndexedScope -- | Vector for binding usage bits type BVector = Vector Word8 -- | Scope usage bitmasks, as a map of expression UID to a pair of scope uid and bitvector. type ScopeUsageEnv = IntMap (UID, BVector) -- | Expression-variable metadata container. data VarPosEnv = VarPosEnv { lcenv :: !ClosureEnv, scenv :: !ScopeEnv, vuenv :: !ScopeUsageEnv } deriving (Eq, Ord, Read, Show, Generic) -- | Traversal indexes, indicating subtree variable (from abstract interpretation or K3) usage. type TrIndex = K3 BVector data instance Annotation BVector = BUID !UID deriving (Eq, Ord, Read, Show, Generic) -- | Traversal environment, from an abstract interpretation (AI) index to -- either another AI index, or a traversal index. type AVTraversalEnv = IntMap (TrIndex, Maybe Int) -- Abstract interpretation environment. data AIVEnv = AIVEnv { avtenv :: !AVTraversalEnv } deriving (Eq, Read, Show, Generic) {- Instances -} instance NFData IndexedScope instance NFData VarPosEnv instance NFData AIVEnv instance NFData (Annotation BVector) instance Binary IndexedScope instance Binary VarPosEnv instance Binary AIVEnv instance Binary (Annotation BVector) instance Serialize IndexedScope instance Serialize VarPosEnv instance Serialize AIVEnv instance Serialize (Annotation BVector) {- BVector helpers -} showbv :: BVector -> String showbv v = foldl showBinary "" $ Vector.toList v where showBinary acc i = acc ++ pad (showIntAtBase 2 intToDigit i "") pad s = replicate (szb - length s) '0' ++ s szb = finiteBitSize (0 :: Word8) szbv :: Int -> Int szbv varSz = scdiv + (if scmod == 0 then 0 else 1) where (scdiv,scmod) = varSz `divMod` (finiteBitSize (0 :: Word8)) emptybv :: BVector emptybv = Vector.empty zerobv :: Int -> BVector zerobv sz = Vector.replicate (szbv sz) 0 bzerobv :: Int -> BVector bzerobv sz = Vector.replicate sz 0 lastbv :: Int -> BVector lastbv sz = singbv (sz-1) sz -- | Returns a bit vector of the desired size with the given bit set. singbv :: Int -> Int -> BVector singbv pos sz = Vector.generate (szbv sz) (\i -> if i == bpos then bit (w8sz - (posinb+1)) else 0) where w8sz = finiteBitSize (0 :: Word8) (bpos, posinb) = pos `divMod` w8sz suffixbv :: Int -> Int -> BVector suffixbv rpos sz = andbv vset vsz where w8sz = finiteBitSize (0 :: Word8) bsz = szbv sz -- position of the first bit. startpos = sz - (rpos+1) (bstart, sposinb) = startpos `divMod` w8sz -- # bits in last byte. bend = bsz - 1 eposinb = sz - (bend * w8sz) lb i = shiftL (oneBits :: Word8) $ w8sz - i rb i = shiftR (oneBits :: Word8) $ i vset = Vector.generate bsz bytei bytei i | i == bstart = rb $ sposinb | i < bstart = zeroBits :: Word8 | otherwise = oneBits :: Word8 vsz = Vector.generate bsz szgen szgen i | i == bend = lb $ eposinb | otherwise = oneBits :: Word8 anybv :: BVector -> Bool anybv = Vector.any (\i -> popCount i > 0) orbv :: BVector -> BVector -> BVector orbv a b = Vector.map (uncurry (.|.)) $ Vector.zip a b andbv :: BVector -> BVector -> BVector andbv a b = Vector.map (uncurry (.&.)) $ Vector.zip a b orsbv :: [BVector] -> BVector orsbv l = case l of [] -> Vector.empty _ -> let maxv = maximumBy longer l in Vector.imap (\i e -> foldl (onIndex i) e l) maxv where onIndex i acc v = maybe acc (acc .|.) $ v !? i longer a b = Vector.length a `compare` Vector.length b andsbv :: [BVector] -> BVector andsbv l = case l of [] -> Vector.empty _ -> let maxv = maximumBy longer l in Vector.imap (\i e -> foldl (onIndex i) e l) maxv where onIndex i acc v = maybe acc (acc .&.) $ v !? i longer a b = Vector.length a `compare` Vector.length b truncateLast :: BVector -> BVector truncateLast v = Vector.take (Vector.length v - 1) v truncateSuffix :: Int -> BVector -> BVector truncateSuffix n v = Vector.take (Vector.length v - n) v {- TrIndex helpers -} rootbv :: TrIndex -> BVector rootbv = tag tilen :: TrIndex -> Int tilen ti = Vector.length $ rootbv ti emptyti :: TrIndex emptyti = tileaf emptybv tinode :: BVector -> [TrIndex] -> TrIndex tinode v ch = Node (v :@: []) ch tileaf :: BVector -> TrIndex tileaf v = Node (v :@: []) [] tising :: BVector -> TrIndex -> TrIndex tising v c = Node (v :@: []) [c] tisdup :: TrIndex -> TrIndex tisdup c@(Node (v :@: _) _) = Node (v :@: []) [c] orti :: [TrIndex] -> TrIndex orti tich = tinode (orsbv $ map rootbv tich) tich unaryti :: TrIndex -> TrIndex unaryti ti = tising (rootbv ti) ti {- VarPosEnv helpers -} vp0 :: VarPosEnv vp0 = VarPosEnv IntMap.empty IntMap.empty IntMap.empty vpunion :: VarPosEnv -> VarPosEnv -> VarPosEnv vpunion a b = VarPosEnv { lcenv = IntMap.union (lcenv a) (lcenv b) , scenv = IntMap.union (scenv a) (scenv b) , vuenv = IntMap.union (vuenv a) (vuenv b) } vpunions :: [VarPosEnv] -> VarPosEnv vpunions l = VarPosEnv { lcenv = IntMap.unions (map lcenv l) , scenv = IntMap.unions (map scenv l) , vuenv = IntMap.unions (map vuenv l) } vplkuplc :: VarPosEnv -> Int -> Either Text [Identifier] vplkuplc env x = maybe err Right $ IntMap.lookup x $ lcenv env where err = Left . T.pack $ "Unbound id in vplc environment: " ++ show x vpextlc :: VarPosEnv -> Int -> [Identifier] -> VarPosEnv vpextlc env x l = env { lcenv = IntMap.insert x l $ lcenv env } vpdellc :: VarPosEnv -> Int -> VarPosEnv vpdellc env x = env { lcenv = IntMap.delete x $ lcenv env } vpmemlc :: VarPosEnv -> Int -> Bool vpmemlc env x = IntMap.member x $ lcenv env vplkupsc :: VarPosEnv -> Int -> Either Text IndexedScope vplkupsc env x = maybe err Right $ IntMap.lookup x $ scenv env where err = Left . T.pack $ "Unbound id in vpsc environment: " ++ show x vpextsc :: VarPosEnv -> Int -> IndexedScope -> VarPosEnv vpextsc env x s = env { scenv = IntMap.insert x s $ scenv env } vpdelsc :: VarPosEnv -> Int -> VarPosEnv vpdelsc env x = env { scenv = IntMap.delete x $ scenv env } vpmemsc :: VarPosEnv -> Int -> Bool vpmemsc env x = IntMap.member x $ scenv env vplkupvu :: VarPosEnv -> Int -> Either Text (UID, BVector) vplkupvu env x = maybe err Right $ IntMap.lookup x $ vuenv env where err = Left . T.pack $ "Unbound id in vpvu environment: " ++ show x vpextvu :: VarPosEnv -> Int -> UID -> BVector -> VarPosEnv vpextvu env x u v = env { vuenv = IntMap.insert x (u,v) $ vuenv env } vpdelvu :: VarPosEnv -> Int -> VarPosEnv vpdelvu env x = env { vuenv = IntMap.delete x $ vuenv env } vpmemvu :: VarPosEnv -> Int -> Bool vpmemvu env x = IntMap.member x $ vuenv env {- AIEnv helpers -} aivenv0 :: AIVEnv aivenv0 = AIVEnv IntMap.empty aivlkup :: AIVEnv -> Int -> Either Text (TrIndex, Maybe Int) aivlkup env x = maybe err Right $ IntMap.lookup x $ avtenv env where err = Left . T.pack $ "Unbound pointer in aiv environment: " ++ show x aivext :: AIVEnv -> Int -> TrIndex -> Maybe Int -> AIVEnv aivext env x ti pOpt = env { avtenv = IntMap.insert x (ti, pOpt) $ avtenv env } aivdel :: AIVEnv -> Int -> AIVEnv aivdel env x = env { avtenv = IntMap.delete x $ avtenv env } aivmem :: AIVEnv -> Int -> Bool aivmem env x = IntMap.member x $ avtenv env {- Indexed traversals -} indexMapRebuildTree :: (Monad m, Pretty (K3 a)) => ([TrIndex] -> [K3 a] -> TrIndex -> K3 a -> m (TrIndex, K3 a)) -> BVector -> TrIndex -> K3 a -> m (TrIndex, K3 a) indexMapRebuildTree f mask ti t = if match then let (tich, ch) = (children ti, children t) in if length tich == length ch then do npairs <- mapM (uncurry rcr) (zip tich ch) let (ntich, nch) = unzip npairs f ntich nch ti t else fail $ msg (length tich) (length ch) ti t else return (ti, t) where match = anybv $ mask `andbv` (tag ti) rcr = indexMapRebuildTree f mask msg lx ly a b = boxToString $ [unwords ["Mismatched index and tree children", show lx, show ly]] %$ prettyLines a %$ prettyLines b {- Common program analyses -} -- | Retrieves all free variables in an expression. freeVariables :: K3 Expression -> [Identifier] freeVariables expr = either (const []) id $ foldMapTree extractVariable [] expr where extractVariable chAcc (tag -> EVariable n) = return $! concat chAcc ++ [n] extractVariable chAcc (tag -> EAssign i) = return $! concat chAcc ++ [i] extractVariable chAcc (tag -> ELambda n) = return $! filter (/= n) $ concat chAcc extractVariable chAcc (tag -> EBindAs b) = return $! (chAcc !! 0) ++ (filter (`notElem` bindingVariables b) $ chAcc !! 1) extractVariable chAcc (tag -> ELetIn i) = return $! (chAcc !! 0) ++ (filter (/= i) $ chAcc !! 1) extractVariable chAcc (tag -> ECaseOf i) = return $! let [e, s, n] = chAcc in e ++ filter (/= i) s ++ n extractVariable chAcc _ = return $! concat chAcc -- | Retrieves all variables introduced by a binder bindingVariables :: Binder -> [Identifier] bindingVariables (BIndirection i) = [i] bindingVariables (BTuple is) = is bindingVariables (BRecord ivs) = snd (unzip ivs) bindingVariables (BSplice _) = [] -- | Retrieves all variables modified in an expression. modifiedVariables :: K3 Expression -> [Identifier] modifiedVariables expr = either (const []) id $ foldMapTree extractVariable [] expr where extractVariable chAcc (tag -> EAssign n) = return $! concat chAcc ++ [n] extractVariable chAcc (tag -> ELambda n) = return $! filter (/= n) $ concat chAcc extractVariable chAcc (tag -> EBindAs b) = return $! (chAcc !! 0) ++ (filter (`notElem` bindingVariables b) $ chAcc !! 1) extractVariable chAcc (tag -> ELetIn i) = return $! (chAcc !! 0) ++ (filter (/= i) $ chAcc !! 1) extractVariable chAcc (tag -> ECaseOf i) = return $! let [e, s, n] = chAcc in e ++ filter (/= i) s ++ n extractVariable chAcc _ = return $! concat chAcc -- | Computes the closure variables captured at lambda expressions. -- This is a one-pass bottom-up implementation. lambdaClosures :: K3 Declaration -> Either String ClosureEnv lambdaClosures p = foldExpression lambdaClosuresExpr IntMap.empty p >>= return . fst lambdaClosuresDecl :: Identifier -> ClosureEnv -> K3 Declaration -> Either String (ClosureEnv, K3 Declaration) lambdaClosuresDecl n lc p = foldNamedDeclExpression n lambdaClosuresExpr lc p lambdaClosuresExpr :: ClosureEnv -> K3 Expression -> Either String (ClosureEnv, K3 Expression) lambdaClosuresExpr lc expr = do (nlc,_) <- biFoldMapTree bind extract [] (IntMap.empty, []) expr return $! (IntMap.union nlc lc, expr) where bind :: [Identifier] -> K3 Expression -> Either String ([Identifier], [[Identifier]]) bind l (tag -> ELambda i) = return (l, [i:l]) bind l (tag -> ELetIn i) = return (l, [l, i:l]) bind l (tag -> EBindAs b) = return (l, [l, bindingVariables b ++ l]) bind l (tag -> ECaseOf i) = return (l, [l, i:l, l]) bind l (children -> ch) = return (l, replicate (length ch) l) extract :: [Identifier] -> [(ClosureEnv, [Identifier])] -> K3 Expression -> Either String (ClosureEnv, [Identifier]) extract _ chAcc (tag -> EVariable i) = rt chAcc (++[i]) extract _ chAcc (tag -> EAssign i) = rt chAcc (++[i]) extract l (concatLc -> (lcAcc,chAcc)) e@(tag -> ELambda n) = extendLc lcAcc e $! filter (onlyLocals n l) $ concat chAcc extract _ (concatLc -> (lcAcc,chAcc)) (tag -> EBindAs b) = return . (lcAcc,) $! (chAcc !! 0) ++ (filter (`notElem` bindingVariables b) $ chAcc !! 1) extract _ (concatLc -> (lcAcc,chAcc)) (tag -> ELetIn i) = return . (lcAcc,) $! (chAcc !! 0) ++ (filter (/= i) $ chAcc !! 1) extract _ (concatLc -> (lcAcc,chAcc)) (tag -> ECaseOf i) = return . (lcAcc,) $! let [e, s, n] = chAcc in e ++ filter (/= i) s ++ n extract _ chAcc _ = rt chAcc id onlyLocals n l i = i /= n && i `elem` l concatLc :: [(ClosureEnv, [Identifier])] -> (ClosureEnv, [[Identifier]]) concatLc subAcc = let (x,y) = unzip subAcc in (IntMap.unions x, y) extendLc :: ClosureEnv -> K3 Expression -> [Identifier] -> Either String (ClosureEnv, [Identifier]) extendLc elc e ids = case e @~ isEUID of Just (EUID (UID i)) -> return $! (IntMap.insert i (nub ids) elc, ids) _ -> Left $ boxToString $ ["No UID found on lambda"] %$ prettyLines e rt subAcc f = return $! second (f . concat) $ concatLc subAcc -- | Compute lambda closures and binding point scopes in a single pass. variablePositions :: K3 Declaration -> Either String VarPosEnv variablePositions p = foldExpression variablePositionsExpr vp0 p >>= return . fst variablePositionsDecl :: Identifier -> VarPosEnv -> K3 Declaration -> Either String (VarPosEnv, K3 Declaration) variablePositionsDecl n vp p = foldNamedDeclExpression n variablePositionsExpr vp p variablePositionsExpr :: VarPosEnv -> K3 Expression -> Either String (VarPosEnv, K3 Expression) variablePositionsExpr vp expr = do (nvp,_) <- biFoldMapTree bind extract ([], -1) (vp0, []) expr return $! (vpunion nvp vp, expr) where uidOf :: K3 Expression -> Either String Int uidOf ((@~ isEUID) -> Just (EUID (UID i))) = return i uidOf e = Left $ boxToString $ ["No UID found for uidOf"] %$ prettyLines e bind :: ([Identifier], Int) -> K3 Expression -> Either String (([Identifier], Int), [([Identifier], Int)]) bind l e@(tag -> ELambda i) = uidOf e >>= \u -> return (l, [((i:fst l), u)]) bind l e@(tag -> ELetIn i) = uidOf e >>= \u -> return (l, [l, ((i:fst l), u)]) bind l e@(tag -> EBindAs b) = uidOf e >>= \u -> return (l, [l, (bindingVariables b ++ fst l, u)]) bind l e@(tag -> ECaseOf i) = uidOf e >>= \u -> return (l, [l, ((i:fst l), u), l]) bind l (children -> ch) = return (l, replicate (length ch) l) extract :: ([Identifier], Int) -> [(VarPosEnv, [Identifier])] -> K3 Expression -> Either String (VarPosEnv, [Identifier]) extract td chAcc e@(tag -> EVariable i) = rt td chAcc e [] $! const $ var i extract td chAcc e@(tag -> EAssign i) = rt td chAcc e [] $! const $ var i extract td@(sc,_) chAcc e@(tag -> ELambda n) = rt td chAcc e [n] $! scope Nothing [n] sc extract td@(sc,_) chAcc e@(tag -> EBindAs b) = let bvs = bindingVariables b in rt td chAcc e bvs $! scope (Just 1) bvs sc extract td@(sc,_) chAcc e@(tag -> ELetIn i) = rt td chAcc e [i] $! scope (Just 1) [i] sc extract td@(sc,_) chAcc e@(tag -> ECaseOf i) = rt td chAcc e [i] $! scope (Just 1) [i] sc extract td chAcc e = rt td chAcc e [] $! const concatvi concatvi :: [VarPosEnv] -> [[Identifier]] -> (VarPosEnv, [Identifier]) concatvi vps subvars = (vpunions vps, concat subvars) var :: Identifier -> [VarPosEnv] -> [[Identifier]] -> (VarPosEnv, [Identifier]) var i vps subvars = (vpunions vps, concat subvars ++ [i]) scope :: Maybe Int -> [Identifier] -> [Identifier] -> Int -> [VarPosEnv] -> [[Identifier]] -> (VarPosEnv, [Identifier]) scope pruneIdxOpt n sc i vps subvars = case pruneIdxOpt of Nothing -> (vpextlc (vpextsc vp' i scentry) i clvars, clvars) Just pruneIdx -> (vpextsc vp' i scentry, prune pruneIdx n subvars) where vp' = vpunions vps scentry = IndexedScope scvars $ length scvars scvars = sc ++ n clvars = subvarsInScope n sc subvars varusage :: [Identifier] -> [Identifier] -> Int -> Int -> [VarPosEnv] -> [[Identifier]] -> VarPosEnv varusage n sc scu u vps subvars = vpextvu vp' u (UID scu) usedmask where vp' = vpunions vps usedvars = subvarsInScope n sc subvars usedmask = Vector.fromList $ snd $ foldl mkmask (0,[]) sc mkmask (c, m) i | ix c == 0 = (c+1, fromBool (used i) : m) mkmask (c, h:t) i = (c+1, (if used i then h `setBit` (ix c) else h):t) mkmask _ _ = error "Mask initialization failed" sz = finiteBitSize (0 :: Word8) ix c = c `mod` sz used i = i `elem` usedvars fromBool False = 0 fromBool True = bit 0 prune :: Int -> [Identifier] -> [[Identifier]] -> [Identifier] prune i vars subvars = concatMap (\(j,l) -> if i == j then (filter (`notElem` vars) l) else l) $ zip [0..(length subvars)] subvars subvarsInScope :: [Identifier] -> [Identifier] -> [[Identifier]] -> [Identifier] subvarsInScope n sc subvars = nub $ filter (onlyLocals n sc) $ concat subvars onlyLocals :: [Identifier] -> [Identifier] -> Identifier -> Bool onlyLocals n l i = i `notElem` n && i `elem` l rt (sc,scu) (unzip -> (acc, iAcc)) e bnds accF = do u <- uidOf e let (nvpe, nids) = accF u acc iAcc return (varusage bnds sc scu u [nvpe] iAcc, nids) -- | Compute all global declarations used by the supplied list of declaration identifiers. -- This method returns all transitive dependencies. minimalProgramDecls :: [Identifier] -> K3 Declaration -> Either String [(Identifier, (Identifier, K3 Declaration))] minimalProgramDecls declIds prog = fixpointAcc True [] $ map ("",) declIds where fixpointAcc asSubstr acc ids = do (dip, _) <- filterDeclIds asSubstr ids prog let nacc = nub $ acc ++ dip next <- foldM declGlobals [] dip if all (isJust . flip lookup nacc) (map snd next) then return nacc else fixpointAcc False nacc next filterDeclIds asSubstr ids p = foldProgram (accF asSubstr ids) idF idF Nothing [] p accF asSubstr ids a d = return $! maybe (a,d) (matchIds asSubstr ids a d) $ declarationName d matchIds asSubstr ids a d i = maybe (a,d) (\(p,mi) -> (a ++ [(i,(p,d))], d)) $ find (matchF asSubstr i) ids matchF asSubstr i (_,y) = if asSubstr then y `isInfixOf` i else y == i idF a b = return (a,b) declGlobals acc (i,(_,d)) = maybe (return acc) (extractGlobals acc i) $ declarationExpr d extractGlobals acc pi e = return $! acc ++ map (pi,) (freeVariables e) instance Pretty TrIndex where prettyLines (Node (tg :@: _) ch) = [showbv tg] ++ drawSubTrees ch instance PT.Pretty TrIndex where prettyLines (Node (tg :@: _) ch) = [T.pack $ showbv tg] ++ PT.drawSubTrees ch
DaMSL/K3
src/Language/K3/Analysis/Core.hs
apache-2.0
20,136
0
15
4,811
7,917
4,165
3,752
355
18
{-# LANGUAGE OverloadedStrings #-} module Main where import Data.Aeson (decode) import Data.Maybe (fromJust) import Network.URI (parseURI) import Test.Hspec import Test.QuickCheck import Types main :: IO () main = hspec $ do describe "app" $ do it "apps" . property $ \x -> (read . show $ x) == (x :: Int) describe "FromJSON Link" $ do it "parses a valid link" $ do let json = "{\"link\": \"https://twitter.com/\", \"tags\": [\"foo\", \"bar\"]}" let obj = decode json :: Maybe Link obj `shouldBe` Just Link {uri = fromJust $ parseURI "https://twitter.com/", tags = [Tag "foo", Tag "bar"]} it "parses an invalid link" $ do let json = "{\"link\": \"!not/a/link\", \"tags\": [\"foo\", \"bar\"]}" let obj = decode json :: Maybe Link obj `shouldBe` Nothing
passy/giflib-api
Tests/Main.hs
apache-2.0
868
0
19
237
255
130
125
22
1
{-# LANGUAGE CPP, TemplateHaskell #-} {-| Shim library for supporting various Template Haskell versions -} {- Copyright (C) 2018, 2021 Ganeti Project Contributors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Ganeti.THH.Compat ( gntInstanceD , gntDataD , extractDataDConstructors , myNotStrict , nonUnaryTupE ) where import Language.Haskell.TH -- | Convert Names to DerivClauses -- -- template-haskell 2.12 (GHC 8.2) has changed the DataD class of -- constructors to expect [DerivClause] instead of [Names]. Handle this in a -- backwards-compatible way. #if MIN_VERSION_template_haskell(2,12,0) derivesFromNames :: [Name] -> [DerivClause] derivesFromNames names = [DerivClause Nothing $ map ConT names] #else derivesFromNames :: [Name] -> Cxt derivesFromNames names = map ConT names #endif -- | DataD "constructor" function -- -- Handle TH 2.11 and 2.12 changes in a transparent manner using the pre-2.11 -- API. gntDataD :: Cxt -> Name -> [TyVarBndr] -> [Con] -> [Name] -> Dec gntDataD x y z a b = #if MIN_VERSION_template_haskell(2,12,0) DataD x y z Nothing a $ derivesFromNames b #elif MIN_VERSION_template_haskell(2,11,0) DataD x y z Nothing a $ map ConT b #else DataD x y z a b #endif -- | InstanceD "constructor" function -- -- Handle TH 2.11 and 2.12 changes in a transparent manner using the pre-2.11 -- API. gntInstanceD :: Cxt -> Type -> [Dec] -> Dec gntInstanceD x y = #if MIN_VERSION_template_haskell(2,11,0) InstanceD Nothing x y #else InstanceD x y #endif -- | Extract constructors from a DataD instance -- -- Handle TH 2.11 changes by abstracting pattern matching against DataD. extractDataDConstructors :: Info -> Maybe [Con] extractDataDConstructors info = case info of #if MIN_VERSION_template_haskell(2,11,0) TyConI (DataD _ _ _ Nothing cons _) -> Just cons #else TyConI (DataD _ _ _ cons _) -> Just cons #endif _ -> Nothing -- | Strict has been replaced by Bang, so redefine NotStrict in terms of the -- latter. #if MIN_VERSION_template_haskell(2,11,0) myNotStrict :: Bang myNotStrict = Bang NoSourceUnpackedness NoSourceStrictness #else myNotStrict = NotStrict #endif -- | TupE changed from '[Exp] -> Exp' to '[Maybe Exp] -> Exp'. -- Provide the old signature for compatibility. nonUnaryTupE :: [Exp] -> Exp #if MIN_VERSION_template_haskell(2,16,0) nonUnaryTupE es = TupE $ map Just es #else nonUnaryTupE es = TupE $ es #endif
ganeti/ganeti
src/Ganeti/THH/Compat.hs
bsd-2-clause
3,633
0
10
610
319
188
131
24
2
{-#LANGUAGE RecordWildCards #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE QuasiQuotes, TemplateHaskell, TypeFamilies #-} {-# LANGUAGE OverloadedStrings, GADTs, FlexibleContexts #-} {-# LANGUAGE GeneralizedNewtypeDeriving, MultiParamTypeClasses #-} module DirectoryServer where import Network hiding (accept, sClose) import Network.Socket hiding (send, recv, sendTo, recvFrom, Broadcast) import Network.Socket.ByteString import Data.ByteString.Char8 (pack, unpack) import System.Environment import System.IO import Control.Concurrent import Control.Concurrent.STM import Control.Exception import Control.Monad (forever, when, join) import Data.List.Split import Data.Word import Text.Printf (printf) import System.Directory import Data.Map (Map) -- from the `containers` library import Data.Time import System.Random import qualified Data.Map as M type Uuid = Int type Address = String type Port = String type Filename = String type Timestamp = IO String --Server data type allows me to pass address and port details easily data DirectoryServer = DirectoryServer { address :: String , port :: String , filemappings :: TVar (M.Map Filename Filemapping) , fileservers :: TVar (M.Map Uuid Fileserver) , fileservercount :: TVar Int } --Constructor newDirectoryServer :: String -> String -> IO DirectoryServer newDirectoryServer address port = atomically $ do DirectoryServer <$> return address <*> return port <*> newTVar M.empty <*> newTVar M.empty <*> newTVar 0 addFilemapping :: DirectoryServer -> Filename -> Uuid -> Address -> Port -> Timestamp -> STM () addFilemapping DirectoryServer{..} filename uuid fmaddress fmport timestamp = do fm <- newFilemapping filename uuid fmaddress fmport timestamp modifyTVar filemappings . M.insert filename $ fm addFileserver :: DirectoryServer -> Uuid -> Address -> Port -> STM () addFileserver DirectoryServer{..} uuid fsaddress fsport = do fs <- newFileserver uuid fsaddress fsport modifyTVar fileservers . M.insert uuid $ fs lookupFilemapping :: DirectoryServer -> Filename -> STM (Maybe Filemapping) lookupFilemapping DirectoryServer{..} filename = M.lookup filename <$> readTVar filemappings lookupFileserver :: DirectoryServer -> Uuid -> STM (Maybe Fileserver) lookupFileserver DirectoryServer{..} uuid = M.lookup uuid <$> readTVar fileservers data Filemapping = Filemapping { fmfilename :: Filename , fmuuid :: Uuid , fmaddress :: Address , fmport :: Port , fmtimestamp :: Timestamp } newFilemapping :: Filename -> Uuid -> Address -> Port -> Timestamp -> STM Filemapping newFilemapping fmfilename fmuuid fmaddress fmport fmtimestamp = Filemapping <$> return fmfilename <*> return fmuuid <*> return fmaddress <*> return fmport <*> return fmtimestamp getFilemappinguuid :: Filemapping -> Uuid getFilemappinguuid Filemapping{..} = fmuuid getFilemappingaddress :: Filemapping -> Address getFilemappingaddress Filemapping{..} = fmaddress getFilemappingport :: Filemapping -> Port getFilemappingport Filemapping{..} = fmport getFilemappingtimestamp :: Filemapping -> Timestamp getFilemappingtimestamp Filemapping{..} = fmtimestamp data Fileserver = Fileserver { fsuuid :: Uuid , fsaddress :: HostName , fsport :: Port } newFileserver :: Uuid -> Address -> Port -> STM Fileserver newFileserver fsuuid fsaddress fsport = Fileserver <$> return fsuuid <*> return fsaddress <*> return fsport getFileserveraddress :: Fileserver -> HostName getFileserveraddress Fileserver{..} = fsaddress getFileserverport :: Fileserver -> Port getFileserverport Fileserver{..} = fsport --4 is easy for testing the pooling maxnumThreads = 4 serverport :: String serverport = "7008" serverhost :: String serverhost = "localhost" dirrun:: IO () dirrun = withSocketsDo $ do --Command line arguments for port and address --args <- getArgs server <- newDirectoryServer serverhost serverport --sock <- listenOn (PortNumber (fromIntegral serverport)) addrinfos <- getAddrInfo (Just (defaultHints {addrFlags = [AI_PASSIVE]})) Nothing (Just serverport) let serveraddr = head addrinfos sock <- socket (addrFamily serveraddr) Stream defaultProtocol bindSocket sock (addrAddress serveraddr) listen sock 5 _ <- printf "Listening on port %s\n" serverport --Listen on port from command line argument --New Abstract FIFO Channel chan <- newChan --Tvars are variables Stored in memory, this way we can access the numThreads from any method numThreads <- atomically $ newTVar 0 --Spawns a new thread to handle the clientconnectHandler method, passes socket, channel, numThreads and server forkIO $ clientconnectHandler sock chan numThreads server --Calls the mainHandler which will monitor the FIFO channel mainHandler sock chan mainHandler :: Socket -> Chan String -> IO () mainHandler sock chan = do --Read current message on the FIFO channel chanMsg <- readChan chan --If KILL_SERVICE, stop mainHandler running, If anything else, call mainHandler again, keeping the service running case (chanMsg) of ("KILL_SERVICE") -> putStrLn "Terminating the Service!" _ -> mainHandler sock chan clientconnectHandler :: Socket -> Chan String -> TVar Int -> DirectoryServer -> IO () clientconnectHandler sock chan numThreads server = do --Accept the socket which returns a handle, host and port --(handle, host, port) <- accept sock (s,a) <- accept sock --handle <- socketToHandle s ReadWriteMode --Read numThreads from memory and print it on server console count <- atomically $ readTVar numThreads putStrLn $ "numThreads = " ++ show count --If there are still threads remaining create new thread and increment (exception if thread is lost -> decrement), else tell user capacity has been reached if (count < maxnumThreads) then do forkFinally (clientHandler s chan server) (\_ -> atomically $ decrementTVar numThreads) atomically $ incrementTVar numThreads else do send s (pack ("Maximum number of threads in use. try again soon"++"\n\n")) sClose s clientconnectHandler sock chan numThreads server clientHandler :: Socket -> Chan String -> DirectoryServer -> IO () clientHandler sock chan server@DirectoryServer{..} = forever $ do message <- recv sock 1024 let msg = unpack message print $ msg ++ "!ENDLINE!" let cmd = head $ words $ head $ splitOn ":" msg print cmd case cmd of ("HELO") -> heloCommand sock server $ (words msg) !! 1 ("KILL_SERVICE") -> killCommand chan sock ("DOWNLOAD") -> downloadCommand sock server msg ("UPLOAD") -> uploadCommand sock server msg ("JOIN") -> joinCommand sock server msg _ -> do send sock (pack ("Unknown Command - " ++ msg ++ "\n\n")) ; return () --Function called when HELO text command recieved heloCommand :: Socket -> DirectoryServer -> String -> IO () heloCommand sock DirectoryServer{..} msg = do send sock $ pack $ "HELO " ++ msg ++ "\n" ++ "IP:" ++ "192.168.6.129" ++ "\n" ++ "Port:" ++ port ++ "\n" ++ "StudentID:12306421\n\n" return () killCommand :: Chan String -> Socket -> IO () killCommand chan sock = do send sock $ pack $ "Service is now terminating!" writeChan chan "KILL_SERVICE" downloadCommand :: Socket -> DirectoryServer ->String -> IO () downloadCommand sock server@DirectoryServer{..} command = do let clines = splitOn "\\n" command filename = (splitOn ":" $ clines !! 1) !! 1 fm <- atomically $ lookupFilemapping server $ filename case fm of Nothing -> send sock $ pack $ "DOWNLOAD: " ++ filename ++ "\n" ++ "STATUS: " ++ "File not found" ++ "\n\n" Just fm -> do downloadmsg filename (getFilemappingaddress fm) (getFilemappingport fm) sock return () downloadmsg :: String -> String -> String -> Socket -> IO(Int) downloadmsg filename host port sock = do addrInfo <- getAddrInfo (Just (defaultHints {addrFlags = [AI_PASSIVE]})) Nothing (Just port) let serverAddr = head addrInfo clsock <- socket (addrFamily serverAddr) Stream defaultProtocol connect clsock (addrAddress serverAddr) sClose clsock send clsock $ pack $ "DOWNLOAD:FILE" ++ "\\n" ++ "FILENAME:" ++ filename ++ "\\n" resp <- recv clsock 1024 let msg = unpack resp let clines = splitOn "\\n" msg fdata = (splitOn ":" $ clines !! 1) !! 1 send sock $ pack $ "DOWNLOAD: " ++ filename ++ "\\n" ++ "DATA: " ++ fdata ++ "\n\n" sClose clsock return (0) uploadCommand :: Socket -> DirectoryServer ->String -> IO () uploadCommand sock server@DirectoryServer{..} command = do let clines = splitOn "\\n" command filename = (splitOn ":" $ clines !! 1) !! 1 fdata = (splitOn ":" $ clines !! 2) !! 1 fm <- atomically $ lookupFilemapping server filename case fm of Just fm -> send sock $ pack $ "UPLOAD: " ++ filename ++ "\n" ++ "STATUS: " ++ "File Already Exists" ++ "\n\n" Nothing -> do numfs <- atomically $ M.size <$> readTVar fileservers printf (show numfs) rand <- randomRIO (0, (numfs-1)) printf (show rand) fs <- atomically $ lookupFileserver server rand case fs of Nothing -> send sock $ pack $ "UPLOAD: " ++ filename ++ "\n"++ "FAILED: " ++ "No valid Fileserver found to host" ++ "\n\n" Just fs -> do uploadmsg sock filename fdata fs rand server return () uploadmsg :: Socket -> String -> String -> Fileserver -> Int -> DirectoryServer -> IO (Int) uploadmsg sock filename fdata fs rand server@DirectoryServer{..} = withSocketsDo $ do addrInfo <- getAddrInfo (Just (defaultHints {addrFlags = [AI_PASSIVE]})) Nothing (Just "7007") let serverAddr = head addrInfo clsock <- socket (addrFamily serverAddr) Stream defaultProtocol connect clsock (addrAddress serverAddr) send clsock $ pack $ "UPLOAD:FILE" ++ "\\n" ++ "FILENAME:" ++ filename ++ "\\n" ++ "DATA:" ++ fdata ++ "\\n" resp <- recv clsock 1024 let msg = unpack resp let clines = splitOn "\\n" msg status = (splitOn ":" $ clines !! 1) !! 1 send sock $ pack $ "UPLOAD: " ++ filename ++ "\\n" ++ "STATUS: " ++ status ++ "\n\n" fm <- atomically $ newFilemapping filename rand (getFileserveraddress fs) (getFileserverport fs) (fmap show getZonedTime) atomically $ addFilemapping server filename rand (getFileserveraddress fs) (getFileserverport fs) (fmap show getZonedTime) sClose clsock return (0) joinCommand :: Socket -> DirectoryServer ->String -> IO () joinCommand sock server@DirectoryServer{..} command = do let clines = splitOn "\\n" command newaddress = (splitOn ":" $ clines !! 1) !! 1 newport = (splitOn ":" $ clines !! 2) !! 1 nodeID <- atomically $ readTVar fileservercount fs <- atomically $ newFileserver nodeID newaddress newport atomically $ addFileserver server nodeID newaddress newport atomically $ incrementFileserverCount fileservercount send sock $ pack $ "JOINED DISTRIBUTED FILE SERVICE as fileserver: " ++ (show nodeID) ++ "\n\n" return () --Increment Tvar stored in memory i.e. numThreads incrementTVar :: TVar Int -> STM () incrementTVar tv = modifyTVar tv ((+) 1) --Decrement Tvar stored in memory i.e. numThreads decrementTVar :: TVar Int -> STM () decrementTVar tv = modifyTVar tv (subtract 1) incrementFileserverCount :: TVar Int -> STM () incrementFileserverCount tv = modifyTVar tv ((+) 1)
Garygunn94/DFS
.stack-work/intero/intero22931Yzc.hs
bsd-3-clause
11,932
276
15
2,752
3,178
1,643
1,535
221
6
{- ArrowObsidian.hs Joel Svensson -} module Obsidian.ArrowObsidian (module Obsidian.ArrowObsidian.Flatten, module Obsidian.ArrowObsidian.Arr, module Obsidian.ArrowObsidian.Core, module Obsidian.ArrowObsidian.Exp, module Obsidian.ArrowObsidian.API, module Obsidian.ArrowObsidian.PureAPI, module Obsidian.ArrowObsidian.CodeGen, module Obsidian.ArrowObsidian.Execute, module Obsidian.ArrowObsidian.Printing, ) where import Obsidian.ArrowObsidian.Printing import Obsidian.ArrowObsidian.Exp import Obsidian.ArrowObsidian.Flatten import Obsidian.ArrowObsidian.Arr import Obsidian.ArrowObsidian.Core import Obsidian.ArrowObsidian.CodeGen import Obsidian.ArrowObsidian.Execute import Obsidian.ArrowObsidian.PureAPI import Obsidian.ArrowObsidian.API
svenssonjoel/ArrowObsidian
Obsidian/ArrowObsidian.hs
bsd-3-clause
835
0
5
138
127
88
39
19
0
{-# LANGUAGE QuasiQuotes, TypeFamilies, FlexibleInstances, OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module PNG( PNG, chunkName, readPNG, ihdr, bplte, plte, bidat, body, aplace, others, writePNG, IHDR(..), PLTE(..), png ) where import Prelude hiding (concat) import File.Binary (binary, Field(..), Binary(..)) import File.Binary.Instances () import File.Binary.Instances.BigEndian () import CRC (crc) import Codec.Compression.Zlib ( decompress, compressWith, defaultCompressParams, CompressParams(..), bestCompression, WindowBits(..)) import qualified Data.ByteString as BS (ByteString, length, readFile, writeFile) import qualified Data.ByteString.Char8 as BSC (unpack) import Data.ByteString.Lazy (ByteString, pack, unpack, concat, toChunks, fromChunks) import Data.Word (Word8, Word32) import Data.Bits (Bits, (.&.), (.|.), shiftL, shiftR) import Data.Monoid (mconcat) import Data.List (find) import Control.Applicative ((<$>)) import Control.Arrow(first) -------------------------------------------------------------------------------- readPNG :: FilePath -> IO PNG readPNG fp = do (p, "") <- fromBinary () <$> BS.readFile fp return p writePNG :: FilePath -> PNG -> IO () writePNG fout = BS.writeFile fout . toBinary () body :: PNG -> ByteString body = decompress . concatIDATs . body' ihdr :: PNG -> IHDR ihdr p = let ChunkIHDR i = chunkData . head . filter ((== "IHDR") . chunkName) $ chunks p in i plte :: PNG -> Maybe PLTE plte p = do ChunkPLTE pl <- chunkData <$> find ((== "PLTE") . chunkName) (chunks p) return pl mkBody :: ByteString -> [Chunk] mkBody = map makeIDAT . toChunks . compressWith defaultCompressParams { compressLevel = bestCompression, compressWindowBits = WindowBits 10 } png :: IHDR -> [Chunk] -> Maybe PLTE -> [Chunk] -> ByteString -> [Chunk] -> [Chunk] -> PNG png i bp (Just p) bi b ap o = PNG { chunks = makeIHDR i : bp ++ makePLTE p : bi ++ mkBody b ++ o ++ ap ++ [iend] } png i bp Nothing bi b ap o = PNG { chunks = makeIHDR i : bp ++ bi ++ mkBody b ++ o ++ ap ++ [iend] } beforePLTEs :: [String] beforePLTEs = ["cHRM", "gAMA", "sBIT", "sRGB", "iCCP"] bplte :: PNG -> [Chunk] bplte = filter ((`elem` beforePLTEs) . chunkName) . chunks beforeIDATs :: [String] beforeIDATs = ["bKGD", "hIST", "tRNS", "pHYs", "sPLT", "oFFs", "pCAL", "sCAL"] bidat :: PNG -> [Chunk] bidat = filter ((`elem` beforeIDATs) . chunkName) . chunks anyplaces :: [String] anyplaces = ["tIME", "tEXt", "zTXt", "iTXt", "gIFg", "gIFt", "gIFx", "fRAc"] aplace :: PNG -> [Chunk] aplace = filter ((`elem` anyplaces) . chunkName) . chunks needs :: [String] needs = ["IHDR", "PLTE", "IDAT", "IEND"] others :: PNG -> [Chunk] others PNG { chunks = cs } = filter ((`notElem` needs ++ beforePLTEs ++ beforeIDATs ++ anyplaces) . chunkName) cs body' :: PNG -> [IDAT] body' PNG { chunks = cs } = map (cidat . chunkData) $ filter ((== "IDAT") . chunkName) cs concatIDATs :: [IDAT] -> ByteString concatIDATs = concat . map idat makeIDAT :: BS.ByteString -> Chunk makeIDAT bs = Chunk { chunkSize = fromIntegral $ BS.length bs, chunkName = "IDAT", chunkData = ChunkIDAT $ IDAT $ fromChunks [bs], chunkCRC = crc $ "IDAT" ++ BSC.unpack bs } makeIHDR :: IHDR -> Chunk makeIHDR = makeChunk . ChunkIHDR makePLTE :: PLTE -> Chunk makePLTE = makeChunk . ChunkPLTE size :: ChunkBody -> Int size (ChunkIHDR _) = 13 size (ChunkPLTE (PLTE d)) = 3 * length d size _ = error "yet" name :: ChunkBody -> String name (ChunkIHDR _) = "IHDR" name (ChunkPLTE _) = "PLTE" name _ = error "yet" makeChunk :: ChunkBody -> Chunk makeChunk cb = Chunk { chunkSize = length (toBinary (size cb, name cb) cb :: String), chunkName = name cb, chunkData = cb, chunkCRC = crc $ name cb ++ toBinary (size cb, name cb) cb } iend :: Chunk iend = Chunk { chunkSize = 0, chunkName = "IEND", chunkData = ChunkIEND IEND, chunkCRC = crc "IEND" } [binary| PNG deriving Show 1: 0x89 3: "PNG" 2: "\r\n" 1: "\SUB" 1: "\n" ((), Nothing){[Chunk]}: chunks |] [binary| Chunk deriving Show 4: chunkSize ((), Just 4){String}: chunkName (chunkSize, chunkName){ChunkBody}: chunkData 4{Word32}:chunkCRC |] {- instance Field Word32 where type FieldArgument Word32 = Int toBinary n = makeBinary . pack . intToWords n fromBinary n = first (wordsToInt . unpack) . getBytes n intToWords :: (Bits i, Integral i) => Int -> i -> [Word8] intToWords = itw [] where itw r 0 _ = r itw r n i = itw (fromIntegral (i .&. 0xff) : r) (n - 1) (i `shiftR` 8) wordsToInt :: Bits i => [Word8] -> i wordsToInt = foldl (\r w -> r `shiftL` 8 .|. fromIntegral w) 0 -} data ChunkBody = ChunkIHDR IHDR | ChunkGAMA GAMA | ChunkSRGB SRGB | ChunkCHRM CHRM | ChunkPLTE PLTE | ChunkBKGD BKGD | ChunkIDAT { cidat :: IDAT } | ChunkTEXT TEXT | ChunkIEND IEND | Others String deriving Show instance Field ChunkBody where type FieldArgument ChunkBody = (Int, String) toBinary _ (ChunkIHDR c) = toBinary () c toBinary _ (ChunkGAMA c) = toBinary () c toBinary _ (ChunkSRGB c) = toBinary () c toBinary (n, _) (ChunkCHRM chrm) = toBinary n chrm toBinary (n, _) (ChunkPLTE p) = toBinary n p toBinary _ (ChunkBKGD c) = toBinary () c toBinary (n, _) (ChunkIDAT c) = toBinary n c toBinary (n, _) (ChunkTEXT c) = toBinary n c toBinary _ (ChunkIEND c) = toBinary () c toBinary (n, _) (Others str) = toBinary ((), Just n) str fromBinary (_, "IHDR") = first ChunkIHDR . fromBinary () fromBinary (_, "gAMA") = first ChunkGAMA . fromBinary () fromBinary (_, "sRGB") = first ChunkSRGB . fromBinary () fromBinary (n, "cHRM") = first ChunkCHRM . fromBinary n fromBinary (n, "PLTE") = first ChunkPLTE . fromBinary n fromBinary (_, "bKGD") = first ChunkBKGD . fromBinary () fromBinary (n, "IDAT") = first ChunkIDAT . fromBinary n fromBinary (n, "tEXt") = first ChunkTEXT . fromBinary n fromBinary (_, "IEND") = first ChunkIEND . fromBinary () fromBinary (n, _) = first Others . fromBinary ((), Just n) [binary| IHDR deriving Show 4: width 4: height 1: depth : False : False : False : False : False {Bool}: alpha {Bool}: color {Bool}: palet 1: compressionType 1: filterType 1: interlaceType |] [binary| GAMA deriving Show 4: gamma |] [binary| SRGB deriving Show 1: srgb |] [binary| CHRM deriving Show arg :: Int (4, Just (arg `div` 4)){[Int]}: chrms |] [binary| PLTE deriving Show arg :: Int ((), Just (arg `div` 3)){[(Int, Int, Int)]}: colors |] instance Field (Int, Int, Int) where type FieldArgument (Int, Int, Int) = () toBinary _ (b, g, r) = mconcat [toBinary 1 b, toBinary 1 g, toBinary 1 r] fromBinary _ s = let (r, rest) = fromBinary 1 s (g, rest') = fromBinary 1 rest (b, rest'') = fromBinary 1 rest' in ((r, g, b), rest'') [binary| BKGD deriving Show 1: bkgd |] [binary| IDAT deriving Show arg :: Int arg{ByteString}: idat |] [binary| TEXT deriving Show arg :: Int ((), Just arg){String}: text |] [binary|IEND deriving Show|]
YoshikuniJujo/binary-file
examples/png/PNG.hs
bsd-3-clause
6,905
80
14
1,309
2,444
1,355
1,089
166
1
{-# LANGUAGE DeriveDataTypeable #-} module Allegro.Display ( withDisplay , createDisplay , Display , DisplayWindow(..) , destroyDisplay -- * Display properties , setWindowTitle , setDisplayIcon -- * Working with the current display , flipDisplay -- * Events , DisplayEvent , HasDisplay(..) -- * Exceptions , FailedToCreateDisplay(..) ) where import Allegro.Types import Allegro.C.Display import Allegro.C.Event import Foreign (nullPtr) import Foreign.C.String ( withCString ) import Data.Bits( (.|.) ) import Control.Monad (when) import Control.Applicative ( (<$>), (<*>) ) import qualified Control.Exception as X import Data.Typeable (Typeable) data DisplayWindow = FixedWindow | ResizableWindow | FullScreen withDisplay :: DisplayWindow -> Int -> Int -> (Display -> IO ()) -> IO () withDisplay win w h k = do d <- createDisplay win w h k d `X.finally` destroyDisplay d createDisplay :: DisplayWindow -> Int -> Int -> IO Display createDisplay win w h = do al_set_new_display_flags $ case win of FullScreen -> fullscreen FixedWindow -> windowed ResizableWindow -> windowed .|. resizeable p <- al_create_display (fromIntegral w) (fromIntegral h) when (p == nullPtr) $ X.throwIO FailedToCreateDisplay return (Display p) setWindowTitle :: Display -> String -> IO () setWindowTitle (Display d) x = withCString x $ \p -> al_set_window_title d p setDisplayIcon :: Display -> Bitmap -> IO () setDisplayIcon (Display d) x = withBitmapPtr x $ \p -> al_set_display_icon d p destroyDisplay :: Display -> IO () destroyDisplay (Display p) = al_destroy_display p flipDisplay :: IO () flipDisplay = al_flip_display -------------------------------------------------------------------------------- -- Display events data DisplayEvent = EvDisplay { dSuper' :: {-# UNPACK #-} !SomeEvent , dDisplay' :: !Display } instance ParseEvent DisplayEvent where eventDetails x p = EvDisplay <$> eventDetails x p <*> (Display <$> event_display_source p) instance HasType DisplayEvent where evType = evType . dSuper' instance HasTimestamp DisplayEvent where evTimestamp = evTimestamp . dSuper' instance HasDisplay DisplayEvent where evDisplay = dDisplay' data FailedToCreateDisplay = FailedToCreateDisplay deriving (Typeable,Show) instance X.Exception FailedToCreateDisplay
yav/allegro
src/Allegro/Display.hs
bsd-3-clause
2,539
0
12
601
659
356
303
64
3
{-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeOperators #-} -- | Description: HTTP API implementation. module Anchor.Tokens.Server.API where import Blaze.ByteString.Builder (toByteString) import Control.Lens import Control.Monad import Control.Monad.Error.Class import Control.Monad.IO.Class import Control.Monad.Trans.Control import Control.Monad.Trans.Reader import Data.ByteString (ByteString) import Data.Time.Clock import qualified Data.ByteString.Lazy.Char8 as BSL import Data.Either import Data.Maybe import Data.Monoid import Data.Pool import Data.Proxy import qualified Data.Set as S import qualified Data.Text as T import qualified Data.Text.Encoding as T import Database.PostgreSQL.Simple import Network.HTTP.Types hiding (Header) import Pipes.Concurrent import Servant.API hiding (URI) import Servant.HTML.Blaze import Servant.Server import System.Log.Logger import URI.ByteString import Text.Blaze.Html5 hiding (map, code,rt) import Network.OAuth2.Server import Anchor.Tokens.Server.Store hiding (logName) import Anchor.Tokens.Server.Types import Anchor.Tokens.Server.UI import Debug.Trace logName :: String logName = "Anchor.Tokens.Server.API" type OAuthUserHeader = "Identity-OAuthUser" type OAuthUserScopeHeader = "Identity-OAuthUserScopes" data TokenRequest = DeleteRequest | CreateRequest Scope instance FromFormUrlEncoded TokenRequest where fromFormUrlEncoded o = trace (show o) $ case lookup "method" o of Nothing -> Left "method field missing" Just "delete" -> Right DeleteRequest Just "create" -> do let processScope x = case (T.encodeUtf8 x) ^? scopeToken of Nothing -> Left $ T.unpack x Just ts -> Right ts let scopes = map (processScope . snd) $ filter (\x -> fst x == "scope") o case lefts scopes of [] -> case S.fromList (rights scopes) ^? scope of Nothing -> Left "empty scope is invalid" Just s -> Right $ CreateRequest s es -> Left $ "invalid scopes: " <> show es Just x -> Left . T.unpack $ "Invalid method field value, got: " <> x data ResponseTypeCode = ResponseTypeCode instance FromText ResponseTypeCode where fromText "code" = Just ResponseTypeCode fromText _ = Nothing -- | OAuth2 Authorization Endpoint -- -- Allows authenticated users to review and authorize a code token grant -- request. -- -- http://tools.ietf.org/html/rfc6749#section-3.1 type AuthorizeEndpoint = "authorize" :> Header OAuthUserHeader UserID :> Header OAuthUserScopeHeader Scope :> QueryParam "response_type" ResponseTypeCode :> QueryParam "client_id" ClientID :> QueryParam "redirect_uri" URI :> QueryParam "scope" Scope :> QueryParam "state" ClientState :> Get '[HTML] Html -- | OAuth2 Authorization Endpoint -- -- Allows authenticated users to review and authorize a code token grant -- request. -- -- http://tools.ietf.org/html/rfc6749#section-3.1 type AuthorizePost = "authorize" :> Header OAuthUserHeader UserID :> ReqBody '[FormUrlEncoded] Code :> Post '[HTML] () -- | Facilitates services checking tokens. -- -- This endpoint allows an authorized client to verify that a token is valid -- and retrieve information about the principal and token scope. type VerifyEndpoint = "verify" :> Header "Authorization" AuthHeader :> ReqBody '[OctetStream] Token :> Post '[JSON] (Headers '[Header "Cache-Control" NoCache] AccessResponse) -- | Facilitates human-readable token listing. -- -- This endpoint allows an authorized client to view their tokens as well as -- revoke them individually. type ListTokens = "tokens" :> Header OAuthUserHeader UserID :> Header OAuthUserScopeHeader Scope :> QueryParam "page" Page :> Get '[HTML] Html type DisplayToken = "tokens" :> Header OAuthUserHeader UserID :> Header OAuthUserScopeHeader Scope :> Capture "token_id" TokenID :> Get '[HTML] Html type PostToken = "tokens" :> Header OAuthUserHeader UserID :> Header OAuthUserScopeHeader Scope :> ReqBody '[FormUrlEncoded] TokenRequest :> QueryParam "token_id" TokenID :> Post '[HTML] Html -- | Anchor Token Server HTTP endpoints. -- -- Includes endpoints defined in RFC6749 describing OAuth2, plus application -- specific extensions. type AnchorOAuth2API = "oauth2" :> TokenEndpoint -- From oauth2-server :<|> "oauth2" :> VerifyEndpoint :<|> "oauth2" :> AuthorizeEndpoint :<|> "oauth2" :> AuthorizePost :<|> ListTokens :<|> DisplayToken :<|> PostToken anchorOAuth2API :: Proxy AnchorOAuth2API anchorOAuth2API = Proxy server :: ServerState -> Server AnchorOAuth2API server state@ServerState{..} = tokenEndpoint serverOAuth2Server :<|> verifyEndpoint state :<|> authorizeEndpoint serverPGConnPool :<|> authorizePost serverPGConnPool :<|> handleShib (serverListTokens serverPGConnPool (optUIPageSize serverOpts)) :<|> handleShib (serverDisplayToken serverPGConnPool) :<|> serverPostToken serverPGConnPool -- Any shibboleth authed endpoint must have all relevant headers defined, -- and any other case is an internal error. handleShib consolidates -- checking these headers. handleShib :: ( MonadIO m , MonadBaseControl IO m , MonadError ServantErr m ) => (UserID -> Scope -> a -> m b) -> Maybe UserID -> Maybe Scope -> a -> m b handleShib f (Just u) (Just s) = f u s handleShib _ _ _ = const $ throwError err500{errBody = "We're having some trouble with our internal auth systems, please try again later =("} authorizeEndpoint :: ( MonadIO m , MonadBaseControl IO m , MonadError ServantErr m ) => Pool Connection -> Maybe UserID -> Maybe Scope -> Maybe ResponseTypeCode -> Maybe ClientID -> Maybe URI -> Maybe Scope -> Maybe ClientState -> m Html authorizeEndpoint pool u' permissions' rt c_id' redirect sc' st = do case rt of Nothing -> error "NOOOO" Just ResponseTypeCode -> return () u_id <- case u' of Nothing -> error "NOOOO" Just u_id -> return u_id permissions <- case permissions' of Nothing -> error "NOOOO" Just permissions -> return permissions sc <- case sc' of Nothing -> error "NOOOO" Just sc -> if sc `compatibleScope` permissions then return sc else error "NOOOOO" c_id <- case c_id' of Nothing -> error "NOOOO" Just c_id -> return c_id request_code <- runReaderT (createCode u_id c_id redirect sc st) pool return $ renderAuthorizePage request_code authorizePost :: ( MonadIO m , MonadBaseControl IO m , MonadError ServantErr m ) => Pool Connection -> Maybe UserID -> Code -> m () authorizePost pool u code' = do u_id <- case u of Nothing -> error "NOOOO" Just u_id -> return u_id res <- runReaderT (activateCode code' u_id) pool case res of Nothing -> error "NOOOO" Just uri -> do let uri' = uri & uriQueryL . queryPairsL %~ (<> [("code", code' ^.re code)]) throwError err302{ errHeaders = [(hLocation, toByteString $ serializeURI uri')] } -- | Verify a token and return information about the principal and grant. -- -- Restricted to authorized clients. verifyEndpoint :: ( MonadIO m , MonadBaseControl IO m , MonadError ServantErr m ) => ServerState -> Maybe AuthHeader -> Token -> m (Headers '[Header "Cache-Control" NoCache] AccessResponse) verifyEndpoint ServerState{..} Nothing _token = throwError err401 { errHeaders = toHeaders challenge , errBody = "You must login to validate a token." } where challenge = BasicAuth $ Realm (optVerifyRealm serverOpts) verifyEndpoint ServerState{..} (Just auth) token' = do -- 1. Check client authentication. client_id' <- runStore serverPGConnPool $ checkClientAuth auth client_id <- case client_id' of Left e -> do logE $ "Error verifying token: " <> show e throwError err500 { errBody = "Error checking client credentials." } Right Nothing -> do logD $ "Invalid client credentials: " <> show auth throwError denied Right (Just cid) -> do return cid -- 2. Load token information. token <- runStore serverPGConnPool $ (loadToken token') case token of Left e -> do logE $ "Error verifying token: " <> show e throwError denied Right Nothing -> do logD $ "Cannot verify token: failed to lookup " <> show token' throwError denied Right (Just details) -> do -- 3. Check client authorization. when (Just client_id /= tokenDetailsClientID details) $ do logD $ "Client " <> show client_id <> " attempted to verify someone elses token: " <> show token' throwError denied -- 4. Send the access response. now <- liftIO getCurrentTime return . addHeader NoCache $ grantResponse now details (Just token') where denied = err404 { errBody = "This is not a valid token for you." } logD = liftIO . debugM (logName <> ".verifyEndpoint") logE = liftIO . errorM (logName <> ".verifyEndpoint") serverDisplayToken :: ( MonadIO m , MonadBaseControl IO m , MonadError ServantErr m ) => Pool Connection -> UserID -> Scope -> TokenID -> m Html serverDisplayToken pool u s t = do res <- runReaderT (displayToken u t) pool case res of Nothing -> throwError err404{errBody = "There's nothing here! =("} Just x -> return $ renderTokensPage s 1 (Page 1) ([x], 1) serverListTokens :: ( MonadIO m , MonadBaseControl IO m , MonadError ServantErr m ) => Pool Connection -> Int -> UserID -> Scope -> Maybe Page -> m Html serverListTokens pool size u s p = do let p' = fromMaybe (Page 1) p res <- runReaderT (listTokens size u p') pool return $ renderTokensPage s size p' res serverPostToken :: ( MonadIO m , MonadBaseControl IO m , MonadError ServantErr m ) => Pool Connection -> Maybe UserID -> Maybe Scope -> TokenRequest -> Maybe TokenID -> m Html serverPostToken pool u s DeleteRequest (Just t) = handleShib (serverRevokeToken pool) u s t serverPostToken pool u s DeleteRequest Nothing = throwError err400{errBody = "Malformed delete request"} serverPostToken pool u s (CreateRequest rs) _ = handleShib (serverCreateToken pool) u s rs serverRevokeToken :: ( MonadIO m , MonadBaseControl IO m , MonadError ServantErr m ) => Pool Connection -> UserID -> Scope -> TokenID -> m Html serverRevokeToken pool u _ t = do runReaderT (revokeToken u t) pool throwError err302{errHeaders = [(hLocation, "/tokens")]} --Redirect to tokens page serverCreateToken :: ( MonadIO m , MonadBaseControl IO m , MonadError ServantErr m ) => Pool Connection -> UserID -> Scope -> Scope -> m Html serverCreateToken pool user_id userScope reqScope = do if compatibleScope reqScope userScope then do TokenID t <- runReaderT (createToken user_id reqScope) pool throwError err302{errHeaders = [(hLocation, "/tokens?token_id=" <> T.encodeUtf8 t)]} --Redirect to tokens page else throwError err403{errBody = "Invalid requested token scope"} -- * OAuth2 Server -- -- $ This defines the 'OAuth2Server' implementation we use to store, load, and -- validate tokens and credentials. anchorOAuth2Server :: ( MonadIO m , MonadBaseControl IO m , MonadError OAuth2Error m ) => Pool Connection -> Output a -> OAuth2Server m anchorOAuth2Server pool out = let oauth2StoreSave grant = runReaderT (saveToken grant) pool oauth2StoreLoad tok = runReaderT (loadToken tok) pool oauth2CheckCredentials auth req = runReaderT (checkCredentials auth req) pool in OAuth2Server{..}
zerobuzz/anchor-token-server
lib/Anchor/Tokens/Server/API.hs
bsd-3-clause
12,791
10
21
3,514
3,119
1,572
1,547
-1
-1
{-# LANGUAGE UndecidableInstances #-} -- | Functionality on promoted lists. module Data.Type.List (module Data.Type.List, module Data.Promotion.Prelude.List) where import Data.Promotion.Prelude.List (Map, (:++)) type family ReverseAcc (xs :: [k]) (acc :: [k]) :: [k] type instance ReverseAcc '[] acc = acc type instance ReverseAcc (x ': xs) acc = ReverseAcc xs (x ': acc) type Reverse (xs :: [k]) = ReverseAcc xs '[]
kosmikus/tilt
src/Data/Type/List.hs
bsd-3-clause
426
0
7
70
150
95
55
-1
-1
{-# language RankNTypes #-} {-# language GADTs #-} {-# language TupleSections #-} {-# language OverloadedStrings #-} module Text.Digestive.Snap where import Snap.Core (MonadSnap, getRequest, rqMethod) import Data.ByteString(ByteString) import Data.Text (Text) import Data.List(isPrefixOf) import Data.Maybe(mapMaybe) import Data.Text.Encoding(decodeUtf8With) import Data.Text.Encoding.Error(lenientDecode) import Text.Digestive.Form(Form) import Text.Digestive.Form.Internal(FormTree(..)) import Text.Digestive.Form.List(DefaultList) import Text.Digestive.Types(Path,Env,FormInput(..),toPath) import Text.Digestive.View(View,postForm,getForm) import Network.Wai(queryString,Request) import Network.Wai.Parse(parseRequestBody,tempFileBackEnd,File,fileContent) import Control.Monad.Trans.Resource(ResourceT,getInternalState) import Control.Monad.Trans(lift,liftIO,MonadIO) import Network.HTTP.Types.Method(StdMethod(..)) import Network.HTTP.Types.QueryLike(QueryLike(..),toQueryValue) import Network.HTTP.Types.URI(Query) import Data.Function(on) newtype FileQuery = FileQuery [File FilePath] instance QueryLike FileQuery where toQuery (FileQuery files) = map (\(k,v) -> (k,toQueryValue $ fileContent v)) files runForm :: MonadSnap m => Text -> Form v m a -> ResourceT m (View v,Maybe a) runForm name frm = do r <- lift $ getRequest case rqMethod r of (Right POST) -> postForm name (mapFM lift frm) (const $ bodyFormEnv__ r) _ -> fmap (,Nothing) $ getForm name (mapFM lift frm) runFormGet :: MonadSnap m => Text -> Form v m a -> ResourceT m (View v,Maybe a) runFormGet name frm = do r <- lift $ getRequest let env = queryFormEnv_ $ queryString r act <- env [] liftIO $ print act case rqMethod r of (Right GET) -> postForm name (mapFM lift frm) (const $ return env) _ -> fmap (,Nothing) $ getForm name (mapFM lift frm) mapFM :: Functor m => (forall a. m a -> m' a) -> Form v m b -> Form v m' b mapFM f (Ref ref ft) = Ref ref $ mapFM f ft mapFM f (Pure field) = Pure field mapFM f (App t ft) = App (mapFM f t) (mapFM f ft) mapFM f (Map t ft) = Map (\x -> f $ t x) (mapFM f ft) mapFM f (Monadic act) = Monadic $ f (fmap (mapFM f) act) mapFM f (List dl ft) = List (fmap (mapFM f) dl) (mapFM f ft) mapFM f (Metadata md ft) = Metadata md $ mapFM f ft bodyFormEnv__ :: (Monad m,MonadIO io) => Request -> ResourceT io (Env m) bodyFormEnv__ req = do st <- getInternalState (query, files) <- liftIO $ parseRequestBody (tempFileBackEnd st) req return $ queryFormEnv_ (toQuery query ++ toQuery (FileQuery files)) -- | Build an 'Text.Digestive.Types.Env' from a query queryFormEnv_ :: (QueryLike q, Monad m) => q -> Env m queryFormEnv_ qs = \pth -> return $ map (TextInput . decodeUtf8With lenientDecode) $ matchPath pth qs' where qs' = toQuery qs matchPath :: Path -> Query -> [ByteString] matchPath pth = mapMaybe snd . filter go where go (key,val) = pth `isPrefixOf` (toPath $ decodeUtf8With lenientDecode key)
jonpetterbergman/wai-snap
src/Text/Digestive/Snap.hs
bsd-3-clause
3,096
0
13
614
1,232
651
581
74
2
{-# LANGUAGE ScopedTypeVariables #-} module ETA.TypeCheck.TcErrors( reportUnsolved, reportAllUnsolved, warnDefaulting, solverDepthErrorTcS ) where import ETA.TypeCheck.TcRnTypes import ETA.TypeCheck.TcRnMonad import ETA.TypeCheck.TcMType import ETA.TypeCheck.TcType import ETA.Types.TypeRep import ETA.Types.Type import ETA.Types.Kind ( isKind ) import ETA.Types.Unify ( tcMatchTys ) import ETA.BasicTypes.Module import ETA.TypeCheck.FamInst import ETA.TypeCheck.Inst import ETA.Types.InstEnv import ETA.Types.TyCon import ETA.BasicTypes.DataCon import ETA.TypeCheck.TcEvidence import ETA.BasicTypes.Name import ETA.BasicTypes.RdrName ( lookupGRE_Name, GlobalRdrEnv ) import ETA.BasicTypes.Id import ETA.BasicTypes.Var import ETA.BasicTypes.VarSet import ETA.BasicTypes.VarEnv import ETA.BasicTypes.NameEnv import ETA.Utils.Bag import ETA.Main.ErrUtils ( ErrMsg, makeIntoWarning, pprLocErrMsg, isWarning ) import ETA.BasicTypes.BasicTypes import ETA.Utils.Util import ETA.Utils.FastString import ETA.Utils.Outputable import ETA.BasicTypes.SrcLoc import ETA.Main.DynFlags import ETA.Main.StaticFlags ( opt_PprStyle_Debug ) import ETA.Utils.ListSetOps ( equivClasses ) import Control.Monad ( when ) import Data.Maybe import Data.List ( partition, mapAccumL, nub, sortBy ) {- ************************************************************************ * * \section{Errors and contexts} * * ************************************************************************ ToDo: for these error messages, should we note the location as coming from the insts, or just whatever seems to be around in the monad just now? Note [Deferring coercion errors to runtime] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ While developing, sometimes it is desirable to allow compilation to succeed even if there are type errors in the code. Consider the following case: module Main where a :: Int a = 'a' main = print "b" Even though `a` is ill-typed, it is not used in the end, so if all that we're interested in is `main` it is handy to be able to ignore the problems in `a`. Since we treat type equalities as evidence, this is relatively simple. Whenever we run into a type mismatch in TcUnify, we normally just emit an error. But it is always safe to defer the mismatch to the main constraint solver. If we do that, `a` will get transformed into co :: Int ~ Char co = ... a :: Int a = 'a' `cast` co The constraint solver would realize that `co` is an insoluble constraint, and emit an error with `reportUnsolved`. But we can also replace the right-hand side of `co` with `error "Deferred type error: Int ~ Char"`. This allows the program to compile, and it will run fine unless we evaluate `a`. This is what `deferErrorsToRuntime` does. It does this by keeping track of which errors correspond to which coercion in TcErrors. TcErrors.reportTidyWanteds does not print the errors and does not fail if -fdefer-type-errors is on, so that we can continue compilation. The errors are turned into warnings in `reportUnsolved`. -} reportUnsolved :: WantedConstraints -> TcM (Bag EvBind) reportUnsolved wanted = do { binds_var <- newTcEvBinds ; defer_errors <- goptM Opt_DeferTypeErrors ; defer_holes <- goptM Opt_DeferTypedHoles ; warn_holes <- woptM Opt_WarnTypedHoles ; warn_partial_sigs <- woptM Opt_WarnPartialTypeSignatures ; report_unsolved (Just binds_var) defer_errors defer_holes warn_holes warn_partial_sigs wanted ; getTcEvBinds binds_var } reportAllUnsolved :: WantedConstraints -> TcM () -- Report all unsolved goals, even if -fdefer-type-errors is on -- See Note [Deferring coercion errors to runtime] reportAllUnsolved wanted = do warn_holes <- woptM Opt_WarnTypedHoles warn_partial_sigs <- woptM Opt_WarnPartialTypeSignatures report_unsolved Nothing False False warn_holes warn_partial_sigs wanted report_unsolved :: Maybe EvBindsVar -- cec_binds -> Bool -- cec_defer_type_errors -> Bool -- cec_defer_holes -> Bool -- cec_warn_holes -> Bool -- cec_warn_partial_type_signatures -> WantedConstraints -> TcM () -- Important precondition: -- WantedConstraints are fully zonked and unflattened, that is, -- zonkWC has already been applied to these constraints. report_unsolved mb_binds_var defer_errors defer_holes warn_holes warn_partial_sigs wanted | isEmptyWC wanted = return () | otherwise = do { traceTc "reportUnsolved (before unflattening)" (ppr wanted) ; env0 <- tcInitTidyEnv -- If we are deferring we are going to need /all/ evidence around, -- including the evidence produced by unflattening (zonkWC) ; let tidy_env = tidyFreeTyVars env0 free_tvs free_tvs = tyVarsOfWC wanted err_ctxt = CEC { cec_encl = [] , cec_tidy = tidy_env , cec_defer_type_errors = defer_errors , cec_defer_holes = defer_holes , cec_warn_holes = warn_holes , cec_warn_partial_type_signatures = warn_partial_sigs , cec_suppress = False -- See Note [Suppressing error messages] , cec_binds = mb_binds_var } ; traceTc "reportUnsolved (after unflattening):" $ vcat [ pprTvBndrs (varSetElems free_tvs) , ppr wanted ] ; reportWanteds err_ctxt wanted } -------------------------------------------- -- Internal functions -------------------------------------------- data ReportErrCtxt = CEC { cec_encl :: [Implication] -- Enclosing implications -- (innermost first) -- ic_skols and givens are tidied, rest are not , cec_tidy :: TidyEnv , cec_binds :: Maybe EvBindsVar -- Nothinng <=> Report all errors, including holes; no bindings -- Just ev <=> make some errors (depending on cec_defer) -- into warnings, and emit evidence bindings -- into 'ev' for unsolved constraints , cec_defer_type_errors :: Bool -- True <=> -fdefer-type-errors -- Defer type errors until runtime -- Irrelevant if cec_binds = Nothing , cec_defer_holes :: Bool -- True <=> -fdefer-typed-holes -- Turn typed holes into runtime errors -- Irrelevant if cec_binds = Nothing , cec_warn_holes :: Bool -- True <=> -fwarn-typed-holes -- Controls whether typed holes produce warnings , cec_warn_partial_type_signatures :: Bool -- True <=> -fwarn-partial-type-signatures -- Controls whether holes in partial type -- signatures produce warnings , cec_suppress :: Bool -- True <=> More important errors have occurred, -- so create bindings if need be, but -- don't issue any more errors/warnings -- See Note [Suppressing error messages] } {- Note [Suppressing error messages] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The cec_suppress flag says "don't report any errors. Instead, just create evidence bindings (as usual). It's used when more important errors have occurred. Specifically (see reportWanteds) * If there are insoluble Givens, then we are in unreachable code and all bets are off. So don't report any further errors. * If there are any insolubles (eg Int~Bool), here or in a nested implication, then suppress errors from the simple constraints here. Sometimes the simple-constraint errors are a knock-on effect of the insolubles. -} reportImplic :: ReportErrCtxt -> Implication -> TcM () reportImplic ctxt implic@(Implic { ic_skols = tvs, ic_given = given , ic_wanted = wanted, ic_binds = evb , ic_insol = ic_insoluble, ic_info = info }) | BracketSkol <- info , not ic_insoluble -- For Template Haskell brackets report only = return () -- definite errors. The whole thing will be re-checked -- later when we plug it in, and meanwhile there may -- certainly be un-satisfied constraints | otherwise = reportWanteds ctxt' wanted where (env1, tvs') = mapAccumL tidyTyVarBndr (cec_tidy ctxt) tvs (env2, info') = tidySkolemInfo env1 info implic' = implic { ic_skols = tvs' , ic_given = map (tidyEvVar env2) given , ic_info = info' } ctxt' = ctxt { cec_tidy = env2 , cec_encl = implic' : cec_encl ctxt , cec_binds = case cec_binds ctxt of Nothing -> Nothing Just {} -> Just evb } reportWanteds :: ReportErrCtxt -> WantedConstraints -> TcM () reportWanteds ctxt wanted@(WC { wc_simple = simples, wc_insol = insols, wc_impl = implics }) = do { reportSimples ctxt (mapBag (tidyCt env) insol_given) ; reportSimples ctxt1 (mapBag (tidyCt env) insol_wanted) ; reportSimples ctxt2 (mapBag (tidyCt env) simples) -- All the Derived ones have been filtered out of simples -- by the constraint solver. This is ok; we don't want -- to report unsolved Derived goals as errors -- See Note [Do not report derived but soluble errors] ; mapBagM_ (reportImplic ctxt1) implics } -- NB ctxt1: don't suppress inner insolubles if there's only a -- wanted insoluble here; but do suppress inner insolubles -- if there's a given insoluble here (= inaccessible code) where (insol_given, insol_wanted) = partitionBag isGivenCt insols env = cec_tidy ctxt -- See Note [Suppressing error messages] suppress0 = cec_suppress ctxt suppress1 = suppress0 || not (isEmptyBag insol_given) suppress2 = suppress0 || insolubleWC wanted ctxt1 = ctxt { cec_suppress = suppress1 } ctxt2 = ctxt { cec_suppress = suppress2 } reportSimples :: ReportErrCtxt -> Cts -> TcM () reportSimples ctxt simples -- Here 'simples' includes insolble goals = traceTc "reportSimples" (vcat [ ptext (sLit "Simples =") <+> ppr simples , ptext (sLit "Suppress =") <+> ppr (cec_suppress ctxt)]) >> tryReporters [ -- First deal with things that are utterly wrong -- Like Int ~ Bool (incl nullary TyCons) -- or Int ~ t a (AppTy on one side) ("Utterly wrong", utterly_wrong, True, mkGroupReporter mkEqErr) , ("Holes", is_hole, False, mkHoleReporter mkHoleError) -- Report equalities of form (a~ty). They are usually -- skolem-equalities, and they cause confusing knock-on -- effects in other errors; see test T4093b. , ("Skolem equalities", skolem_eq, True, mkSkolReporter) -- Other equalities; also confusing knock on effects , ("Equalities", is_equality, True, mkGroupReporter mkEqErr) , ("Implicit params", is_ip, False, mkGroupReporter mkIPErr) , ("Irreds", is_irred, False, mkGroupReporter mkIrredErr) , ("Dicts", is_dict, False, mkGroupReporter mkDictErr) ] panicReporter ctxt (bagToList simples) -- TuplePreds should have been expanded away by the constraint -- simplifier, so they shouldn't show up at this point where utterly_wrong, skolem_eq, is_hole, is_dict, is_equality, is_ip, is_irred :: Ct -> PredTree -> Bool utterly_wrong _ (EqPred _ ty1 ty2) = isRigid ty1 && isRigid ty2 utterly_wrong _ _ = False is_hole ct _ = isHoleCt ct skolem_eq _ (EqPred NomEq ty1 ty2) = isRigidOrSkol ty1 && isRigidOrSkol ty2 skolem_eq _ _ = False is_equality _ (EqPred {}) = True is_equality _ _ = False is_dict _ (ClassPred {}) = True is_dict _ _ = False is_ip _ (ClassPred cls _) = isIPClass cls is_ip _ _ = False is_irred _ (IrredPred {}) = True is_irred _ _ = False --------------- isRigid, isRigidOrSkol :: Type -> Bool isRigid ty | Just (tc,_) <- tcSplitTyConApp_maybe ty = isDecomposableTyCon tc | Just {} <- tcSplitAppTy_maybe ty = True | isForAllTy ty = True | otherwise = False isRigidOrSkol ty | Just tv <- getTyVar_maybe ty = isSkolemTyVar tv | otherwise = isRigid ty isTyFun_maybe :: Type -> Maybe TyCon isTyFun_maybe ty = case tcSplitTyConApp_maybe ty of Just (tc,_) | isTypeFamilyTyCon tc -> Just tc _ -> Nothing -------------------------------------------- -- Reporters -------------------------------------------- type Reporter = ReportErrCtxt -> [Ct] -> TcM () type ReporterSpec = ( String -- Name , Ct -> PredTree -> Bool -- Pick these ones , Bool -- True <=> suppress subsequent reporters , Reporter) -- The reporter itself panicReporter :: Reporter panicReporter _ cts | null cts = return () | otherwise = pprPanic "reportSimples" (ppr cts) mkSkolReporter :: Reporter -- Suppress duplicates with the same LHS mkSkolReporter ctxt cts = mapM_ (reportGroup mkEqErr ctxt) (equivClasses cmp_lhs_type cts) where cmp_lhs_type ct1 ct2 = case (classifyPredType (ctPred ct1), classifyPredType (ctPred ct2)) of (EqPred eq_rel1 ty1 _, EqPred eq_rel2 ty2 _) -> (eq_rel1 `compare` eq_rel2) `thenCmp` (ty1 `cmpType` ty2) _ -> pprPanic "mkSkolReporter" (ppr ct1 $$ ppr ct2) mkHoleReporter :: (ReportErrCtxt -> Ct -> TcM ErrMsg) -> Reporter -- Reports errors one at a time mkHoleReporter mk_err ctxt = mapM_ $ \ct -> do { err <- mk_err ctxt ct ; maybeReportHoleError ctxt err ; maybeAddDeferredHoleBinding ctxt err ct } mkGroupReporter :: (ReportErrCtxt -> [Ct] -> TcM ErrMsg) -- Make error message for a group -> Reporter -- Deal with lots of constraints -- Group together errors from same location, -- and report only the first (to avoid a cascade) mkGroupReporter mk_err ctxt cts = mapM_ (reportGroup mk_err ctxt) (equivClasses cmp_loc cts) where cmp_loc ct1 ct2 = ctLocSpan (ctLoc ct1) `compare` ctLocSpan (ctLoc ct2) reportGroup :: (ReportErrCtxt -> [Ct] -> TcM ErrMsg) -> ReportErrCtxt -> [Ct] -> TcM () reportGroup mk_err ctxt cts = do { err <- mk_err ctxt cts ; maybeReportError ctxt err ; mapM_ (maybeAddDeferredBinding ctxt err) cts } -- Add deferred bindings for all -- But see Note [Always warn with -fdefer-type-errors] maybeReportHoleError :: ReportErrCtxt -> ErrMsg -> TcM () maybeReportHoleError ctxt err -- When -XPartialTypeSignatures is on, warnings (instead of errors) are -- generated for holes in partial type signatures. Unless -- -fwarn_partial_type_signatures is not on, in which case the messages are -- discarded. | isWarning err = when (cec_warn_partial_type_signatures ctxt) (reportWarning err) | cec_defer_holes ctxt = when (cec_warn_holes ctxt) (reportWarning (makeIntoWarning err)) | otherwise = reportError err maybeReportError :: ReportErrCtxt -> ErrMsg -> TcM () -- Report the error and/or make a deferred binding for it maybeReportError ctxt err -- See Note [Always warn with -fdefer-type-errors] | cec_defer_type_errors ctxt = reportWarning (makeIntoWarning err) | cec_suppress ctxt = return () | otherwise = reportError err addDeferredBinding :: ReportErrCtxt -> ErrMsg -> Ct -> TcM () -- See Note [Deferring coercion errors to runtime] addDeferredBinding ctxt err ct | CtWanted { ctev_pred = pred, ctev_evar = ev_id } <- ctEvidence ct -- Only add deferred bindings for Wanted constraints , Just ev_binds_var <- cec_binds ctxt -- We have somewhere to put the bindings = do { dflags <- getDynFlags ; let err_msg = pprLocErrMsg err err_fs = mkFastString $ showSDoc dflags $ err_msg $$ text "(deferred type error)" -- Create the binding ; addTcEvBind ev_binds_var ev_id (EvDelayedError pred err_fs) } | otherwise -- Do not set any evidence for Given/Derived = return () maybeAddDeferredHoleBinding :: ReportErrCtxt -> ErrMsg -> Ct -> TcM () maybeAddDeferredHoleBinding ctxt err ct | cec_defer_holes ctxt && isTypedHoleCt ct = addDeferredBinding ctxt err ct | otherwise = return () maybeAddDeferredBinding :: ReportErrCtxt -> ErrMsg -> Ct -> TcM () maybeAddDeferredBinding ctxt err ct | cec_defer_type_errors ctxt = addDeferredBinding ctxt err ct | otherwise = return () tryReporters :: [ReporterSpec] -> Reporter -> Reporter -- Use the first reporter in the list whose predicate says True tryReporters reporters deflt ctxt cts = do { traceTc "tryReporters {" (ppr cts) ; go ctxt reporters cts ; traceTc "tryReporters }" empty } where go ctxt [] cts = deflt ctxt cts go ctxt ((str, pred, suppress_after, reporter) : rs) cts | null yeses = do { traceTc "tryReporters: no" (text str) ; go ctxt rs cts } | otherwise = do { traceTc "tryReporters: yes" (text str <+> ppr yeses) ; reporter ctxt yeses :: TcM () ; let ctxt' = ctxt { cec_suppress = suppress_after || cec_suppress ctxt } ; go ctxt' rs nos } -- Carry on with the rest, because we must make -- deferred bindings for them if we have -- -fdefer-type-errors -- But suppress their error messages where (yeses, nos) = partition keep_me cts keep_me ct = pred ct (classifyPredType (ctPred ct)) -- Add the "arising from..." part to a message about bunch of dicts addArising :: CtOrigin -> SDoc -> SDoc addArising orig msg = hang msg 2 (pprArising orig) pprWithArising :: [Ct] -> (CtLoc, SDoc) -- Print something like -- (Eq a) arising from a use of x at y -- (Show a) arising from a use of p at q -- Also return a location for the error message -- Works for Wanted/Derived only pprWithArising [] = panic "pprWithArising" pprWithArising (ct:cts) | null cts = (loc, addArising (ctLocOrigin loc) (pprTheta [ctPred ct])) | otherwise = (loc, vcat (map ppr_one (ct:cts))) where loc = ctLoc ct ppr_one ct' = hang (parens (pprType (ctPred ct'))) 2 (pprArisingAt (ctLoc ct')) mkErrorMsg :: ReportErrCtxt -> Ct -> SDoc -> TcM ErrMsg mkErrorMsg ctxt ct msg = do { let tcl_env = ctLocEnv (ctLoc ct) ; err_info <- mkErrInfo (cec_tidy ctxt) (tcl_ctxt tcl_env) ; mkLongErrAt (RealSrcSpan (tcl_loc tcl_env)) msg err_info } type UserGiven = ([EvVar], SkolemInfo, Bool, RealSrcSpan) getUserGivens :: ReportErrCtxt -> [UserGiven] -- One item for each enclosing implication getUserGivens (CEC {cec_encl = ctxt}) = reverse $ [ (givens, info, no_eqs, tcl_loc env) | Implic { ic_given = givens, ic_env = env , ic_no_eqs = no_eqs, ic_info = info } <- ctxt , not (null givens) ] {- Note [Always warn with -fdefer-type-errors] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When -fdefer-type-errors is on we warn about *all* type errors, even if cec_suppress is on. This can lead to a lot more warnings than you would get errors without -fdefer-type-errors, but if we suppress any of them you might get a runtime error that wasn't warned about at compile time. This is an easy design choice to change; just flip the order of the first two equations for maybeReportError To be consistent, we should also report multiple warnings from a single location in mkGroupReporter, when -fdefer-type-errors is on. But that is perhaps a bit *over*-consistent! Again, an easy choice to change. Note [Do not report derived but soluble errors] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The wc_simples include Derived constraints that have not been solved, but are not insoluble (in that case they'd be in wc_insols). We do not want to report these as errors: * Superclass constraints. If we have an unsolved [W] Ord a, we'll also have an unsolved [D] Eq a, and we do not want to report that; it's just noise. * Functional dependencies. For givens, consider class C a b | a -> b data T a where MkT :: C a d => [d] -> T a f :: C a b => T a -> F Int f (MkT xs) = length xs Then we get a [D] b~d. But there *is* a legitimate call to f, namely f (MkT [True]) :: T Bool, in which b=d. So we should not reject the program. For wanteds, something similar data T a where MkT :: C Int b => a -> b -> T a g :: C Int c => c -> () f :: T a -> () f (MkT x y) = g x Here we get [G] C Int b, [W] C Int a, hence [D] a~b. But again f (MkT True True) is a legitimate call. (We leave the Deriveds in wc_simple until reportErrors, so that we don't lose derived superclasses between iterations of the solver.) For functional dependencies, here is a real example, stripped off from libraries/utf8-string/Codec/Binary/UTF8/Generic.hs class C a b | a -> b g :: C a b => a -> b -> () f :: C a b => a -> b -> () f xa xb = let loop = g xa in loop xb We will first try to infer a type for loop, and we will succeed: C a b' => b' -> () Subsequently, we will type check (loop xb) and all is good. But, recall that we have to solve a final implication constraint: C a b => (C a b' => .... cts from body of loop .... )) And now we have a problem as we will generate an equality b ~ b' and fail to solve it. ************************************************************************ * * Irreducible predicate errors * * ************************************************************************ -} mkIrredErr :: ReportErrCtxt -> [Ct] -> TcM ErrMsg mkIrredErr ctxt cts = do { (ctxt, binds_msg) <- relevantBindings True ctxt ct1 ; mkErrorMsg ctxt ct1 (msg $$ binds_msg) } where (ct1:_) = cts orig = ctLocOrigin (ctLoc ct1) givens = getUserGivens ctxt msg = couldNotDeduce givens (map ctPred cts, orig) ---------------- mkHoleError :: ReportErrCtxt -> Ct -> TcM ErrMsg mkHoleError ctxt ct@(CHoleCan { cc_occ = occ }) = do { partial_sigs <- xoptM Opt_PartialTypeSignatures ; let tyvars = varSetElems (tyVarsOfCt ct) tyvars_msg = map loc_msg tyvars msg = vcat [ hang (ptext (sLit "Found hole") <+> quotes (ppr occ)) 2 (ptext (sLit "with type:") <+> pprType (ctEvPred (ctEvidence ct))) , ppUnless (null tyvars_msg) (ptext (sLit "Where:") <+> vcat tyvars_msg) , if in_typesig && not partial_sigs then pts_hint else empty ] ; (ctxt, binds_doc) <- relevantBindings False ctxt ct -- The 'False' means "don't filter the bindings; see Trac #8191 ; errMsg <- mkErrorMsg ctxt ct (msg $$ binds_doc) ; if in_typesig && partial_sigs then return $ makeIntoWarning errMsg else return errMsg } where in_typesig = not $ isTypedHoleCt ct pts_hint = ptext (sLit "To use the inferred type, enable PartialTypeSignatures") loc_msg tv = case tcTyVarDetails tv of SkolemTv {} -> quotes (ppr tv) <+> skol_msg MetaTv {} -> quotes (ppr tv) <+> ptext (sLit "is an ambiguous type variable") det -> pprTcTyVarDetails det where skol_msg = pprSkol (getSkolemInfo (cec_encl ctxt) tv) (getSrcLoc tv) mkHoleError _ ct = pprPanic "mkHoleError" (ppr ct) ---------------- mkIPErr :: ReportErrCtxt -> [Ct] -> TcM ErrMsg mkIPErr ctxt cts = do { (ctxt, bind_msg) <- relevantBindings True ctxt ct1 ; mkErrorMsg ctxt ct1 (msg $$ bind_msg) } where (ct1:_) = cts orig = ctLocOrigin (ctLoc ct1) preds = map ctPred cts givens = getUserGivens ctxt msg | null givens = addArising orig $ sep [ ptext (sLit "Unbound implicit parameter") <> plural cts , nest 2 (pprTheta preds) ] | otherwise = couldNotDeduce givens (preds, orig) {- ************************************************************************ * * Equality errors * * ************************************************************************ Note [Inaccessible code] ~~~~~~~~~~~~~~~~~~~~~~~~ Consider data T a where T1 :: T a T2 :: T Bool f :: (a ~ Int) => T a -> Int f T1 = 3 f T2 = 4 -- Unreachable code Here the second equation is unreachable. The original constraint (a~Int) from the signature gets rewritten by the pattern-match to (Bool~Int), so the danger is that we report the error as coming from the *signature* (Trac #7293). So, for Given errors we replace the env (and hence src-loc) on its CtLoc with that from the immediately enclosing implication. -} mkEqErr :: ReportErrCtxt -> [Ct] -> TcM ErrMsg -- Don't have multiple equality errors from the same location -- E.g. (Int,Bool) ~ (Bool,Int) one error will do! mkEqErr ctxt (ct:_) = mkEqErr1 ctxt ct mkEqErr _ [] = panic "mkEqErr" mkEqErr1 :: ReportErrCtxt -> Ct -> TcM ErrMsg -- Wanted constraints only! mkEqErr1 ctxt ct | isGiven ev = do { (ctxt, binds_msg) <- relevantBindings True ctxt ct ; let (given_loc, given_msg) = mk_given (cec_encl ctxt) ; dflags <- getDynFlags ; mkEqErr_help dflags ctxt (given_msg $$ binds_msg) (ct { cc_ev = ev {ctev_loc = given_loc}}) -- Note [Inaccessible code] Nothing ty1 ty2 } | otherwise -- Wanted or derived = do { (ctxt, binds_msg) <- relevantBindings True ctxt ct ; (env1, tidy_orig) <- zonkTidyOrigin (cec_tidy ctxt) (ctLocOrigin loc) ; rdr_env <- getGlobalRdrEnv ; fam_envs <- tcGetFamInstEnvs ; let (is_oriented, wanted_msg) = mk_wanted_extra tidy_orig coercible_msg = case ctEvEqRel ev of NomEq -> empty ReprEq -> mkCoercibleExplanation rdr_env fam_envs ty1 ty2 ; dflags <- getDynFlags ; traceTc "mkEqErr1" (ppr ct $$ pprCtOrigin (ctLocOrigin loc) $$ pprCtOrigin tidy_orig) ; mkEqErr_help dflags (ctxt {cec_tidy = env1}) (wanted_msg $$ coercible_msg $$ binds_msg) ct is_oriented ty1 ty2 } where ev = ctEvidence ct loc = ctEvLoc ev (ty1, ty2) = getEqPredTys (ctEvPred ev) mk_given :: [Implication] -> (CtLoc, SDoc) -- For given constraints we overwrite the env (and hence src-loc) -- with one from the implication. See Note [Inaccessible code] mk_given [] = (loc, empty) mk_given (implic : _) = (setCtLocEnv loc (ic_env implic) , hang (ptext (sLit "Inaccessible code in")) 2 (ppr (ic_info implic))) -- If the types in the error message are the same as the types -- we are unifying, don't add the extra expected/actual message mk_wanted_extra orig@(TypeEqOrigin {}) = mkExpectedActualMsg ty1 ty2 orig mk_wanted_extra (KindEqOrigin cty1 cty2 sub_o) = (Nothing, msg1 $$ msg2) where msg1 = hang (ptext (sLit "When matching types")) 2 (vcat [ ppr cty1 <+> dcolon <+> ppr (typeKind cty1) , ppr cty2 <+> dcolon <+> ppr (typeKind cty2) ]) msg2 = case sub_o of TypeEqOrigin {} -> snd (mkExpectedActualMsg cty1 cty2 sub_o) _ -> empty mk_wanted_extra orig@(FunDepOrigin1 {}) = (Nothing, pprArising orig) mk_wanted_extra orig@(FunDepOrigin2 {}) = (Nothing, pprArising orig) mk_wanted_extra orig@(DerivOriginCoerce _ oty1 oty2) = (Nothing, pprArising orig $+$ mkRoleSigs oty1 oty2) mk_wanted_extra orig@(CoercibleOrigin oty1 oty2) -- if the origin types are the same as the final types, don't -- clutter output with repetitive information | not (oty1 `eqType` ty1 && oty2 `eqType` ty2) && not (oty1 `eqType` ty2 && oty2 `eqType` ty1) = (Nothing, pprArising orig $+$ mkRoleSigs oty1 oty2) | otherwise -- still print role sigs even if types line up = (Nothing, mkRoleSigs oty1 oty2) mk_wanted_extra _ = (Nothing, empty) -- | This function tries to reconstruct why a "Coercible ty1 ty2" constraint -- is left over. mkCoercibleExplanation :: GlobalRdrEnv -> FamInstEnvs -> TcType -> TcType -> SDoc mkCoercibleExplanation rdr_env fam_envs ty1 ty2 | Just (tc, tys) <- tcSplitTyConApp_maybe ty1 , (rep_tc, _, _) <- tcLookupDataFamInst fam_envs tc tys , Just msg <- coercible_msg_for_tycon rep_tc = msg | Just (tc, tys) <- splitTyConApp_maybe ty2 , (rep_tc, _, _) <- tcLookupDataFamInst fam_envs tc tys , Just msg <- coercible_msg_for_tycon rep_tc = msg | Just (s1, _) <- tcSplitAppTy_maybe ty1 , Just (s2, _) <- tcSplitAppTy_maybe ty2 , s1 `eqType` s2 , has_unknown_roles s1 = hang (text "NB: We cannot know what roles the parameters to" <+> quotes (ppr s1) <+> text "have;") 2 (text "we must assume that the role is nominal") | otherwise = empty where coercible_msg_for_tycon tc | isAbstractTyCon tc = Just $ hsep [ text "NB: The type constructor" , quotes (pprSourceTyCon tc) , text "is abstract" ] | isNewTyCon tc , [data_con] <- tyConDataCons tc , let dc_name = dataConName data_con , null (lookupGRE_Name rdr_env dc_name) = Just $ hang (text "The data constructor" <+> quotes (ppr dc_name)) 2 (sep [ text "of newtype" <+> quotes (pprSourceTyCon tc) , text "is not in scope" ]) | otherwise = Nothing has_unknown_roles ty | Just (tc, tys) <- tcSplitTyConApp_maybe ty = length tys >= tyConArity tc -- oversaturated tycon | Just (s, _) <- tcSplitAppTy_maybe ty = has_unknown_roles s | isTyVarTy ty = True | otherwise = False -- | Make a listing of role signatures for all the parameterised tycons -- used in the provided types mkRoleSigs :: Type -> Type -> SDoc mkRoleSigs ty1 ty2 = ppUnless (null role_sigs) $ hang (text "Relevant role signatures:") 2 (vcat role_sigs) where tcs = nameEnvElts $ tyConsOfType ty1 `plusNameEnv` tyConsOfType ty2 role_sigs = mapMaybe ppr_role_sig tcs ppr_role_sig tc | null roles -- if there are no parameters, don't bother printing = Nothing | otherwise = Just $ hsep $ [text "type role", ppr tc] ++ map ppr roles where roles = tyConRoles tc mkEqErr_help :: DynFlags -> ReportErrCtxt -> SDoc -> Ct -> Maybe SwapFlag -- Nothing <=> not sure -> TcType -> TcType -> TcM ErrMsg mkEqErr_help dflags ctxt extra ct oriented ty1 ty2 | Just tv1 <- tcGetTyVar_maybe ty1 = mkTyVarEqErr dflags ctxt extra ct oriented tv1 ty2 | Just tv2 <- tcGetTyVar_maybe ty2 = mkTyVarEqErr dflags ctxt extra ct swapped tv2 ty1 | otherwise = reportEqErr ctxt extra ct oriented ty1 ty2 where swapped = fmap flipSwap oriented reportEqErr :: ReportErrCtxt -> SDoc -> Ct -> Maybe SwapFlag -- Nothing <=> not sure -> TcType -> TcType -> TcM ErrMsg reportEqErr ctxt extra1 ct oriented ty1 ty2 = do { let extra2 = mkEqInfoMsg ct ty1 ty2 ; mkErrorMsg ctxt ct (vcat [ misMatchOrCND ctxt ct oriented ty1 ty2 , extra2, extra1]) } mkTyVarEqErr :: DynFlags -> ReportErrCtxt -> SDoc -> Ct -> Maybe SwapFlag -> TcTyVar -> TcType -> TcM ErrMsg -- tv1 and ty2 are already tidied mkTyVarEqErr dflags ctxt extra ct oriented tv1 ty2 | isUserSkolem ctxt tv1 -- ty2 won't be a meta-tyvar, or else the thing would -- be oriented the other way round; -- see TcCanonical.canEqTyVarTyVar || isSigTyVar tv1 && not (isTyVarTy ty2) || ctEqRel ct == ReprEq && not (isTyVarUnderDatatype tv1 ty2) -- the cases below don't really apply to ReprEq (except occurs check) = mkErrorMsg ctxt ct (vcat [ misMatchOrCND ctxt ct oriented ty1 ty2 , extraTyVarInfo ctxt tv1 ty2 , extra ]) -- So tv is a meta tyvar (or started that way before we -- generalised it). So presumably it is an *untouchable* -- meta tyvar or a SigTv, else it'd have been unified | not (k2 `tcIsSubKind` k1) -- Kind error = mkErrorMsg ctxt ct $ (kindErrorMsg (mkTyVarTy tv1) ty2 $$ extra) | OC_Occurs <- occ_check_expand , ctEqRel ct == NomEq || isTyVarUnderDatatype tv1 ty2 -- See Note [Occurs check error] in TcCanonical = do { let occCheckMsg = hang (text "Occurs check: cannot construct the infinite type:") 2 (sep [ppr ty1, char '~', ppr ty2]) extra2 = mkEqInfoMsg ct ty1 ty2 ; mkErrorMsg ctxt ct (occCheckMsg $$ extra2 $$ extra) } | OC_Forall <- occ_check_expand = do { let msg = vcat [ ptext (sLit "Cannot instantiate unification variable") <+> quotes (ppr tv1) , hang (ptext (sLit "with a type involving foralls:")) 2 (ppr ty2) , nest 2 (ptext (sLit "Perhaps you want ImpredicativeTypes")) ] ; mkErrorMsg ctxt ct msg } -- If the immediately-enclosing implication has 'tv' a skolem, and -- we know by now its an InferSkol kind of skolem, then presumably -- it started life as a SigTv, else it'd have been unified, given -- that there's no occurs-check or forall problem | (implic:_) <- cec_encl ctxt , Implic { ic_skols = skols } <- implic , tv1 `elem` skols = mkErrorMsg ctxt ct (vcat [ misMatchMsg oriented eq_rel ty1 ty2 , extraTyVarInfo ctxt tv1 ty2 , extra ]) -- Check for skolem escape | (implic:_) <- cec_encl ctxt -- Get the innermost context , Implic { ic_env = env, ic_skols = skols, ic_info = skol_info } <- implic , let esc_skols = filter (`elemVarSet` (tyVarsOfType ty2)) skols , not (null esc_skols) = do { let msg = misMatchMsg oriented eq_rel ty1 ty2 esc_doc = sep [ ptext (sLit "because type variable") <> plural esc_skols <+> pprQuotedList esc_skols , ptext (sLit "would escape") <+> if isSingleton esc_skols then ptext (sLit "its scope") else ptext (sLit "their scope") ] tv_extra = vcat [ nest 2 $ esc_doc , sep [ (if isSingleton esc_skols then ptext (sLit "This (rigid, skolem) type variable is") else ptext (sLit "These (rigid, skolem) type variables are")) <+> ptext (sLit "bound by") , nest 2 $ ppr skol_info , nest 2 $ ptext (sLit "at") <+> ppr (tcl_loc env) ] ] ; mkErrorMsg ctxt ct (msg $$ tv_extra $$ extra) } -- Nastiest case: attempt to unify an untouchable variable | (implic:_) <- cec_encl ctxt -- Get the innermost context , Implic { ic_env = env, ic_given = given, ic_info = skol_info } <- implic = do { let msg = misMatchMsg oriented eq_rel ty1 ty2 tclvl_extra = nest 2 $ sep [ quotes (ppr tv1) <+> ptext (sLit "is untouchable") , nest 2 $ ptext (sLit "inside the constraints") <+> pprEvVarTheta given , nest 2 $ ptext (sLit "bound by") <+> ppr skol_info , nest 2 $ ptext (sLit "at") <+> ppr (tcl_loc env) ] tv_extra = extraTyVarInfo ctxt tv1 ty2 add_sig = suggestAddSig ctxt ty1 ty2 ; mkErrorMsg ctxt ct (vcat [msg, tclvl_extra, tv_extra, add_sig, extra]) } | otherwise = reportEqErr ctxt extra ct oriented (mkTyVarTy tv1) ty2 -- This *can* happen (Trac #6123, and test T2627b) -- Consider an ambiguous top-level constraint (a ~ F a) -- Not an occurs check, because F is a type function. where occ_check_expand = occurCheckExpand dflags tv1 ty2 k1 = tyVarKind tv1 k2 = typeKind ty2 ty1 = mkTyVarTy tv1 eq_rel = ctEqRel ct mkEqInfoMsg :: Ct -> TcType -> TcType -> SDoc -- Report (a) ambiguity if either side is a type function application -- e.g. F a0 ~ Int -- (b) warning about injectivity if both sides are the same -- type function application F a ~ F b -- See Note [Non-injective type functions] mkEqInfoMsg ct ty1 ty2 = tyfun_msg $$ ambig_msg where mb_fun1 = isTyFun_maybe ty1 mb_fun2 = isTyFun_maybe ty2 ambig_msg | isJust mb_fun1 || isJust mb_fun2 = snd (mkAmbigMsg ct) | otherwise = empty tyfun_msg | Just tc1 <- mb_fun1 , Just tc2 <- mb_fun2 , tc1 == tc2 = ptext (sLit "NB:") <+> quotes (ppr tc1) <+> ptext (sLit "is a type function, and may not be injective") | otherwise = empty isUserSkolem :: ReportErrCtxt -> TcTyVar -> Bool -- See Note [Reporting occurs-check errors] isUserSkolem ctxt tv = isSkolemTyVar tv && any is_user_skol_tv (cec_encl ctxt) where is_user_skol_tv (Implic { ic_skols = sks, ic_info = skol_info }) = tv `elem` sks && is_user_skol_info skol_info is_user_skol_info (InferSkol {}) = False is_user_skol_info _ = True misMatchOrCND :: ReportErrCtxt -> Ct -> Maybe SwapFlag -> TcType -> TcType -> SDoc -- If oriented then ty1 is actual, ty2 is expected misMatchOrCND ctxt ct oriented ty1 ty2 | null givens || (isRigid ty1 && isRigid ty2) || isGivenCt ct -- If the equality is unconditionally insoluble -- or there is no context, don't report the context = misMatchMsg oriented eq_rel ty1 ty2 | otherwise = couldNotDeduce givens ([eq_pred], orig) where eq_rel = ctEqRel ct givens = [ given | given@(_, _, no_eqs, _) <- getUserGivens ctxt, not no_eqs] -- Keep only UserGivens that have some equalities (eq_pred, orig) = case eq_rel of NomEq -> ( mkTcEqPred ty1 ty2 , TypeEqOrigin { uo_actual = ty1, uo_expected = ty2 }) ReprEq -> ( mkCoerciblePred ty1 ty2 , CoercibleOrigin ty1 ty2 ) couldNotDeduce :: [UserGiven] -> (ThetaType, CtOrigin) -> SDoc couldNotDeduce givens (wanteds, orig) = vcat [ addArising orig (ptext (sLit "Could not deduce") <+> pprTheta wanteds) , vcat (pp_givens givens)] pp_givens :: [UserGiven] -> [SDoc] pp_givens givens = case givens of [] -> [] (g:gs) -> ppr_given (ptext (sLit "from the context")) g : map (ppr_given (ptext (sLit "or from"))) gs where ppr_given herald (gs, skol_info, _, loc) = hang (herald <+> pprEvVarTheta gs) 2 (sep [ ptext (sLit "bound by") <+> ppr skol_info , ptext (sLit "at") <+> ppr loc]) extraTyVarInfo :: ReportErrCtxt -> TcTyVar -> TcType -> SDoc -- Add on extra info about skolem constants -- NB: The types themselves are already tidied extraTyVarInfo ctxt tv1 ty2 = nest 2 (tv_extra tv1 $$ ty_extra ty2) where implics = cec_encl ctxt ty_extra ty = case tcGetTyVar_maybe ty of Just tv -> tv_extra tv Nothing -> empty tv_extra tv | isTcTyVar tv, isSkolemTyVar tv , let pp_tv = quotes (ppr tv) = case tcTyVarDetails tv of SkolemTv {} -> pp_tv <+> pprSkol (getSkolemInfo implics tv) (getSrcLoc tv) FlatSkol {} -> pp_tv <+> ptext (sLit "is a flattening type variable") RuntimeUnk {} -> pp_tv <+> ptext (sLit "is an interactive-debugger skolem") MetaTv {} -> empty | otherwise -- Normal case = empty suggestAddSig :: ReportErrCtxt -> TcType -> TcType -> SDoc -- See Note [Suggest adding a type signature] suggestAddSig ctxt ty1 ty2 | null inferred_bndrs = empty | [bndr] <- inferred_bndrs = ptext (sLit "Possible fix: add a type signature for") <+> quotes (ppr bndr) | otherwise = ptext (sLit "Possible fix: add type signatures for some or all of") <+> (ppr inferred_bndrs) where inferred_bndrs = nub (get_inf ty1 ++ get_inf ty2) get_inf ty | Just tv <- tcGetTyVar_maybe ty , isTcTyVar tv, isSkolemTyVar tv , InferSkol prs <- getSkolemInfo (cec_encl ctxt) tv = map fst prs | otherwise = [] kindErrorMsg :: TcType -> TcType -> SDoc -- Types are already tidy kindErrorMsg ty1 ty2 = vcat [ ptext (sLit "Kind incompatibility when matching types:") , nest 2 (vcat [ ppr ty1 <+> dcolon <+> ppr k1 , ppr ty2 <+> dcolon <+> ppr k2 ]) ] where k1 = typeKind ty1 k2 = typeKind ty2 -------------------- misMatchMsg :: Maybe SwapFlag -> EqRel -> TcType -> TcType -> SDoc -- Types are already tidy -- If oriented then ty1 is actual, ty2 is expected misMatchMsg oriented eq_rel ty1 ty2 | Just IsSwapped <- oriented = misMatchMsg (Just NotSwapped) eq_rel ty2 ty1 | Just NotSwapped <- oriented = sep [ text "Couldn't match" <+> repr1 <+> text "expected" <+> what <+> quotes (ppr ty2) , nest (12 + extra_space) $ text "with" <+> repr2 <+> text "actual" <+> what <+> quotes (ppr ty1) , sameOccExtra ty2 ty1 ] | otherwise = sep [ text "Couldn't match" <+> repr1 <+> what <+> quotes (ppr ty1) , nest (15 + extra_space) $ text "with" <+> repr2 <+> quotes (ppr ty2) , sameOccExtra ty1 ty2 ] where what | isKind ty1 = ptext (sLit "kind") | otherwise = ptext (sLit "type") (repr1, repr2, extra_space) = case eq_rel of NomEq -> (empty, empty, 0) ReprEq -> (text "representation of", text "that of", 10) mkExpectedActualMsg :: Type -> Type -> CtOrigin -> (Maybe SwapFlag, SDoc) -- NotSwapped means (actual, expected), IsSwapped is the reverse mkExpectedActualMsg ty1 ty2 (TypeEqOrigin { uo_actual = act, uo_expected = exp }) | act `pickyEqType` ty1, exp `pickyEqType` ty2 = (Just NotSwapped, empty) | exp `pickyEqType` ty1, act `pickyEqType` ty2 = (Just IsSwapped, empty) | otherwise = (Nothing, msg) where msg = vcat [ text "Expected type:" <+> ppr exp , text " Actual type:" <+> ppr act ] mkExpectedActualMsg _ _ _ = panic "mkExprectedAcutalMsg" sameOccExtra :: TcType -> TcType -> SDoc -- See Note [Disambiguating (X ~ X) errors] sameOccExtra ty1 ty2 | Just (tc1, _) <- tcSplitTyConApp_maybe ty1 , Just (tc2, _) <- tcSplitTyConApp_maybe ty2 , let n1 = tyConName tc1 n2 = tyConName tc2 same_occ = nameOccName n1 == nameOccName n2 same_pkg = modulePackageKey (nameModule n1) == modulePackageKey (nameModule n2) , n1 /= n2 -- Different Names , same_occ -- but same OccName = ptext (sLit "NB:") <+> (ppr_from same_pkg n1 $$ ppr_from same_pkg n2) | otherwise = empty where ppr_from same_pkg nm | isGoodSrcSpan loc = hang (quotes (ppr nm) <+> ptext (sLit "is defined at")) 2 (ppr loc) | otherwise -- Imported things have an UnhelpfulSrcSpan = hang (quotes (ppr nm)) 2 (sep [ ptext (sLit "is defined in") <+> quotes (ppr (moduleName mod)) , ppUnless (same_pkg || pkg == mainPackageKey) $ nest 4 $ ptext (sLit "in package") <+> quotes (ppr pkg) ]) where pkg = modulePackageKey mod mod = nameModule nm loc = nameSrcSpan nm {- Note [Suggest adding a type signature] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The OutsideIn algorithm rejects GADT programs that don't have a principal type, and indeed some that do. Example: data T a where MkT :: Int -> T Int f (MkT n) = n Does this have type f :: T a -> a, or f :: T a -> Int? The error that shows up tends to be an attempt to unify an untouchable type variable. So suggestAddSig sees if the offending type variable is bound by an *inferred* signature, and suggests adding a declared signature instead. This initially came up in Trac #8968, concerning pattern synonyms. Note [Disambiguating (X ~ X) errors] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ See Trac #8278 Note [Reporting occurs-check errors] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Given (a ~ [a]), if 'a' is a rigid type variable bound by a user-supplied type signature, then the best thing is to report that we can't unify a with [a], because a is a skolem variable. That avoids the confusing "occur-check" error message. But nowadays when inferring the type of a function with no type signature, even if there are errors inside, we still generalise its signature and carry on. For example f x = x:x Here we will infer somethiing like f :: forall a. a -> [a] with a suspended error of (a ~ [a]). So 'a' is now a skolem, but not one bound by the programmer! Here we really should report an occurs check. So isUserSkolem distinguishes the two. Note [Non-injective type functions] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ It's very confusing to get a message like Couldn't match expected type `Depend s' against inferred type `Depend s1' so mkTyFunInfoMsg adds: NB: `Depend' is type function, and hence may not be injective Warn of loopy local equalities that were dropped. ************************************************************************ * * Type-class errors * * ************************************************************************ -} mkDictErr :: ReportErrCtxt -> [Ct] -> TcM ErrMsg mkDictErr ctxt cts = --ASSERT( not (null cts) ) do { inst_envs <- tcGetInstEnvs ; let (ct1:_) = cts -- ct1 just for its location min_cts = elim_superclasses cts ; lookups <- mapM (lookup_cls_inst inst_envs) min_cts ; let (no_inst_cts, overlap_cts) = partition is_no_inst lookups -- Report definite no-instance errors, -- or (iff there are none) overlap errors -- But we report only one of them (hence 'head') because they all -- have the same source-location origin, to try avoid a cascade -- of error from one location ; (ctxt, err) <- mk_dict_err ctxt (head (no_inst_cts ++ overlap_cts)) ; mkErrorMsg ctxt ct1 err } where no_givens = null (getUserGivens ctxt) is_no_inst (ct, (matches, unifiers, _)) = no_givens && null matches && (null unifiers || all (not . isAmbiguousTyVar) (varSetElems (tyVarsOfCt ct))) lookup_cls_inst inst_envs ct = do { tys_flat <- mapM quickFlattenTy tys -- Note [Flattening in error message generation] ; return (ct, lookupInstEnv inst_envs clas tys_flat) } where (clas, tys) = getClassPredTys (ctPred ct) -- When simplifying [W] Ord (Set a), we need -- [W] Eq a, [W] Ord a -- but we really only want to report the latter elim_superclasses cts = filter (\ct -> any (eqPred (ctPred ct)) min_preds) cts where min_preds = mkMinimalBySCs (map ctPred cts) mk_dict_err :: ReportErrCtxt -> (Ct, ClsInstLookupResult) -> TcM (ReportErrCtxt, SDoc) -- Report an overlap error if this class constraint results -- from an overlap (returning Left clas), otherwise return (Right pred) mk_dict_err ctxt (ct, (matches, unifiers, safe_haskell)) | null matches -- No matches but perhaps several unifiers = do { let (is_ambig, ambig_msg) = mkAmbigMsg ct ; (ctxt, binds_msg) <- relevantBindings True ctxt ct ; traceTc "mk_dict_err" (ppr ct $$ ppr is_ambig $$ ambig_msg) ; return (ctxt, cannot_resolve_msg is_ambig binds_msg ambig_msg) } | not safe_haskell -- Some matches => overlap errors = return (ctxt, overlap_msg) | otherwise = return (ctxt, safe_haskell_msg) where orig = ctLocOrigin (ctLoc ct) pred = ctPred ct (clas, tys) = getClassPredTys pred ispecs = [ispec | (ispec, _) <- matches] givens = getUserGivens ctxt all_tyvars = all isTyVarTy tys cannot_resolve_msg has_ambig_tvs binds_msg ambig_msg = vcat [ addArising orig no_inst_msg , vcat (pp_givens givens) , ppWhen (has_ambig_tvs && not (null unifiers && null givens)) (vcat [ ambig_msg, binds_msg, potential_msg ]) , show_fixes (add_to_ctxt_fixes has_ambig_tvs ++ drv_fixes) ] potential_msg = ppWhen (not (null unifiers) && want_potential orig) $ hang (if isSingleton unifiers then ptext (sLit "Note: there is a potential instance available:") else ptext (sLit "Note: there are several potential instances:")) 2 (ppr_insts (sortBy fuzzyClsInstCmp unifiers)) -- Report "potential instances" only when the constraint arises -- directly from the user's use of an overloaded function want_potential (TypeEqOrigin {}) = False want_potential _ = True add_to_ctxt_fixes has_ambig_tvs | not has_ambig_tvs && all_tyvars , (orig:origs) <- usefulContext ctxt pred = [sep [ ptext (sLit "add") <+> pprParendType pred <+> ptext (sLit "to the context of") , nest 2 $ ppr_skol orig $$ vcat [ ptext (sLit "or") <+> ppr_skol orig | orig <- origs ] ] ] | otherwise = [] ppr_skol (PatSkol dc _) = ptext (sLit "the data constructor") <+> quotes (ppr dc) ppr_skol skol_info = ppr skol_info no_inst_msg | null givens && null matches = ptext (sLit "No instance for") <+> pprParendType pred $$ if type_has_arrow pred then nest 2 $ ptext (sLit "(maybe you haven't applied enough arguments to a function?)") else empty | otherwise = ptext (sLit "Could not deduce") <+> pprParendType pred type_has_arrow (TyVarTy _) = False type_has_arrow (AppTy t1 t2) = type_has_arrow t1 || type_has_arrow t2 type_has_arrow (TyConApp _ ts) = or $ map type_has_arrow ts type_has_arrow (FunTy _ _) = True type_has_arrow (ForAllTy _ t) = type_has_arrow t type_has_arrow (LitTy _) = False drv_fixes = case orig of DerivOrigin -> [drv_fix] DerivOriginDC {} -> [drv_fix] DerivOriginCoerce {} -> [drv_fix] _ -> [] drv_fix = hang (ptext (sLit "use a standalone 'deriving instance' declaration,")) 2 (ptext (sLit "so you can specify the instance context yourself")) -- Normal overlap error overlap_msg = --ASSERT( not (null matches) ) vcat [ addArising orig (ptext (sLit "Overlapping instances for") <+> pprType (mkClassPred clas tys)) , ppUnless (null matching_givens) $ sep [ptext (sLit "Matching givens (or their superclasses):") , nest 2 (vcat matching_givens)] , sep [ptext (sLit "Matching instances:"), nest 2 (vcat [pprInstances ispecs, pprInstances unifiers])] , ppWhen (null matching_givens && isSingleton matches && null unifiers) $ -- Intuitively, some given matched the wanted in their -- flattened or rewritten (from given equalities) form -- but the matcher can't figure that out because the -- constraints are non-flat and non-rewritten so we -- simply report back the whole given -- context. Accelerate Smart.hs showed this problem. sep [ ptext (sLit "There exists a (perhaps superclass) match:") , nest 2 (vcat (pp_givens givens))] , ppWhen (isSingleton matches) $ parens (vcat [ ptext (sLit "The choice depends on the instantiation of") <+> quotes (pprWithCommas ppr (varSetElems (tyVarsOfTypes tys))) , ppWhen (null (matching_givens)) $ vcat [ ptext (sLit "To pick the first instance above, use IncoherentInstances") , ptext (sLit "when compiling the other instance declarations")] ])] where ispecs = [ispec | (ispec, _) <- matches] givens = getUserGivens ctxt matching_givens = mapMaybe matchable givens matchable (evvars,skol_info,_,loc) = case ev_vars_matching of [] -> Nothing _ -> Just $ hang (pprTheta ev_vars_matching) 2 (sep [ ptext (sLit "bound by") <+> ppr skol_info , ptext (sLit "at") <+> ppr loc]) where ev_vars_matching = filter ev_var_matches (map evVarPred evvars) ev_var_matches ty = case getClassPredTys_maybe ty of Just (clas', tys') | clas' == clas , Just _ <- tcMatchTys (tyVarsOfTypes tys) tys tys' -> True | otherwise -> any ev_var_matches (immSuperClasses clas' tys') Nothing -> False -- Overlap error because of Safe Haskell (first -- match should be the most specific match) safe_haskell_msg = --ASSERT( length matches > 1 ) vcat [ addArising orig (ptext (sLit "Unsafe overlapping instances for") <+> pprType (mkClassPred clas tys)) , sep [ptext (sLit "The matching instance is:"), nest 2 (pprInstance $ head ispecs)] , vcat [ ptext $ sLit "It is compiled in a Safe module and as such can only" , ptext $ sLit "overlap instances from the same module, however it" , ptext $ sLit "overlaps the following instances from different modules:" , nest 2 (vcat [pprInstances $ tail ispecs]) ] ] usefulContext :: ReportErrCtxt -> TcPredType -> [SkolemInfo] usefulContext ctxt pred = go (cec_encl ctxt) where pred_tvs = tyVarsOfType pred go [] = [] go (ic : ics) = case ic_info ic of -- Do not suggest adding constraints to an *inferred* type signature! SigSkol (InfSigCtxt {}) _ -> rest info -> info : rest where -- Stop when the context binds a variable free in the predicate rest | any (`elemVarSet` pred_tvs) (ic_skols ic) = [] | otherwise = go ics show_fixes :: [SDoc] -> SDoc show_fixes [] = empty show_fixes (f:fs) = sep [ ptext (sLit "Possible fix:") , nest 2 (vcat (f : map (ptext (sLit "or") <+>) fs))] ppr_insts :: [ClsInst] -> SDoc ppr_insts insts = pprInstances (take 3 insts) $$ dot_dot_message where n_extra = length insts - 3 dot_dot_message | n_extra <= 0 = empty | otherwise = ptext (sLit "...plus") <+> speakNOf n_extra (ptext (sLit "other")) ---------------------- quickFlattenTy :: TcType -> TcM TcType -- See Note [Flattening in error message generation] quickFlattenTy ty | Just ty' <- tcView ty = quickFlattenTy ty' quickFlattenTy ty@(TyVarTy {}) = return ty quickFlattenTy ty@(ForAllTy {}) = return ty -- See quickFlattenTy ty@(LitTy {}) = return ty -- Don't flatten because of the danger or removing a bound variable quickFlattenTy (AppTy ty1 ty2) = do { fy1 <- quickFlattenTy ty1 ; fy2 <- quickFlattenTy ty2 ; return (AppTy fy1 fy2) } quickFlattenTy (FunTy ty1 ty2) = do { fy1 <- quickFlattenTy ty1 ; fy2 <- quickFlattenTy ty2 ; return (FunTy fy1 fy2) } quickFlattenTy (TyConApp tc tys) | not (isTypeFamilyTyCon tc) = do { fys <- mapM quickFlattenTy tys ; return (TyConApp tc fys) } | otherwise = do { let (funtys,resttys) = splitAt (tyConArity tc) tys -- Ignore the arguments of the type family funtys ; v <- newMetaTyVar (TauTv False) (typeKind (TyConApp tc funtys)) ; flat_resttys <- mapM quickFlattenTy resttys ; return (foldl AppTy (mkTyVarTy v) flat_resttys) } {- Note [Flattening in error message generation] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider (C (Maybe (F x))), where F is a type function, and we have instances C (Maybe Int) and C (Maybe a) Since (F x) might turn into Int, this is an overlap situation, and indeed (because of flattening) the main solver will have refrained from solving. But by the time we get to error message generation, we've un-flattened the constraint. So we must *re*-flatten it before looking up in the instance environment, lest we only report one matching instance when in fact there are two. Re-flattening is pretty easy, because we don't need to keep track of evidence. We don't re-use the code in TcCanonical because that's in the TcS monad, and we are in TcM here. Note [Quick-flatten polytypes] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If we see C (Ix a => blah) or C (forall a. blah) we simply refrain from flattening any further. After all, there can be no instance declarations that match such things. And flattening under a for-all is problematic anyway; consider C (forall a. F a) Note [Suggest -fprint-explicit-kinds] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ It can be terribly confusing to get an error message like (Trac #9171) Couldn't match expected type ‘GetParam Base (GetParam Base Int)’ with actual type ‘GetParam Base (GetParam Base Int)’ The reason may be that the kinds don't match up. Typically you'll get more useful information, but not when it's as a result of ambiguity. This test suggests -fprint-explicit-kinds when all the ambiguous type variables are kind variables. -} mkAmbigMsg :: Ct -> (Bool, SDoc) mkAmbigMsg ct | null ambig_tkvs = (False, empty) | otherwise = (True, msg) where ambig_tkv_set = filterVarSet isAmbiguousTyVar (tyVarsOfCt ct) ambig_tkvs = varSetElems ambig_tkv_set (ambig_kvs, ambig_tvs) = partition isKindVar ambig_tkvs msg | any isRuntimeUnkSkol ambig_tkvs -- See Note [Runtime skolems] = vcat [ ptext (sLit "Cannot resolve unknown runtime type") <> plural ambig_tvs <+> pprQuotedList ambig_tvs , ptext (sLit "Use :print or :force to determine these types")] | not (null ambig_tvs) = pp_ambig (ptext (sLit "type")) ambig_tvs | otherwise -- All ambiguous kind variabes; suggest -fprint-explicit-kinds = vcat [ pp_ambig (ptext (sLit "kind")) ambig_kvs , sdocWithDynFlags suggest_explicit_kinds ] pp_ambig what tkvs = ptext (sLit "The") <+> what <+> ptext (sLit "variable") <> plural tkvs <+> pprQuotedList tkvs <+> is_or_are tkvs <+> ptext (sLit "ambiguous") is_or_are [_] = text "is" is_or_are _ = text "are" suggest_explicit_kinds dflags -- See Note [Suggest -fprint-explicit-kinds] | gopt Opt_PrintExplicitKinds dflags = empty | otherwise = ptext (sLit "Use -fprint-explicit-kinds to see the kind arguments") pprSkol :: SkolemInfo -> SrcLoc -> SDoc pprSkol UnkSkol _ = ptext (sLit "is an unknown type variable") pprSkol skol_info tv_loc = sep [ ptext (sLit "is a rigid type variable bound by"), sep [ppr skol_info, ptext (sLit "at") <+> ppr tv_loc]] getSkolemInfo :: [Implication] -> TcTyVar -> SkolemInfo -- Get the skolem info for a type variable -- from the implication constraint that binds it getSkolemInfo [] tv = pprPanic "No skolem info:" (ppr tv) getSkolemInfo (implic:implics) tv | tv `elem` ic_skols implic = ic_info implic | otherwise = getSkolemInfo implics tv ----------------------- -- relevantBindings looks at the value environment and finds values whose -- types mention any of the offending type variables. It has to be -- careful to zonk the Id's type first, so it has to be in the monad. -- We must be careful to pass it a zonked type variable, too. -- -- We always remove closed top-level bindings, though, -- since they are never relevant (cf Trac #8233) relevantBindings :: Bool -- True <=> filter by tyvar; False <=> no filtering -- See Trac #8191 -> ReportErrCtxt -> Ct -> TcM (ReportErrCtxt, SDoc) relevantBindings want_filtering ctxt ct = do { dflags <- getDynFlags ; (tidy_env', docs, discards) <- go (cec_tidy ctxt) (maxRelevantBinds dflags) emptyVarSet [] False (tcl_bndrs lcl_env) -- tcl_bndrs has the innermost bindings first, -- which are probably the most relevant ones ; traceTc "relevantBindings" (ppr ct $$ ppr [id | TcIdBndr id _ <- tcl_bndrs lcl_env]) ; let doc = hang (ptext (sLit "Relevant bindings include")) 2 (vcat docs $$ max_msg) max_msg | discards = ptext (sLit "(Some bindings suppressed; use -fmax-relevant-binds=N or -fno-max-relevant-binds)") | otherwise = empty ; if null docs then return (ctxt, empty) else do { traceTc "rb" doc ; return (ctxt { cec_tidy = tidy_env' }, doc) } } where loc = ctLoc ct lcl_env = ctLocEnv loc ct_tvs = tyVarsOfCt ct `unionVarSet` extra_tvs -- For *kind* errors, report the relevant bindings of the -- enclosing *type* equality, because that's more useful for the programmer extra_tvs = case ctLocOrigin loc of KindEqOrigin t1 t2 _ -> tyVarsOfTypes [t1,t2] _ -> emptyVarSet run_out :: Maybe Int -> Bool run_out Nothing = False run_out (Just n) = n <= 0 dec_max :: Maybe Int -> Maybe Int dec_max = fmap (\n -> n - 1) go :: TidyEnv -> Maybe Int -> TcTyVarSet -> [SDoc] -> Bool -- True <=> some filtered out due to lack of fuel -> [TcIdBinder] -> TcM (TidyEnv, [SDoc], Bool) -- The bool says if we filtered any out -- because of lack of fuel go tidy_env _ _ docs discards [] = return (tidy_env, reverse docs, discards) go tidy_env n_left tvs_seen docs discards (TcIdBndr id top_lvl : tc_bndrs) = do { (tidy_env', tidy_ty) <- zonkTidyTcType tidy_env (idType id) ; traceTc "relevantBindings 1" (ppr id <+> dcolon <+> ppr tidy_ty) ; let id_tvs = tyVarsOfType tidy_ty doc = sep [ pprPrefixOcc id <+> dcolon <+> ppr tidy_ty , nest 2 (parens (ptext (sLit "bound at") <+> ppr (getSrcLoc id)))] new_seen = tvs_seen `unionVarSet` id_tvs ; if (want_filtering && not opt_PprStyle_Debug && id_tvs `disjointVarSet` ct_tvs) -- We want to filter out this binding anyway -- so discard it silently then go tidy_env n_left tvs_seen docs discards tc_bndrs else if isTopLevel top_lvl && not (isNothing n_left) -- It's a top-level binding and we have not specified -- -fno-max-relevant-bindings, so discard it silently then go tidy_env n_left tvs_seen docs discards tc_bndrs else if run_out n_left && id_tvs `subVarSet` tvs_seen -- We've run out of n_left fuel and this binding only -- mentions aleady-seen type variables, so discard it then go tidy_env n_left tvs_seen docs True tc_bndrs -- Keep this binding, decrement fuel else go tidy_env' (dec_max n_left) new_seen (doc:docs) discards tc_bndrs } ----------------------- warnDefaulting :: Cts -> Type -> TcM () warnDefaulting wanteds default_ty = do { warn_default <- woptM Opt_WarnTypeDefaults ; env0 <- tcInitTidyEnv ; let tidy_env = tidyFreeTyVars env0 $ tyVarsOfCts wanteds tidy_wanteds = mapBag (tidyCt tidy_env) wanteds (loc, ppr_wanteds) = pprWithArising (bagToList tidy_wanteds) warn_msg = hang (ptext (sLit "Defaulting the following constraint(s) to type") <+> quotes (ppr default_ty)) 2 ppr_wanteds ; setCtLoc loc $ warnTc warn_default warn_msg } {- Note [Runtime skolems] ~~~~~~~~~~~~~~~~~~~~~~ We want to give a reasonably helpful error message for ambiguity arising from *runtime* skolems in the debugger. These are created by in RtClosureInspect.zonkRTTIType. ************************************************************************ * * Error from the canonicaliser These ones are called *during* constraint simplification * * ************************************************************************ -} solverDepthErrorTcS :: SubGoalCounter -> CtEvidence -> TcM a solverDepthErrorTcS cnt ev = setCtLoc loc $ do { pred <- zonkTcType (ctEvPred ev) ; env0 <- tcInitTidyEnv ; let tidy_env = tidyFreeTyVars env0 (tyVarsOfType pred) tidy_pred = tidyType tidy_env pred ; failWithTcM (tidy_env, hang (msg cnt) 2 (ppr tidy_pred)) } where loc = ctEvLoc ev depth = ctLocDepth loc value = subGoalCounterValue cnt depth msg CountConstraints = vcat [ ptext (sLit "Context reduction stack overflow; size =") <+> int value , ptext (sLit "Use -fcontext-stack=N to increase stack size to N") ] msg CountTyFunApps = vcat [ ptext (sLit "Type function application stack overflow; size =") <+> int value , ptext (sLit "Use -ftype-function-depth=N to increase stack size to N") ]
alexander-at-github/eta
compiler/ETA/TypeCheck/TcErrors.hs
bsd-3-clause
68,130
164
21
20,557
13,705
7,112
6,593
956
15
{-# LANGUAGE TypeFamilies, UndecidableInstances #-} module PrioritySync.Internal.Schedule (Schedule(..)) where import PrioritySync.Internal.UserData import PrioritySync.Internal.Room import PrioritySync.Internal.Queue import PrioritySync.Internal.ClaimContext import PrioritySync.Internal.RoomGroup import Control.Concurrent.STM import Control.Monad import Data.List -- | Schedule a task to run from a prioritized 'Queue'. The task will wait until it arrives at (or, with failover, near) the top of queue. Typical usage: -- -- > Schedule q 2 room1 -- -- Only the rooms inside the 'Schedule' declaration are claimed with scheduling. If access to a room doesn't need to be prioritized, it can be set outside -- the schedule: -- -- > (Schedule q 2 room1,room2) -- data Schedule p c = Schedule (Queue p) p c type instance UserData (Schedule p c) = UserData c instance (RoomGroup c) => RoomGroup (Schedule p c) where roomsOf (Schedule _ _ c) = roomsOf c instance (Ord p,RoomGroup c,ClaimContext c,ClaimHandle c ~ ()) => ClaimContext (Schedule p c) where type ClaimHandle (Schedule p c) = Maybe (TaskHandle p) approveClaimsEntering = scheduleClaims approveClaimsEntering approveClaimsExiting = scheduleClaims approveClaimsExiting waitingAction (Schedule _ _ c) Nothing = waitingAction c () waitingAction (Schedule _ _ c) (Just task) = flip unless retry . or =<< mapM (\m -> m >> return True `orElse` return False) [pullFromTop task >> return (), waitingAction c ()] scheduleClaims :: (Ord p,RoomGroup c,ClaimContext c,ClaimHandle c ~ ()) => (c -> [Claim (UserData c)] -> STM ()) -> Schedule p c -> [Claim (UserData c)] -> STM (Maybe (TaskHandle p)) scheduleClaims approveClaimsX (Schedule _ _ c) cs | null (intersect (map claimedRoom cs) $ roomsOf c) = approveClaimsX c cs >> return Nothing scheduleClaims approveClaimsX (Schedule q p c) cs = liftM Just $ putTask q p (approveClaimsX c cs)
clanehin/priority-sync
PrioritySync/Internal/Schedule.hs
bsd-3-clause
1,942
0
13
338
591
307
284
26
1
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE CPP , NoImplicitPrelude , RecordWildCards , NondecreasingIndentation #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} ----------------------------------------------------------------------------- -- | -- Module : GHC.IO.Handle -- Copyright : (c) The University of Glasgow, 1994-2009 -- License : see libraries/base/LICENSE -- -- Maintainer : [email protected] -- Stability : provisional -- Portability : non-portable -- -- External API for GHC's Handle implementation -- ----------------------------------------------------------------------------- module GHC.IO.Handle ( Handle, BufferMode(..), mkFileHandle, mkDuplexHandle, hFileSize, hSetFileSize, hIsEOF, hLookAhead, hSetBuffering, hSetBinaryMode, hSetEncoding, hGetEncoding, hFlush, hFlushAll, hDuplicate, hDuplicateTo, hClose, hClose_help, HandlePosition, HandlePosn(..), hGetPosn, hSetPosn, SeekMode(..), hSeek, hTell, hIsOpen, hIsClosed, hIsReadable, hIsWritable, hGetBuffering, hIsSeekable, hSetEcho, hGetEcho, hIsTerminalDevice, hSetNewlineMode, Newline(..), NewlineMode(..), nativeNewline, noNewlineTranslation, universalNewlineMode, nativeNewlineMode, hShow, hWaitForInput, hGetChar, hGetLine, hGetContents, hPutChar, hPutStr, hGetBuf, hGetBufNonBlocking, hPutBuf, hPutBufNonBlocking ) where import GHC.IO import GHC.IO.Exception import GHC.IO.Encoding import GHC.IO.Buffer import GHC.IO.BufferedIO ( BufferedIO ) import GHC.IO.Device as IODevice import GHC.IO.Handle.Types import GHC.IO.Handle.Internals import GHC.IO.Handle.Text import qualified GHC.IO.BufferedIO as Buffered import GHC.Base import {-# SOURCE #-} GHC.Exception import GHC.MVar import GHC.IORef import GHC.Show import GHC.Num import GHC.Real import Data.Maybe import Data.Typeable -- --------------------------------------------------------------------------- -- Closing a handle -- | Computation 'hClose' @hdl@ makes handle @hdl@ closed. Before the -- computation finishes, if @hdl@ is writable its buffer is flushed as -- for 'hFlush'. -- Performing 'hClose' on a handle that has already been closed has no effect; -- doing so is not an error. All other operations on a closed handle will fail. -- If 'hClose' fails for any reason, any further operations (apart from -- 'hClose') on the handle will still fail as if @hdl@ had been successfully -- closed. hClose :: Handle -> IO () hClose h@(FileHandle _ m) = do mb_exc <- hClose' h m hClose_maybethrow mb_exc h hClose h@(DuplexHandle _ r w) = do excs <- mapM (hClose' h) [r,w] hClose_maybethrow (listToMaybe (catMaybes excs)) h hClose_maybethrow :: Maybe SomeException -> Handle -> IO () hClose_maybethrow Nothing h = return () hClose_maybethrow (Just e) h = hClose_rethrow e h hClose_rethrow :: SomeException -> Handle -> IO () hClose_rethrow e h = case fromException e of Just ioe -> ioError (augmentIOError ioe "hClose" h) Nothing -> throwIO e hClose' :: Handle -> MVar Handle__ -> IO (Maybe SomeException) hClose' h m = withHandle' "hClose" h m $ hClose_help ----------------------------------------------------------------------------- -- Detecting and changing the size of a file -- | For a handle @hdl@ which attached to a physical file, -- 'hFileSize' @hdl@ returns the size of that file in 8-bit bytes. hFileSize :: Handle -> IO Integer hFileSize handle = withHandle_ "hFileSize" handle $ \ handle_@Handle__{haDevice=dev} -> do case haType handle_ of ClosedHandle -> ioe_closedHandle SemiClosedHandle -> ioe_closedHandle _ -> do flushWriteBuffer handle_ r <- IODevice.getSize dev if r /= -1 then return r else ioException (IOError Nothing InappropriateType "hFileSize" "not a regular file" Nothing Nothing) -- | 'hSetFileSize' @hdl@ @size@ truncates the physical file with handle @hdl@ to @size@ bytes. hSetFileSize :: Handle -> Integer -> IO () hSetFileSize handle size = withHandle_ "hSetFileSize" handle $ \ handle_@Handle__{haDevice=dev} -> do case haType handle_ of ClosedHandle -> ioe_closedHandle SemiClosedHandle -> ioe_closedHandle _ -> do flushWriteBuffer handle_ IODevice.setSize dev size return () -- --------------------------------------------------------------------------- -- Detecting the End of Input -- | For a readable handle @hdl@, 'hIsEOF' @hdl@ returns -- 'True' if no further input can be taken from @hdl@ or for a -- physical file, if the current I\/O position is equal to the length of -- the file. Otherwise, it returns 'False'. -- -- NOTE: 'hIsEOF' may block, because it has to attempt to read from -- the stream to determine whether there is any more data to be read. hIsEOF :: Handle -> IO Bool hIsEOF handle = wantReadableHandle_ "hIsEOF" handle $ \Handle__{..} -> do cbuf <- readIORef haCharBuffer if not (isEmptyBuffer cbuf) then return False else do bbuf <- readIORef haByteBuffer if not (isEmptyBuffer bbuf) then return False else do -- NB. do no decoding, just fill the byte buffer; see #3808 (r,bbuf') <- Buffered.fillReadBuffer haDevice bbuf if r == 0 then return True else do writeIORef haByteBuffer bbuf' return False -- --------------------------------------------------------------------------- -- Looking ahead -- | Computation 'hLookAhead' returns the next character from the handle -- without removing it from the input buffer, blocking until a character -- is available. -- -- This operation may fail with: -- -- * 'isEOFError' if the end of file has been reached. hLookAhead :: Handle -> IO Char hLookAhead handle = wantReadableHandle_ "hLookAhead" handle hLookAhead_ -- --------------------------------------------------------------------------- -- Buffering Operations -- Three kinds of buffering are supported: line-buffering, -- block-buffering or no-buffering. See GHC.IO.Handle for definition and -- further explanation of what the type represent. -- | Computation 'hSetBuffering' @hdl mode@ sets the mode of buffering for -- handle @hdl@ on subsequent reads and writes. -- -- If the buffer mode is changed from 'BlockBuffering' or -- 'LineBuffering' to 'NoBuffering', then -- -- * if @hdl@ is writable, the buffer is flushed as for 'hFlush'; -- -- * if @hdl@ is not writable, the contents of the buffer is discarded. -- -- This operation may fail with: -- -- * 'isPermissionError' if the handle has already been used for reading -- or writing and the implementation does not allow the buffering mode -- to be changed. hSetBuffering :: Handle -> BufferMode -> IO () hSetBuffering handle mode = withAllHandles__ "hSetBuffering" handle $ \ handle_@Handle__{..} -> do case haType of ClosedHandle -> ioe_closedHandle _ -> do if mode == haBufferMode then return handle_ else do -- See [note Buffer Sizing] in GHC.IO.Handle.Types -- check for errors: case mode of BlockBuffering (Just n) | n <= 0 -> ioe_bufsiz n _ -> return () -- for input terminals we need to put the terminal into -- cooked or raw mode depending on the type of buffering. is_tty <- IODevice.isTerminal haDevice when (is_tty && isReadableHandleType haType) $ case mode of #ifndef mingw32_HOST_OS -- 'raw' mode under win32 is a bit too specialised (and troublesome -- for most common uses), so simply disable its use here. NoBuffering -> IODevice.setRaw haDevice True #else NoBuffering -> return () #endif _ -> IODevice.setRaw haDevice False -- throw away spare buffers, they might be the wrong size writeIORef haBuffers BufferListNil return Handle__{ haBufferMode = mode,.. } -- ----------------------------------------------------------------------------- -- hSetEncoding -- | The action 'hSetEncoding' @hdl@ @encoding@ changes the text encoding -- for the handle @hdl@ to @encoding@. The default encoding when a 'Handle' is -- created is 'localeEncoding', namely the default encoding for the current -- locale. -- -- To create a 'Handle' with no encoding at all, use 'openBinaryFile'. To -- stop further encoding or decoding on an existing 'Handle', use -- 'hSetBinaryMode'. -- -- 'hSetEncoding' may need to flush buffered data in order to change -- the encoding. -- hSetEncoding :: Handle -> TextEncoding -> IO () hSetEncoding hdl encoding = do withAllHandles__ "hSetEncoding" hdl $ \h_@Handle__{..} -> do flushCharBuffer h_ closeTextCodecs h_ openTextEncoding (Just encoding) haType $ \ mb_encoder mb_decoder -> do bbuf <- readIORef haByteBuffer ref <- newIORef (error "last_decode") return (Handle__{ haLastDecode = ref, haDecoder = mb_decoder, haEncoder = mb_encoder, haCodec = Just encoding, .. }) -- | Return the current 'TextEncoding' for the specified 'Handle', or -- 'Nothing' if the 'Handle' is in binary mode. -- -- Note that the 'TextEncoding' remembers nothing about the state of -- the encoder/decoder in use on this 'Handle'. For example, if the -- encoding in use is UTF-16, then using 'hGetEncoding' and -- 'hSetEncoding' to save and restore the encoding may result in an -- extra byte-order-mark being written to the file. -- hGetEncoding :: Handle -> IO (Maybe TextEncoding) hGetEncoding hdl = withHandle_ "hGetEncoding" hdl $ \h_@Handle__{..} -> return haCodec -- ----------------------------------------------------------------------------- -- hFlush -- | The action 'hFlush' @hdl@ causes any items buffered for output -- in handle @hdl@ to be sent immediately to the operating system. -- -- This operation may fail with: -- -- * 'isFullError' if the device is full; -- -- * 'isPermissionError' if a system resource limit would be exceeded. -- It is unspecified whether the characters in the buffer are discarded -- or retained under these circumstances. hFlush :: Handle -> IO () hFlush handle = wantWritableHandle "hFlush" handle flushWriteBuffer -- | The action 'hFlushAll' @hdl@ flushes all buffered data in @hdl@, -- including any buffered read data. Buffered read data is flushed -- by seeking the file position back to the point before the bufferred -- data was read, and hence only works if @hdl@ is seekable (see -- 'hIsSeekable'). -- -- This operation may fail with: -- -- * 'isFullError' if the device is full; -- -- * 'isPermissionError' if a system resource limit would be exceeded. -- It is unspecified whether the characters in the buffer are discarded -- or retained under these circumstances; -- -- * 'isIllegalOperation' if @hdl@ has buffered read data, and is not -- seekable. hFlushAll :: Handle -> IO () hFlushAll handle = withHandle_ "hFlushAll" handle flushBuffer -- ----------------------------------------------------------------------------- -- Repositioning Handles data HandlePosn = HandlePosn Handle HandlePosition instance Eq HandlePosn where (HandlePosn h1 p1) == (HandlePosn h2 p2) = p1==p2 && h1==h2 instance Show HandlePosn where showsPrec p (HandlePosn h pos) = showsPrec p h . showString " at position " . shows pos -- HandlePosition is the Haskell equivalent of POSIX' off_t. -- We represent it as an Integer on the Haskell side, but -- cheat slightly in that hGetPosn calls upon a C helper -- that reports the position back via (merely) an Int. type HandlePosition = Integer -- | Computation 'hGetPosn' @hdl@ returns the current I\/O position of -- @hdl@ as a value of the abstract type 'HandlePosn'. hGetPosn :: Handle -> IO HandlePosn hGetPosn handle = do posn <- hTell handle return (HandlePosn handle posn) -- | If a call to 'hGetPosn' @hdl@ returns a position @p@, -- then computation 'hSetPosn' @p@ sets the position of @hdl@ -- to the position it held at the time of the call to 'hGetPosn'. -- -- This operation may fail with: -- -- * 'isPermissionError' if a system resource limit would be exceeded. hSetPosn :: HandlePosn -> IO () hSetPosn (HandlePosn h i) = hSeek h AbsoluteSeek i -- --------------------------------------------------------------------------- -- hSeek {- Note: - when seeking using `SeekFromEnd', positive offsets (>=0) means seeking at or past EOF. - we possibly deviate from the report on the issue of seeking within the buffer and whether to flush it or not. The report isn't exactly clear here. -} -- | Computation 'hSeek' @hdl mode i@ sets the position of handle -- @hdl@ depending on @mode@. -- The offset @i@ is given in terms of 8-bit bytes. -- -- If @hdl@ is block- or line-buffered, then seeking to a position which is not -- in the current buffer will first cause any items in the output buffer to be -- written to the device, and then cause the input buffer to be discarded. -- Some handles may not be seekable (see 'hIsSeekable'), or only support a -- subset of the possible positioning operations (for instance, it may only -- be possible to seek to the end of a tape, or to a positive offset from -- the beginning or current position). -- It is not possible to set a negative I\/O position, or for -- a physical file, an I\/O position beyond the current end-of-file. -- -- This operation may fail with: -- -- * 'isIllegalOperationError' if the Handle is not seekable, or does -- not support the requested seek mode. -- -- * 'isPermissionError' if a system resource limit would be exceeded. hSeek :: Handle -> SeekMode -> Integer -> IO () hSeek handle mode offset = wantSeekableHandle "hSeek" handle $ \ handle_@Handle__{..} -> do debugIO ("hSeek " ++ show (mode,offset)) buf <- readIORef haCharBuffer if isWriteBuffer buf then do flushWriteBuffer handle_ IODevice.seek haDevice mode offset else do let r = bufL buf; w = bufR buf if mode == RelativeSeek && isNothing haDecoder && offset >= 0 && offset < fromIntegral (w - r) then writeIORef haCharBuffer buf{ bufL = r + fromIntegral offset } else do flushCharReadBuffer handle_ flushByteReadBuffer handle_ IODevice.seek haDevice mode offset -- | Computation 'hTell' @hdl@ returns the current position of the -- handle @hdl@, as the number of bytes from the beginning of -- the file. The value returned may be subsequently passed to -- 'hSeek' to reposition the handle to the current position. -- -- This operation may fail with: -- -- * 'isIllegalOperationError' if the Handle is not seekable. -- hTell :: Handle -> IO Integer hTell handle = wantSeekableHandle "hGetPosn" handle $ \ handle_@Handle__{..} -> do posn <- IODevice.tell haDevice -- we can't tell the real byte offset if there are buffered -- Chars, so must flush first: flushCharBuffer handle_ bbuf <- readIORef haByteBuffer let real_posn | isWriteBuffer bbuf = posn + fromIntegral (bufferElems bbuf) | otherwise = posn - fromIntegral (bufferElems bbuf) cbuf <- readIORef haCharBuffer debugIO ("\nhGetPosn: (posn, real_posn) = " ++ show (posn, real_posn)) debugIO (" cbuf: " ++ summaryBuffer cbuf ++ " bbuf: " ++ summaryBuffer bbuf) return real_posn -- ----------------------------------------------------------------------------- -- Handle Properties -- A number of operations return information about the properties of a -- handle. Each of these operations returns `True' if the handle has -- the specified property, and `False' otherwise. hIsOpen :: Handle -> IO Bool hIsOpen handle = withHandle_ "hIsOpen" handle $ \ handle_ -> do case haType handle_ of ClosedHandle -> return False SemiClosedHandle -> return False _ -> return True hIsClosed :: Handle -> IO Bool hIsClosed handle = withHandle_ "hIsClosed" handle $ \ handle_ -> do case haType handle_ of ClosedHandle -> return True _ -> return False {- not defined, nor exported, but mentioned here for documentation purposes: hSemiClosed :: Handle -> IO Bool hSemiClosed h = do ho <- hIsOpen h hc <- hIsClosed h return (not (ho || hc)) -} hIsReadable :: Handle -> IO Bool hIsReadable (DuplexHandle _ _ _) = return True hIsReadable handle = withHandle_ "hIsReadable" handle $ \ handle_ -> do case haType handle_ of ClosedHandle -> ioe_closedHandle SemiClosedHandle -> ioe_closedHandle htype -> return (isReadableHandleType htype) hIsWritable :: Handle -> IO Bool hIsWritable (DuplexHandle _ _ _) = return True hIsWritable handle = withHandle_ "hIsWritable" handle $ \ handle_ -> do case haType handle_ of ClosedHandle -> ioe_closedHandle SemiClosedHandle -> ioe_closedHandle htype -> return (isWritableHandleType htype) -- | Computation 'hGetBuffering' @hdl@ returns the current buffering mode -- for @hdl@. hGetBuffering :: Handle -> IO BufferMode hGetBuffering handle = withHandle_ "hGetBuffering" handle $ \ handle_ -> do case haType handle_ of ClosedHandle -> ioe_closedHandle _ -> -- We're being non-standard here, and allow the buffering -- of a semi-closed handle to be queried. -- sof 6/98 return (haBufferMode handle_) -- could be stricter.. hIsSeekable :: Handle -> IO Bool hIsSeekable handle = withHandle_ "hIsSeekable" handle $ \ handle_@Handle__{..} -> do case haType of ClosedHandle -> ioe_closedHandle SemiClosedHandle -> ioe_closedHandle AppendHandle -> return False _ -> IODevice.isSeekable haDevice -- ----------------------------------------------------------------------------- -- Changing echo status (Non-standard GHC extensions) -- | Set the echoing status of a handle connected to a terminal. hSetEcho :: Handle -> Bool -> IO () hSetEcho handle on = do isT <- hIsTerminalDevice handle if not isT then return () else withHandle_ "hSetEcho" handle $ \ Handle__{..} -> do case haType of ClosedHandle -> ioe_closedHandle _ -> IODevice.setEcho haDevice on -- | Get the echoing status of a handle connected to a terminal. hGetEcho :: Handle -> IO Bool hGetEcho handle = do isT <- hIsTerminalDevice handle if not isT then return False else withHandle_ "hGetEcho" handle $ \ Handle__{..} -> do case haType of ClosedHandle -> ioe_closedHandle _ -> IODevice.getEcho haDevice -- | Is the handle connected to a terminal? hIsTerminalDevice :: Handle -> IO Bool hIsTerminalDevice handle = do withHandle_ "hIsTerminalDevice" handle $ \ Handle__{..} -> do case haType of ClosedHandle -> ioe_closedHandle _ -> IODevice.isTerminal haDevice -- ----------------------------------------------------------------------------- -- hSetBinaryMode -- | Select binary mode ('True') or text mode ('False') on a open handle. -- (See also 'openBinaryFile'.) -- -- This has the same effect as calling 'hSetEncoding' with 'char8', together -- with 'hSetNewlineMode' with 'noNewlineTranslation'. -- hSetBinaryMode :: Handle -> Bool -> IO () hSetBinaryMode handle bin = withAllHandles__ "hSetBinaryMode" handle $ \ h_@Handle__{..} -> do flushCharBuffer h_ closeTextCodecs h_ mb_te <- if bin then return Nothing else fmap Just getLocaleEncoding openTextEncoding mb_te haType $ \ mb_encoder mb_decoder -> do -- should match the default newline mode, whatever that is let nl | bin = noNewlineTranslation | otherwise = nativeNewlineMode bbuf <- readIORef haByteBuffer ref <- newIORef (error "codec_state", bbuf) return Handle__{ haLastDecode = ref, haEncoder = mb_encoder, haDecoder = mb_decoder, haCodec = mb_te, haInputNL = inputNL nl, haOutputNL = outputNL nl, .. } -- ----------------------------------------------------------------------------- -- hSetNewlineMode -- | Set the 'NewlineMode' on the specified 'Handle'. All buffered -- data is flushed first. hSetNewlineMode :: Handle -> NewlineMode -> IO () hSetNewlineMode handle NewlineMode{ inputNL=i, outputNL=o } = withAllHandles__ "hSetNewlineMode" handle $ \h_@Handle__{..} -> do flushBuffer h_ return h_{ haInputNL=i, haOutputNL=o } -- ----------------------------------------------------------------------------- -- Duplicating a Handle -- | Returns a duplicate of the original handle, with its own buffer. -- The two Handles will share a file pointer, however. The original -- handle's buffer is flushed, including discarding any input data, -- before the handle is duplicated. hDuplicate :: Handle -> IO Handle hDuplicate h@(FileHandle path m) = do withHandle_' "hDuplicate" h m $ \h_ -> dupHandle path h Nothing h_ (Just handleFinalizer) hDuplicate h@(DuplexHandle path r w) = do write_side@(FileHandle _ write_m) <- withHandle_' "hDuplicate" h w $ \h_ -> dupHandle path h Nothing h_ (Just handleFinalizer) read_side@(FileHandle _ read_m) <- withHandle_' "hDuplicate" h r $ \h_ -> dupHandle path h (Just write_m) h_ Nothing return (DuplexHandle path read_m write_m) dupHandle :: FilePath -> Handle -> Maybe (MVar Handle__) -> Handle__ -> Maybe HandleFinalizer -> IO Handle dupHandle filepath h other_side h_@Handle__{..} mb_finalizer = do -- flush the buffer first, so we don't have to copy its contents flushBuffer h_ case other_side of Nothing -> do new_dev <- IODevice.dup haDevice dupHandle_ new_dev filepath other_side h_ mb_finalizer Just r -> withHandle_' "dupHandle" h r $ \Handle__{haDevice=dev} -> do dupHandle_ dev filepath other_side h_ mb_finalizer dupHandle_ :: (IODevice dev, BufferedIO dev, Typeable dev) => dev -> FilePath -> Maybe (MVar Handle__) -> Handle__ -> Maybe HandleFinalizer -> IO Handle dupHandle_ new_dev filepath other_side h_@Handle__{..} mb_finalizer = do -- XXX wrong! mb_codec <- if isJust haEncoder then fmap Just getLocaleEncoding else return Nothing mkHandle new_dev filepath haType True{-buffered-} mb_codec NewlineMode { inputNL = haInputNL, outputNL = haOutputNL } mb_finalizer other_side -- ----------------------------------------------------------------------------- -- Replacing a Handle {- | Makes the second handle a duplicate of the first handle. The second handle will be closed first, if it is not already. This can be used to retarget the standard Handles, for example: > do h <- openFile "mystdout" WriteMode > hDuplicateTo h stdout -} hDuplicateTo :: Handle -> Handle -> IO () hDuplicateTo h1@(FileHandle path m1) h2@(FileHandle _ m2) = do withHandle__' "hDuplicateTo" h2 m2 $ \h2_ -> do _ <- hClose_help h2_ withHandle_' "hDuplicateTo" h1 m1 $ \h1_ -> do dupHandleTo path h1 Nothing h2_ h1_ (Just handleFinalizer) hDuplicateTo h1@(DuplexHandle path r1 w1) h2@(DuplexHandle _ r2 w2) = do withHandle__' "hDuplicateTo" h2 w2 $ \w2_ -> do _ <- hClose_help w2_ withHandle_' "hDuplicateTo" h1 w1 $ \w1_ -> do dupHandleTo path h1 Nothing w2_ w1_ (Just handleFinalizer) withHandle__' "hDuplicateTo" h2 r2 $ \r2_ -> do _ <- hClose_help r2_ withHandle_' "hDuplicateTo" h1 r1 $ \r1_ -> do dupHandleTo path h1 (Just w1) r2_ r1_ Nothing hDuplicateTo h1 _ = ioe_dupHandlesNotCompatible h1 ioe_dupHandlesNotCompatible :: Handle -> IO a ioe_dupHandlesNotCompatible h = ioException (IOError (Just h) IllegalOperation "hDuplicateTo" "handles are incompatible" Nothing Nothing) dupHandleTo :: FilePath -> Handle -> Maybe (MVar Handle__) -> Handle__ -> Handle__ -> Maybe HandleFinalizer -> IO Handle__ dupHandleTo filepath h other_side hto_@Handle__{haDevice=devTo,..} h_@Handle__{haDevice=dev} mb_finalizer = do flushBuffer h_ case cast devTo of Nothing -> ioe_dupHandlesNotCompatible h Just dev' -> do _ <- IODevice.dup2 dev dev' FileHandle _ m <- dupHandle_ dev' filepath other_side h_ mb_finalizer takeMVar m -- --------------------------------------------------------------------------- -- showing Handles. -- -- | 'hShow' is in the 'IO' monad, and gives more comprehensive output -- than the (pure) instance of 'Show' for 'Handle'. hShow :: Handle -> IO String hShow h@(FileHandle path _) = showHandle' path False h hShow h@(DuplexHandle path _ _) = showHandle' path True h showHandle' :: String -> Bool -> Handle -> IO String showHandle' filepath is_duplex h = withHandle_ "showHandle" h $ \hdl_ -> let showType | is_duplex = showString "duplex (read-write)" | otherwise = shows (haType hdl_) in return (( showChar '{' . showHdl (haType hdl_) (showString "loc=" . showString filepath . showChar ',' . showString "type=" . showType . showChar ',' . showString "buffering=" . showBufMode (unsafePerformIO (readIORef (haCharBuffer hdl_))) (haBufferMode hdl_) . showString "}" ) ) "") where showHdl :: HandleType -> ShowS -> ShowS showHdl ht cont = case ht of ClosedHandle -> shows ht . showString "}" _ -> cont showBufMode :: Buffer e -> BufferMode -> ShowS showBufMode buf bmo = case bmo of NoBuffering -> showString "none" LineBuffering -> showString "line" BlockBuffering (Just n) -> showString "block " . showParen True (shows n) BlockBuffering Nothing -> showString "block " . showParen True (shows def) where def :: Int def = bufSize buf
bitemyapp/ghc
libraries/base/GHC/IO/Handle.hs
bsd-3-clause
26,434
0
24
6,110
4,837
2,490
2,347
373
5
module Botworld.Display where import Botworld hiding (Cell) import Botworld.TextBlock import Control.Applicative import Control.Monad (join) import Data.List (sortBy) import Data.Map (Map) import qualified Data.Map as Map import Data.Ord (comparing) import qualified Data.Set as Set import Text.Printf (printf) colorChar :: Color -> Char colorChar Red = 'R' colorChar Orange = 'O' colorChar Yellow = 'Y' colorChar Green = 'G' colorChar Blue = 'B' colorChar Violet = 'V' colorChar Black = 'Ω' colorChar White = 'W' showPos :: Position -> String showPos = uncurry (printf "(%d, %d)") squareStatus :: Square -> TextBlock squareStatus = pure . robotStatus . robotsIn changeStatus :: Event -> TextBlock changeStatus res = [robotStatus presentRobots, actionStatus acts] where acts = snd <$> robotActions res presentRobots = [r | (r, a) <- robotActions res, not $ isExit a] robotStatus :: [Robot] -> String robotStatus rs = case colorChar . color . frame <$> rs of [c] -> printf " %c " c [c1, c2] -> printf " %c %c " c1 c2 (c1:c2:c3:c4:_:_) -> printf "%c%c%c%c…" c1 c2 c3 c4 cs -> printf "%-5s" cs actionStatus :: [Action] -> String actionStatus as = liftDropFlag : (uncurry bit <$> flags) where bit p f = if any p as then f else ' ' flags = [(isMake, '+'), (isKill, '×'), (isInspect, '?'), (isInvalid, '!')] liftDropFlag = case (any isLift as, any isDrop as) of (False, False) -> ' ' (True, False) -> '↑' (False, True) -> '↓' (True, True) -> '↕' isLift a = case a of { Lifted _ -> True; _ -> False } isDrop a = case a of { Dropped _ -> True; _ -> False } isMake a = case a of { Created -> True; _ -> False } isKill a = case a of { Destroyed _ -> True; _ -> False } isInspect a = case a of { Inspected _ _ -> True; _ -> False } isInvalid a = case a of { Invalid -> True; _ -> False } robotSummary :: Int -> Robot -> TextBlock robotSummary i r = [ show i , show $ color $ frame r , printf "%d spd, %d str" (speed $ processor r) (strength $ frame r) ] actionSummary :: Action -> String actionSummary a = case a of Created -> "created" Passed -> "passed" MoveBlocked d -> printf "%s %s" "blocked" (show d) MovedOut d -> printf "%s %s" "exited" (show d) MovedIn d -> printf "%s %s" "entered" (show d) CannotLift i -> printf "%s %2d" "cantlift" i GrappledOver i -> printf "%s %2d" "grappled" i Lifted i -> printf "%s %2d" "lift" i Dropped i -> printf "%s %2d" "drop" i InspectTargetFled i -> printf "%s %2d" "evadedby" i InspectBlocked i -> printf "%s %2d" "assaulted" i Inspected i _ -> printf "%s %2d" "inspected" i DestroyTargetFled i -> printf "%s %2d" "missed" i DestroyBlocked i -> printf "%s %2d" "battered" i Destroyed i -> printf "%s %2d" "destroyed" i BuildInterrupted is -> printf "%s %2d" "interrupted" $ ilist is Built is _ -> printf "%s %s" "built" $ ilist is Invalid -> "invalid" where ilist is = unwords $ printf "%2d" <$> is itemDetail :: Item -> TextBlock itemDetail DestroyShield = ["[†]"] itemDetail InspectShield = ["[°]"] itemDetail (FramePart f) = [printf "[%c]" $ colorChar $ color f, show $ strength f] itemDetail (ProcessorPart p) = ["[#]", show $ speed p] itemDetail (RegisterPart r) = ["[|]", show $ limit r] itemDetail (Cargo t w) = [printf "$%d" t, printf "%dg" w] cellDetail :: Position -> Event -> TextBlock cellDetail pos res = labeled (showPos pos) [summary, robotSection, itemSection] where summary = labeled "Summary" [summaryGrid res] robotSection = labeled "Robots" $ uncurry robotDetail <$> robotActions res itemSection = labeled "Items" [untouchedSection, droppedSection, fallenSection] untouchedSection = labeled "Untouched" [itemGrid $ untouchedItems res] droppedSection = labeled "Dropped" [itemGrid $ droppedItems res] fallenSection = labeled "Fallen" $ fallenGrid <$> fallenItems res summaryGrid :: Event -> TextBlock summaryGrid = renderGrid' . vGrid 4 . zipWith summarize [0..] . robotActions summarize :: Int -> (Robot, Action) -> TextBlock summarize i (r, a) = robotSummary i r ++ [actionSummary a] robotDetail :: Robot -> Action -> TextBlock robotDetail r a = [ show $ color $ frame r , printf "Action: %s" $ actionSummary a , printf "Strength: %d" $ strength $ frame r , printf "Speed: %d" $ speed $ processor r , printf "Registers: %d" $ length $ memory r ] ++ labeled "Items" [itemGrid $ inventory r] itemGrid :: [Item] -> TextBlock itemGrid [] = ["None."] itemGrid items = renderGrid' . vGrid 6 $ itemDetail <$> items fallenGrid :: ItemCache -> TextBlock fallenGrid (ItemCache xs ys) = renderGrid' $ join <$> vGrid 6 items where items = (Just . itemDetail <$> xs) ++ [Nothing] ++ (Just . itemDetail <$> ys) renderBotworld :: Map String Player -> Botworld -> TextBlock renderBotworld players g = renderWorld (fmap squareStatus <$> g) homes Map.empty where homes = Map.fold (Set.insert . home) Set.empty players displayBotworld :: Map String Player -> Botworld -> IO () displayBotworld ps = display . renderBotworld ps renderEventGrid :: Map String Player -> EventGrid -> TextBlock renderEventGrid ps g = renderWorld (fmap changeStatus <$> g) homes moves where homes = Map.fold (Set.insert . home) Set.empty ps moves = Map.fromList $ makeViolation <$> indices g makeViolation pos = (pos, Set.fromList $ allViolations $ at g pos) allViolations (Just res) = [Right d | MovedIn d <- snd <$> robotActions res] ++ [Left d | MovedOut d <- snd <$> robotActions res] allViolations Nothing = [] displayEventGrid :: Map String Player -> EventGrid -> IO () displayEventGrid ps = display . renderEventGrid ps renderScoreboard :: Map String Player -> Botworld -> TextBlock renderScoreboard ps w = blankSeparated $ uncurry scoreDetail <$> sortedPlayers where sortedPlayers = sortBy (comparing $ score w . snd) (Map.assocs ps) scoreDetail name p = labeled label [scores] where scores = robotScore <$> maybe [] robotsIn (at w $ home p) len = max (length label1) $ if null scores then 8 else 2 + maximum (length <$> scores) label = label1 ++ label2 label1 = printf " %s: %d$\n" name (score w p) label2 = replicate len '─' robotScore r = printf "%s robot: %d points" (show $ color $ frame r) (points p r) displayScoreboard :: Map String Player -> Botworld -> IO () displayScoreboard ps = display . renderScoreboard ps renderChangesAt :: EventGrid -> Position -> TextBlock renderChangesAt w pos = maybe wall (cellDetail pos) (at w pos) where wall = labeled (showPos pos) [["Wall."]] displayChangesAt :: EventGrid -> Position -> IO () displayChangesAt w = display . renderChangesAt w
machine-intelligence/Botworld
Botworld/Display.hs
bsd-3-clause
6,816
0
14
1,496
2,541
1,294
1,247
141
18
{-# LANGUAGE CPP , OverloadedStrings , PatternGuards , DataKinds , GADTs , TypeOperators #-} module Main where import Language.Hakaru.Syntax.AST.Transforms import Language.Hakaru.Syntax.TypeCheck import Language.Hakaru.Syntax.Value import Language.Hakaru.Syntax.IClasses import Language.Hakaru.Types.Sing import Language.Hakaru.Types.DataKind import Language.Hakaru.Sample import Language.Hakaru.Pretty.Concrete import Language.Hakaru.Command ( parseAndInfer, parseAndInfer' , readFromFile', Term, Source ) #if __GLASGOW_HASKELL__ < 710 import Control.Applicative (Applicative(..), (<$>)) #endif import Control.Monad import Data.Monoid import Data.Text import qualified Data.Text.IO as IO import qualified Data.Vector as V import Data.Word import System.IO (stderr) import Text.PrettyPrint (renderStyle, style, mode, Mode(LeftMode)) import qualified Options.Applicative as O import qualified System.Random.MWC as MWC data Options = Options { noWeights :: Bool , seed :: Maybe Word32 , transition :: Maybe String , prog :: String } options :: O.Parser Options options = Options <$> O.switch ( O.short 'w' <> O.long "no-weights" <> O.help "Don't print the weights" ) <*> O.optional (O.option O.auto ( O.long "seed" <> O.help "Set random seed" <> O.metavar "seed")) <*> O.optional (O.strOption ( O.long "transition-kernel" <> O.metavar "k" <> O.help "Use this program as transition kernel for running a markov chain")) <*> O.strArgument ( O.metavar "PROGRAM" <> O.help "Hakaru program to run" ) parseOpts :: IO Options parseOpts = O.execParser $ O.info (O.helper <*> options) (O.fullDesc <> O.progDesc "Run a hakaru program") main :: IO () main = do args <- parseOpts g <- case seed args of Nothing -> MWC.createSystemRandom Just s -> MWC.initialize (V.singleton s) case transition args of Nothing -> runHakaru' g (noWeights args) =<< readFromFile' (prog args) Just prog2 -> do prog' <- readFromFile' (prog args) trans <- readFromFile' prog2 randomWalk' g trans prog' -- TODO: A better needs to be found for passing weights around illustrate :: Sing a -> Bool -> MWC.GenIO -> Value a -> IO () illustrate (SMeasure s) weights g (VMeasure m) = do x <- m (VProb 1) g case x of Just (samp, w) -> (if weights then id else withWeight w) (illustrate s weights g samp) Nothing -> illustrate (SMeasure s) weights g (VMeasure m) illustrate _ _ _ x = renderLn x withWeight :: Value 'HProb -> IO () -> IO () withWeight w m = render w >> putStr "\t" >> m render :: Value a -> IO () render = putStr . renderStyle style {mode = LeftMode} . prettyValue renderLn :: Value a -> IO () renderLn = putStrLn . renderStyle style {mode = LeftMode} . prettyValue -- TODO: A better needs to be found for passing weights around runHakaru :: MWC.GenIO -> Bool -> Source -> IO () runHakaru g weights prog' = parseAndInfer' prog' >>= \prog'' -> case prog'' of Left err -> IO.hPutStrLn stderr err Right (TypedAST typ ast) -> do case typ of SMeasure _ -> forever (illustrate typ weights g $ run ast) _ -> illustrate typ weights g $ run ast where run :: Term a -> Value a run = runEvaluate . expandTransformations -- TODO: A better needs to be found for passing weights around runHakaru' :: MWC.GenIO -> Bool -> Source -> IO () runHakaru' g weights prog = do prog' <- parseAndInfer' prog case prog' of Left err -> IO.hPutStrLn stderr err Right (TypedAST typ ast) -> do case typ of SMeasure _ -> forever (illustrate typ weights g $ run ast) _ -> illustrate typ weights g $ run ast where run :: Term a -> Value a run = runEvaluate . expandTransformations randomWalk :: MWC.GenIO -> Source -> Source -> IO () randomWalk g p1 p2 = (,) <$> parseAndInfer' p1 <*> parseAndInfer' p2 >>= \ps -> case ps of (Right (TypedAST typ1 ast1), Right (TypedAST typ2 ast2)) -> -- TODO: Use better error messages for type mismatch case (typ1, typ2) of (SFun a (SMeasure b), SMeasure c) | (Just Refl, Just Refl) <- (jmEq1 a b, jmEq1 b c) -> iterateM_ (chain $ run ast1) (run ast2) _ -> IO.hPutStrLn stderr "hakaru: programs have wrong type" (Left err, _) -> IO.hPutStrLn stderr err (_, Left err) -> IO.hPutStrLn stderr err where run :: Term a -> Value a run = runEvaluate . expandTransformations chain :: Value (a ':-> b) -> Value ('HMeasure a) -> IO (Value b) chain (VLam f) (VMeasure m) = do Just (samp,_) <- m (VProb 1) g renderLn samp return (f samp) randomWalk' :: MWC.GenIO -> Source -> Source -> IO () randomWalk' g p1 p2 = do p1' <- parseAndInfer' p1 p2' <- parseAndInfer' p2 case (p1', p2') of (Right (TypedAST typ1 ast1), Right (TypedAST typ2 ast2)) -> -- TODO: Use better error messages for type mismatch case (typ1, typ2) of (SFun a (SMeasure b), SMeasure c) | (Just Refl, Just Refl) <- (jmEq1 a b, jmEq1 b c) -> iterateM_ (chain $ run ast1) (run ast2) _ -> IO.hPutStrLn stderr "hakaru: programs have wrong type" (Left err, _) -> IO.hPutStrLn stderr err (_, Left err) -> IO.hPutStrLn stderr err where run :: Term a -> Value a run = runEvaluate . expandTransformations chain :: Value (a ':-> b) -> Value ('HMeasure a) -> IO (Value b) chain (VLam f) (VMeasure m) = do Just (samp,_) <- m (VProb 1) g renderLn samp return (f samp) -- From monad-loops iterateM_ :: Monad m => (a -> m a) -> a -> m b iterateM_ f = g where g x = f x >>= g
zachsully/hakaru
commands/Hakaru.hs
bsd-3-clause
6,211
0
18
1,902
2,086
1,050
1,036
140
4
module RPC.Internal.IO where import qualified Control.Monad.IO.Class as MIO import qualified Data.Aeson as A import qualified Data.Attoparsec as AP import qualified Data.ByteString.Lazy as BSL import qualified Data.Enumerator as E import qualified Data.Enumerator.Binary as EB import qualified Data.Enumerator.List as EL import qualified GHC.IO.Handle as GIO import qualified GHC.IO.Handle.FD as GIOF import Data.Attoparsec.Enumerator (iterParser) mkHandler :: MIO.MonadIO m => GIO.Handle -> GIO.Handle -> ((A.Value -> m ()) -> m (), A.Value -> m (), m ()) mkHandler input output = (handle, send, close) where handle dispatch = E.run_ (EB.enumHandle 10240 input E.$$ (E.sequence (iterParser jsonOrEOF) E.=$ EL.isolateWhile isRight E.=$ EL.map (\(Right v) -> v) E.=$ EL.mapM_ dispatch)) send value = MIO.liftIO $ do BSL.hPut output $ A.encode value GIO.hFlush output close = MIO.liftIO $ GIO.hClose output isRight (Left _) = False isRight (Right _) = True jsonOrEOF = AP.takeWhile (AP.inClass " \t\r\n") >> AP.eitherP (AP.try AP.endOfInput) A.json
max630/json-exec
RPC/Internal/IO.hs
bsd-3-clause
1,174
0
17
271
407
226
181
26
1
{-# language NamedFieldPuns #-} {-# language DataKinds #-} {-# language OverloadedStrings #-} {-# language ViewPatterns #-} module Gueb ( noJobs , makeHandlers ) where import Data.Text import Data.Map as Map import Data.Aeson import Data.Functor import Data.Bifunctor (first) import Data.Time import Control.Lens import Control.Exception import Control.Monad import Control.Comonad import Control.Comonad.Cofree (coiter,unwrap) import Control.Concurrent.MVar import Control.Concurrent.Async import Control.Monad.Trans.Except import Control.Monad.IO.Class import Servant import Gueb.Types import Gueb.Types.API import System.Process.Streaming noJobs :: Jobs () () noJobs = Jobs mempty makeHandlers :: Plan -> IO (Server JobsAPI) makeHandlers plan = do let theJobs = Jobs (fmap (Executions () mempty) plan) idstream = Data.Text.pack . show <$> coiter (Identity . succ) (0::Int) tvar <- newMVar (idstream,theJobs) pure (makeHandlersFromRef tvar) -- http://haskell-servant.readthedocs.org/en/tutorial/tutorial/Server.html makeHandlersFromRef :: MVar (Unending ExecutionId,Jobs () (Async ())) -> Server JobsAPI makeHandlersFromRef ref = (query id) :<|> (\jobid -> query (jobs . ix jobid)) :<|> (\jobid -> command (startExecution jobid)) :<|> (\jobid execid -> query (jobs . ix jobid . executions . ix execid)) :<|> (\jobid execid -> command (cancelExecution jobid execid)) where query somelens = do root <- void . addUri . extract <$> liftIO (readMVar ref) Page <$> noteT err404 (preview somelens root) command handler = do oldState <- liftIO (takeMVar ref) catchE (do (newState,result) <- handler oldState deferrer liftIO (do putMVar ref newState return (Page <$> result))) (\e -> do liftIO (putMVar ref oldState) throwE e) deferrer action post = async (do (do _ <- action change <- post notify change) `onException` (do change <- post notify change)) notify change = modifyMVar_ ref (\s -> evaluate (change s)) noteT :: Monad m => e -> Maybe a -> ExceptT e m a noteT e = maybe (throwE e) pure reason :: ServantErr -> Text -> ServantErr reason err msg = err { errBody = jsonError msg } where jsonError = encode . Map.singleton ("result"::Text) startExecution :: JobId -> GlobalState -> (IO () -> IO (GlobalState -> GlobalState) -> IO (Async ())) -> ExceptT ServantErr IO (GlobalState, Headers '[Header "Location" String] Created) startExecution jobId (advance -> (executionId,root)) deferrer = do let Traversal runningJobs = Traversal (_2 . jobs . traversed . executions . traversed . currentState . _Right) Traversal ixJob = Traversal (_2 . jobs . ix jobId) Traversal atExecution = Traversal (ixJob . executions . at executionId) unless (not (has runningJobs root)) (throwE (err409 `reason` "Job already running")) Job {scriptPath} <- noteT (err404 `reason` "Job not found") (preview (ixJob . executable) root) launched <- liftIO (launch scriptPath atExecution) return (set atExecution (Just launched) root ,let linkUri = mkExecutionUri jobId executionId in addHeader linkUri (Created linkUri)) where launch scriptPath atExecution = do pid <- deferrer (execute (piped (proc scriptPath [])) (pure ())) (do t <- getCurrentTime pure (set (atExecution . _Just . currentState) (Left t))) t <- getCurrentTime pure (Execution {executionView = (), startTime=t, _currentState=Right pid}) cancelExecution :: JobId -> ExecutionId -> GlobalState -> (IO () -> IO (GlobalState -> GlobalState) -> IO (Async ())) -> ExceptT ServantErr IO (GlobalState, Headers '[] Deleted) cancelExecution jobId executionId root _ = do let Traversal ixJob = Traversal (_2 . jobs . ix jobId) Traversal atExecutionState = Traversal (ixJob . executions . ix executionId . currentState . _Right) liftIO (forMOf_ atExecutionState root (async . cancel)) let root' = set (ixJob . executions . at executionId) Nothing root return (root', Headers Deleted HNil) {-| World's most obscure i++ -} advance :: GlobalState -> (ExecutionId,GlobalState) advance = first extract . duplicate . first (runIdentity . unwrap) addUri :: Jobs () a -> Jobs Links a addUri (Jobs j) = Jobs (iover itraversed addUriExecutions j) where addUriExecutions i xs = let topURI = pack ('/' : show (safeLink jobsAPI (Proxy::Proxy JobsEndpoint))) jobURI = pack ('/' : show (safeLink jobsAPI (Proxy::Proxy JobEndpoint) i)) in xs { executionsView = Links topURI jobURI, _executions = iover itraversed (addUriExecution jobURI i) (_executions xs)} addUriExecution upwards i i' x = x { executionView = Links upwards (pack (mkExecutionUri i i')) } mkExecutionUri :: Text -> Text -> String mkExecutionUri i i' = '/': show (safeLink jobsAPI (Proxy::Proxy ExecutionEndpoint) i i')
danidiaz/gueb
lib/Gueb.hs
bsd-3-clause
5,536
0
19
1,605
1,833
925
908
108
1
{- vim: set encoding=utf-8 : -*- coding: utf-8 -*- -} ---------------------------------------- ---- STDLIB ---------------------------------------- ---------------------------------------- ---- SITE-PACKAGES ---------------------------------------- import Network.EmailSend.SendMail (SendMailBackend(..)) import Data.Email (sendSimpleEmail) import Network.EmailSend(sendMessage, MailBackend(..), SendingReceipt, ) import Network.EmailSend.SMTP (SMTPBackend(..)) import Network.EmailSend.SendMail (SendMailBackend(..)) ---------------------------------------- ---- LOCAL ---------------------------------------- main = do putStrLn "Sending Mail..." let smtp = SMTPBackend "localhost" "localhost" --sendSimpleEmail StdSendMailBackend "dirk" "weissi" "test ääööüü" "hallo ääüüöö" x <- sendSimpleEmail smtp "dirk" "weissi" "test ääööüü" "hallo ääüüöö" case x of Nothing -> putStrLn "done." Just m -> putStrLn $ "ERROR: "++m putStrLn "bye bye"
weissi/haskell-email
testemail.hs
bsd-3-clause
1,003
0
11
126
170
97
73
13
2
----------------------------------------------------------------------------- -- | -- Module : Distribution.Client.Dependency.Types -- Copyright : (c) Duncan Coutts 2008 -- License : BSD-like -- -- Maintainer : [email protected] -- Stability : provisional -- Portability : portable -- -- Common types for dependency resolution. ----------------------------------------------------------------------------- module Distribution.Client.Dependency.Types ( ExtDependency(..), Solver(..), DependencyResolver, PackageConstraint(..), PackagePreferences(..), InstalledPreference(..), PackagesPreferenceDefault(..), Progress(..), foldProgress, ) where import Control.Applicative ( Applicative(..), Alternative(..) ) import Data.Char ( isAlpha, toLower ) import Data.Monoid ( Monoid(..) ) import Distribution.Client.Types ( SourcePackage(..) ) import qualified Distribution.Client.InstallPlan as InstallPlan import Distribution.Compat.ReadP ( (<++) ) import qualified Distribution.Compat.ReadP as Parse ( pfail, munch1 ) import Distribution.PackageDescription ( FlagAssignment ) import qualified Distribution.Client.PackageIndex as PackageIndex ( PackageIndex ) import qualified Distribution.Simple.PackageIndex as InstalledPackageIndex ( PackageIndex ) import Distribution.Package ( Dependency, PackageName, InstalledPackageId ) import Distribution.Version ( VersionRange ) import Distribution.Compiler ( CompilerId ) import Distribution.System ( Platform ) import Distribution.Text ( Text(..) ) import Text.PrettyPrint ( text ) import Prelude hiding (fail) -- | Covers source dependencies and installed dependencies in -- one type. data ExtDependency = SourceDependency Dependency | InstalledDependency InstalledPackageId instance Text ExtDependency where disp (SourceDependency dep) = disp dep disp (InstalledDependency dep) = disp dep parse = (SourceDependency `fmap` parse) <++ (InstalledDependency `fmap` parse) -- | All the solvers that can be selected. data Solver = TopDown | Modular deriving (Eq, Ord, Show, Bounded, Enum) instance Text Solver where disp TopDown = text "topdown" disp Modular = text "modular" parse = do name <- Parse.munch1 isAlpha case map toLower name of "topdown" -> return TopDown "modular" -> return Modular _ -> Parse.pfail -- | A dependency resolver is a function that works out an installation plan -- given the set of installed and available packages and a set of deps to -- solve for. -- -- The reason for this interface is because there are dozens of approaches to -- solving the package dependency problem and we want to make it easy to swap -- in alternatives. -- type DependencyResolver = Platform -> CompilerId -> InstalledPackageIndex.PackageIndex -> PackageIndex.PackageIndex SourcePackage -> (PackageName -> PackagePreferences) -> [PackageConstraint] -> [PackageName] -> Progress String String [InstallPlan.PlanPackage] -- | Per-package constraints. Package constraints must be respected by the -- solver. Multiple constraints for each package can be given, though obviously -- it is possible to construct conflicting constraints (eg impossible version -- range or inconsistent flag assignment). -- data PackageConstraint = PackageConstraintVersion PackageName VersionRange | PackageConstraintInstalled PackageName | PackageConstraintSource PackageName | PackageConstraintFlags PackageName FlagAssignment deriving (Show,Eq) -- | A per-package preference on the version. It is a soft constraint that the -- 'DependencyResolver' should try to respect where possible. It consists of -- a 'InstalledPreference' which says if we prefer versions of packages -- that are already installed. It also hase a 'PackageVersionPreference' which -- is a suggested constraint on the version number. The resolver should try to -- use package versions that satisfy the suggested version constraint. -- -- It is not specified if preferences on some packages are more important than -- others. -- data PackagePreferences = PackagePreferences VersionRange InstalledPreference -- | Wether we prefer an installed version of a package or simply the latest -- version. -- data InstalledPreference = PreferInstalled | PreferLatest -- | Global policy for all packages to say if we prefer package versions that -- are already installed locally or if we just prefer the latest available. -- data PackagesPreferenceDefault = -- | Always prefer the latest version irrespective of any existing -- installed version. -- -- * This is the standard policy for upgrade. -- PreferAllLatest -- | Always prefer the installed versions over ones that would need to be -- installed. Secondarily, prefer latest versions (eg the latest installed -- version or if there are none then the latest source version). | PreferAllInstalled -- | Prefer the latest version for packages that are explicitly requested -- but prefers the installed version for any other packages. -- -- * This is the standard policy for install. -- | PreferLatestForSelected -- | A type to represent the unfolding of an expensive long running -- calculation that may fail. We may get intermediate steps before the final -- retult which may be used to indicate progress and\/or logging messages. -- data Progress step fail done = Step step (Progress step fail done) | Fail fail | Done done -- | Consume a 'Progres' calculation. Much like 'foldr' for lists but with -- two base cases, one for a final result and one for failure. -- -- Eg to convert into a simple 'Either' result use: -- -- > foldProgress (flip const) Left Right -- foldProgress :: (step -> a -> a) -> (fail -> a) -> (done -> a) -> Progress step fail done -> a foldProgress step fail done = fold where fold (Step s p) = step s (fold p) fold (Fail f) = fail f fold (Done r) = done r instance Functor (Progress step fail) where fmap f = foldProgress Step Fail (Done . f) instance Monad (Progress step fail) where return a = Done a p >>= f = foldProgress Step Fail f p instance Applicative (Progress step fail) where pure a = Done a p <*> x = foldProgress Step Fail (flip fmap x) p instance Monoid fail => Alternative (Progress step fail) where empty = Fail mempty p <|> q = foldProgress Step (const q) Done p
IreneKnapp/Faction
faction/Distribution/Client/Dependency/Types.hs
bsd-3-clause
6,809
0
14
1,559
1,052
616
436
99
3
{-# LANGUAGE OverloadedStrings #-} module ScottyCA where import Web.Scotty import Data.ByteString.Lazy (ByteString, append, empty, pack, toStrict, fromStrict) import qualified Data.ByteString.Lazy.Char8 as L hiding (length) import Data.Binary import System.IO import Crypto.Cipher.AES import Control.Monad.Trans import qualified Data.Text.Lazy as LazyText import Data.Monoid (mconcat) import qualified Data.Text.Lazy.Encoding as LazyEncoding import qualified Demo3Shared as AD --ArmoredData import TPM import Database.HDBC import Database.HDBC.Sqlite3 import Demo3Shared scottyCAMain = scotty 3000 $ do Web.Scotty.get "/" $ text "foobar" {- Web.Scotty.get "/foo" $ do v <- param "fooparam" html $ mconcat ["<h1>", v, "</h1>"] post "/" $ do -- req <- request -- bod <- body -- a <- jsonData :: ActionM String -- text a --json (bod :: String) --(a :: String) a <- (param "request") :: ActionM LazyText.Text html a let jj = (AD.jsonEitherDecode (LazyEncoding.encodeUtf8 a) :: Either String AD.CARequest) case jj of (Left err) -> text (LazyText.pack ("Error decoding CARequest from JSON. Error was: " ++ err)) (Right caReq) -> do eitherCAResp <- liftIO $ handleCAReq caReq case eitherCAResp of (Left err) -> text (LazyText.pack ("Error formulating CAResponse. Error was: " ++ err)) (Right caResp) -> do --caResp' <- liftIO caResp json caResp --return () --text "posted!" -- text (LazyText.pack (L.unpack bod)) handleCAReq :: AD.CARequest -> IO (Either String AD.CAResponse) handleCAReq (AD.CARequest id (AD.Signed idContents idSig)) = do eitherEKPubKey <- ekLookup id case (eitherEKPubKey) of (Left err) -> return (Left ("LOOKUP FAILURE. Error was: " ++ err)) (Right ekPubKey) -> do let iPubKey = identityPubKey idContents iDigest = tpm_digest $ encode iPubKey asymContents = contents iDigest blob = encode asymContents encBlob = tpm_rsa_pubencrypt ekPubKey blob caPriKey = snd AD.generateCAKeyPair caCert = AD.signPack caPriKey iPubKey certBytes = encode caCert strictCert = toStrict certBytes encryptedCert = encryptCTR aes ctr strictCert enc = fromStrict encryptedCert --encryptedSignedAIK = crypt' CTR symKey symKey Encrypt signedAIK --enc = encrypt key certBytes return (Right (AD.CAResponse enc encBlob)) where symKey = TPM_SYMMETRIC_KEY (tpm_alg_aes128) (tpm_es_sym_ctr) key v:: Word8 v = 1 key = ({-B.-}Data.ByteString.Lazy.pack $ replicate 16 v) --strictKey = toStrict key aes = initAES $ toStrict key ctr = toStrict key contents dig = TPM_ASYM_CA_CONTENTS symKey dig databaseName = "armoredDB.db" ekLookup :: Int -> IO (Either String TPM_PUBKEY) ekLookup my_id = do putStrLn "beginning..." conn <- connectSqlite3 databaseName res <- quickQuery' conn ("SELECT jsontpmkey from pubkeys where id =" ++ (show my_id)) [] putStrLn "Here is the result of the query:" putStrLn (show res) if (length res) < 1 then do return (Left ("No entry in " ++ databaseName ++ " found for given ID: " ++ (show my_id))) else do let res' = (res !! 0) !! 0 convertedRes = fromSql res' :: ByteString putStrLn " Here is the bytestring version: " putStrLn (show convertedRes) let x = jsonEitherDecode convertedRes :: Either String TPM_PUBKEY putStrLn "Here is the JSON decoded version: " putStrLn (show x) case x of (Left err) -> do --putStrLn "Failed to get from DB properly. Error was: " ++ err return (Left ("Failed to convert DB entry of key from JSON to Haskell type. Error was: " ++ err)) (Right k) -> do putStrLn "SUCCESS! Good job. successfully read the TPM_PUBKEY out of the sql db as json and converted to TPM_PUBKEY object" return (Right k) --putStrLn "thats all for now" readPubEK :: IO TPM_PUBKEY readPubEK = do handle <- openFile AD.exportEKFileName ReadMode pubKeyString <- hGetLine handle let pubKey :: TPM_PUBKEY pubKey = read pubKeyString hClose handle return pubKey -}
armoredsoftware/protocol
tpm/mainline/privacyCA/ScottyCA.hs
bsd-3-clause
4,301
0
10
1,096
156
102
54
19
1
module Globber (matchGlob) where import Globber.GlobParser import Globber.Glob -- | Matches a glob on a string. -- -- >>> matchGlob "abcd" "abcd" -- True -- -- >>> matchGlob "a[b-z]c" "adc" -- True -- -- >>> matchGlob "a[abcd]c" "abc" -- True -- -- >>> matchGlob "a[xyz]c" "abc" -- False -- -- >>> matchGlob "a?c" "adc" -- True -- -- >>> matchGlob "/usr/*/stuff" "/usr/glob/stuff" -- True -- -- >>> matchGlob "/usr/*/stuff" "/usr/stuff" -- False -- -- >>> matchGlob "\\a\\b\\c\\d\\e\\[]" "abcde[]" -- True -- -- >>> matchGlob "da?id*[1-9]" "davidcool3" -- True -- -- >>> matchGlob "da?id*[1-9]" "davidcool" -- False matchGlob :: String -> String -> Bool matchGlob glob input = match input . parseGlob $ glob
andgate/globber
src/Globber.hs
bsd-3-clause
712
0
7
117
84
60
24
6
1
-- | Layout routine for Data.Tree module Tree ( module Data.Tree , module Autolib.Dot.Dot , module Tree.Class , peng ) where import Data.Tree import Autolib.Dot.Dot import Autolib.Dot.Dotty import Tree.Class import Tree.Dot
Erdwolf/autotool-bonn
src/Tree.hs
gpl-2.0
233
0
5
40
56
37
19
10
0
-- | Transform an error to a user-friendly string. module Language.Java.Paragon.ErrorTxt (errorTxt, errorTxtOld) where import Language.Java.Paragon.Error import Language.Java.Paragon.SourcePos import System.Exit -- for old style error messages -- | Comvert context information into a string, always ends with a new line. contextTxt :: ContextInfo -> String contextTxt (ClassContext s) = "In the context of class " ++ s ++ ":\n" contextTxt (MethodContext s) = "In the context of method " ++ s ++ ":\n" contextTxt (LockStateContext s) = "In the context of lock state " ++ s ++ ":\n" contextTxt (LockSignatureContext s) = "When checking the signature of lock " ++ s ++ ":\n" contextTxt (ConstructorBodyContext s) = "When checking the body of constructor " ++ s ++ ":\n" contextTxt EmptyContext = "" contextTxt (FallbackContext s) = "In fallback context. " ++ s ++ ":\n" -- | Prints error information for all errors found in this file errorTxt :: (String, [Error]) -> IO () errorTxt (_, []) = return () errorTxt (file, err) = mapM_ (\(Error info pos context) -> do dispSourcePos file pos putStrLn $ concat (map contextTxt (reverse context)) ++ errorTxt' info putStrLn "" ) (reverse err) -- | Old style error message reporting, for keeping the test suite working errorTxtOld :: (String, [Error]) -> IO () errorTxtOld (_, []) = return () errorTxtOld (_, [Error info _pos context]) = do putStrLn $ concat (map contextTxt (reverse context)) ++ errorTxt' info exitWith $ ExitFailure (-1) errorTxtOld (s, _e:err) = errorTxtOld (s, err) -- | Displays name of the file, line in the file and an ascii-art arrow -- pointing to the column in the specified sourcepos (unless the position is -- the default, in which case only the name of the file is shown). dispSourcePos :: String -> SourcePos -> IO () dispSourcePos file pos = if (realEqSourcePos pos defaultPos) then do putStrLn $ "In " ++ file ++ " at unknown line:" else do putStrLn $ "In " ++ file ++ " line " ++ (show . sourceLine $ pos) ++ ":" fc <- readFile file putStrLn $ " " ++ (lines fc !! (sourceLine pos - 1)) putStrLn $ " " ++ (replicate (sourceColumn pos - 1) '-') ++ "^" -- | Convert an error to a human readable string errorTxt' :: ErrorInfo -> String -- NameResolution errorTxt' (UnresolvedName typ name) = "Unresolved name: " ++ typ ++ " " ++ name ++ " not in scope" errorTxt' (AmbiguousName nt ident pre1 pre2) = "Ambiguous " ++ nt ++ " " ++ ident ++ "\nCould refer to either of:" ++ "\n " ++ pre1 ++ "\n " ++ pre2 errorTxt' (IllegalDeref typ name) = "Cannot dereference " ++ typ ++ ": " ++ name errorTxt' (EInPackage expr expType pkg) = "Package " ++ pkg ++ " cannot have " ++ expType ++ " " ++ expr ++ " as a direct member." -- TcDeclM errorTxt' (FileClassMismatch className) = "Class " ++ className ++ " is public, should be declared in a file named " ++ className ++ ".para" errorTxt' (FileInterfaceMismatch interfaceName) = "Interface " ++ interfaceName ++ " is public, should be declared in a file named " ++ interfaceName ++ ".para" errorTxt' (FileClassMismatchFetchType fname cname) = "Filename " ++ fname ++ " does not match expected class name " ++ cname errorTxt' (VariableAlreadyDefined varName) = "Variable " ++ varName ++ " is already defined" errorTxt' (FieldAlreadyDefined fieldName) = "Field " ++ fieldName ++ " is already defined" errorTxt' (PolicyAlreadyDefined policyName) = "Policy " ++ policyName ++ " is already defined" errorTxt' (ParameterAlreadyDefined paramName) = "Parameter " ++ paramName ++ " is already defined" errorTxt' (MethodAlreadyDefined methodName) = "Method " ++ methodName ++ " is already defined" errorTxt' ConstructorAlreadyDefined = "Such constructor is already defined" -- TcCodeM errorTxt' MissingReturnStatement = "Missing return statement" errorTxt' (NonStaticMethodReferencedFromStatic methodName) = "Non-static method " ++ methodName ++ " cannot be referenced from a static context" errorTxt' (NonStaticFieldReferencedFromStatic fieldName) = "Non-static field " ++ fieldName ++ " cannot be referenced from a static context" -- TcExp errorTxt' (LArityMismatch lname expr got) = "Lock " ++ lname ++ " expects " ++ (show expr) ++ " arguments, but has been " ++ "given " ++ (show got) ++ "." errorTxt' (FieldLRTObject field obj opol fpol) = "Cannot update field " ++ field ++ " of object " ++ obj ++ ": policy of field must be no less restrictive than that of the " ++ "object when updating.\n" ++ "Object policy: " ++ opol ++ "\n" ++ "Field policy: " ++ fpol errorTxt' (ArrayLRTIndex arr arrP ind indP) = "When assigning into an array, the policy on the index expression may be no " ++ "more restrictive than the policy of the array itself\n" ++ "Array: " ++ arr ++ "\n" ++ " has policy " ++ arrP ++ "\n" ++ "Index: " ++ ind ++ "\n" ++ " has policy " ++ indP errorTxt' (ExprLRTArray expr arrP expP) = "Cannot update element in array resulting from expression " ++ expr ++ ": policy of elements must be no less restrictive than that of the " ++ "array itself when updating\n" ++ "Array policy: " ++ arrP ++ "\n" ++ "Element policy: " ++ expP errorTxt' (NoSuchField oref otype field) = "Object " ++ oref ++ " of type " ++ otype ++ " does not have a field named " ++ field errorTxt' (PolViolatedAss frEx frPo toEx toPo) = "Cannot assign result of expression " ++ frEx ++ " with policy " ++ frPo ++ " to location " ++ toEx ++ " with policy " ++ toPo errorTxt' (NonIntIndex ty) = "Non-integral expression of type " ++ ty ++ " used as array index expression" errorTxt' (NonArrayIndexed expr ty) = "Cannot index non-array expression " ++ expr ++ " of type " ++ ty errorTxt' (NotSupported sort val) = "Not supported " ++ sort ++ ": " ++ val errorTxt' (NNFieldAssN field expr) = "Field " ++ field ++ " can't be assigned to the potentially null expression " ++ expr errorTxt' (TypeMismatch ty1 ty2) = "Type mismatch: " ++ ty1 ++ " <=> " ++ ty2 errorTxt' (UnificationFailed loc)= "Cannot unify policy type parameters at " ++ loc errorTxt' (WriteBounded lhs lhsP src writeB) = "Assignment to " ++ lhs ++ " with policy " ++ lhsP ++ " not allowed in " ++ src ++ " with write effect bound " ++ writeB errorTxt' (CondNotBool ty) = "Conditional expression requires a condition of type compatible with boolean" ++ "\nFound type: " ++ ty errorTxt' BranchTypeMismatch = "Types of branches don't match" errorTxt' (OpNotIntegral op ty) = op ++ " operator used at non-integral type " ++ ty errorTxt' (OpNotBoolean op ty) = op ++ " operator used at non-boolean type " ++ ty errorTxt' (OpNotNumeric op ty) = op ++ " operator used at non-numeric type " ++ ty errorTxt' WrongCastT = "Wrong type at cast" errorTxt' ArrayZeroDim = "Array creation must have at least one dimension expression, or an explicit " ++ "initializer" errorTxt' (NonIntDimArray ty) = "Non-integral expression of type " ++ ty ++ " used as dimension expression in array creation" errorTxt' (ArrayDimPol expr pol polB) = "Array dimension expression has too restrictive policy:\n" ++ "Expression: " ++ expr ++ "\n" ++ " with policy: " ++ pol ++ "\n" ++ "Declared policy bound: " ++ polB errorTxt' (ArrayInitExpPol expr exprP polB) = "Expression in array initializer has too restrictive policy:\n" ++ "Expression: " ++ expr ++ "\n" ++ " with policy: " ++ exprP ++ "\n" ++ "Declared policy bound: " ++ polB errorTxt' (MethodArgRestr mi arg argP parP) = "Method applied to argument with too restrictive policy:\n" ++ "Method invocation: " ++ mi ++ "\n" ++ "Argument: " ++ arg ++ "\n" ++ " with policy: " ++ argP ++ "\n" ++ "Declared policy bound: " ++ parP errorTxt' (ParsingError p) = "Parsing error: " ++ p errorTxt' (FallbackError e) = e -- Others errorTxt' e = "Extra error: Show instance for this error not available:\n" ++ show e
bvdelft/parac2
src/Language/Java/Paragon/ErrorTxt.hs
bsd-3-clause
8,013
0
16
1,672
1,936
983
953
163
2
{-| Module : Idris.ElabDecls Description : Code to elaborate declarations. Copyright : License : BSD3 Maintainer : The Idris Community. -} {-# LANGUAGE DeriveFunctor, FlexibleInstances, MultiParamTypeClasses, PatternGuards #-} module Idris.ElabDecls where import Idris.AbsSyntax import Idris.ASTUtils import Idris.Core.CaseTree import Idris.Core.Elaborate hiding (Tactic(..)) import Idris.Core.Evaluate import Idris.Core.Execute import Idris.Core.TT import Idris.Core.Typecheck import Idris.Coverage import Idris.DataOpts import Idris.DeepSeq import Idris.Delaborate import Idris.Directives import Idris.Docstrings hiding (Unchecked) import Idris.DSL import Idris.Elab.Clause import Idris.Elab.Data import Idris.Elab.Implementation import Idris.Elab.Interface import Idris.Elab.Provider import Idris.Elab.Record import Idris.Elab.RunElab import Idris.Elab.Term import Idris.Elab.Transform import Idris.Elab.Type import Idris.Elab.Utils import Idris.Elab.Value import Idris.Error import Idris.Imports import Idris.Inliner import Idris.Output (iWarn, iputStrLn, pshow, sendHighlighting) import Idris.PartialEval import Idris.Primitives import Idris.Providers import Idris.Termination import IRTS.Lang import Util.Pretty (pretty, text) import Prelude hiding (id, (.)) import Control.Applicative hiding (Const) import Control.Category import Control.DeepSeq import Control.Monad import Control.Monad.State.Strict as State import Data.Char (isLetter, toLower) import Data.List import Data.List.Split (splitOn) import qualified Data.Map as Map import Data.Maybe import qualified Data.Set as S import qualified Data.Text as T import Debug.Trace -- | Top level elaborator info, supporting recursive elaboration recinfo :: FC -> ElabInfo recinfo fc = EInfo [] emptyContext id [] (Just fc) (fc_fname fc) 0 id elabDecl' -- | Return the elaborated term which calls 'main' elabMain :: Idris Term elabMain = do (m, _) <- elabVal (recinfo fc) ERHS (PApp fc (PRef fc [] (sUN "run__IO")) [pexp $ PRef fc [] (sNS (sUN "main") ["Main"])]) return m where fc = fileFC "toplevel" -- | Elaborate primitives elabPrims :: Idris () elabPrims = do i <- getIState let cs_in = idris_constraints i let mkdec opt decl docs argdocs = PData docs argdocs defaultSyntax (fileFC "builtin") opt decl elabDecl' EAll (recinfo primfc) (mkdec inferOpts inferDecl emptyDocstring []) -- We don't want the constraints generated by 'Infer' since -- it's only scaffolding for the elaborator i <- getIState putIState $ i { idris_constraints = cs_in } elabDecl' EAll (recinfo primfc) (mkdec eqOpts eqDecl eqDoc eqParamDoc) addNameHint eqTy (sUN "prf") mapM_ elabPrim primitives -- Special case prim__believe_me because it doesn't work on just constants elabBelieveMe -- Finally, syntactic equality elabSynEq where elabPrim :: Prim -> Idris () elabPrim (Prim n ty i def sc tot) = do updateContext (addOperator n ty i (valuePrim def)) setTotality n tot i <- getIState putIState i { idris_scprims = (n, sc) : idris_scprims i } primfc = fileFC "primitive" valuePrim :: ([Const] -> Maybe Const) -> [Value] -> Maybe Value valuePrim prim vals = fmap VConstant (mapM getConst vals >>= prim) getConst (VConstant c) = Just c getConst _ = Nothing p_believeMe [_,_,x] = Just x p_believeMe _ = Nothing believeTy = Bind (sUN "a") (Pi RigW Nothing (TType (UVar [] (-2))) (TType (UVar [] (-1)))) (Bind (sUN "b") (Pi RigW Nothing (TType (UVar [] (-2))) (TType (UVar [] (-1)))) (Bind (sUN "x") (Pi RigW Nothing (V 1) (TType (UVar [] (-1)))) (V 1))) elabBelieveMe = do let prim__believe_me = sUN "prim__believe_me" updateContext (addOperator prim__believe_me believeTy 3 p_believeMe) -- The point is that it is believed to be total, even -- though it clearly isn't :) setTotality prim__believe_me (Total []) i <- getIState putIState i { idris_scprims = (prim__believe_me, (3, LNoOp)) : idris_scprims i } p_synEq [t,_,x,y] | x == y = Just (VApp (VApp vnJust VErased) (VApp (VApp vnRefl t) x)) | otherwise = Just (VApp vnNothing VErased) p_synEq args = Nothing nMaybe = P (TCon 0 2) (sNS (sUN "Maybe") ["Maybe", "Prelude"]) Erased vnJust = VP (DCon 1 2 False) (sNS (sUN "Just") ["Maybe", "Prelude"]) VErased vnNothing = VP (DCon 0 1 False) (sNS (sUN "Nothing") ["Maybe", "Prelude"]) VErased vnRefl = VP (DCon 0 2 False) eqCon VErased synEqTy = Bind (sUN "a") (Pi RigW Nothing (TType (UVar [] (-3))) (TType (UVar [] (-2)))) (Bind (sUN "b") (Pi RigW Nothing (TType (UVar [] (-3))) (TType (UVar [] (-2)))) (Bind (sUN "x") (Pi RigW Nothing (V 1) (TType (UVar [] (-2)))) (Bind (sUN "y") (Pi RigW Nothing (V 1) (TType (UVar [] (-2)))) (mkApp nMaybe [mkApp (P (TCon 0 4) eqTy Erased) [V 3, V 2, V 1, V 0]])))) elabSynEq = do let synEq = sUN "prim__syntactic_eq" updateContext (addOperator synEq synEqTy 4 p_synEq) setTotality synEq (Total []) i <- getIState putIState i { idris_scprims = (synEq, (4, LNoOp)) : idris_scprims i } elabDecls :: ElabInfo -> [PDecl] -> Idris () elabDecls info ds = do mapM_ (elabDecl EAll info) ds elabDecl :: ElabWhat -> ElabInfo -> PDecl -> Idris () elabDecl what info d = let info' = info { rec_elabDecl = elabDecl' } in idrisCatch (withErrorReflection $ elabDecl' what info' d) (setAndReport) elabDecl' _ info (PFix _ _ _) = return () -- nothing to elaborate elabDecl' _ info (PSyntax _ p) = return () -- nothing to elaborate elabDecl' what info (PTy doc argdocs s f o n nfc ty) | what /= EDefns = do logElab 1 $ "Elaborating type decl " ++ show n ++ show o elabType info s doc argdocs f o n nfc ty return () elabDecl' what info (PPostulate b doc s f nfc o n ty) | what /= EDefns = do logElab 1 $ "Elaborating postulate " ++ show n ++ show o if b then elabExtern info s doc f nfc o n ty else elabPostulate info s doc f nfc o n ty elabDecl' what info (PData doc argDocs s f co d) | what /= ETypes = do logElab 1 $ "Elaborating " ++ show (d_name d) elabData info s doc argDocs f co d | otherwise = do logElab 1 $ "Elaborating [type of] " ++ show (d_name d) elabData info s doc argDocs f co (PLaterdecl (d_name d) (d_name_fc d) (d_tcon d)) elabDecl' what info d@(PClauses f o n ps) | what /= ETypes = do logElab 1 $ "Elaborating clause " ++ show n i <- getIState -- get the type options too let o' = case lookupCtxt n (idris_flags i) of [fs] -> fs [] -> [] elabClauses info f (o ++ o') n ps elabDecl' what info (PMutual f ps) = do case ps of [p] -> elabDecl what info p _ -> do mapM_ (elabDecl ETypes info) ps mapM_ (elabDecl EDefns info) ps -- record mutually defined data definitions let datans = concatMap declared (getDataDecls ps) mapM_ (setMutData datans) datans logElab 1 $ "Rechecking for positivity " ++ show datans mapM_ (\x -> do setTotality x Unchecked) datans -- Do totality checking after entire mutual block i <- get mapM_ (\n -> do logElab 5 $ "Simplifying " ++ show n ctxt' <- do ctxt <- getContext tclift $ simplifyCasedef n (getErasureInfo i) ctxt setContext ctxt') (map snd (idris_totcheck i)) mapM_ buildSCG (idris_totcheck i) mapM_ checkDeclTotality (idris_totcheck i) -- We've only checked that things are total independently. Given -- the ordering, something we think is total might have called -- something we hadn't checked yet mapM_ verifyTotality (idris_totcheck i) clear_totcheck where isDataDecl (PData _ _ _ _ _ _) = True isDataDecl _ = False getDataDecls (PNamespace _ _ ds : decls) = getDataDecls ds ++ getDataDecls decls getDataDecls (d : decls) | isDataDecl d = d : getDataDecls decls | otherwise = getDataDecls decls getDataDecls [] = [] setMutData ns n = do i <- getIState case lookupCtxt n (idris_datatypes i) of [x] -> do let x' = x { mutual_types = ns } putIState $ i { idris_datatypes = addDef n x' (idris_datatypes i) } _ -> return () elabDecl' what info (PParams f ns ps) = do i <- getIState logElab 1 $ "Expanding params block with " ++ show ns ++ " decls " ++ show (concatMap tldeclared ps) let nblock = pblock i mapM_ (elabDecl' what info) nblock where pinfo = let ds = concatMap tldeclared ps newps = params info ++ ns dsParams = map (\n -> (n, map fst newps)) ds newb = addAlist dsParams (inblock info) in info { params = newps, inblock = newb } pblock i = map (expandParamsD False i id ns (concatMap tldeclared ps)) ps elabDecl' what info (POpenInterfaces f ns ds) = do open <- addOpenImpl ns mapM_ (elabDecl' what info) ds setOpenImpl open elabDecl' what info (PNamespace n nfc ps) = do mapM_ (elabDecl' what ninfo) ps let ns = reverse (map T.pack newNS) sendHighlighting [(nfc, AnnNamespace ns Nothing)] where newNS = n : namespace info ninfo = info { namespace = newNS } elabDecl' what info (PInterface doc s f cs n nfc ps pdocs fds ds cn cd) | what /= EDefns = do logElab 1 $ "Elaborating interface " ++ show n elabInterface info (s { syn_params = [] }) doc f cs n nfc ps pdocs fds ds cn cd elabDecl' what info (PImplementation doc argDocs s f cs pnames acc fnopts n nfc ps pextra t expn ds) = do logElab 1 $ "Elaborating implementation " ++ show n elabImplementation info s doc argDocs what f cs pnames acc fnopts n nfc ps pextra t expn ds elabDecl' what info (PRecord doc rsyn fc opts name nfc ps pdocs fs cname cdoc csyn) = do logElab 1 $ "Elaborating record " ++ show name elabRecord info what doc rsyn fc opts name nfc ps pdocs fs cname cdoc csyn {- | otherwise = do logElab 1 $ "Elaborating [type of] " ++ show tyn elabData info s doc [] f [] (PLaterdecl tyn ty) -} elabDecl' _ info (PDSL n dsl) = do i <- getIState unless (DSLNotation `elem` idris_language_extensions i) $ ifail "You must turn on the DSLNotation extension to use a dsl block" putIState (i { idris_dsls = addDef n dsl (idris_dsls i) }) addIBC (IBCDSL n) elabDecl' what info (PDirective i) | what /= EDefns = directiveAction i elabDecl' what info (PProvider doc syn fc nfc provWhat n) | what /= EDefns = do logElab 1 $ "Elaborating type provider " ++ show n elabProvider doc info syn fc nfc provWhat n elabDecl' what info (PTransform fc safety old new) = do elabTransform info fc safety old new return () elabDecl' what info (PRunElabDecl fc script ns) = do i <- getIState unless (ElabReflection `elem` idris_language_extensions i) $ ierror $ At fc (Msg "You must turn on the ElabReflection extension to use %runElab") elabRunElab info fc script ns return () elabDecl' _ _ _ = return () -- skipped this time
bravit/Idris-dev
src/Idris/ElabDecls.hs
bsd-3-clause
12,461
0
21
3,986
4,096
2,044
2,052
247
8
{-# LANGUAGE Haskell98 #-} {-# LINE 1 "Blaze/ByteString/Builder/ByteString.hs" #-} ------------------------------------------------------------------------------ -- | -- Module: Blaze.ByteString.Builder.ByteString -- Copyright: (c) 2013 Leon P Smith -- License: BSD3 -- Maintainer: Leon P Smith <[email protected]> -- Stability: experimental -- -- 'Write's and 'B.Builder's for strict and lazy bytestrings. -- -- We assume the following qualified imports in order to differentiate between -- strict and lazy bytestrings in the code examples. -- -- > import qualified Data.ByteString as S -- > import qualified Data.ByteString.Lazy as L -- ------------------------------------------------------------------------------ module Blaze.ByteString.Builder.ByteString ( -- * Strict bytestrings writeByteString , fromByteString , fromByteStringWith , copyByteString , insertByteString -- * Lazy bytestrings , fromLazyByteString , fromLazyByteStringWith , copyLazyByteString , insertLazyByteString ) where import Blaze.ByteString.Builder.Internal.Write ( Write, exactWrite ) import Foreign import qualified Data.ByteString.Builder as B import qualified Data.ByteString.Builder.Extra as B import qualified Data.ByteString as S import qualified Data.ByteString.Internal as S import qualified Data.ByteString.Lazy as L -- | Write a strict 'S.ByteString' to a buffer. writeByteString :: S.ByteString -> Write writeByteString bs = exactWrite l io where (fptr, o, l) = S.toForeignPtr bs io pf = withForeignPtr fptr $ \p -> copyBytes pf (p `plusPtr` o) l {-# INLINE writeByteString #-} -- | Create a 'B.Builder' denoting the same sequence of bytes as a strict -- 'S.ByteString'. -- The 'B.Builder' inserts large 'S.ByteString's directly, but copies small ones -- to ensure that the generated chunks are large on average. fromByteString :: S.ByteString -> B.Builder fromByteString = B.byteString {-# INLINE fromByteString #-} -- | Construct a 'B.Builder' that copies the strict 'S.ByteString's, if it is -- smaller than the treshold, and inserts it directly otherwise. -- -- For example, @fromByteStringWith 1024@ copies strict 'S.ByteString's whose size -- is less or equal to 1kb, and inserts them directly otherwise. This implies -- that the average chunk-size of the generated lazy 'L.ByteString' may be as -- low as 513 bytes, as there could always be just a single byte between the -- directly inserted 1025 byte, strict 'S.ByteString's. -- fromByteStringWith :: Int -- ^ Maximal number of bytes to copy. -> S.ByteString -- ^ Strict 'S.ByteString' to serialize. -> B.Builder -- ^ Resulting 'B.Builder'. fromByteStringWith = B.byteStringThreshold {-# INLINE fromByteStringWith #-} -- | Construct a 'B.Builder' that copies the strict 'S.ByteString'. -- -- Use this function to create 'B.Builder's from smallish (@<= 4kb@) -- 'S.ByteString's or if you need to guarantee that the 'S.ByteString' is not -- shared with the chunks generated by the 'B.Builder'. -- copyByteString :: S.ByteString -> B.Builder copyByteString = B.byteStringCopy {-# INLINE copyByteString #-} -- | Construct a 'B.Builder' that always inserts the strict 'S.ByteString' -- directly as a chunk. -- -- This implies flushing the output buffer, even if it contains just -- a single byte. You should therefore use 'insertByteString' only for large -- (@> 8kb@) 'S.ByteString's. Otherwise, the generated chunks are too -- fragmented to be processed efficiently afterwards. -- insertByteString :: S.ByteString -> B.Builder insertByteString = B.byteStringInsert {-# INLINE insertByteString #-} -- | Create a 'B.Builder' denoting the same sequence of bytes as a lazy -- 'S.ByteString'. -- The 'B.Builder' inserts large chunks of the lazy 'L.ByteString' directly, -- but copies small ones to ensure that the generated chunks are large on -- average. -- fromLazyByteString :: L.ByteString -> B.Builder fromLazyByteString = B.lazyByteString {-# INLINE fromLazyByteString #-} -- | Construct a 'B.Builder' that uses the thresholding strategy of 'fromByteStringWith' -- for each chunk of the lazy 'L.ByteString'. -- fromLazyByteStringWith :: Int -> L.ByteString -> B.Builder fromLazyByteStringWith = B.lazyByteStringThreshold {-# INLINE fromLazyByteStringWith #-} -- | Construct a 'B.Builder' that copies the lazy 'L.ByteString'. -- copyLazyByteString :: L.ByteString -> B.Builder copyLazyByteString = B.lazyByteStringCopy {-# INLINE copyLazyByteString #-} -- | Construct a 'B.Builder' that inserts all chunks of the lazy 'L.ByteString' -- directly. -- insertLazyByteString :: L.ByteString -> B.Builder insertLazyByteString = B.lazyByteStringInsert {-# INLINE insertLazyByteString #-}
phischu/fragnix
tests/packages/scotty/Blaze.ByteString.Builder.ByteString.hs
bsd-3-clause
4,814
0
11
807
426
283
143
51
1
module Main where import Prelude import Test.Hspec import IHaskell.Test.Completion (testCompletions) import IHaskell.Test.Parser (testParser) import IHaskell.Test.Eval (testEval) main :: IO () main = hspec $ do testParser testEval testCompletions
thomasjm/IHaskell
src/tests/Hspec.hs
mit
316
0
7
97
73
42
31
12
1
module Keyboard (Keyboard ,pressed ,keyboardCallback ,initialKeyboardState) where import Data.IORef import qualified Data.Set as Set import qualified Graphics.UI.GLUT as GLUT newtype Keyboard = Keyboard (Set.Set GLUT.Key) pressed :: GLUT.Key -> Keyboard -> Bool pressed key (Keyboard set) = Set.member key set keyboardCallback :: IORef Keyboard -> GLUT.KeyboardMouseCallback keyboardCallback ref key GLUT.Down _ _ = modifyIORef ref add where add (Keyboard set) = Keyboard $ Set.insert key set keyboardCallback ref key GLUT.Up _ _ = modifyIORef ref remove where remove (Keyboard set) = Keyboard $ Set.delete key set initialKeyboardState :: Keyboard initialKeyboardState = Keyboard Set.empty
SonOfLilit/purewars
Keyboard.hs
bsd-3-clause
748
0
9
151
225
120
105
17
1
{-# LANGUAGE TemplateHaskell, MultiParamTypeClasses #-} -- | Support for quotes module Plugin.Slap (theModule) where import Plugin import qualified Message (nick, showNick) $(plugin "Quote") instance Module QuoteModule () where moduleCmds _ = ["slap", "smack"] moduleHelp _ _ = "slap <nick>. Slap someone amusingly." process _ msg _ _ rest = ios $ slapRandom (if rest == "me" then sender else rest) where sender = Message.showNick msg $ Message.nick msg ------------------------------------------------------------------------ -- | Return a random arr-quote slapRandom :: String -> IO String slapRandom = (randomElem slapList `ap`) . return slapList :: [String -> String] slapList = [(\x -> "/me slaps " ++ x) ,(\x -> "/me smacks " ++ x ++ " about with a large trout") ,(\x -> "/me beats up " ++ x) ,(\x -> "/me pokes " ++ x ++ " in the eye") ,(\x -> "why on earth would I slap " ++ x ++ "?") ,(\x -> "*SMACK*, *SLAM*, take that " ++ x ++ "!") ,(\_ -> "/me activates her slap-o-matic...") ,(\x -> "/me orders her trained monkeys to punch " ++ x) ,(\x -> "/me smashes a lamp on " ++ possesiveForm x ++ " head") ,(\x -> "/me hits " ++ x ++ " with a hammer, so they breaks into a thousand pieces") ,(\x -> "/me throws some pointy lambdas at " ++ x) ,(\x -> "/me loves " ++ x ++ ", so no slapping") ,(\x -> "/me would never hurt " ++ x ++ "!") ,(\x -> "go slap " ++ x ++ " yourself") ,(\_ -> "I won't; I want to go get some cookies instead.") ,(\x -> "I'd rather not; " ++ x ++ " looks rather dangerous.") ,(\_ -> "I don't perform such side effects on command!") ,(\_ -> "stop telling me what to do") ,(\x -> "/me clobbers " ++ x ++ " with an untyped language") ,(\x -> "/me pulls " ++ x ++ " through the Evil Mangler") ,(\x -> "/me secretly deletes " ++ possesiveForm x ++ " source code") ,(\x -> "/me places her fist firmly on " ++ possesiveForm x ++ " jaw") ,(\x -> "/me locks up " ++ x ++ " in a Monad") ,(\x -> "/me submits " ++ possesiveForm x ++ " email address to a dozen spam lists") ,(\x -> "/me moulds " ++ x ++ " into a delicous cookie, and places it in her oven") ,(\_ -> "/me will count to five...") ,(\x -> "/me jabs " ++ x ++ " with a C pointer") ,(\x -> "/me is overcome by a sudden desire to hurt " ++ x) ,(\x -> "/me karate-chops " ++ x ++ " into two equally sized halves") ,(\x -> "Come on, let's all slap " ++ x) ,(\x -> "/me pushes " ++ x ++ " from his chair") ,(\x -> "/me hits " ++ x ++ " with an assortment of kitchen utensils") ,(\x -> "/me slaps " ++ x ++ " with a slab of concrete") ,(\x -> "/me puts on her slapping gloves, and slaps " ++ x) ,(\x -> "/me decomposes " ++ x ++ " into several parts using the Banach-Tarski theorem and reassembles them to get two copies of " ++ x ++ "!") ] -- | The possesive form of a name, "x's" possesiveForm :: String -> String possesiveForm [] = [] possesiveForm x | last x == 's' = x ++ "'" | otherwise = x ++ "'s"
dmalikov/lambdabot
Plugin/Slap.hs
mit
3,071
0
11
772
859
489
370
54
1
module Distribution.Client.Dependency.Modular.Validate (validateTree) where -- Validation of the tree. -- -- The task here is to make sure all constraints hold. After validation, any -- assignment returned by exploration of the tree should be a complete valid -- assignment, i.e., actually constitute a solution. import Control.Applicative import Control.Monad.Reader hiding (sequence) import Data.List as L import Data.Map as M import Data.Set as S import Data.Traversable import Prelude hiding (sequence) import Language.Haskell.Extension (Extension, Language) import Distribution.Compiler (CompilerInfo(..)) import Distribution.Client.Dependency.Modular.Assignment import Distribution.Client.Dependency.Modular.Dependency import Distribution.Client.Dependency.Modular.Flag import Distribution.Client.Dependency.Modular.Index import Distribution.Client.Dependency.Modular.Package import qualified Distribution.Client.Dependency.Modular.PSQ as P import Distribution.Client.Dependency.Modular.Tree import Distribution.Client.ComponentDeps (Component) -- In practice, most constraints are implication constraints (IF we have made -- a number of choices, THEN we also have to ensure that). We call constraints -- that for which the preconditions are fulfilled ACTIVE. We maintain a set -- of currently active constraints that we pass down the node. -- -- We aim at detecting inconsistent states as early as possible. -- -- Whenever we make a choice, there are two things that need to happen: -- -- (1) We must check that the choice is consistent with the currently -- active constraints. -- -- (2) The choice increases the set of active constraints. For the new -- active constraints, we must check that they are consistent with -- the current state. -- -- We can actually merge (1) and (2) by saying the the current choice is -- a new active constraint, fixing the choice. -- -- If a test fails, we have detected an inconsistent state. We can -- disable the current subtree and do not have to traverse it any further. -- -- We need a good way to represent the current state, i.e., the current -- set of active constraints. Since the main situation where we have to -- search in it is (1), it seems best to store the state by package: for -- every package, we store which versions are still allowed. If for any -- package, we have inconsistent active constraints, we can also stop. -- This is a particular way to read task (2): -- -- (2, weak) We only check if the new constraints are consistent with -- the choices we've already made, and add them to the active set. -- -- (2, strong) We check if the new constraints are consistent with the -- choices we've already made, and the constraints we already have. -- -- It currently seems as if we're implementing the weak variant. However, -- when used together with 'preferEasyGoalChoices', we will find an -- inconsistent state in the very next step. -- -- What do we do about flags? -- -- Like for packages, we store the flag choices we have already made. -- Now, regarding (1), we only have to test whether we've decided the -- current flag before. Regarding (2), the interesting bit is in discovering -- the new active constraints. To this end, we look up the constraints for -- the package the flag belongs to, and traverse its flagged dependencies. -- Wherever we find the flag in question, we start recording dependencies -- underneath as new active dependencies. If we encounter other flags, we -- check if we've chosen them already and either proceed or stop. -- | The state needed during validation. data ValidateState = VS { supportedExt :: Extension -> Bool, supportedLang :: Language -> Bool, index :: Index, saved :: Map QPN (FlaggedDeps Component QPN), -- saved, scoped, dependencies pa :: PreAssignment, qualifyOptions :: QualifyOptions } type Validate = Reader ValidateState validate :: Tree QGoalReasonChain -> Validate (Tree QGoalReasonChain) validate = cata go where go :: TreeF QGoalReasonChain (Validate (Tree QGoalReasonChain)) -> Validate (Tree QGoalReasonChain) go (PChoiceF qpn gr ts) = PChoice qpn gr <$> sequence (P.mapWithKey (goP qpn gr) ts) go (FChoiceF qfn gr b m ts) = do -- Flag choices may occur repeatedly (because they can introduce new constraints -- in various places). However, subsequent choices must be consistent. We thereby -- collapse repeated flag choice nodes. PA _ pfa _ <- asks pa -- obtain current flag-preassignment case M.lookup qfn pfa of Just rb -> -- flag has already been assigned; collapse choice to the correct branch case P.lookup rb ts of Just t -> goF qfn gr rb t Nothing -> return $ Fail (toConflictSet (Goal (F qfn) gr)) (MalformedFlagChoice qfn) Nothing -> -- flag choice is new, follow both branches FChoice qfn gr b m <$> sequence (P.mapWithKey (goF qfn gr) ts) go (SChoiceF qsn gr b ts) = do -- Optional stanza choices are very similar to flag choices. PA _ _ psa <- asks pa -- obtain current stanza-preassignment case M.lookup qsn psa of Just rb -> -- stanza choice has already been made; collapse choice to the correct branch case P.lookup rb ts of Just t -> goS qsn gr rb t Nothing -> return $ Fail (toConflictSet (Goal (S qsn) gr)) (MalformedStanzaChoice qsn) Nothing -> -- stanza choice is new, follow both branches SChoice qsn gr b <$> sequence (P.mapWithKey (goS qsn gr) ts) -- We don't need to do anything for goal choices or failure nodes. go (GoalChoiceF ts) = GoalChoice <$> sequence ts go (DoneF rdm ) = pure (Done rdm) go (FailF c fr ) = pure (Fail c fr) -- What to do for package nodes ... goP :: QPN -> QGoalReasonChain -> POption -> Validate (Tree QGoalReasonChain) -> Validate (Tree QGoalReasonChain) goP qpn@(Q _pp pn) gr (POption i _) r = do PA ppa pfa psa <- asks pa -- obtain current preassignment extSupported <- asks supportedExt -- obtain the supported extensions langSupported <- asks supportedLang -- obtain the supported languages idx <- asks index -- obtain the index svd <- asks saved -- obtain saved dependencies qo <- asks qualifyOptions -- obtain dependencies and index-dictated exclusions introduced by the choice let (PInfo deps _ mfr) = idx ! pn ! i -- qualify the deps in the current scope let qdeps = qualifyDeps qo qpn deps -- the new active constraints are given by the instance we have chosen, -- plus the dependency information we have for that instance let goal = Goal (P qpn) gr let newactives = Dep qpn (Fixed i goal) : L.map (resetGoal goal) (extractDeps pfa psa qdeps) -- We now try to extend the partial assignment with the new active constraints. let mnppa = extend extSupported langSupported goal ppa newactives -- In case we continue, we save the scoped dependencies let nsvd = M.insert qpn qdeps svd case mfr of Just fr -> -- The index marks this as an invalid choice. We can stop. return (Fail (toConflictSet goal) fr) _ -> case mnppa of Left (c, d) -> -- We have an inconsistency. We can stop. return (Fail c (Conflicting d)) Right nppa -> -- We have an updated partial assignment for the recursive validation. local (\ s -> s { pa = PA nppa pfa psa, saved = nsvd }) r -- What to do for flag nodes ... goF :: QFN -> QGoalReasonChain -> Bool -> Validate (Tree QGoalReasonChain) -> Validate (Tree QGoalReasonChain) goF qfn@(FN (PI qpn _i) _f) gr b r = do PA ppa pfa psa <- asks pa -- obtain current preassignment extSupported <- asks supportedExt -- obtain the supported extensions langSupported <- asks supportedLang -- obtain the supported languages svd <- asks saved -- obtain saved dependencies -- Note that there should be saved dependencies for the package in question, -- because while building, we do not choose flags before we see the packages -- that define them. let qdeps = svd ! qpn -- We take the *saved* dependencies, because these have been qualified in the -- correct scope. -- -- Extend the flag assignment let npfa = M.insert qfn b pfa -- We now try to get the new active dependencies we might learn about because -- we have chosen a new flag. let newactives = extractNewDeps (F qfn) gr b npfa psa qdeps -- As in the package case, we try to extend the partial assignment. case extend extSupported langSupported (Goal (F qfn) gr) ppa newactives of Left (c, d) -> return (Fail c (Conflicting d)) -- inconsistency found Right nppa -> local (\ s -> s { pa = PA nppa npfa psa }) r -- What to do for stanza nodes (similar to flag nodes) ... goS :: QSN -> QGoalReasonChain -> Bool -> Validate (Tree QGoalReasonChain) -> Validate (Tree QGoalReasonChain) goS qsn@(SN (PI qpn _i) _f) gr b r = do PA ppa pfa psa <- asks pa -- obtain current preassignment extSupported <- asks supportedExt -- obtain the supported extensions langSupported <- asks supportedLang -- obtain the supported languages svd <- asks saved -- obtain saved dependencies -- Note that there should be saved dependencies for the package in question, -- because while building, we do not choose flags before we see the packages -- that define them. let qdeps = svd ! qpn -- We take the *saved* dependencies, because these have been qualified in the -- correct scope. -- -- Extend the flag assignment let npsa = M.insert qsn b psa -- We now try to get the new active dependencies we might learn about because -- we have chosen a new flag. let newactives = extractNewDeps (S qsn) gr b pfa npsa qdeps -- As in the package case, we try to extend the partial assignment. case extend extSupported langSupported (Goal (S qsn) gr) ppa newactives of Left (c, d) -> return (Fail c (Conflicting d)) -- inconsistency found Right nppa -> local (\ s -> s { pa = PA nppa pfa npsa }) r -- | We try to extract as many concrete dependencies from the given flagged -- dependencies as possible. We make use of all the flag knowledge we have -- already acquired. extractDeps :: FAssignment -> SAssignment -> FlaggedDeps comp QPN -> [Dep QPN] extractDeps fa sa deps = do d <- deps case d of Simple sd _ -> return sd Flagged qfn _ td fd -> case M.lookup qfn fa of Nothing -> mzero Just True -> extractDeps fa sa td Just False -> extractDeps fa sa fd Stanza qsn td -> case M.lookup qsn sa of Nothing -> mzero Just True -> extractDeps fa sa td Just False -> [] -- | We try to find new dependencies that become available due to the given -- flag or stanza choice. We therefore look for the choice in question, and then call -- 'extractDeps' for everything underneath. extractNewDeps :: Var QPN -> QGoalReasonChain -> Bool -> FAssignment -> SAssignment -> FlaggedDeps comp QPN -> [Dep QPN] extractNewDeps v gr b fa sa = go where go :: FlaggedDeps comp QPN -> [Dep QPN] -- Type annotation necessary (polymorphic recursion) go deps = do d <- deps case d of Simple _ _ -> mzero Flagged qfn' _ td fd | v == F qfn' -> L.map (resetGoal (Goal v gr)) $ if b then extractDeps fa sa td else extractDeps fa sa fd | otherwise -> case M.lookup qfn' fa of Nothing -> mzero Just True -> go td Just False -> go fd Stanza qsn' td | v == S qsn' -> L.map (resetGoal (Goal v gr)) $ if b then extractDeps fa sa td else [] | otherwise -> case M.lookup qsn' sa of Nothing -> mzero Just True -> go td Just False -> [] -- | Interface. validateTree :: CompilerInfo -> Index -> Tree QGoalReasonChain -> Tree QGoalReasonChain validateTree cinfo idx t = runReader (validate t) VS { supportedExt = maybe (const True) -- if compiler has no list of extensions, we assume everything is supported (\ es -> let s = S.fromList es in \ x -> S.member x s) (compilerInfoExtensions cinfo) , supportedLang = maybe (const True) (flip L.elem) -- use list lookup because language list is small and no Ord instance (compilerInfoLanguages cinfo) , index = idx , saved = M.empty , pa = PA M.empty M.empty M.empty , qualifyOptions = defaultQualifyOptions idx }
randen/cabal
cabal-install/Distribution/Client/Dependency/Modular/Validate.hs
bsd-3-clause
13,465
0
22
3,854
2,575
1,329
1,246
145
14
data Bool = False | True not :: Bool -> Bool not = undefined (&&) :: Bool -> Bool -> Bool (&&) = undefined (||) :: Bool -> Bool -> Bool (||) = undefined class Eq a where (==) :: a -> a -> Bool x == y = not (x /= y) (/=) :: a -> a -> Bool x /= y = not (x == y) infix 4 == infix 4 /= instance Eq a => Eq [a] where [] == [] = True (x:xs) == [] = False [] == (y:ys) = False (x:xs) == (y:ys) = x == y && xs == ys
themattchan/tandoori
input/Eq.hs
bsd-3-clause
525
0
9
224
270
145
125
19
1
module A (message) where message :: String message = "Hello!!"
sdiehl/ghc
testsuite/tests/driver/T16500/A.hs
bsd-3-clause
64
0
4
11
19
12
7
3
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE FlexibleInstances #-} -- | Shared types for various stackage packages. module Stack.Types.BuildPlan ( -- * Types BuildPlan (..) , PackagePlan (..) , PackageConstraints (..) , TestState (..) , SystemInfo (..) , Maintainer (..) , ExeName (..) , SimpleDesc (..) , DepInfo (..) , Component (..) , SnapName (..) , MiniBuildPlan (..) , MiniPackageInfo (..) , renderSnapName , parseSnapName , isWindows ) where import Control.Applicative import Control.Arrow ((&&&)) import Control.Exception (Exception) import Control.Monad.Catch (MonadThrow, throwM) import Data.Aeson (FromJSON (..), ToJSON (..), object, withObject, withText, (.!=), (.:), (.:?), (.=)) import Data.Binary.VersionTagged import Data.ByteString (ByteString) import qualified Data.ByteString.Char8 as S8 import Data.Hashable (Hashable) import qualified Data.HashMap.Strict as HashMap import Data.Map (Map) import qualified Data.Map as Map import Data.Maybe (fromMaybe) import Data.Monoid import Data.Set (Set) import Data.String (IsString, fromString) import Data.Text (Text, pack, unpack) import qualified Data.Text as T import Data.Text.Encoding (encodeUtf8) import Data.Text.Read (decimal) import Data.Time (Day) import qualified Data.Traversable as T import Data.Typeable (TypeRep, Typeable, typeOf) import Data.Vector (Vector) import Distribution.System (Arch, OS (..)) import qualified Distribution.Text as DT import qualified Distribution.Version as C import GHC.Generics (Generic) import Prelude -- Fix AMP warning import Safe (readMay) import Stack.Types.FlagName import Stack.Types.PackageName import Stack.Types.Version -- | The name of an LTS Haskell or Stackage Nightly snapshot. data SnapName = LTS !Int !Int | Nightly !Day deriving (Show, Eq, Ord) data BuildPlan = BuildPlan { bpSystemInfo :: SystemInfo , bpTools :: Vector (PackageName, Version) , bpPackages :: Map PackageName PackagePlan , bpGithubUsers :: Map Text (Set Text) } deriving (Show, Eq) instance ToJSON BuildPlan where toJSON BuildPlan {..} = object [ "system-info" .= bpSystemInfo , "tools" .= fmap goTool bpTools , "packages" .= bpPackages , "github-users" .= bpGithubUsers ] where goTool (k, v) = object [ "name" .= k , "version" .= v ] instance FromJSON BuildPlan where parseJSON = withObject "BuildPlan" $ \o -> do bpSystemInfo <- o .: "system-info" bpTools <- o .: "tools" >>= T.mapM goTool bpPackages <- o .: "packages" bpGithubUsers <- o .:? "github-users" .!= mempty return BuildPlan {..} where goTool = withObject "Tool" $ \o -> (,) <$> o .: "name" <*> o .: "version" data PackagePlan = PackagePlan { ppVersion :: Version , ppGithubPings :: Set Text , ppUsers :: Set PackageName , ppConstraints :: PackageConstraints , ppDesc :: SimpleDesc } deriving (Show, Eq) instance ToJSON PackagePlan where toJSON PackagePlan {..} = object [ "version" .= ppVersion , "github-pings" .= ppGithubPings , "users" .= ppUsers , "constraints" .= ppConstraints , "description" .= ppDesc ] instance FromJSON PackagePlan where parseJSON = withObject "PackageBuild" $ \o -> do ppVersion <- o .: "version" ppGithubPings <- o .:? "github-pings" .!= mempty ppUsers <- o .:? "users" .!= mempty ppConstraints <- o .: "constraints" ppDesc <- o .: "description" return PackagePlan {..} display :: DT.Text a => a -> Text display = fromString . DT.display simpleParse :: (MonadThrow m, DT.Text a, Typeable a) => Text -> m a simpleParse orig = withTypeRep $ \rep -> case DT.simpleParse str of Nothing -> throwM (ParseFailedException rep (pack str)) Just v -> return v where str = unpack orig withTypeRep :: Typeable a => (TypeRep -> m a) -> m a withTypeRep f = res where res = f (typeOf (unwrap res)) unwrap :: m a -> a unwrap _ = error "unwrap" data BuildPlanTypesException = ParseSnapNameException Text | ParseFailedException TypeRep Text deriving Typeable instance Exception BuildPlanTypesException instance Show BuildPlanTypesException where show (ParseSnapNameException t) = "Invalid snapshot name: " ++ T.unpack t show (ParseFailedException rep t) = "Unable to parse " ++ show t ++ " as " ++ show rep data PackageConstraints = PackageConstraints { pcVersionRange :: VersionRange , pcMaintainer :: Maybe Maintainer , pcTests :: TestState , pcHaddocks :: TestState , pcBuildBenchmarks :: Bool , pcFlagOverrides :: Map FlagName Bool , pcEnableLibProfile :: Bool } deriving (Show, Eq) instance ToJSON PackageConstraints where toJSON PackageConstraints {..} = object $ addMaintainer [ "version-range" .= display pcVersionRange , "tests" .= pcTests , "haddocks" .= pcHaddocks , "build-benchmarks" .= pcBuildBenchmarks , "flags" .= pcFlagOverrides , "library-profiling" .= pcEnableLibProfile ] where addMaintainer = maybe id (\m -> (("maintainer" .= m):)) pcMaintainer instance FromJSON PackageConstraints where parseJSON = withObject "PackageConstraints" $ \o -> do pcVersionRange <- (o .: "version-range") >>= either (fail . show) return . simpleParse pcTests <- o .: "tests" pcHaddocks <- o .: "haddocks" pcBuildBenchmarks <- o .: "build-benchmarks" pcFlagOverrides <- o .: "flags" pcMaintainer <- o .:? "maintainer" pcEnableLibProfile <- fmap (fromMaybe True) (o .:? "library-profiling") return PackageConstraints {..} data TestState = ExpectSuccess | ExpectFailure | Don'tBuild -- ^ when the test suite will pull in things we don't want deriving (Show, Eq, Ord, Bounded, Enum) testStateToText :: TestState -> Text testStateToText ExpectSuccess = "expect-success" testStateToText ExpectFailure = "expect-failure" testStateToText Don'tBuild = "do-not-build" instance ToJSON TestState where toJSON = toJSON . testStateToText instance FromJSON TestState where parseJSON = withText "TestState" $ \t -> case HashMap.lookup t states of Nothing -> fail $ "Invalid state: " ++ unpack t Just v -> return v where states = HashMap.fromList $ map (\x -> (testStateToText x, x)) [minBound..maxBound] data SystemInfo = SystemInfo { siGhcVersion :: Version , siOS :: OS , siArch :: Arch , siCorePackages :: Map PackageName Version , siCoreExecutables :: Set ExeName } deriving (Show, Eq, Ord) instance ToJSON SystemInfo where toJSON SystemInfo {..} = object [ "ghc-version" .= siGhcVersion , "os" .= display siOS , "arch" .= display siArch , "core-packages" .= siCorePackages , "core-executables" .= siCoreExecutables ] instance FromJSON SystemInfo where parseJSON = withObject "SystemInfo" $ \o -> do let helper name = (o .: name) >>= either (fail . show) return . simpleParse siGhcVersion <- o .: "ghc-version" siOS <- helper "os" siArch <- helper "arch" siCorePackages <- o .: "core-packages" siCoreExecutables <- o .: "core-executables" return SystemInfo {..} newtype Maintainer = Maintainer { unMaintainer :: Text } deriving (Show, Eq, Ord, Hashable, ToJSON, FromJSON, IsString) -- | Name of an executable. newtype ExeName = ExeName { unExeName :: ByteString } deriving (Show, Eq, Ord, Hashable, IsString, Generic, NFData) instance Binary ExeName instance ToJSON ExeName where toJSON = toJSON . S8.unpack . unExeName instance FromJSON ExeName where parseJSON = withText "ExeName" $ return . ExeName . encodeUtf8 -- | A simplified package description that tracks: -- -- * Package dependencies -- -- * Build tool dependencies -- -- * Provided executables -- -- It has fully resolved all conditionals data SimpleDesc = SimpleDesc { sdPackages :: Map PackageName DepInfo , sdTools :: Map ExeName DepInfo , sdProvidedExes :: Set ExeName , sdModules :: Set Text -- ^ modules exported by the library } deriving (Show, Eq) instance Monoid SimpleDesc where mempty = SimpleDesc mempty mempty mempty mempty mappend (SimpleDesc a b c d) (SimpleDesc w x y z) = SimpleDesc (Map.unionWith (<>) a w) (Map.unionWith (<>) b x) (c <> y) (d <> z) instance ToJSON SimpleDesc where toJSON SimpleDesc {..} = object [ "packages" .= sdPackages , "tools" .= sdTools , "provided-exes" .= sdProvidedExes , "modules" .= sdModules ] instance FromJSON SimpleDesc where parseJSON = withObject "SimpleDesc" $ \o -> do sdPackages <- o .: "packages" sdTools <- o .: "tools" sdProvidedExes <- o .: "provided-exes" sdModules <- o .: "modules" return SimpleDesc {..} data DepInfo = DepInfo { diComponents :: Set Component , diRange :: VersionRange } deriving (Show, Eq) instance Monoid DepInfo where mempty = DepInfo mempty C.anyVersion DepInfo a x `mappend` DepInfo b y = DepInfo (mappend a b) (C.intersectVersionRanges x y) instance ToJSON DepInfo where toJSON DepInfo {..} = object [ "components" .= diComponents , "range" .= display diRange ] instance FromJSON DepInfo where parseJSON = withObject "DepInfo" $ \o -> do diComponents <- o .: "components" diRange <- o .: "range" >>= either (fail . show) return . simpleParse return DepInfo {..} data Component = CompLibrary | CompExecutable | CompTestSuite | CompBenchmark deriving (Show, Read, Eq, Ord, Enum, Bounded) compToText :: Component -> Text compToText CompLibrary = "library" compToText CompExecutable = "executable" compToText CompTestSuite = "test-suite" compToText CompBenchmark = "benchmark" instance ToJSON Component where toJSON = toJSON . compToText instance FromJSON Component where parseJSON = withText "Component" $ \t -> maybe (fail $ "Invalid component: " ++ unpack t) return (HashMap.lookup t comps) where comps = HashMap.fromList $ map (compToText &&& id) [minBound..maxBound] -- | Convert a 'SnapName' into its short representation, e.g. @lts-2.8@, -- @nightly-2015-03-05@. renderSnapName :: SnapName -> Text renderSnapName (LTS x y) = T.pack $ concat ["lts-", show x, ".", show y] renderSnapName (Nightly d) = T.pack $ "nightly-" ++ show d -- | Parse the short representation of a 'SnapName'. parseSnapName :: MonadThrow m => Text -> m SnapName parseSnapName t0 = case lts <|> nightly of Nothing -> throwM $ ParseSnapNameException t0 Just sn -> return sn where lts = do t1 <- T.stripPrefix "lts-" t0 Right (x, t2) <- Just $ decimal t1 t3 <- T.stripPrefix "." t2 Right (y, "") <- Just $ decimal t3 return $ LTS x y nightly = do t1 <- T.stripPrefix "nightly-" t0 Nightly <$> readMay (T.unpack t1) instance ToJSON a => ToJSON (Map ExeName a) where toJSON = toJSON . Map.mapKeysWith const (S8.unpack . unExeName) instance FromJSON a => FromJSON (Map ExeName a) where parseJSON = fmap (Map.mapKeysWith const (ExeName . encodeUtf8)) . parseJSON -- | A simplified version of the 'BuildPlan' + cabal file. data MiniBuildPlan = MiniBuildPlan { mbpGhcVersion :: !Version , mbpPackages :: !(Map PackageName MiniPackageInfo) } deriving (Generic, Show, Eq) instance Binary MiniBuildPlan instance NFData MiniBuildPlan where rnf = genericRnf instance BinarySchema MiniBuildPlan where -- Don't forget to update this if you change the datatype in any way! binarySchema _ = 1 -- | Information on a single package for the 'MiniBuildPlan'. data MiniPackageInfo = MiniPackageInfo { mpiVersion :: !Version , mpiFlags :: !(Map FlagName Bool) , mpiPackageDeps :: !(Set PackageName) , mpiToolDeps :: !(Set ByteString) -- ^ Due to ambiguity in Cabal, it is unclear whether this refers to the -- executable name, the package name, or something else. We have to guess -- based on what's available, which is why we store this is an unwrapped -- 'ByteString'. , mpiExes :: !(Set ExeName) -- ^ Executables provided by this package , mpiHasLibrary :: !Bool -- ^ Is there a library present? } deriving (Generic, Show, Eq) instance Binary MiniPackageInfo instance NFData MiniPackageInfo where rnf = genericRnf isWindows :: OS -> Bool isWindows Windows = True isWindows (OtherOS "windowsintegersimple") = True isWindows _ = False
wskplho/stack
src/Stack/Types/BuildPlan.hs
bsd-3-clause
14,121
0
17
4,224
3,574
1,921
1,653
340
2
{-# LANGUAGE MultiParamTypeClasses #-} module Opaleye.SQLite.Internal.Distinct where import Opaleye.SQLite.QueryArr (Query) import Opaleye.SQLite.Column (Column) import Opaleye.SQLite.Aggregate (Aggregator, groupBy, aggregate) import Control.Applicative (Applicative, pure, (<*>)) import qualified Data.Profunctor as P import qualified Data.Profunctor.Product as PP import Data.Profunctor.Product.Default (Default, def) -- We implement distinct simply by grouping by all columns. We could -- instead implement it as SQL's DISTINCT but implementing it in terms -- of something else that we already have is easier at this point. distinctExplicit :: Distinctspec columns columns' -> Query columns -> Query columns' distinctExplicit (Distinctspec agg) = aggregate agg newtype Distinctspec a b = Distinctspec (Aggregator a b) instance Default Distinctspec (Column a) (Column a) where def = Distinctspec groupBy -- { Boilerplate instances instance Functor (Distinctspec a) where fmap f (Distinctspec g) = Distinctspec (fmap f g) instance Applicative (Distinctspec a) where pure = Distinctspec . pure Distinctspec f <*> Distinctspec x = Distinctspec (f <*> x) instance P.Profunctor Distinctspec where dimap f g (Distinctspec q) = Distinctspec (P.dimap f g q) instance PP.ProductProfunctor Distinctspec where empty = PP.defaultEmpty (***!) = PP.defaultProfunctorProduct instance PP.SumProfunctor Distinctspec where Distinctspec x1 +++! Distinctspec x2 = Distinctspec (x1 PP.+++! x2) -- }
bergmark/haskell-opaleye
opaleye-sqlite/src/Opaleye/SQLite/Internal/Distinct.hs
bsd-3-clause
1,579
0
9
290
393
216
177
27
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE TypeOperators #-} {- Exercising avoidance of known landmines. We need one each of PostTc id Kind PostTc id Type PostRn id Fixity PostRn id NameSet -} module MineKind where data HList :: [*] -> * where HNil :: HList '[] HCons :: a -> HList t -> HList (a ': t) data Tuple :: (*,*) -> * where Tuple :: a -> b -> Tuple '(a,b)
urbanslug/ghc
testsuite/tests/ghc-api/landmines/MineKind.hs
bsd-3-clause
440
0
10
103
104
61
43
10
0
module Mod126_A where class T a where m1 :: a -> a data T1 = T
urbanslug/ghc
testsuite/tests/module/Mod126_A.hs
bsd-3-clause
66
0
7
19
29
16
13
3
0
{-# LANGUAGE BangPatterns, DataKinds, DeriveDataTypeable, FlexibleInstances, MultiParamTypeClasses #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} module Hadoop.Protos.ClientNamenodeProtocolProtos.SetBalancerBandwidthResponseProto (SetBalancerBandwidthResponseProto(..)) where import Prelude ((+), (/)) import qualified Prelude as Prelude' import qualified Data.Typeable as Prelude' import qualified Data.Data as Prelude' import qualified Text.ProtocolBuffers.Header as P' data SetBalancerBandwidthResponseProto = SetBalancerBandwidthResponseProto{} deriving (Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data) instance P'.Mergeable SetBalancerBandwidthResponseProto where mergeAppend SetBalancerBandwidthResponseProto SetBalancerBandwidthResponseProto = SetBalancerBandwidthResponseProto instance P'.Default SetBalancerBandwidthResponseProto where defaultValue = SetBalancerBandwidthResponseProto instance P'.Wire SetBalancerBandwidthResponseProto where wireSize ft' self'@(SetBalancerBandwidthResponseProto) = case ft' of 10 -> calc'Size 11 -> P'.prependMessageSize calc'Size _ -> P'.wireSizeErr ft' self' where calc'Size = 0 wirePut ft' self'@(SetBalancerBandwidthResponseProto) = case ft' of 10 -> put'Fields 11 -> do P'.putSize (P'.wireSize 10 self') put'Fields _ -> P'.wirePutErr ft' self' where put'Fields = do Prelude'.return () wireGet ft' = case ft' of 10 -> P'.getBareMessageWith update'Self 11 -> P'.getMessageWith update'Self _ -> P'.wireGetErr ft' where update'Self wire'Tag old'Self = case wire'Tag of _ -> let (field'Number, wire'Type) = P'.splitWireTag wire'Tag in P'.unknown field'Number wire'Type old'Self instance P'.MessageAPI msg' (msg' -> SetBalancerBandwidthResponseProto) SetBalancerBandwidthResponseProto where getVal m' f' = f' m' instance P'.GPB SetBalancerBandwidthResponseProto instance P'.ReflectDescriptor SetBalancerBandwidthResponseProto where getMessageInfo _ = P'.GetMessageInfo (P'.fromDistinctAscList []) (P'.fromDistinctAscList []) reflectDescriptorInfo _ = Prelude'.read "DescriptorInfo {descName = ProtoName {protobufName = FIName \".hadoop.hdfs.SetBalancerBandwidthResponseProto\", haskellPrefix = [MName \"Hadoop\",MName \"Protos\"], parentModule = [MName \"ClientNamenodeProtocolProtos\"], baseName = MName \"SetBalancerBandwidthResponseProto\"}, descFilePath = [\"Hadoop\",\"Protos\",\"ClientNamenodeProtocolProtos\",\"SetBalancerBandwidthResponseProto.hs\"], isGroup = False, fields = fromList [], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False}" instance P'.TextType SetBalancerBandwidthResponseProto where tellT = P'.tellSubMessage getT = P'.getSubMessage instance P'.TextMsg SetBalancerBandwidthResponseProto where textPut msg = Prelude'.return () textGet = Prelude'.return P'.defaultValue
alexbiehl/hoop
hadoop-protos/src/Hadoop/Protos/ClientNamenodeProtocolProtos/SetBalancerBandwidthResponseProto.hs
mit
3,137
1
16
543
554
291
263
53
0
{- Goldbach's other conjecture Problem 46 It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square. 9 = 7 + 2×12 15 = 7 + 2×22 21 = 3 + 2×32 25 = 7 + 2×32 27 = 19 + 2×22 33 = 31 + 2×12 It turns out that the conjecture was false. What is the smallest odd composite that cannot be written as the sum of a prime and twice a square? -} import Data.List import Data.Numbers.Primes maxn = 1000 cartProd xs ys = [(x,y) | x <- xs, y <- ys] pri = take maxn primes sq2 = map (\x -> 2*(x^2)) [0..maxn] check :: [Int] -> (Int,Int) check s | (length s) < 2 = (0,0) | 2 /= (b-a) = (a,b) | otherwise = check (tail s) where a = head s b = head $ tail s solve = check $ filter odd $ map head $ group $ sort $ map (\(a,b) -> a+b) $ cartProd pri sq2 main = do print solve {- Most of the runtime is in the "check" function, and I don't understand why. -}
bertdouglas/euler-haskell
001-050/46a.hs
mit
975
0
11
265
284
150
134
23
1
{-# OPTIONS_GHC -fno-warn-orphans #-} module CyclicList (tests) where import Data.Foldable (toList) import Test.Tasty (TestTree, testGroup) import Test.Tasty.QuickCheck (Arbitrary (arbitrary, shrink), (===), testProperty) import Numeric.QuadraticIrrational.CyclicList instance Arbitrary a => Arbitrary (CycList a) where arbitrary = CycList <$> arbitrary <*> arbitrary shrink (CycList as bs) = (CycList <$> pure as <*> shrink bs) ++ (CycList <$> shrink as <*> pure bs) tests :: TestTree tests = testGroup "CyclicList" [ testProperty "toList" . withListEquiv $ \asC asL -> take 1000 (toList asC) === take 1000 asL ] withListEquiv :: (CycList Integer -> [Integer] -> b) -> CycList Integer -> b withListEquiv f cl@(CycList as bs) = f cl (as ++ if null bs then [] else cycle bs)
ion1/quadratic-irrational
tests/CyclicList.hs
mit
828
0
12
169
290
156
134
18
2
import System.IO import System.Directory main = do handle <- openFile "./resources/testText.txt" ReadMode (tempName, tempHandle) <- openTempFile "." "temp" reading <- hGetContents handle let numberOfEdges = read $ (lines reading) !! 2 putStr $ unlines $ take (6+numberOfEdges) $ lines reading hPutStr tempHandle (unlines $ drop (6+numberOfEdges) $ lines reading) hClose handle hClose tempHandle removeFile "./resources/testText.txt" renameFile tempName "./resources/testText.txt"
Maaarcocr/ATFMC
resources/readingTest.hs
mit
503
0
13
81
165
75
90
13
1
module Hubris.Syntax where import Bound import Control.Applicative import Prelude.Extras data Term a = Ascribe (Term a) (Term a) -- e : T | Type -- Type | Pi (Term a) (Scope () Term a) -- (x : A) => e | Var a -- x | Apply (Term a) (Term a) -- e e' | Lam (Scope () Term a) -- \x -> e | Let a (Term a) (Maybe (Term a)) -- let e = x ?(in t) deriving (Eq, Ord, Show, Read) instance Functor Term where fmap f (Var a) = Var (f a) fmap f (Apply fun arg) = Apply (fmap f fun) (fmap f arg) fmap f (Lam scope) = Lam (fmap f scope) fmap f (Pi ty scope) = Pi (fmap f ty) (fmap f scope) fmap f Type = Type fmap f (Ascribe e t) = Ascribe (fmap f e) (fmap f t) instance Applicative Term where pure = return fa <*> v = do f <- fa a <- v return (f a) instance Monad Term where return = Var Var a >>= f = f a Apply h g >>= f = Apply (h >>= f) (g >>= f) Lam scope >>= f = Lam (scope >>>= f) Pi ty scope >>= f = Pi (ty >>= f) (scope >>>= f) Type >>= f = Type Ascribe e t >>= f = Ascribe (e >>= f) (t >>= f) instance Eq1 Term where (==#) = (==) instance Ord1 Term where compare1 = compare instance Show1 Term where showsPrec1 = showsPrec instance Read1 Term where readsPrec1 = readsPrec
jroesch/dependent-tychk
src/Hubris/Syntax.hs
mit
1,481
0
10
580
628
320
308
37
0
{-# LANGUAGE PatternSynonyms #-} -- For HasCallStack compatibility {-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} module JSDOM.Generated.SVGFEOffsetElement (getIn1, getDx, getDy, SVGFEOffsetElement(..), gTypeSVGFEOffsetElement) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..)) import qualified Prelude (error) import Data.Typeable (Typeable) import Data.Traversable (mapM) import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!)) import Data.Int (Int64) import Data.Word (Word, Word64) import JSDOM.Types import Control.Applicative ((<$>)) import Control.Monad (void) import Control.Lens.Operators ((^.)) import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import JSDOM.Enums -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGFEOffsetElement.in1 Mozilla SVGFEOffsetElement.in1 documentation> getIn1 :: (MonadDOM m) => SVGFEOffsetElement -> m SVGAnimatedString getIn1 self = liftDOM ((self ^. js "in1") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGFEOffsetElement.dx Mozilla SVGFEOffsetElement.dx documentation> getDx :: (MonadDOM m) => SVGFEOffsetElement -> m SVGAnimatedNumber getDx self = liftDOM ((self ^. js "dx") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGFEOffsetElement.dy Mozilla SVGFEOffsetElement.dy documentation> getDy :: (MonadDOM m) => SVGFEOffsetElement -> m SVGAnimatedNumber getDy self = liftDOM ((self ^. js "dy") >>= fromJSValUnchecked)
ghcjs/jsaddle-dom
src/JSDOM/Generated/SVGFEOffsetElement.hs
mit
1,826
0
10
207
451
280
171
25
1
module NginxLint.Parse where import Text.ParserCombinators.Parsec hiding (spaces) import Text.ParserCombinators.Parsec.Language (emptyDef) import qualified Text.ParserCombinators.Parsec.Token as T import NginxLint.Data parseFile :: Parser NgFile parseFile = do whiteSpace pos <- getPosition ds <- many decl eof return $ NgFile (sourceName pos) ds decl :: Parser Decl decl = try ifDecl <|> nonIfDecl nonIfDecl :: Parser Decl nonIfDecl = try blockDecl <|> oneDecl oneDecl :: Parser Decl oneDecl = do whiteSpace pos <- getPosition name <- identifier args <- many argument _ <- lexeme (char ';') return $ Decl pos name args <?> "directive" blockDecl :: Parser Decl blockDecl = do whiteSpace pos <- getPosition name <- identifier args <- many argument ds <- braces (many decl) return $ Block pos name args ds <?> "block directive" ifDecl :: Parser Decl ifDecl = do whiteSpace pos <- getPosition reserved "if" args <- parens $ many1 ifArgument ds <- braces $ many nonIfDecl return $ Block pos "if" args ds <?> "if directive" where ifArgument = try parseInteger <|> try quotedString <|> plain <?> "if argument" plain = mkString " \"\v\t\r\n(){};" "if plain string" argument :: Parser Arg argument = try parseInteger <|> try quotedString <|> plainString parseInteger :: Parser Arg parseInteger = do pos <- getPosition n <- integer return $ Integer pos n quotedString :: Parser Arg quotedString = do pos <- getPosition _ <- symbol q s <- many (noneOf q) _ <- symbol q return $ QuotedString pos s where q = "\"" mkString :: String -> String -> Parser Arg mkString excl help = p <?> help where p = do pos <- getPosition s <- lexeme $ many1 (noneOf excl) return $ RawString pos s plainString = mkString " \"\v\t\r\n{};" "plain string" lexer :: T.TokenParser () lexer = T.makeTokenParser nginxDef nginxDef = emptyDef { T.commentLine = "#" , T.identStart = alphaNum <|> char '_' , T.nestedComments = False , T.opLetter = oneOf "<=>" , T.reservedNames = ["if"] } braces = T.braces lexer --comma = T.comma lexer --commaSep = T.commaSep lexer --commaSep1 = T.commaSep1 lexer --dot = T.dot lexer --float = T.float lexer identifier = T.identifier lexer integer = T.natural lexer lexeme = T.lexeme lexer --natural = T.natural lexer parens = T.parens lexer reserved = T.reserved lexer --semi = T.semi lexer --semiSep = T.semiSep lexer symbol = T.symbol lexer whiteSpace = T.whiteSpace lexer
temoto/nginx-lint
NginxLint/Parse.hs
mit
3,010
0
13
1,023
798
393
405
78
1
import qualified Network.IRC.DCCTest as DCC import Test.Tasty main :: IO () main = DCC.spec >>= defaultMain
JanGe/irc-dcc
test/Spec.hs
mit
119
0
6
27
36
21
15
4
1
-- Just another toy example {-# LANGUAGE CPP #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE InstanceSigs #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE TypeOperators #-} import Control.Monad (replicateM) import GHC.Generics import Test.QuickCheck (Arbitrary(..), Gen, quickCheck, sample, generate) import Generic.Random (genericArbitraryG, (:+)(..), (%)) data MyType = OneThing Int | TwoThings Double String | ThreeThings (Maybe Integer) [()] (Bool -> Word) deriving (Show, Generic) custom :: Gen (Maybe Integer) :+ () custom = (Just <$> arbitrary) :+ () instance Arbitrary MyType where arbitrary :: Gen MyType arbitrary = genericArbitraryG custom (1 % 4 % 4 % ()) -- arbitrary = frequency -- [ (1, OneThing <$> arbitrary) -- , (4, TwoThings <$> arbitrary <*> arbitrary) -- , (4, ThreeThings <$> (Just <$> arbitrary) <*> arbitrary <*> arbitrary) -- ] main :: IO () #ifndef BENCHMODE main = do -- Print some examples sample (arbitrary :: Gen MyType) -- Check the property that ThreeThings contains three things. quickCheck $ \case ThreeThings Nothing _ _ -> False _ -> True #else -- Quick and dirty benchmark main = do xs <- generate (replicateM 1000000 (arbitrary :: Gen MyType)) go xs where go [] = print () go (x : xs) = x `seq` go xs #endif -- Ew. Sorry. instance Show a => Show (Bool -> a) where show f = "<True -> " ++ show (f True) ++ ",False -> " ++ show (f False) ++ ">"
Lysxia/generic-random
examples/tour.hs
mit
1,508
0
12
310
342
193
149
29
2
module Types where import Text.HTML.TagSoup (Tag) import qualified Data.ByteString as B {-- Types for parsing the wire content and transforming it to HTML. --} type ChanneledHeaderRequest = (HTTPRequestType, URI, [RequestHeader], RequestPayload, [ResponseHeader], ResponsePayload) type Header = (HeaderType, HeaderValue) type HeaderType = Payload type HeaderValue = Payload type Payload = B.ByteString type RequestHeader = Header type RequestPayload = Payload type ResponseHeader = Header type ResponsePayload = Payload type TaggedHeaderRequest = (HTTPRequestType, URI, [RequestHeader], RequestPayload, [ResponseHeader], [Tag Payload]) type URI = Payload data HTTPRequestType = GET | POST deriving (Eq, Show, Ord, Enum) {-- Types for getting the data out of HTML and into the DB. --} type AP = Int type ASP = Int type ATP = Double type Bounties = Int type CompetencyLevel = Int type CompetencyPercentage = Int type Credits = Int type FactionLevel = Payload -- TODO: change to Int type FactionPercentage = Int type KDCount = Int type Medals = Int type NPCKill = Int type NPCName = Payload type PlayersOnline = Int type RepA = Int type RepE = Int type RepF = Int type RepU = Int type Skill = Double type XP = Int data DBCommand = AP AP | AM Skill Skill | ASP ASP | ATP ATP | AllianceID Int | AllianceMemberCount Int | AllianceMember Payload | Bounties Bounties | CLK Skill Skill | Competency CompetencyLevel CompetencyPercentage | Credits Credits | Debug Payload | DestroyBounties Bounties | EC Skill Skill | ENG Skill Skill | FC Skill Skill | Faction FactionLevel FactionPercentage | GC Skill Skill | HA Skill Skill | HACK Skill Skill | KillBounties Bounties | MAN Skill Skill | MM [Tag Payload] | NPCKill KDCount | NPCList [(NPCName, NPCKill)] | POnline PlayersOnline | PilotDeath KDCount | PilotKill KDCount | Rep RepF RepE RepU RepA | Ribbons Medals | TAC Skill Skill | Turnover Credits | WEAP Skill Skill | WarMedals Medals | XP XP deriving Show
mihaimaruseac/petulant-octo-avenger
src/Types.hs
mit
2,029
0
8
397
532
333
199
73
0
{-# htermination showList :: [Ordering] -> String -> String #-}
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/full_haskell/Prelude_showList_12.hs
mit
64
0
2
10
3
2
1
1
0
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE ViewPatterns #-} module Ch24.BoundedChan ( BoundedChan , newBoundedChan , writeBoundedChan , readBoundedChan , main ) where import Control.Concurrent.Chan import Control.Concurrent.MVar import Control.Concurrent import Control.DeepSeq (NFData, force) type State = (MVar Int, Int) newtype BoundedChan a = BoundedChan (MVar (State, Chan a)) newBoundedChan :: Int -> IO (BoundedChan a) newBoundedChan n = do ch <- newChan counter <- newMVar n mvar <- newMVar ((counter, n), ch) return (BoundedChan mvar) writeBoundedChan :: BoundedChan a -> a -> IO () writeBoundedChan (BoundedChan mvar) msg = do (counter, ch) <- modifyMVar mvar $ \bch@((counter, limit), ch) -> do mMVar <- tryTakeMVar counter case mMVar of Nothing -> return (bch, (counter, ch)) Just x | x == 0 -> do empty <- newEmptyMVar -- it's ok here to discard the mvar since nobody can be waiting on it, -- the call to `modifyMVar mvar` assures this. return (((empty, limit), ch), (empty, ch)) | otherwise -> do putMVar counter (x - 1) return (bch, (counter, ch)) -- will block until counter is not empty withMVar counter $ const (writeChan ch msg) readBoundedChan :: BoundedChan a -> IO a readBoundedChan (BoundedChan mvar) = do ch <- modifyMVar mvar $ \bch@((counter, limit), ch) -> do mMVar <- tryTakeMVar counter putMVar counter (maybe 1 (\x -> max limit (x + 1)) mMVar) return (bch, ch) -- will block until there's something to read from ch readChan ch writeBoundedChan' :: NFData a => BoundedChan a -> a -> IO () writeBoundedChan' bch msg = writeBoundedChan bch msg' where !msg' = force msg -- writeBoundedChan' bch (force -> !msg) = -- writeBoundedChan bch msg readBoundedChan' :: NFData a => BoundedChan a -> IO a readBoundedChan' bch = return . force =<< readBoundedChan bch {- Wrote 'foo' Wrote 'bar' Read:foo Read:bar Wrote 'buzz' *** Exception: thread blocked indefinitely in an MVar operation -} main :: IO () main = do ch <- newBoundedChan 2 sem <- newMVar () _ <- forkIO $ writeBoundedChan ch "foo" >> withMVar sem (\_ -> putStrLn "Wrote 'foo'") _ <- forkIO $ writeBoundedChan ch "bar" >> withMVar sem (\_ -> putStrLn "Wrote 'bar'") _ <- forkIO $ writeBoundedChan ch "buzz" >> withMVar sem (\_ -> putStrLn "Wrote 'buzz'") --threadDelay (10^3 * 500) xs1 <- readBoundedChan ch withMVar sem (\_ -> putStrLn $ "Read:" ++ xs1) xs2 <- readBoundedChan ch withMVar sem (\_ -> putStrLn $ "Read:" ++ xs2) -- threadDelay (10^6) xs3 <- readBoundedChan ch putStrLn $ "Read:" ++ xs3
futtetennista/IntroductionToFunctionalProgramming
RWH/src/Ch24/BoundedChan.hs
mit
2,856
0
21
782
873
441
432
66
2
-- -- A common security method used for online banking is to ask the user for -- three random characters from a passcode. For example, if the passcode was -- 531278, they may ask for the 2nd, 3rd, and 5th characters; the expected -- reply would be: 317. -- -- The text file, keylog.txt, contains fifty successful login attempts. -- -- Given that the three characters are always asked for in order, analyse the -- file so as to determine the shortest possible secret passcode of unknown length. -- import Data.Char import Data.List main = do contents <- readFile "keylog.txt" let codes = map (filter isDigit) $ lines contents print $ sort codes containsAllCodes p = all (containsCode p) containsCode _ [] = True containsCode [] _ = False containsCode (p:ps) (c:cs) | p == c = containsCode ps cs | otherwise = containsCode ps (c:cs)
stu-smith/project-euler-haskell
Euler-079.hs
mit
894
0
13
209
173
88
85
15
1
module Data.Mapping where class Mapping m where apply :: m a b -> a -> b bind :: Eq a => a -> b -> m a b -> m a b instance Mapping (->) where apply = id bind n t s x | n == x = t | otherwise = s x
pxqr/unification
Data/Mapping.hs
mit
225
0
11
83
119
58
61
9
0
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TypeFamilies #-} module Network.HTTP.Client.Free.Examples ( ) where import Control.Applicative ((<$>), (<*>)) import Data.ByteString (ByteString) import Data.ByteString.Char8 (pack) import Data.Maybe (fromJust) import Data.Time (UTCTime(UTCTime), fromGregorian) import Network.HTTP.Types.Header import Network.HTTP.Types.Status import Network.HTTP.Types.Method (StdMethod (..)) import Network.HTTP.Types.Version (http09, http10, http11, HttpVersion) import Network.HTTP.Client (defaultManagerSettings, newManager, parseUrl, responseStatus, Request) import Network.HTTP.Client.Free (get) import qualified Network.HTTP.Client.Free.ArbitraryClient as ArbitraryClient import Network.HTTP.Client.Free.HttpClient (HttpClient) import qualified Network.HTTP.Client.Free.HttpClient as HttpClient import Network.HTTP.Client.Free.Types (FreeHttp, RequestType, ResponseType) import Network.HTTP.Client.Internal (Cookie(Cookie), CookieJar, createCookieJar, Response(Response), ResponseClose(ResponseClose)) import Test.QuickCheck (choose, Gen, Arbitrary(arbitrary), elements, listOf, sample', suchThat) -- | an arbitrary 'Status' arbStatus :: Gen Status arbStatus = elements [ status100 , status101 , status200 , status201 , status203 , status204 , status205 , status206 , status300 , status301 , status302 , status303 , status304 , status305 , status307 , status400 , status401 , status402 , status403 , status404 , status405 , status406 , status407 , status408 , status409 , status410 , status411 , status412 , status413 , status414 , status415 , status416 , status417 , status418 , status428 , status429 , status431 , status500 , status501 , status502 , status503 , status504 , status505 , status511 ] -- | an arbitrary 'HttpVersion' arbHttpVersion :: Gen HttpVersion arbHttpVersion = elements [ http09 , http10 , http11 ] -- | an arbitrary 'HeaderName' arbHeaderName :: Gen HeaderName arbHeaderName = elements [ hAccept , hAcceptLanguage , hAuthorization , hCacheControl , hConnection , hContentEncoding , hContentLength , hContentMD5 , hContentType , hCookie , hDate , hIfModifiedSince , hIfRange , hLastModified , hLocation , hRange , hReferer , hServer , hUserAgent ] -- | an arbitrary Header. This is not performant, but you shouldn't -- be using this client in production anyway. arbHeader :: Gen Header arbHeader = (,) <$> arbHeaderName <*> fmap pack arbitrary -- | an arbitrary UTCTime arbUtcTime :: Gen UTCTime arbUtcTime = do rDay <- choose (1,29) :: Gen Int rMonth <- choose (1,12) :: Gen Int rYear <- choose (1970, 2015) :: Gen Integer rTime <- choose (0,86401) :: Gen Int return $ UTCTime (fromGregorian rYear rMonth rDay) (fromIntegral rTime) -- | an arbtirary Cookie arbCookie :: Gen Cookie arbCookie = do cCreationTime <- arbUtcTime cLastAccessTime <- suchThat arbUtcTime (cCreationTime >=) cExpiryTime <- suchThat arbUtcTime (cLastAccessTime >=) cName <- fmap pack arbitrary cValue <- fmap pack arbitrary cDomain <- fmap pack arbitrary cPath <- fmap pack arbitrary cPersistent <- arbitrary cHostOnly <- arbitrary cSecureOnly <- arbitrary cHttpOnly <- arbitrary return $ Cookie cName cValue cExpiryTime cDomain cPath cCreationTime cLastAccessTime cPersistent cHostOnly cSecureOnly cHttpOnly -- | unexported instance for arbitrary responses instance Arbitrary (Response ByteString) where arbitrary = Response <$> arbStatus <*> arbHttpVersion <*> listOf arbHeader <*> (pack <$> arbitrary) <*> (createCookieJar <$> listOf arbCookie) <*> return (ResponseClose (return ())) -- | A sample request weirdReq :: Request weirdReq = fromJust (parseUrl "http://weirdcanada.com/api") -- | A program that checks to see if the weird canada api is up. checkWeird :: ( Request ~ RequestType client , Response b ~ ResponseType client , Monad m ) => FreeHttp client m Bool checkWeird = do resp <- get weirdReq (return . (== status200) . responseStatus) resp data ExampleClient type instance RequestType ExampleClient = Request type instance ResponseType ExampleClient = Response ByteString main :: IO () main = do -- a result using the arbitrary interpreter arbResult <- ArbitraryClient.runHttp () (checkWeird :: FreeHttp ExampleClient IO Bool) putStrLn ("Arbitrary client returned: " ++ show arbResult) -- a result using the actual http client mgr <- newManager defaultManagerSettings realResult <- HttpClient.runHttp mgr (checkWeird :: FreeHttp HttpClient IO Bool) putStrLn ("http-client returned: " ++ show realResult)
aaronlevin/free-http
src/Network/HTTP/Client/Free/Examples.hs
mit
6,534
0
12
2,668
1,181
674
507
-1
-1
{-# LANGUAGE CPP #-} module Test.Hspec.Core.Example.Location ( Location(..) , extractLocation -- for testing , parseAssertionFailed , parseCallStack , parseLocation , parseSourceSpan ) where import Prelude () import Test.Hspec.Core.Compat import Control.Exception import Data.Char import Data.Maybe import GHC.IO.Exception -- | @Location@ is used to represent source locations. data Location = Location { locationFile :: FilePath , locationLine :: Int , locationColumn :: Int } deriving (Eq, Show, Read) extractLocation :: SomeException -> Maybe Location extractLocation e = locationFromErrorCall e <|> locationFromPatternMatchFail e <|> locationFromRecConError e <|> locationFromIOException e <|> locationFromNoMethodError e <|> locationFromAssertionFailed e locationFromNoMethodError :: SomeException -> Maybe Location locationFromNoMethodError e = case fromException e of Just (NoMethodError s) -> listToMaybe (words s) >>= parseSourceSpan Nothing -> Nothing locationFromAssertionFailed :: SomeException -> Maybe Location locationFromAssertionFailed e = case fromException e of Just (AssertionFailed loc) -> parseAssertionFailed loc Nothing -> Nothing parseAssertionFailed :: String -> Maybe Location parseAssertionFailed loc = parseCallStack loc <|> parseSourceSpan loc locationFromErrorCall :: SomeException -> Maybe Location locationFromErrorCall e = case fromException e of #if MIN_VERSION_base(4,9,0) Just (ErrorCallWithLocation err loc) -> parseCallStack loc <|> #else Just (ErrorCall err) -> #endif fromPatternMatchFailureInDoExpression err Nothing -> Nothing locationFromPatternMatchFail :: SomeException -> Maybe Location locationFromPatternMatchFail e = case fromException e of Just (PatternMatchFail s) -> listToMaybe (words s) >>= parseSourceSpan Nothing -> Nothing locationFromRecConError :: SomeException -> Maybe Location locationFromRecConError e = case fromException e of Just (RecConError s) -> listToMaybe (words s) >>= parseSourceSpan Nothing -> Nothing locationFromIOException :: SomeException -> Maybe Location locationFromIOException e = case fromException e of Just (IOError {ioe_type = UserError, ioe_description = xs}) -> fromPatternMatchFailureInDoExpression xs Just _ -> Nothing Nothing -> Nothing fromPatternMatchFailureInDoExpression :: String -> Maybe Location fromPatternMatchFailureInDoExpression input = #if MIN_VERSION_base(4,16,0) stripPrefix "Pattern match failure in 'do' block at " input >>= parseSourceSpan #else stripPrefix "Pattern match failure in do expression at " input >>= parseSourceSpan #endif parseCallStack :: String -> Maybe Location parseCallStack input = case reverse (lines input) of [] -> Nothing line : _ -> findLocation line where findLocation xs = case xs of [] -> Nothing _ : ys -> case stripPrefix prefix xs of Just zs -> parseLocation (takeWhile (not . isSpace) zs) Nothing -> findLocation ys prefix = ", called at " parseLocation :: String -> Maybe Location parseLocation input = case fmap breakColon (breakColon input) of (file, (line, column)) -> Location file <$> readMaybe line <*> readMaybe column parseSourceSpan :: String -> Maybe Location parseSourceSpan input = case breakColon input of (file, xs) -> (uncurry $ Location file) <$> (tuple <|> colonSeparated) where lineAndColumn :: String lineAndColumn = takeWhile (/= '-') xs tuple :: Maybe (Int, Int) tuple = readMaybe lineAndColumn colonSeparated :: Maybe (Int, Int) colonSeparated = case breakColon lineAndColumn of (l, c) -> (,) <$> readMaybe l <*> readMaybe c breakColon :: String -> (String, String) breakColon = fmap (drop 1) . break (== ':')
hspec/hspec
hspec-core/src/Test/Hspec/Core/Example/Location.hs
mit
3,808
0
17
705
1,005
515
490
83
4
import Control.Arrow import Data.List main :: IO () main = interact solve type Value = Float data RGB = RGB Value Value Value data Gray = Gray Value type ImageRow a = [a] data Image2d pixelType = Image2d [ImageRow pixelType] data Position = Position Int Int (|>) :: x -> (x -> y) -> y (|>) x y = y x infixl 0 |> instance Show RGB where show (RGB r g b) = "RGB " ++ show r ++ "/" ++ show g ++ "/" ++ show b instance Show Gray where show (Gray v) = "Gray " ++ show v class PixelType pixelType where divide :: pixelType -> Float -> pixelType add :: pixelType -> pixelType -> pixelType mult :: pixelType -> Float -> pixelType black :: pixelType white :: pixelType sumUp :: [pixelType] -> pixelType sumUp = foldr add white listToColor :: [Value] -> pixelType readColor :: String -> pixelType readColor = wordsWhen (==',') >>> map read >>> listToColor instance PixelType RGB where divide (RGB r g b) x = RGB (r/x) (g/x) (b/x) add (RGB r1 g1 b1) (RGB r2 g2 b2) = RGB (r1+r2) (g1+g2) (b1+b2) mult (RGB r1 g1 b1) f = RGB (f*r1) (f*g1) (f*b1) black = RGB 0 0 0 white = RGB 255 255 255 listToColor [r, g, b] = RGB r g b listToColor _ = error "invalid RGB list" instance PixelType Gray where divide (Gray v) x = Gray (v/x) add (Gray v1) (Gray v2) = Gray (v1 + v2) mult (Gray v) f = Gray (f*v) black = Gray 0 white = Gray 255 listToColor [v] = Gray v listToColor _ = error "invalid Gray list" class PixelType pixelType => Image pixelType where pixelSum :: Image2d pixelType -> pixelType pixelSum (Image2d rows) = rows |> map sumUp |> sumUp averageColor :: Image2d pixelType -> pixelType averageColor image = divide sumVal divisor where sumVal = pixelSum image divisor = pixelCount image |> fromIntegral imageRows :: Int -> Int -> Image2d pixelType -> Image2d pixelType imageRows y0 y1 (Image2d rows) = rows |> slice y0 y1 |> Image2d imageSize :: Image2d pixelType -> Position imageSize (Image2d rows) = Position (length (head rows)) (length rows) getRows :: Image2d pixelType -> [ImageRow pixelType] getRows (Image2d rows) = rows regionOfInterest :: Position -> Position -> Image2d pixelType -> Image2d pixelType regionOfInterest (Position x0 y0) (Position x1 y1) = imageRows y0 y1 >>> transposeImage >>> imageRows x0 x1 >>> transposeImage transposeImage :: Image2d pixelType -> Image2d pixelType transposeImage = getRows >>> transpose >>> Image2d pixelCount :: Image2d pixelType -> Int pixelCount = getRows >>> map length >>> sum readImage :: String -> Image2d pixelType readImage = lines >>> map (words >>> map readColor) >>> Image2d instance Image RGB where instance Image Gray where toValue :: Gray -> Value toValue (Gray v) = v rgbToGray :: RGB -> Gray rgbToGray (RGB r g b) = Gray (0.299 * r + 0.587 * g + 0.114 * b) grayToRgb :: Gray -> RGB grayToRgb (Gray v) = RGB v v v readImageRGB :: String -> Image2d RGB readImageRGB = readImage solve :: String -> String solve = readImage >>> imageRows 0 2 >>> averageColor >>> rgbToGray >>> toValue >>> toDayTime where toDayTime val = if val >= 96 then "day" else "night" slice :: Int -> Int -> [a] -> [a] slice begin end xs = take (end - begin) (drop begin xs) wordsWhen :: (Char -> Bool) -> String -> [String] wordsWhen p s = case dropWhile p s of "" -> [] s' -> w : wordsWhen p s'' where (w, s'') = break p s'
Dobiasd/HackerRank-solutions
Artificial_Intelligence/Digital_Image_Analysis/Digital_Camera_Autodetect_Day_or_Night/Main.hs
mit
3,580
0
12
934
1,437
734
703
96
2
module ItemsEqual where import qualified Data.List ( isPrefixOf ) -- Exercise: -- -- ( i.) Write a primitive recursive function that indicates if all items in a list are equal to a given reference item. -- -- Constraint: (!) The function that uses primitive recursion has to be conform to this pattern: -- -- ... -- Other definition(s). -- -- f :: ... -- Type signature. -- f ... = ... -- Condition for termination. -- f ... = ... (f ...) -- Primitive recursion. -- -- No more matchings for f than the one for termination listed above! -- -- Choose a descriptive name for your function f and complete the definitions where the dots are. -- What could you do in the case of an empty list? Do something. -- -- Hints: ItemsEqual.txt -- -- ( ii.) Copy only the constricted primitive recursive function definition (your f) and paste it below. -- Change it to work correctly again by extending its pattern with additional conditions (f ... = ...). -- -- -- Bonus: -- -- (iii.) Find another definition using the function "Data.List.isPrefixOf" and a list comprehension -- instead of primitive recursion. -- -- Insert "import qualified Data.List ( isPrefixOf )" after "module ... where" to be able to use -- "Data.List.isPrefixOf" in your script without complications. If you leave out the "qualified" -- you don't need the "Data.List." before "isPrefixOf". -- -- Hints: ItemsEqual.txt -- Possible solutions: -- i. areEqual :: Eq t => t -> [t] -> Bool areEqual referenceItem [ ] = error "No items." -- Alternatives: "False" or "True". areEqual referenceItem list = areEqual_ ( referenceItem : list ) where -- f = areEqual_ :: Eq t => [t] -> Bool areEqual_ [ singleListItem ] = True areEqual_ ( listItem : nextListItem : remainingListItems ) = listItem == nextListItem && areEqual_ ( nextListItem : remainingListItems ) {- GHCi> areEqual 0 [ ] areEqual 0 [ 0 ] areEqual 0 [ 1 ] areEqual 0 [ 0, 0 ] areEqual 0 [ 0, 1 ] -} -- *** Exception: No items. -- True -- False -- True -- False -- ii. areEqual' :: Eq t => t -> [t] -> Bool areEqual' _ [ ] = error "No items." -- Alternatives: "False" or "True". areEqual' item [ singleListItem ] = item == singleListItem areEqual' item ( listItem : remainingListItems ) = item == listItem && areEqual' item remainingListItems {- GHCi> areEqual' 0 [ ] areEqual' 0 [ 0 ] areEqual' 0 [ 1 ] areEqual' 0 [ 0, 0 ] areEqual' 0 [ 0, 1 ] -} -- *** Exception: No items. -- True -- False -- True -- False -- iii. areEqual'' :: Eq t => [t] -> Bool areEqual'' [ ] = error "No items." areEqual'' ( listItem : remainingListItems ) = Data.List.isPrefixOf remainingListItems ( repeat listItem ) -- Alternative: [ listItem | _ <- [ 1, 1 .. ] ] {- GHCi> areEqual'' 0 [ ] areEqual'' 0 [ 0 ] areEqual'' 0 [ 1 ] areEqual'' 0 [ 0, 0 ] areEqual'' 0 [ 0, 1 ] -} -- *** Exception: No items. -- True -- False -- True -- False
pascal-knodel/haskell-craft
Exercises/Primitive Recursion/ItemsEqual.hs
mit
3,238
0
10
940
347
208
139
19
2
module Analysis( loadOrigins, filterLoadOriginPools, classifierToExpression, exprToCriticalSections, criticalSectionToBinpatch, mkEnforcer, classifyFutures, autoFix) where import Types import History import ReplayState() import Timing import Util import Explore import Classifier import Reassembly import Logfile import Data.Word import Data.List import Numeric import Control.Monad.Error byteListToCString :: [Word8] -> String byteListToCString bl = '"':(concatMap word8ToCChar bl) ++ "\"" where word8ToCChar x = "\\x" ++ (showHex x "") {- All of the memory accesses made going from start to end. The Bool is true for stores and false for loads. -} memTraceTo :: History -> History -> Either String [(Bool, MemAccess)] memTraceTo start end = let worker [] = return [] worker ((TraceRecord (TraceLoad _ _ ptr _ _) tid acc):others) = do rest <- worker others rip <- getRipAtAccess end acc return $ (False, (tid, (rip, ptr))):rest worker ((TraceRecord (TraceStore _ _ ptr _ _) tid acc):others) = do rest <- worker others rip <- getRipAtAccess end acc return $ (True, (tid, (rip, ptr))):rest worker (_:others) = worker others in traceTo start end >>= worker {- Run from prefix to hist, recording every load, and, for every load, where the data loaded came from. This will be either Nothing if it was imported, or Just MemAccess if it came from a store. -} loadOrigins :: History -> History -> Either String [(MemAccess, Maybe MemAccess)] loadOrigins prefix hist = let worker [] = [] worker ((False, acc):others) = let store = find (\acc' -> (snd $ snd acc) == (snd $ snd acc')) [a | (True, a) <- others] in (acc, store):(worker others) worker (_:others) = worker others in fmap (reverse . worker . reverse) $ memTraceTo prefix hist {- Filter the results of loadOrigins, assuming that the first argument is from running loadOrigins over a bunch of runs which crashed and the second is from running it over a bunch of runs which didn't crash. We try to remove the boring accesses, where an access is defined to be boring if: a) It has the same origin every time it appears. -} filterLoadOriginPools :: [[(MemAccess, Maybe MemAccess)]] -> [[(MemAccess, Maybe MemAccess)]] -> ([[(MemAccess, Maybe MemAccess)]], [[(MemAccess, Maybe MemAccess)]]) filterLoadOriginPools poolA poolB = let poolA' = map sort poolA poolB' = map sort poolB pool = concat $ poolA' ++ poolB' accesses = fastNub $ map fst pool originsForAcc acc = fastNub $ map snd $ filter ((==) acc . fst) pool origins = [(acc, originsForAcc acc) | acc <- accesses] isBoring acc = case lookup acc origins of Nothing -> error "Huh? lost an access in filterLoadOriginPools" Just [] -> error "access with no origin" Just [_] -> True Just (_:_:_) -> False removeBoring :: [(MemAccess, Maybe MemAccess)] -> [(MemAccess, Maybe MemAccess)] removeBoring = filter (not . isBoring . fst) in (map removeBoring poolA', map removeBoring poolB') {- Try to extract a critical sections list from a scheduling constraint expression. The representation of critical sections here is as a list of pairs of RIPs. A thread enters a critical section whenever it steps on the first RIP in a pair, and exits when it steps on the second one, and all critical sections must be atomic with respect to each other. Whoever turns the CS list into a patch is responsible for doing enough analysis to be sure that all locks eventually get dropped. If they discover that there's a branch out of the critical section then they should drop the lock at that point. -} {- We only handle one very simple special case: X:A<Y:B & Y:C<X:D gets turned into two critical sections, one covering A->D and one covering B->C. -} exprToCriticalSections :: BooleanExpression SchedulingConstraint -> Maybe [(Word64, Word64)] exprToCriticalSections (BooleanAnd (BooleanLeaf (SchedulingConstraint xa yb)) (BooleanLeaf (SchedulingConstraint yc xd))) | fst xa == fst xd && fst yb == fst yc = Just [(fst $ snd xa, fst $ snd xd), (fst $ snd yb, fst $ snd yc)] exprToCriticalSections _ = Nothing asmLabelToC :: AssemblyLabel -> String asmLabelToC (AssemblyLabelOffset i) = "{bpl_offset, " ++ (show i) ++ "}" asmLabelToC (AssemblyLabelSymbol s) = "{bpl_absolute, (unsigned long)" ++ s ++ "}" {- the compiler will do the lookup for us -} asmLabelToC (AssemblyLabelAbsolute s) = "{bpl_absolute, 0x" ++ (showHex s "") ++ "}" relocToC :: AssemblyReloc -> String relocToC ar = "{" ++ (show $ as_offset ar) ++ ", " ++ (show $ as_addend ar) ++ ", " ++ (show $ as_size ar) ++ ", " ++ (case as_relative ar of True -> "1" False -> "0") ++ ", " ++ (asmLabelToC $ as_target ar) ++ "}" reassemblyToC :: String -> (Word64, [Word8], [AssemblyReloc], a) -> String reassemblyToC ident (rip, payload, relocs, _) = "struct binpatch_fixup " ++ ident ++ "_fixups[] = {\n " ++ (foldr (\a b -> a ++ ",\n " ++ b) "" $ map relocToC relocs) ++ "};\n" ++ "struct binpatch " ++ ident ++ " __attribute__ ((section (\"fixup_table\"))) = {\n" ++ " 0x" ++ (showHex rip "") ++ ",\n" ++ " " ++ byteListToCString payload ++ ",\n" ++ " " ++ (show $ length payload) ++ ",\n" ++ " " ++ ident ++ "_fixups,\n" ++ " " ++ (show $ length relocs) ++ "\n" ++ "};\n" criticalSectionToBinpatch' :: String -> History -> Word64 -> Word64 -> Either String String criticalSectionToBinpatch' ident hist start end = do cfg <- buildCFG hist start end res <- reassemble hist start (map fst cfg) return $ reassemblyToC ident res criticalSectionToBinpatch :: History -> Word64 -> Word64 -> Either String String criticalSectionToBinpatch = criticalSectionToBinpatch' "myIdent" loToBinpatch :: History -> [[(MemAccess, Maybe MemAccess)]] -> [[(MemAccess, Maybe MemAccess)]] -> Maybe String loToBinpatch hist crash_origins nocrash_origins = let int = filterLoadOriginPools crash_origins nocrash_origins predictors = mkBinaryClassifier (fst int) (snd int) classifiers = map classifierToExpression predictors critsects = map exprToCriticalSections classifiers mkBinpatch :: [(Word64, Word64)] -> Either String String mkBinpatch ranges = fmap concat $ sequence [criticalSectionToBinpatch' ident hist enter exit | ((enter,exit),ident) <- zip ranges ["ident_" ++ (show x) | x <- [(0::Int)..]]] deMaybe :: [Maybe a] -> [a] deMaybe = foldr (\item acc -> case item of Just x -> x:acc Nothing -> acc) [] deEither :: [Either b a] -> [a] deEither = foldr (\item acc -> case item of Right x -> x:acc Left _ -> acc) [] patches = deEither $ map mkBinpatch $ deMaybe critsects in tlog ("predictors " ++ (show predictors)) $ tlog ("classifiers " ++ (show classifiers)) $ tlog ("crit sects " ++ (show critsects)) $ case patches of [] -> Nothing x:_ -> Just x {- Make a binpatch which will stop the bad histories from recurring while leaving the good histories possible. -} mkEnforcer :: History -> [History] -> [History] -> Either String (Maybe String) mkEnforcer hist bad_histories good_histories = let bad_origins = mapM (loadOrigins hist) bad_histories good_origins = mapM (loadOrigins hist) good_histories in do b <- bad_origins g <- good_origins return $ loToBinpatch hist b g classifyFutures :: Logfile -> History -> ([History], [History]) classifyFutures logfile start = let allFutures = enumerateHistories logfile start allFutureStates = zip allFutures $ map replayState allFutures interestingFutureStates = filter (isInteresting . snd) allFutureStates where isInteresting (ReplayStateOkay _) = False isInteresting (ReplayStateFailed _ _ _ (FailureReasonWrongThread _)) = False isInteresting _ = True crashes = filter (crashed.fst) interestingFutureStates where crashed hist = or $ map (ts_crashed . snd) $ threadState hist lastCrash = last $ sort $ map (rs_access_nr . snd) crashes nocrash = filter (survivesTo (lastCrash + 1) . snd) interestingFutureStates where survivesTo acc s = {- Strictly speaking, we should be checking whether any threads have crashed, but we kind of know they haven't because we're past lastCrash, and it's all okay. -} rs_access_nr s >= acc in case crashes of [] -> ([], []) {- lastCrash, and hence nocrash, is _|_ if crashes is [] -} _ -> (map fst crashes, map fst nocrash) {- Given a history which crashes, generate a binpatch which would make it not crash. -} autoFix :: Logfile -> History -> Either String String autoFix logfile hist = let baseThreshold = rs_access_nr $ replayState hist tryThreshold thresh = tlog ("tryThreshold " ++ (show thresh)) $ let t = deError $ truncateHistory hist $ Finite thresh in case classifyFutures logfile t of ([], _) -> {- hist's truncation doesn't have any crashing futures -> hist didn't crash -> we can't fix it. -} Left "trying to fix a working history?" (_, []) -> {- Every possible future of hist's truncation crashes -> we need to backtrack further -} tryThreshold (thresh - 10) (crashes, nocrashes) -> case mkEnforcer t crashes nocrashes of Left e -> Left e Right Nothing -> tryThreshold (thresh - 1) Right (Just m) -> Right m in tryThreshold baseThreshold
sos22/ppres
ppres/driver/Analysis.hs
gpl-2.0
10,653
0
32
3,231
2,745
1,413
1,332
165
5
import Control.Exception import Control.Monad import Data.List import System.Environment import System.Directory main = do argList <- getArgs -- if no arguments are provided, list the contents of current directory let args = if length argList == 0 then ["."] else argList forM (zip [1..] args) $ \(id, path) -> do result <- try (getDirectoryContents path) :: IO (Either SomeException [FilePath]) case result of -- error, output the message Left exc -> putStrLn $ show exc -- no error, list contents Right dirContents -> do -- some formatting stuff if id /= 1 then putStrLn "" else return () -- sort the names alphabetically putStrLn $ unlines $ sort dirContents return ()
tomicm/puh-hash
bin/ls.hs
gpl-2.0
761
0
18
199
212
107
105
16
4
{-# language DeriveGeneric #-} module Flow.State ( State , lookup , all_states ) where import Prelude hiding ( lookup ) import Autolib.TES.Identifier import Autolib.Hash import Autolib.ToDoc import Autolib.Reader import Autolib.Util.Size import Data.Map ( Map ) import qualified Data.Map as M import Data.Set ( Set ) import qualified Data.Set as S import Control.Monad ( forM ) import GHC.Int import GHC.Generics -- | possible status of tests (predicates) data State = State { hashcode :: Int , contents :: Map Identifier Bool } deriving ( Eq, Ord ) instance Hashable State where hashWithSalt _ = hashcode instance Size State -- who needs this? instance ToDoc State where toDoc s = text "state" <+> text ( show $ M.toList $ contents s ) instance Show State where show = render . toDoc instance Reader State where reader = do my_reserved "state" m <- reader return $ state m state :: [ (Identifier, Bool) ] -> State state m = State { contents = M.fromList m , hashcode = hash m } lookup :: Identifier -> State -> Maybe Bool lookup i s = M.lookup i $ contents s all_states :: Set Identifier -> Set State all_states s = S.fromList $ map state $ forM ( S.toList s ) $ \ v -> [ (v,False), (v,True) ]
marcellussiegburg/autotool
collection/src/Flow/State.hs
gpl-2.0
1,336
0
11
354
427
234
193
42
1
{-# OPTIONS_GHC -fno-warn-orphans #-} {-# LANGUAGE TypeSynonymInstances, FlexibleInstances, ScopedTypeVariables #-} -- provides Arbitrary instance for Pandoc types module Tests.Arbitrary () where import Test.QuickCheck.Gen import Test.QuickCheck.Arbitrary import Control.Monad (liftM, liftM2) import Text.Pandoc.Definition import Text.Pandoc.Shared (normalize, escapeURI) import Text.Pandoc.Builder realString :: Gen String realString = resize 8 $ listOf $ frequency [ (9, elements [' '..'\127']) , (1, elements ['\128'..'\9999']) ] arbAttr :: Gen Attr arbAttr = do id' <- elements ["","loc"] classes <- elements [[],["haskell"],["c","numberLines"]] keyvals <- elements [[],[("start","22")],[("a","11"),("b_2","a b c")]] return (id',classes,keyvals) instance Arbitrary Inlines where arbitrary = liftM (fromList :: [Inline] -> Inlines) arbitrary instance Arbitrary Blocks where arbitrary = liftM (fromList :: [Block] -> Blocks) arbitrary instance Arbitrary Inline where arbitrary = resize 3 $ arbInline 2 arbInlines :: Int -> Gen [Inline] arbInlines n = listOf1 (arbInline n) `suchThat` (not . startsWithSpace) where startsWithSpace (Space:_) = True startsWithSpace _ = False -- restrict to 3 levels of nesting max; otherwise we get -- bogged down in indefinitely large structures arbInline :: Int -> Gen Inline arbInline n = frequency $ [ (60, liftM Str realString) , (60, return Space) , (10, liftM2 Code arbAttr realString) , (5, elements [ RawInline (Format "html") "<a id=\"eek\">" , RawInline (Format "latex") "\\my{command}" ]) ] ++ [ x | x <- nesters, n > 1] where nesters = [ (10, liftM Emph $ arbInlines (n-1)) , (10, liftM Strong $ arbInlines (n-1)) , (10, liftM Strikeout $ arbInlines (n-1)) , (10, liftM Superscript $ arbInlines (n-1)) , (10, liftM Subscript $ arbInlines (n-1)) , (10, liftM SmallCaps $ arbInlines (n-1)) , (10, do x1 <- arbitrary x2 <- arbInlines (n-1) return $ Quoted x1 x2) , (10, do x1 <- arbitrary x2 <- realString return $ Math x1 x2) , (10, do x1 <- arbInlines (n-1) x3 <- realString x2 <- liftM escapeURI realString return $ Link x1 (x2,x3)) , (10, do x1 <- arbInlines (n-1) x3 <- realString x2 <- liftM escapeURI realString atr <- arbAttr return $ Image atr x1 (x2,x3)) , (2, liftM2 Cite arbitrary (arbInlines 1)) , (2, liftM Note $ resize 3 $ listOf1 $ arbBlock (n-1)) ] instance Arbitrary Block where arbitrary = resize 3 $ arbBlock 2 arbBlock :: Int -> Gen Block arbBlock n = frequency $ [ (10, liftM Plain $ arbInlines (n-1)) , (15, liftM Para $ arbInlines (n-1)) , (5, liftM2 CodeBlock arbAttr realString) , (2, elements [ RawBlock (Format "html") "<div>\n*&amp;*\n</div>" , RawBlock (Format "latex") "\\begin[opt]{env}\nhi\n{\\end{env}" ]) , (5, do x1 <- choose (1 :: Int, 6) x2 <- arbInlines (n-1) return (Header x1 nullAttr x2)) , (2, return HorizontalRule) ] ++ [x | x <- nesters, n > 0] where nesters = [ (5, liftM BlockQuote $ listOf1 $ arbBlock (n-1)) , (5, do x2 <- arbitrary x3 <- arbitrary x1 <- arbitrary `suchThat` (> 0) x4 <- listOf1 $ listOf1 $ arbBlock (n-1) return $ OrderedList (x1,x2,x3) x4 ) , (5, liftM BulletList $ (listOf1 $ listOf1 $ arbBlock (n-1))) , (5, do items <- listOf1 $ do x1 <- listOf1 $ listOf1 $ arbBlock (n-1) x2 <- arbInlines (n-1) return (x2,x1) return $ DefinitionList items) , (2, do rs <- choose (1 :: Int, 4) cs <- choose (1 :: Int, 4) x1 <- arbInlines (n-1) x2 <- vector cs x3 <- vectorOf cs $ elements [0, 0.25] x4 <- vectorOf cs $ listOf $ arbBlock (n-1) x5 <- vectorOf rs $ vectorOf cs $ listOf $ arbBlock (n-1) return (Table x1 x2 x3 x4 x5)) ] instance Arbitrary Pandoc where arbitrary = resize 8 $ liftM normalize $ liftM2 Pandoc arbitrary arbitrary instance Arbitrary CitationMode where arbitrary = do x <- choose (0 :: Int, 2) case x of 0 -> return AuthorInText 1 -> return SuppressAuthor 2 -> return NormalCitation _ -> error "FATAL ERROR: Arbitrary instance, logic bug" instance Arbitrary Citation where arbitrary = do x1 <- listOf $ elements $ ['a'..'z'] ++ ['0'..'9'] ++ ['_'] x2 <- arbInlines 1 x3 <- arbInlines 1 x4 <- arbitrary x5 <- arbitrary x6 <- arbitrary return (Citation x1 x2 x3 x4 x5 x6) instance Arbitrary MathType where arbitrary = do x <- choose (0 :: Int, 1) case x of 0 -> liftM DisplayMath arbAttr 1 -> return InlineMath _ -> error "FATAL ERROR: Arbitrary instance, logic bug" instance Arbitrary QuoteType where arbitrary = do x <- choose (0 :: Int, 1) case x of 0 -> return SingleQuote 1 -> return DoubleQuote _ -> error "FATAL ERROR: Arbitrary instance, logic bug" instance Arbitrary Meta where arbitrary = do (x1 :: Inlines) <- arbitrary (x2 :: [Inlines]) <- liftM (filter (not . isNull)) arbitrary (x3 :: Inlines) <- arbitrary return $ setMeta "title" x1 $ setMeta "author" x2 $ setMeta "date" x3 $ nullMeta instance Arbitrary Alignment where arbitrary = do x <- choose (0 :: Int, 3) case x of 0 -> return AlignLeft 1 -> return AlignRight 2 -> return AlignCenter 3 -> return AlignDefault _ -> error "FATAL ERROR: Arbitrary instance, logic bug" instance Arbitrary ListNumberStyle where arbitrary = do x <- choose (0 :: Int, 6) case x of 0 -> return DefaultStyle 1 -> return Example 2 -> return Decimal 3 -> return LowerRoman 4 -> return UpperRoman 5 -> return LowerAlpha 6 -> return UpperAlpha _ -> error "FATAL ERROR: Arbitrary instance, logic bug" instance Arbitrary ListNumberDelim where arbitrary = do x <- choose (0 :: Int, 3) case x of 0 -> return DefaultDelim 1 -> return Period 2 -> return OneParen 3 -> return TwoParens _ -> error "FATAL ERROR: Arbitrary instance, logic bug"
timtylin/scholdoc
tests/Tests/Arbitrary.hs
gpl-2.0
8,312
0
19
3,737
2,386
1,220
1,166
167
2
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE TypeFamilies #-} -- Copyright (C) 2009-2012 John Millikin <[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 -- 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/>. -- | D-Bus sockets are used for communication between two peers. In this model, -- there is no \"bus\" or \"client\", simply two endpoints sending messages. -- -- Most users will want to use the "DBus.Client" module instead. module DBus.Socket ( -- * Sockets Socket , send , receive -- * Socket errors , SocketError , socketError , socketErrorMessage , socketErrorFatal , socketErrorAddress -- * Socket options , SocketOptions , socketAuthenticator , socketTransportOptions , defaultSocketOptions -- * Opening and closing sockets , open , openWith , close -- * Listening for connections , SocketListener , listen , listenWith , accept , closeListener , socketListenerAddress -- * Authentication , Authenticator , authenticator , authenticatorClient , authenticatorServer ) where import Prelude hiding (getLine) import Control.Concurrent import Control.Exception import Control.Monad (mplus) import qualified Data.ByteString import qualified Data.ByteString.Char8 as Char8 import Data.Char (ord) import Data.IORef import Data.List (isPrefixOf) import Data.Typeable (Typeable) import qualified System.Posix.User import Text.Printf (printf) import DBus import DBus.Transport import DBus.Wire (unmarshalMessageM) -- | Stores information about an error encountered while creating or using a -- 'Socket'. data SocketError = SocketError { socketErrorMessage :: String , socketErrorFatal :: Bool , socketErrorAddress :: Maybe Address } deriving (Eq, Show, Typeable) instance Exception SocketError socketError :: String -> SocketError socketError msg = SocketError msg True Nothing data SomeTransport = forall t. (Transport t) => SomeTransport t instance Transport SomeTransport where data TransportOptions SomeTransport = SomeTransportOptions transportDefaultOptions = SomeTransportOptions transportPut (SomeTransport t) = transportPut t transportGet (SomeTransport t) = transportGet t transportClose (SomeTransport t) = transportClose t -- | An open socket to another process. Messages can be sent to the remote -- peer using 'send', or received using 'receive'. data Socket = Socket { socketTransport :: SomeTransport , socketAddress :: Maybe Address , socketSerial :: IORef Serial , socketReadLock :: MVar () , socketWriteLock :: MVar () } -- | An Authenticator defines how the local peer (client) authenticates -- itself to the remote peer (server). data Authenticator t = Authenticator { -- | Defines the client-side half of an authenticator. authenticatorClient :: t -> IO Bool -- | Defines the server-side half of an authenticator. The UUID is -- allocated by the socket listener. , authenticatorServer :: t -> UUID -> IO Bool } -- | Used with 'openWith' and 'listenWith' to provide custom authenticators or -- transport options. data SocketOptions t = SocketOptions { -- | Used to perform authentication with the remote peer. After a -- transport has been opened, it will be passed to the authenticator. -- If the authenticator returns true, then the socket was -- authenticated. socketAuthenticator :: Authenticator t -- | Options for the underlying transport, to be used by custom transports -- for controlling how to connect to the remote peer. -- -- See "DBus.Transport" for details on defining custom transports , socketTransportOptions :: TransportOptions t } -- | Default 'SocketOptions', which uses the default Unix/TCP transport and -- authenticator. defaultSocketOptions :: SocketOptions SocketTransport defaultSocketOptions = SocketOptions { socketTransportOptions = transportDefaultOptions , socketAuthenticator = authExternal } -- | Open a socket to a remote peer listening at the given address. -- -- @ --open = 'openWith' 'defaultSocketOptions' -- @ -- -- Throws 'SocketError' on failure. open :: Address -> IO Socket open = openWith defaultSocketOptions -- | Open a socket to a remote peer listening at the given address. -- -- Most users should use 'open'. This function is for users who need to define -- custom authenticators or transports. -- -- Throws 'SocketError' on failure. openWith :: TransportOpen t => SocketOptions t -> Address -> IO Socket openWith opts addr = toSocketError (Just addr) $ bracketOnError (transportOpen (socketTransportOptions opts) addr) transportClose (\t -> do authed <- authenticatorClient (socketAuthenticator opts) t if not authed then throwIO (socketError "Authentication failed") { socketErrorAddress = Just addr } else do serial <- newIORef firstSerial readLock <- newMVar () writeLock <- newMVar () return (Socket (SomeTransport t) (Just addr) serial readLock writeLock)) data SocketListener = forall t. (TransportListen t) => SocketListener (TransportListener t) (Authenticator t) -- | Begin listening at the given address. -- -- Use 'accept' to create sockets from incoming connections. -- -- Use 'closeListener' to stop listening, and to free underlying transport -- resources such as file descriptors. -- -- Throws 'SocketError' on failure. listen :: Address -> IO SocketListener listen = listenWith defaultSocketOptions -- | Begin listening at the given address. -- -- Use 'accept' to create sockets from incoming connections. -- -- Use 'closeListener' to stop listening, and to free underlying transport -- resources such as file descriptors. -- -- This function is for users who need to define custom authenticators -- or transports. -- -- Throws 'SocketError' on failure. listenWith :: TransportListen t => SocketOptions t -> Address -> IO SocketListener listenWith opts addr = toSocketError (Just addr) $ bracketOnError (transportListen (socketTransportOptions opts) addr) transportListenerClose (\l -> return (SocketListener l (socketAuthenticator opts))) -- | Accept a new connection from a socket listener. -- -- Throws 'SocketError' on failure. accept :: SocketListener -> IO Socket accept (SocketListener l auth) = toSocketError Nothing $ bracketOnError (transportAccept l) transportClose (\t -> do let uuid = transportListenerUUID l authed <- authenticatorServer auth t uuid if not authed then throwIO (socketError "Authentication failed") else do serial <- newIORef firstSerial readLock <- newMVar () writeLock <- newMVar () return (Socket (SomeTransport t) Nothing serial readLock writeLock)) -- | Close an open 'Socket'. Once closed, the socket is no longer valid and -- must not be used. close :: Socket -> IO () close = transportClose . socketTransport -- | Close an open 'SocketListener'. Once closed, the listener is no longer -- valid and must not be used. closeListener :: SocketListener -> IO () closeListener (SocketListener l _) = transportListenerClose l -- | Get the address to use to connect to a listener. socketListenerAddress :: SocketListener -> Address socketListenerAddress (SocketListener l _) = transportListenerAddress l -- | Send a single message, with a generated 'Serial'. The second parameter -- exists to prevent race conditions when registering a reply handler; it -- receives the serial the message /will/ be sent with, before it's -- actually sent. -- -- Sockets are thread-safe. Only one message may be sent at a time; if -- multiple threads attempt to send messages concurrently, one will block -- until after the other has finished. -- -- Throws 'SocketError' on failure. send :: Message msg => Socket -> msg -> (Serial -> IO a) -> IO a send sock msg io = toSocketError (socketAddress sock) $ do serial <- nextSocketSerial sock case marshal LittleEndian serial msg of Right bytes -> do let t = socketTransport sock a <- io serial withMVar (socketWriteLock sock) (\_ -> transportPut t bytes) return a Left err -> throwIO (socketError ("Message cannot be sent: " ++ show err)) { socketErrorFatal = False } nextSocketSerial :: Socket -> IO Serial nextSocketSerial sock = atomicModifyIORef (socketSerial sock) (\x -> (nextSerial x, x)) -- | Receive the next message from the socket , blocking until one is available. -- -- Sockets are thread-safe. Only one message may be received at a time; if -- multiple threads attempt to receive messages concurrently, one will block -- until after the other has finished. -- -- Throws 'SocketError' on failure. receive :: Socket -> IO ReceivedMessage receive sock = toSocketError (socketAddress sock) $ do -- TODO: after reading the length, read all bytes from the -- handle, then return a closure to perform the parse -- outside of the lock. let t = socketTransport sock let get n = if n == 0 then return Data.ByteString.empty else transportGet t n received <- withMVar (socketReadLock sock) (\_ -> unmarshalMessageM get) case received of Left err -> throwIO (socketError ("Error reading message from socket: " ++ show err)) Right msg -> return msg toSocketError :: Maybe Address -> IO a -> IO a toSocketError addr io = catches io handlers where handlers = [ Handler catchTransportError , Handler updateSocketError , Handler catchIOException ] catchTransportError err = throwIO (socketError (transportErrorMessage err)) { socketErrorAddress = addr } updateSocketError err = throwIO err { socketErrorAddress = mplus (socketErrorAddress err) addr } catchIOException exc = throwIO (socketError (show (exc :: IOException))) { socketErrorAddress = addr } -- | An empty authenticator. Use 'authenticatorClient' or 'authenticatorServer' -- to control how the authentication is performed. -- -- @ --myAuthenticator :: Authenticator MyTransport --myAuthenticator = authenticator -- { 'authenticatorClient' = clientMyAuth -- , 'authenticatorServer' = serverMyAuth -- } -- --clientMyAuth :: MyTransport -> IO Bool --serverMyAuth :: MyTransport -> String -> IO Bool -- @ authenticator :: Authenticator t authenticator = Authenticator (\_ -> return False) (\_ _ -> return False) -- | Implements the D-Bus @EXTERNAL@ mechanism, which uses credential -- passing over a Unix socket. authExternal :: Authenticator SocketTransport authExternal = authenticator { authenticatorClient = clientAuthExternal , authenticatorServer = serverAuthExternal } clientAuthExternal :: SocketTransport -> IO Bool clientAuthExternal t = do transportPut t (Data.ByteString.pack [0]) uid <- System.Posix.User.getRealUserID let token = concatMap (printf "%02X" . ord) (show uid) transportPutLine t ("AUTH EXTERNAL " ++ token) resp <- transportGetLine t case splitPrefix "OK " resp of Just _ -> do transportPutLine t "BEGIN" return True Nothing -> return False serverAuthExternal :: SocketTransport -> UUID -> IO Bool serverAuthExternal t uuid = do let waitForBegin = do resp <- transportGetLine t if resp == "BEGIN" then return () else waitForBegin let checkToken token = do (_, uid, _) <- socketTransportCredentials t let wantToken = concatMap (printf "%02X" . ord) (show uid) if token == wantToken then do transportPutLine t ("OK " ++ formatUUID uuid) waitForBegin return True else return False c <- transportGet t 1 if c /= Char8.pack "\x00" then return False else do line <- transportGetLine t case splitPrefix "AUTH EXTERNAL " line of Just token -> checkToken token Nothing -> if line == "AUTH EXTERNAL" then do dataLine <- transportGetLine t case splitPrefix "DATA " dataLine of Just token -> checkToken token Nothing -> return False else return False transportPutLine :: Transport t => t -> String -> IO () transportPutLine t line = transportPut t (Char8.pack (line ++ "\r\n")) transportGetLine :: Transport t => t -> IO String transportGetLine t = do let getchr = Char8.head `fmap` transportGet t 1 raw <- readUntil "\r\n" getchr return (dropEnd 2 raw) -- | Drop /n/ items from the end of a list dropEnd :: Int -> [a] -> [a] dropEnd n xs = take (length xs - n) xs splitPrefix :: String -> String -> Maybe String splitPrefix prefix str = if isPrefixOf prefix str then Just (drop (length prefix) str) else Nothing -- | Read values from a monad until a guard value is read; return all -- values, including the guard. readUntil :: (Monad m, Eq a) => [a] -> m a -> m [a] readUntil guard getx = readUntil' [] where guard' = reverse guard step xs | isPrefixOf guard' xs = return (reverse xs) | otherwise = readUntil' xs readUntil' xs = do x <- getx step (x:xs)
jotrk/haskell-dbus
lib/DBus/Socket.hs
gpl-3.0
13,324
143
24
2,507
2,825
1,486
1,339
224
7
module Event where class Input i where fetch :: IO i class Output o where send :: o -> IO () class (Input d, Output d) => IODevice d where source :: d -> [Input d] dest :: d -> [Output d] class Test t where apply :: a -> t a
Jon0/status
src/Event.hs
gpl-3.0
249
0
9
76
119
60
59
10
0
{-# LANGUAGE DeriveGeneric, DefaultSignatures, FlexibleInstances, OverlappingInstances #-} module Template where import Data.Serialize import Data.Serialize.Put import Data.Serialize.Get import GHC.Generics import qualified Data.ByteString as BS import Data.Bits import GHC.Int import GHC.Word import Control.Monad import Control.Monad.Loops import Control.Applicative import Data.List import Data.Maybe import qualified Data.Map as M import Debug.Trace type Fixed = Word32 type FWord = Int16 type DateTime = Word64 data PArray w a = PArray w [a] deriving Show puts x = mapM_ put x getN n = replicateM (fromIntegral n) get instance (Serialize w, Serialize as, Integral w) => Serialize (PArray w as) where get = do n <- get as <- getN n return (PArray n as) put (PArray n s) = do put n puts s type PString = PArray Word8 Char newtype BArray a = BArray [a] deriving Show instance (Serialize as) => Serialize (BArray as) where get = do error "Infinite array get!" put (BArray cs) = puts cs type BString = BArray Char getb n = do a <- getN n return (BArray a) instance Serialize (BArray PString) where get = do bs <- whileM (do r <- remaining if r > 0 then liftM ((<= r) . fromIntegral) (lookAhead get :: Get Word8) else return False ) get return $ BArray bs put (BArray ps) = do mapM_ put ps data TTF = TTF { ttfOffset :: Offset, tableDefs :: BArray TableDef, tables :: BArray Table } deriving (Generic, Show) instance Serialize TTF where get = do o@(Offset s n r e sh) <- get tdefs <- replicateM (fromIntegral n) get let sdefs = sortBy (\(TableDef {off=l}) (TableDef {off=r}) -> l `compare` r) tdefs let mdefs = M.fromList $ map (\t@(TableDef {tag=(BArray tag)}) -> (tag, t)) sdefs let start = 12 + 16*(fromIntegral n) head <- lookAhead (tableFromTag start (mdefs M.! "head") (M.fromList [])) hhea <- lookAhead (tableFromTag start (mdefs M.! "hhea") (M.fromList [])) maxp <- lookAhead (tableFromTag start (mdefs M.! "maxp") (M.fromList [])) let neededTabs = M.fromList [("head",head),("hhea",hhea),("maxp",maxp)] tabs <- mapM (\e -> lookAhead (tableFromTag start e neededTabs)) sdefs return $ TTF o (BArray tdefs) (BArray tabs) put (TTF o d (BArray ts)) = do put o put d mapM_ putByteString $ map padbs $ map encode ts tableFromTag :: Word32 -> TableDef -> M.Map String Table -> Get Table tableFromTag start (TableDef (BArray tag) _ off len) tabs = do skip $ fromIntegral (off-start) bs <- getBytes $ fromIntegral len case (runGet (fromTag tag bs tabs) bs) of (Left m) -> error m (Right t) -> return t fromTag :: String -> BS.ByteString -> M.Map String Table -> Get Table fromTag tag bs tabs = do case tag of "cmap" -> liftM CmapTable get "cvt " -> liftM CvtTable get "fpgm" -> liftM FpgmTable get --"glyf" -> liftM GlyfTable (getGlyf (tabs M.! "maxp") (tabs M.! "head")) "head" -> liftM HeadTable get "hhea" -> liftM HheaTable get "hmtx" -> liftM HmtxTable (getHmtx (tabs M.! "maxp") (tabs M.! "hhea")) "loca" -> liftM LocaTable (getLoca (tabs M.! "maxp") (tabs M.! "head")) "maxp" -> liftM MaxpTable get "name" -> liftM NameTable get "post" -> liftM PostTable get _ -> return $ UnknownTable tag bs tagFromTable t = case t of (CmapTable _) -> BArray "cmap" (CvtTable _) -> BArray "cmap" (FpgmTable _) -> BArray "fpgm" (GlyfTable _) -> BArray "glyf" (HeadTable _) -> BArray "head" (HheaTable _) -> BArray "hhea" (HmtxTable _) -> BArray "hmtx" (LocaTable _) -> BArray "loca" (MaxpTable _) -> BArray "maxp" (NameTable _) -> BArray "name" (PostTable _) -> BArray "post" (UnknownTable tag _) -> BArray tag padbs bs = let bsl = fromIntegral $ BS.length bs pad = 3 - ((bsl - 1)`mod` 4) in bs `BS.append` (BS.pack (take pad $ repeat 0)) accum a (tag, bs) = let padd = padbs bs anext = a + (fromIntegral $ BS.length padd) dnext = tableEntry tag padd (fromIntegral a) in (anext, dnext) ttfTables tables = do let n = fromIntegral $ length tables let tabs = map (\t -> (tagFromTable t,encode t)) tables let (_, tdefs) = mapAccumL accum (12 + 16*(fromIntegral n)) tabs put $ offset n puts tdefs puts $ map snd tabs data Offset = Offset { scalarType :: Word32, numTables :: Word16, searchRange :: Word16, entrySelector :: Word16, rangeShift :: Word16 } deriving (Generic, Show) instance Serialize Offset offset numTables = let largest2 n = if 2^n > numTables then n else largest2 $ n+1 eSel = largest2 1 sRange = 2^eSel in Offset 0x10000 numTables (sRange*16) eSel (numTables*16 - sRange*16) data TableDef = TableDef { tag :: BString, checkSum :: Word32, off :: Word32, len :: Word32 } deriving (Generic, Show) instance Serialize TableDef where get = do tag <- getb 4 liftM3 (TableDef tag) get get get getBS tc d = let r = runGet tc $ d in case r of Left m -> error m Right s -> s tableChecksum table = let tc = do e <- remaining if e < 4 then return 0 else do w <- getWord32be r <- tc return $ w + r in getBS tc table tableEntry tag table offset = TableDef tag (tableChecksum table) offset (fromIntegral $ BS.length table) data Table = CmapTable Cmap | CvtTable Cvt | GlyfTable Glyf | FpgmTable Fpgm | HeadTable Head | HheaTable Hhea | HmtxTable Hmtx | LocaTable Loca | MaxpTable Maxp | NameTable Name | PostTable Post | UnknownTable String BS.ByteString deriving (Generic, Show) instance Serialize Table where put (CmapTable t) = put t put (CvtTable t) = put t put (FpgmTable t) = put t put (GlyfTable t) = put t put (HeadTable t) = put t put (HheaTable t) = put t put (LocaTable t) = put t put (HmtxTable t) = put t put (MaxpTable t) = put t put (NameTable t) = put t put (PostTable t) = put t put (UnknownTable _ bs) = putByteString bs data Cmap = Cmap { version :: Word16, encs :: PArray Word16 CmapEnc, formats :: BArray CmapFormat } deriving (Generic, Show) instance Serialize Cmap where get = do vers <- get encs@(PArray _ es) <- get let fmts = length $ nub $ map encOff es liftM (Cmap vers encs) (getb fmts) data CmapEnc = CmapEnc { pID :: Word16, pSpecID :: Word16, encOff :: Word32 } deriving (Generic, Show) instance Serialize CmapEnc data CmapFormat = CmapFormat0 { cmapFormat :: Word16, formatLen :: Word16, formatLang :: Word16, glyphIndices:: BArray Word8 } | CmapUnknown16 Word16 Word16 BS.ByteString | CmapUnknown32 Word32 Word32 BS.ByteString deriving (Generic, Show) instance Serialize CmapFormat where get = do fmt <- get if fmt == 0 then do flen <- get liftM2 (CmapFormat0 0 flen) get (getb (flen-6)) else if fmt == 2 || fmt == 4 || fmt == 6 then do flen <- get liftM (CmapUnknown16 fmt flen) (getBytes $ (fromIntegral flen)-4) else do fmt2 <- get :: Get Word16 flen <- get let fmt32 = ((fromIntegral fmt) `shift` 16) .|. (fromIntegral fmt2) liftM (CmapUnknown32 fmt32 flen) (getBytes $ (fromIntegral flen)-8) put (CmapFormat0 f l a g) = do puts [f, l, a] put g put (CmapUnknown16 f l bs) = do put f; put l putByteString bs put (CmapUnknown32 f l bs) = do put f; put l putByteString bs blength (BArray bs) = fromIntegral $ length bs cmapFormat0 language glyphIndices = let n = (blength glyphIndices)+6 in CmapFormat0 0 n language glyphIndices data Cvt = Cvt (BArray FWord) deriving (Generic, Show) instance Serialize Cvt where get = do r <- remaining liftM Cvt (getb (r `shift` (-1))) data Fpgm = Fpgm (BArray Word8) deriving (Generic, Show) instance Serialize Fpgm where get = do r <- remaining bs <- getByteString r return $ Fpgm $ BArray (BS.unpack bs) data Glyf = Glyf (BArray GlyphDesc) deriving (Generic, Show) instance Serialize Glyf getAligned long = do pre <- remaining x <- get post <- remaining let diff = pre - post let npad = if long == 1 then 3 - ((diff - 1) `mod` 4) else (if diff `mod` 2 == 1 then 1 else 0) got <- getN npad :: Get [Word8] return x getGlyf (MaxpTable m) (HeadTable h) = do xs <- replicateM (fromIntegral $ numGlyphs m) $ getAligned $ iToLoc h return $ Glyf $ BArray xs data Point = PointB Word8 | PointS Int16 deriving (Generic, Show) instance Serialize Point where put (PointB p) = put p put (PointS p) = put p data GlyphDesc = GlyphDesc { nContours :: Int16, xMin :: FWord, yMin :: FWord, xMax :: FWord, yMax :: FWord, glyph :: Glyph } deriving (Generic, Show) data Glyph = SimpleGlyph { endPts :: BArray Word16, instrs :: PArray Word16 Word8, pflags :: BArray Word8, xs :: BArray Point, ys :: BArray Point } | CompoundGlyph { cflags :: Word16, glyphIndex :: Word16, arg1 :: Point, arg2 :: Point, trans :: Point } deriving (Generic, Show) instance Serialize Glyph where get = error "Serializing lone glyph" put (SimpleGlyph e i p x y) = do put e; put i; put p put x; put y put (CompoundGlyph c g a1 a2 t) = do put c; put g put a1; put a2 put t getpflags n | n > 0 = do flag <- get if flag .&. 8 == 8 then do rep <- get :: Get Word8 let flags = flag:(take (fromIntegral rep) $ repeat flag) rest <- getpflags (n - 1 - (fromIntegral rep)) return (flags ++ rest) else do rest <- getpflags (n - 1) return (flag:rest) | otherwise = return [] getps i j (p:ps) prev = do if p .&. i /= 0 then do num <- get let new = PointB (if p .&. j == 0 then num else -num) rest <- getps i j ps new return (new:rest) else if p .&. j == 0 then do new <- liftM PointS get rest <- getps i j ps new return (new:rest) else do rest <- getps i j ps prev return (prev:rest) getps _ _ [] _ = return [] instance Serialize GlyphDesc where get = do nc <- get x0 <- get; y0 <- get xm <- get; ym <- get let gp = GlyphDesc nc x0 y0 xm ym if nc < 0 then error "Compound glyph!" else liftM gp (simpleGlyph nc) simpleGlyph nc = do end <- getN nc instrs <- get let n = foldr max 0 $ map (+ 1) end pflag <- getpflags n xs <- getps 2 16 pflag (PointS 0) ys <- getps 4 32 pflag (PointS 0) return $ SimpleGlyph (BArray end) instrs (BArray pflag) (BArray xs) (BArray ys) {- data GlyphPoint = GPoint Word16 Word8 Int Int -- TODO: full glyph support simpleGlyph :: [Word16] -> (State Program ()) -> [Word8] -> [Word8] -> [Word8] -> (State Program ()) simpleGlyph endPts instrs flags xs ys =_simpleGlyph endPts (slen instrs) instrs flags xs ys glyph xMin yMin xMax yMax endPts instrs flags xs ys = let g = do glyphDesc (fromIntegral $ length endPts) xMin yMin xMax yMax ; simpleGlyph endPts instrs flags xs ys in if ((length endPts) == (length xs)) && ((length endPts) == (length ys) && ((length endPts) == (length flags))) then g else error "Mismatched lengths" -} data Head = Head { headVersion :: Fixed, revision :: Fixed, csAdjust :: Word32, magic :: Word32, flags :: Word16, unitsPerEm :: Word16, created :: DateTime, modified :: DateTime, allXMin :: FWord, allYMin :: FWord, allXMax :: FWord, allYMax :: FWord, macStyle :: Word16, lowestRec :: Word16, direction :: Int16, iToLoc :: Int16, format :: Int16 } deriving (Generic, Show) instance Serialize Head {- headTable = _head 0x00010000 0 0x5f0f3cf5 -} data Hhea = Hhea { hheaVersion :: Fixed, ascent :: Int16, descent :: Int16, lineGap :: Int16, aWidthMax :: Word16, minLeft :: Int16, minRight :: Int16, xMaxExtent :: Int16, cSlopeRise :: Int16, cSlopeRun :: Int16, cOffset :: Int16, r0 :: Int16, r1 :: Int16, r2 :: Int16, r3 :: Int16, mDataFormat :: Int16, nMetrics :: Word16 } deriving (Generic, Show) instance Serialize Hhea {- hhea ascent descent lineGap aWidthMax minLeft minRight cSlopeRise cSlopeRun cOffset nMetrics = _hhea 0x00010000 ascent descent lineGap aWidthMax minLeft minRight 0 cSlopeRise cSlopeRun cOffset 0 0 0 0 0 nMetrics -- TODO short version _loca entries = do mapM_ uint entries -- TODO ordering loca m = _loca $ map (\(k,v) -> v) (M.toList m) -} data Hmtx = Hmtx (BArray HmtxEntry) (BArray FWord) deriving (Generic, Show) instance Serialize Hmtx getHmtx (MaxpTable m) (HheaTable h) = do let nhor = nMetrics h let nglf = numGlyphs m liftM2 Hmtx (getb nhor) (getb (nglf - nhor)) data HmtxEntry = HmtxEntry { advanceWidth :: Word16, leftSideBearing :: Int16 } deriving (Generic, Show) instance Serialize HmtxEntry data Loca = LocaShort (BArray Word16) | LocaLong (BArray Word32) deriving (Generic, Show) instance Serialize Loca where put (LocaShort ws) = put ws put (LocaLong ws) = put ws getLoca (MaxpTable m) (HeadTable h) = let fmt = iToLoc h n = (numGlyphs m)+1 in case fmt of 0 -> liftM LocaShort (getb n) 1 -> liftM LocaLong (getb n) data Maxp = Maxp { maxpVersion :: Fixed, numGlyphs :: Word16, maxPoints :: Word16, maxContours :: Word16, maxComponentPoints :: Word16, maxComponentContours :: Word16, maxZones :: Word16, maxTwilightPoints :: Word16, maxStorage :: Word16, maxFunctionDefs :: Word16, maxInstructionDefs :: Word16, maxStackElements :: Word16, maxSizeOfInstructions :: Word16, maxComponentElements :: Word16, maxComponentDepth :: Word16 } deriving (Generic, Show) instance Serialize Maxp {- maxp numGlyphs maxPoints maxContours maxComponentPoints maxComponentContours = _maxp 0x00010000 numGlyphs maxPoints maxContours maxComponentPoints maxComponentContours -} data Name = Name { nameFormat :: Word16, count :: Word16, strOffset :: Word16, nameRecords :: BArray NameRecord, names :: BS.ByteString } deriving (Generic, Show) instance Serialize Name where get = do nf <- get; c <- get; o <- get; nr <- getb c r <- remaining ns <- getBytes r return $ Name nf c o nr ns put (Name f c s r n) = do puts [f,c,s] put r putByteString n {- name nameRecords names count = _name 0 count (count*12+6) nameRecords names data NameRecord = NRecord Word16 Word16 Word16 Word16 String data MSNameRecord = MSNRecord NameID String data NameID = Copyright | Family | Subfamily | UUID | Fullname | Version | Postscript | Trademark deriving Enum -} data NameRecord = NameRecord { namepID :: Word16, namepsID :: Word16, namelID :: Word16, namenID :: Word16, nameLength :: Word16, nameOffset :: Word16 } deriving (Generic, Show) instance Serialize NameRecord {- string16 s = '\00' : (intersperse '\00' s) nameHeaderMS records = nameHeader $ map (\(MSNRecord nid str) -> NRecord 3 1 0x409 (fromIntegral $ fromEnum nid) (string16 str)) records nameHeader records = let nh ((NRecord pid psid lid nid str):rs) c = (pid, psid, lid, fromIntegral $ fromEnum nid, fromIntegral (length str), c):(nh rs (c + fromIntegral(length str))) nh [] c = [] recs = nh records 0 names = map (\(NRecord _ _ _ _ s) -> s) records in name (do mapM_ (\(pid, psid, lid, nid, len, off) -> nameRecord pid psid lid nid len off) recs) (do mapM_ string names) (fromIntegral $ length records) -} data Post = Post { postFormat :: Fixed, iAngle :: Fixed, uPos :: Int16, uThick :: Int16, fixed :: Word32, minMemT42 :: Word32, maxMemT42 :: Word32, minMemT1 :: Word32, maxMemT1 :: Word32, postf :: PostFormat } deriving (Generic, Show) instance Serialize Post data PostFormat = PostFormat2 { glyphNameInd :: PArray Word16 Word16, pNames :: BArray PString } deriving (Generic, Show) instance Serialize PostFormat {- post format iAngle uPos uThick fixed = _post format iAngle uPos uThick (if fixed then 1 else 0) 0 0 0 0 post3 iAngle uPos uThick fixed = post 0x00030000 iAngle uPos uThick fixed -}
jseaton/ttasm
Template.hs
gpl-3.0
17,694
303
18
5,571
4,888
2,588
2,300
-1
-1
-- This file is part of Engulidor. -- -- Engulidor 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. -- -- Engulidor 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 Engulidor. If not, see <http://www.gnu.org/licenses/>. {-# LANGUAGE NoMonomorphismRestriction #-} module Parser where import Prelude hiding (concat) import Control.Applicative ((<$>), (<$), (<*>), (<*), (*>)) import Data.ByteString (concat, pack, singleton) import Data.Char (digitToInt) import Text.Parsec ((<?>), (<|>), endBy, eof, many1, noneOf, parse , sepBy1, skipMany, try) import Text.Parsec.Char (char, endOfLine, hexDigit, oneOf) import Text.Parsec.Language (emptyDef) import qualified Text.Parsec.Token as Token (identLetter, identStart , identifier, makeTokenParser , symbol, whiteSpace) import Data (Cfg(Cfg), Cmd(..)) cfgDef = emptyDef { Token.identStart = noneOf " =\t\r\f\v\xa0\n" , Token.identLetter = noneOf " =\t\r\f\v\xa0\n" } lexer = Token.makeTokenParser cfgDef ident = Token.identifier lexer symbol = Token.symbol lexer whiteSpace = Token.whiteSpace lexer blankSpace = skipMany (oneOf " \t\r\f\v\xa0") hexNumber = foldl (\ x -> (16 * x +) . fromIntegral . digitToInt) 0 <$> try (many1 hexDigit) <?> "hexadecimal number" hexNumbers = sepBy1 hexNumber blankSpace <?> "hexadecimal numbers" binding = (,) <$> ident <* symbol "=" <*> (pack <$> hexNumbers) <?> "binding" bindings = endBy (whiteSpace *> binding) endOfLine <?> "bindings" portName = ident <?> "port name" cfg = Cfg <$> portName <*> bindings parseCfg = parse (cfg <* eof) dataList binds = concat <$> sepBy1 atom blankSpace where atom = try (ident >>= \ bind -> maybe (fail $ "undeclared binding: " ++ bind) return $ lookup bind binds) <|> (singleton <$> hexNumber) parseDataList binds = parse (dataList binds <* eof) "<interactive>" cmd = Quit <$ char 'q' <|> Help <$ char 'h' <|> Binds <$ char 'b' parseCmd = parse (cmd <* eof) "<interactive>"
gahag/Engulidor
src/Parser.hs
gpl-3.0
2,898
0
16
912
595
345
250
50
1
{- ---------------------------------------------------------------------------------- - Copyright (C) 2010-2011 Massachusetts Institute of Technology - Copyright (C) 2010-2011 Yuan Tang <[email protected]> - Charles E. Leiserson <[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/>. - - Suggestsions: [email protected] - Bugs: [email protected] - -------------------------------------------------------------------------------- -} module PMainParser (pParser) where import Text.ParserCombinators.Parsec import Control.Monad import PBasicParser import PParser2 import PUtils import PData import PShow -- import Text.Show import qualified Data.Map as Map -- The main parser, which ALSO is the main code generator. pParser :: GenParser Char ParserState String pParser = do tokens0 <- many $ pToken eof return $ concat tokens0 -- start a second pass! -- setInput $ concat tokens0 -- tokens1 <- many pToken1 -- return $ concat tokens1 pToken :: GenParser Char ParserState String pToken = try pParseCPPComment <|> try pParseMacro <|> try pParsePochoirArray <|> try pParsePochoirArrayAsParam <|> try pParsePochoirStencil <|> try pParsePochoirStencilWithShape <|> try pParsePochoirStencilAsParam <|> try pParsePochoirStencilWithShapeAsParam <|> try pParsePochoirShapeInfo <|> try pParsePochoirDomain <|> try pParsePochoirKernel1D <|> try pParsePochoirKernel2D <|> try pParsePochoirKernel3D <|> try pParsePochoirAutoKernel <|> try pParsePochoirArrayMember <|> try pParsePochoirStencilMember <|> do ch <- anyChar return [ch] <?> "line" pParseMacro :: GenParser Char ParserState String pParseMacro = do reserved "#define" l_name <- identifier pMacroValue l_name pParsePochoirArray :: GenParser Char ParserState String pParsePochoirArray = do reserved "Pochoir_Array" (l_type, l_rank) <- angles $ try pDeclStatic l_arrayDecl <- commaSep1 pDeclDynamic l_delim <- pDelim updateState $ updatePArray $ transPArray (l_type, l_rank) l_arrayDecl return (breakline ++ "/* Known*/ Pochoir_Array <" ++ show l_type ++ ", " ++ show l_rank ++ "> " ++ pShowDynamicDecl l_arrayDecl pShowArrayDim ++ l_delim) pParsePochoirArrayAsParam :: GenParser Char ParserState String pParsePochoirArrayAsParam = do reserved "Pochoir_Array" (l_type, l_rank) <- angles $ try pDeclStatic l_arrayDecl <- pDeclDynamic l_delim <- pDelim updateState $ updatePArray $ transPArray (l_type, l_rank) [l_arrayDecl] return (breakline ++ "/* Known*/ Pochoir_Array <" ++ show l_type ++ ", " ++ show l_rank ++ "> " ++ pShowDynamicDecl [l_arrayDecl] pShowArrayDim ++ l_delim) pParsePochoirStencil :: GenParser Char ParserState String pParsePochoirStencil = do reserved "Pochoir" l_rank <- angles exprDeclDim l_rawStencils <- commaSep1 pDeclPochoir l_delim <- pDelim l_state <- getState let l_stencils = map pSecond l_rawStencils let l_shapes = map pThird l_rawStencils let l_pShapes = map (getPShape l_state) l_shapes let l_toggles = map shapeToggle l_pShapes updateState $ updatePStencil $ transPStencil l_rank l_stencils l_pShapes return (breakline ++ "/* Known */ Pochoir <" ++ show l_rank ++ "> " ++ pShowDynamicDecl l_rawStencils (showString "") ++ l_delim ++ "/* toggles = " ++ show l_toggles ++ "*/") pParsePochoirStencilWithShape :: GenParser Char ParserState String pParsePochoirStencilWithShape = do reserved "Pochoir" l_rank <- angles exprDeclDim l_rawStencils <- commaSep1 pDeclPochoirWithShape l_delim <- pDelim l_state <- getState let l_stencils = map pSecond l_rawStencils let l_pShapes = map pThird l_rawStencils let l_toggles = map shapeToggle l_pShapes updateState $ updatePStencil $ transPStencil l_rank l_stencils l_pShapes return (breakline ++ "/* Known */ Pochoir <" ++ show l_rank ++ "> " ++ pShowDynamicDecl l_rawStencils (pShowShapes . shape) ++ l_delim ++ "/* toggles = " ++ (show $ map shapeToggle l_pShapes) ++ "*/") pParsePochoirStencilAsParam :: GenParser Char ParserState String pParsePochoirStencilAsParam = do reserved "Pochoir" l_rank <- angles exprDeclDim l_rawStencil <- pDeclPochoir l_delim <- pDelim l_state <- getState let l_stencil = pSecond l_rawStencil let l_shape = pThird l_rawStencil let l_pShape = getPShape l_state l_shape let l_toggle = shapeToggle l_pShape updateState $ updatePStencil $ transPStencil l_rank [l_stencil] [l_pShape] return (breakline ++ "/* Known */ Pochoir <" ++ show l_rank ++ "> " ++ pShowDynamicDecl [l_rawStencil] (showString "") ++ l_delim ++ "/* toggles = " ++ show l_toggle ++ "*/") pParsePochoirStencilWithShapeAsParam :: GenParser Char ParserState String pParsePochoirStencilWithShapeAsParam = do reserved "Pochoir" l_rank <- angles exprDeclDim l_rawStencil <- pDeclPochoirWithShape l_delim <- pDelim l_state <- getState let l_stencil = pSecond l_rawStencil let l_pShape = pThird l_rawStencil let l_toggle = shapeToggle l_pShape updateState $ updatePStencil $ transPStencil l_rank [l_stencil] [l_pShape] return (breakline ++ "/* Known */ Pochoir <" ++ show l_rank ++ "> " ++ pShowDynamicDecl [l_rawStencil] (pShowShapes . shape) ++ l_delim ++ "/* toggles = " ++ (show $ shapeToggle l_pShape) ++ "*/") pParsePochoirShapeInfo :: GenParser Char ParserState String pParsePochoirShapeInfo = do reserved "Pochoir_Shape" l_rank <- angles pDeclStaticNum l_name <- identifier brackets $ option 0 pDeclStaticNum reservedOp "=" l_shapes <- braces (commaSep1 ppShape) semi let l_len = length l_shapes let l_toggle = getToggleFromShape l_shapes let l_slopes = getSlopesFromShape (l_toggle-1) l_shapes updateState $ updatePShape (l_name, l_rank, l_len, l_toggle, l_slopes, l_shapes) return (breakline ++ "/* Known */ Pochoir_Shape <" ++ show l_rank ++ "> " ++ l_name ++ " [" ++ show l_len ++ "] = " ++ pShowShapes l_shapes ++ ";\n" ++ breakline ++ "/* toggle: " ++ show l_toggle ++ "; slopes: " ++ show l_slopes ++ " */\n") pParsePochoirDomain :: GenParser Char ParserState String pParsePochoirDomain = do reserved "Pochoir_Domain" l_rangeDecl <- commaSep1 pDeclDynamic semi updateState $ updatePRange $ transURange l_rangeDecl return (breakline ++ "Pochoir_Domain " ++ pShowDynamicDecl l_rangeDecl pShowArrayDim ++ ";\n") pParsePochoirKernel1D :: GenParser Char ParserState String pParsePochoirKernel1D = do reserved "Pochoir_Kernel_1D" pPochoirKernel pParsePochoirKernel2D :: GenParser Char ParserState String pParsePochoirKernel2D = do reserved "Pochoir_Kernel_2D" pPochoirKernel pParsePochoirKernel3D :: GenParser Char ParserState String pParsePochoirKernel3D = do reserved "Pochoir_Kernel_3D" pPochoirKernel pParsePochoirAutoKernel :: GenParser Char ParserState String pParsePochoirAutoKernel = do reserved "auto" pPochoirAutoKernel pParsePochoirArrayMember :: GenParser Char ParserState String pParsePochoirArrayMember = do l_id <- try (pIdentifier) l_state <- getState try $ ppArray l_id l_state pParsePochoirStencilMember :: GenParser Char ParserState String pParsePochoirStencilMember = do l_id <- try (pIdentifier) l_state <- getState try $ ppStencil l_id l_state pParseCPPComment :: GenParser Char ParserState String pParseCPPComment = do try (string "/*") str <- manyTill anyChar (try $ string "*/") -- return ("/* comment */") return ("/*" ++ str ++ "*/") <|> do try (string "//") str <- manyTill anyChar (try $ eol) -- return ("// comment\n") return ("//" ++ str ++ "\n") pPochoirKernel :: GenParser Char ParserState String pPochoirKernel = do l_kernel_params <- parens $ commaSep1 identifier exprStmts <- manyTill pStatement (try $ reserved "Pochoir_Kernel_End") l_state <- getState let l_iters = getFromStmts (getPointer $ tail l_kernel_params) (pArray l_state) exprStmts let l_revIters = transIterN 0 l_iters let l_kernel = PKernel { kName = head l_kernel_params, kParams = tail l_kernel_params, kStmt = exprStmts, kIter = l_revIters } updateState $ updatePKernel l_kernel return (pShowKernel (kName l_kernel) l_kernel) pPochoirAutoKernel :: GenParser Char ParserState String pPochoirAutoKernel = do l_kernel_name <- identifier reservedOp "=" symbol "[&]" l_kernel_params <- parens $ commaSep1 (reserved "int" >> identifier) symbol "{" exprStmts <- manyTill pStatement (try $ reserved "};") let l_kernel = PKernel { kName = l_kernel_name, kParams = l_kernel_params, kStmt = exprStmts, kIter = [] } updateState $ updatePKernel l_kernel return (pShowAutoKernel l_kernel_name l_kernel) pMacroValue :: String -> GenParser Char ParserState String pMacroValue l_name = -- l_value <- liftM fromInteger $ try (natural) do l_value <- try (natural) >>= return . fromInteger -- Because Macro is usually just 1 line, we omit the state update updateState $ updatePMacro (l_name, l_value) return ("#define " ++ l_name ++ " " ++ show (l_value) ++ "\n") <|> do l_value <- manyTill anyChar $ try eol return ("#define " ++ l_name ++ " " ++ l_value ++ "\n") <?> "Macro Definition" transPArray :: (PType, Int) -> [([PName], PName, [DimExpr])] -> [(PName, PArray)] transPArray (l_type, l_rank) [] = [] transPArray (l_type, l_rank) (p:ps) = let l_name = pSecond p l_dims = pThird p in (l_name, PArray {aName = l_name, aType = l_type, aRank = l_rank, aDims = l_dims, aMaxShift = 0, aToggle = 0, aRegBound = False}) : transPArray (l_type, l_rank) ps transPStencil :: Int -> [PName] -> [PShape] -> [(PName, PStencil)] transPStencil l_rank [] _ = [] -- sToggle by default is two (2) transPStencil l_rank (p:ps) (a:as) = (p, PStencil {sName = p, sRank = l_rank, sToggle = shapeToggle a, sArrayInUse = [], sShape = a, sRegBound = False}) : transPStencil l_rank ps as transURange :: [([PName], PName, [DimExpr])] -> [(PName, PRange)] transURange [] = [] transURange (p:ps) = (l_name, PRange {rName = l_name, rFirst = l_first, rLast = l_last, rStride = DimINT 1}) : transURange ps where l_name = pSecond p l_first = head $ pThird p l_last = head . tail $ pThird p
rrnewton/PochoirMods
PMainParser.hs
gpl-3.0
11,854
36
47
3,009
2,675
1,325
1,350
221
1
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE UnicodeSyntax #-} {-# OPTIONS_GHC -Wall -Wno-orphans #-} module Main where import GHC.Generics import Control.Exception import qualified Control.Exception as EX import qualified Data.HashMap.Lazy as HM import Data.Semigroup import Options.Applicative as OA import Prelude.Unicode import Text.Show.Pretty import Text.Printf (printf) import Text.Show.Unicode import Youtrack main ∷ IO () main = do params ← get_params iss_orelse ← either_exception_or $ do (yt, projects) ← yt_connect params iss ← yt_issues yt projects (Filter $ printf "has: comments") 1 pure (yt, iss) (_, iss) ← case iss_orelse of Right pr_iss → pure pr_iss Left ex → error $ printf "YT Project not accessible due to service access failure: %s" $ show ex case iss of [] → error "No issues with comments in whole YouTrack repository, showcase unavailable." (issue@Issue{..}:_) → do let Project{..} = issue_project putStrLn $ ppShow $ issue comments ← projectRequest issue_project issue $ RIssueComments project_alias issue_id case comments of [] → error "Youtrack returned a comment-free issue for a comment-only issue list request, showcase unavailable." (Comment{..}:_) → do printf "=========== Comment # %s, by %s, at %s\n" comm_id (show comm_author) (show comm_created) uprint comm_text deriving instance (Show Issue) deriving instance (Show Comment) deriving instance (Show Description) deriving instance (Show Hours) deriving instance (Show Link) deriving instance (Show State) deriving instance (Show Summary) deriving instance (Show Tag) deriving instance (Show Type) deriving instance (Show Priority) deriving instance (Show IId) instance (Show Project) where show x = show ∘ fromPName $ project_name x deriving instance (Show PAlias) deriving instance (Show PName) deriving instance (Show YT) instance (Show Member) where show x = show ∘ fromMLogin $ member_login x deriving instance (Show MLogin) deriving instance (Generic YT) yt_connect ∷ Params → IO (YT, ProjectDict) yt_connect Params{..} = do let preyt = YT { ytHostname = param_server , ytRestSuffix = param_restprefix , ytLogin = MLogin param_login , ytWreqOptions = (⊥) , ytJar = (⊥) } yt ← ytConnect preyt (SSLOptions "" param_server_cacert) Nothing projects ← ytRequest yt yt RProjectAll let projdict = HM.fromList [ (project_alias, p) | p@Project{..} ← projects ] pure $ (yt, projdict) yt_issues ∷ YT → ProjectDict → Filter → Int → IO [Issue] yt_issues yt pdict ifilter ilimit = do ytRequest yt pdict ∘ RIssue ifilter ilimit $ Field <$> ["projectShortName", "numberInProject", "Type", "summary", "created", "reporterName"] either_exception_or ∷ IO a → IO (Either SomeException a) either_exception_or ioaction = let handler (e ∷ SomeException) = pure $ Left e in EX.handle handler $ fmap Right $ evaluate =<< ioaction data Params where Params ∷ { param_server ∷ String , param_restprefix ∷ String , param_server_cacert ∷ String , param_login ∷ String } → Params deriving (Show) get_params ∷ IO Params get_params = customExecParser (prefs $ disambiguate <> showHelpOnError) (info (helper <*> (Params <$> strOption (help "Youtrack instance" <> long "server" <> metavar "HOSTNAME" <> mempty) <*> strOption (help "Youtrack instance REST URL prefix" <> long "rest-prefix" <> metavar "PREFIX" <> value "/rest") <*> strOption (help "CA certificate that validates server" <> long "cacert" <> metavar "FILE" <> mempty) <*> strOption (help "YouTrack login" <> long "login" <> metavar "LOGIN" <> mempty))) ( fullDesc <> progDesc "Perform a test query against some Youtrack instance." <> header "youtrack-test" ))
deepfire/youtrack
test.hs
gpl-3.0
4,503
2
20
1,231
1,206
620
586
105
4
module AfterExp ( testAfterExp , testAfterExpSuperSampling ) where import Data.Maybe import Data.List import Text.Printf import System.Random import System.IO import Control.Parallel.Strategies import FRP.FrABS import FRP.Yampa testAfterExp :: IO () testAfterExp = do let eventTime = 1 / 5 :: DTime let reps = 10000 let dts = [ 5 , 2 , 1 , 1 / 2 , 1 / 5 , 1 / 10 , 1 / 20 , 1 / 50 , 1 / 100 ] let avgs = map (sampleAfterExp eventTime reps) dts let avgDts = zip dts avgs writeAfterExpFile avgDts eventTime testAfterExpSuperSampling :: IO () testAfterExpSuperSampling = do let eventTime = 1 / 5 :: DTime let reps = 10000 let dt = 1.0 let ns = [ 1, 2, 5, 10, 100, 1000 ] :: [Int] let avgs = map (superSampleAfterExp eventTime reps dt) ns let avgTs = zip ns avgs writeAfterExpSSFile avgTs eventTime sampleAfterExp :: DTime -> Int -> DTime -> Double sampleAfterExp eventTime reps dt = sum ts / fromIntegral (length ts) where ts = parMap rpar (runAfterExp eventTime dt) [1..reps] runAfterExp :: DTime -> DTime -> Int -> DTime runAfterExp expEventTime dt seed = actualEventime where g = mkStdGen seed sf = afterExp g expEventTime () -- RandomGen g => g -> DTime -> b -> SF a (Event b) deltas = repeat (dt, Nothing) bs = embed sf ((), deltas) -- SF a b -> (a, [(DTime, Maybe a)]) -> [b] firstEventIdx = fromIntegral $ fromJust $ findIndex isEvent bs actualEventime = dt * firstEventIdx superSampleAfterExp :: DTime -> Int -> DTime -> Int -> Double superSampleAfterExp eventTime reps dt n = sum ts / fromIntegral (length ts) where ts = parMap rpar (runAfterExpSuperSampled n eventTime dt) [1..reps] runAfterExpSuperSampled :: Int -> DTime -> DTime -> Int -> DTime runAfterExpSuperSampled n expEventTime dt seed = actualEventime where g = mkStdGen seed sf = afterExp g expEventTime () -- RandomGen g => g -> DTime -> b -> SF a (Event b) ssSf = superSampling n sf deltas = repeat (dt, Nothing) bss = embed ssSf ((), deltas) -- SF a b -> (a, [(DTime, Maybe a)]) -> [b] bs = concat bss firstEventIdx = fromJust $ findIndex isEvent bs firstEventIdxSSAdjusted = fromIntegral firstEventIdx / fromIntegral n actualEventime = dt * firstEventIdxSSAdjusted writeAfterExpFile :: [(Double, Double)] -> DTime -> IO () writeAfterExpFile avgDts eventTime = do let fileName = "samplingTest_afterExp_" ++ show eventTime ++ "time.m" fileHdl <- openFile fileName WriteMode hPutStrLn fileHdl "dtAvgs = [" mapM_ (hPutStrLn fileHdl . avgDtToString) avgDts hPutStrLn fileHdl "];" hPutStrLn fileHdl ("eventTime = " ++ show eventTime ++ ";") hPutStrLn fileHdl "dt = dtAvgs (:, 1);" hPutStrLn fileHdl "avg = dtAvgs (:, 2);" hPutStrLn fileHdl "n = length (dt);" hPutStrLn fileHdl "ecsTheoryLinePoints = n + 1;" hPutStrLn fileHdl "ecsTheoryLineX = [0; dt];" hPutStrLn fileHdl "ecsTheoryLineY = ones(ecsTheoryLinePoints, 1) * eventTime;" hPutStrLn fileHdl "figure;" hPutStrLn fileHdl "semilogx (dt, avg, 'color', 'blue', 'linewidth', 2);" hPutStrLn fileHdl "hold on" hPutStrLn fileHdl "plot (ecsTheoryLineX, ecsTheoryLineY, 'color', 'red', 'linewidth', 2);" hPutStrLn fileHdl "xLabels = cellstr(num2str(dt));" hPutStrLn fileHdl "yLabels = cellstr(num2str(avg));" hPutStrLn fileHdl "set(gca,'YTick', avg);" hPutStrLn fileHdl "set(gca,'XTick', dt);" hPutStrLn fileHdl "set(gca, 'xticklabel', xLabels);" hPutStrLn fileHdl "set(gca, 'yticklabel', yLabels);" hPutStrLn fileHdl "xlabel ('Time-Deltas');" hPutStrLn fileHdl "ylabel ('Average Time-Out');" hPutStrLn fileHdl "legend ('Average Time-Out per Time-Deltas', 'Theoretical Maximum');" hPutStrLn fileHdl ("title ('Sampling afterExp with average timeout of " ++ show eventTime ++ " time-units');") hClose fileHdl where avgDtToString :: (DTime, Double) -> String avgDtToString (dt, avg) = printf "%.3f" dt ++ "," ++ printf "%.3f" avg ++ ";" writeAfterExpSSFile :: [(Int, Double)] -> DTime -> IO () writeAfterExpSSFile avgDts eventTime = do let fileName = "samplingTest_afterExp_ss_" ++ show eventTime ++ "time.m" fileHdl <- openFile fileName WriteMode hPutStrLn fileHdl "dtAvgs = [" mapM_ (hPutStrLn fileHdl . avgDtToString) avgDts hPutStrLn fileHdl "];" hPutStrLn fileHdl ("eventTime = " ++ show eventTime ++ ";") hPutStrLn fileHdl "ss = dtAvgs (:, 1);" hPutStrLn fileHdl "avg = dtAvgs (:, 2);" hPutStrLn fileHdl "n = length (ss);" hPutStrLn fileHdl "ecsTheoryLinePoints = n + 1;" hPutStrLn fileHdl "ecsTheoryLineX = [0; ss];" hPutStrLn fileHdl "ecsTheoryLineY = ones(ecsTheoryLinePoints, 1) * eventTime;" hPutStrLn fileHdl "figure;" hPutStrLn fileHdl "semilogx (ss, avg, 'color', 'blue', 'linewidth', 2);" hPutStrLn fileHdl "hold on" hPutStrLn fileHdl "plot (ecsTheoryLineX, ecsTheoryLineY, 'color', 'red', 'linewidth', 2);" hPutStrLn fileHdl "xLabels = cellstr(num2str(ss));" hPutStrLn fileHdl "yLabels = cellstr(num2str(avg));" hPutStrLn fileHdl "set(gca,'YTick', avg);" hPutStrLn fileHdl "set(gca,'XTick', ss);" hPutStrLn fileHdl "set(gca, 'xticklabel', xLabels);" hPutStrLn fileHdl "set(gca, 'yticklabel', yLabels);" hPutStrLn fileHdl "xlabel ('Super Samples');" hPutStrLn fileHdl "ylabel ('Average Time-Out');" hPutStrLn fileHdl "legend ('Average Time-Out per Super Samples', 'Theoretical Maximum');" hPutStrLn fileHdl ("title ('Super-Sampling afterExp with Time-Delta of 1.0 and average timeout of " ++ show eventTime ++ " time-units');") hClose fileHdl where avgDtToString :: (Int, Double) -> String avgDtToString (dt, avg) = printf "%d" dt ++ "," ++ printf "%.3f" avg ++ ";"
thalerjonathan/phd
coding/papers/FrABS/Haskell/prototyping/SamplingTests/AfterExp.hs
gpl-3.0
6,232
0
12
1,632
1,456
695
761
135
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.DataFusion.Projects.Locations.Instances.SetIAMPolicy -- 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) -- -- Sets the access control policy on the specified resource. Replaces any -- existing policy. Can return \`NOT_FOUND\`, \`INVALID_ARGUMENT\`, and -- \`PERMISSION_DENIED\` errors. -- -- /See:/ <https://cloud.google.com/data-fusion/docs Cloud Data Fusion API Reference> for @datafusion.projects.locations.instances.setIamPolicy@. module Network.Google.Resource.DataFusion.Projects.Locations.Instances.SetIAMPolicy ( -- * REST Resource ProjectsLocationsInstancesSetIAMPolicyResource -- * Creating a Request , projectsLocationsInstancesSetIAMPolicy , ProjectsLocationsInstancesSetIAMPolicy -- * Request Lenses , plisipXgafv , plisipUploadProtocol , plisipAccessToken , plisipUploadType , plisipPayload , plisipResource , plisipCallback ) where import Network.Google.DataFusion.Types import Network.Google.Prelude -- | A resource alias for @datafusion.projects.locations.instances.setIamPolicy@ method which the -- 'ProjectsLocationsInstancesSetIAMPolicy' request conforms to. type ProjectsLocationsInstancesSetIAMPolicyResource = "v1" :> CaptureMode "resource" "setIamPolicy" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] SetIAMPolicyRequest :> Post '[JSON] Policy -- | Sets the access control policy on the specified resource. Replaces any -- existing policy. Can return \`NOT_FOUND\`, \`INVALID_ARGUMENT\`, and -- \`PERMISSION_DENIED\` errors. -- -- /See:/ 'projectsLocationsInstancesSetIAMPolicy' smart constructor. data ProjectsLocationsInstancesSetIAMPolicy = ProjectsLocationsInstancesSetIAMPolicy' { _plisipXgafv :: !(Maybe Xgafv) , _plisipUploadProtocol :: !(Maybe Text) , _plisipAccessToken :: !(Maybe Text) , _plisipUploadType :: !(Maybe Text) , _plisipPayload :: !SetIAMPolicyRequest , _plisipResource :: !Text , _plisipCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectsLocationsInstancesSetIAMPolicy' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'plisipXgafv' -- -- * 'plisipUploadProtocol' -- -- * 'plisipAccessToken' -- -- * 'plisipUploadType' -- -- * 'plisipPayload' -- -- * 'plisipResource' -- -- * 'plisipCallback' projectsLocationsInstancesSetIAMPolicy :: SetIAMPolicyRequest -- ^ 'plisipPayload' -> Text -- ^ 'plisipResource' -> ProjectsLocationsInstancesSetIAMPolicy projectsLocationsInstancesSetIAMPolicy pPlisipPayload_ pPlisipResource_ = ProjectsLocationsInstancesSetIAMPolicy' { _plisipXgafv = Nothing , _plisipUploadProtocol = Nothing , _plisipAccessToken = Nothing , _plisipUploadType = Nothing , _plisipPayload = pPlisipPayload_ , _plisipResource = pPlisipResource_ , _plisipCallback = Nothing } -- | V1 error format. plisipXgafv :: Lens' ProjectsLocationsInstancesSetIAMPolicy (Maybe Xgafv) plisipXgafv = lens _plisipXgafv (\ s a -> s{_plisipXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). plisipUploadProtocol :: Lens' ProjectsLocationsInstancesSetIAMPolicy (Maybe Text) plisipUploadProtocol = lens _plisipUploadProtocol (\ s a -> s{_plisipUploadProtocol = a}) -- | OAuth access token. plisipAccessToken :: Lens' ProjectsLocationsInstancesSetIAMPolicy (Maybe Text) plisipAccessToken = lens _plisipAccessToken (\ s a -> s{_plisipAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). plisipUploadType :: Lens' ProjectsLocationsInstancesSetIAMPolicy (Maybe Text) plisipUploadType = lens _plisipUploadType (\ s a -> s{_plisipUploadType = a}) -- | Multipart request metadata. plisipPayload :: Lens' ProjectsLocationsInstancesSetIAMPolicy SetIAMPolicyRequest plisipPayload = lens _plisipPayload (\ s a -> s{_plisipPayload = a}) -- | REQUIRED: The resource for which the policy is being specified. See the -- operation documentation for the appropriate value for this field. plisipResource :: Lens' ProjectsLocationsInstancesSetIAMPolicy Text plisipResource = lens _plisipResource (\ s a -> s{_plisipResource = a}) -- | JSONP plisipCallback :: Lens' ProjectsLocationsInstancesSetIAMPolicy (Maybe Text) plisipCallback = lens _plisipCallback (\ s a -> s{_plisipCallback = a}) instance GoogleRequest ProjectsLocationsInstancesSetIAMPolicy where type Rs ProjectsLocationsInstancesSetIAMPolicy = Policy type Scopes ProjectsLocationsInstancesSetIAMPolicy = '["https://www.googleapis.com/auth/cloud-platform"] requestClient ProjectsLocationsInstancesSetIAMPolicy'{..} = go _plisipResource _plisipXgafv _plisipUploadProtocol _plisipAccessToken _plisipUploadType _plisipCallback (Just AltJSON) _plisipPayload dataFusionService where go = buildClient (Proxy :: Proxy ProjectsLocationsInstancesSetIAMPolicyResource) mempty
brendanhay/gogol
gogol-datafusion/gen/Network/Google/Resource/DataFusion/Projects/Locations/Instances/SetIAMPolicy.hs
mpl-2.0
6,237
0
16
1,301
783
459
324
122
1
module ObjD.Link.Extends ( superDataType, superDataTypes, isInstanceOf, isInstanceOfTp, isInstanceOfCheck, baseDataType, firstCommonSuperDataType, commonSuperDataType, reduceDataTypes )where import ObjD.Link.Struct import ObjD.Link.Env import ObjD.Link.DataType import Data.Maybe import Data.List superDataType :: Env -> DataType -> ExtendsRef -> DataType superDataType _ (TPClass _ gens cl) extRef@(extCl, _) = TPClass (refDataTypeMod extCl) (superGenericsList (buildGenerics cl gens) extRef) extCl superDataType _ (TPObject _ _) (extCl, _) = TPObject (refDataTypeMod extCl) extCl superDataType env tp extRef@(extCl, _) = TPClass (refDataTypeMod extCl) (superGenericsList (buildGenerics (dataTypeClass env tp) (dataTypeGenerics tp)) extRef) extCl -- superDataType _ _ = TPVoid superDataTypes :: Env -> DataType -> [DataType] superDataTypes env tp = map (superDataType env tp) $ extendsRefs $ classExtends $ dataTypeClass env tp isInstanceOf :: Class -> Class -> Bool isInstanceOf cl Generic{_classExtendsRef = extends} = all (( cl `isInstanceOf` ) . fst ) extends isInstanceOf cl target | target == cl = True | otherwise = any (\extendsRef -> fst extendsRef `isInstanceOf` target) $ extendsRefs (classExtends cl) isInstanceOfTp :: Env -> DataType -> DataType -> Bool isInstanceOfTp _ cl target | target == cl = True isInstanceOfTp _ TPUnset{} _ = True isInstanceOfTp _ TPNumber{} TPNumber{} = True isInstanceOfTp _ TPNumber{} TPFloatNumber{} = True isInstanceOfTp _ TPFloatNumber{} TPNumber{} = True isInstanceOfTp _ TPFloatNumber{} TPFloatNumber{} = True isInstanceOfTp env (TPSelf l) r = isInstanceOfTp env (refDataType l []) r isInstanceOfTp env l (TPSelf r) = isInstanceOfTp env l (refDataType r []) isInstanceOfTp env l (TPGenericWrap _ r) = isInstanceOfTp env l r isInstanceOfTp env (TPGenericWrap _ l) r = isInstanceOfTp env l r isInstanceOfTp env l@(TPClass TPMType _ _) r = isInstanceOfTp env (fromJust $ superType l) r isInstanceOfTp env l r@(TPClass TPMType _ _) = isInstanceOfTp env l (fromJust $ superType r) isInstanceOfTp _ _ TPAny = True isInstanceOfTp _ _ TPThrow = True isInstanceOfTp _ TPThrow _ = True isInstanceOfTp _ TPNil (TPOption _ _) = True isInstanceOfTp _ TPNil TPVoid = True isInstanceOfTp _ TPAnyGeneric _ = True isInstanceOfTp _ _ TPAnyGeneric = True isInstanceOfTp _ _ TPUnknown{} = True isInstanceOfTp env (TPOption _ a) (TPOption _ b) | a == b = True | otherwise = isInstanceOfTp env a b isInstanceOfTp env a (TPOption _ b) = isInstanceOfTp env a b isInstanceOfTp env (TPOption True a) b = isInstanceOfTp env a b isInstanceOfTp _ TPVoid (TPClass TPMGeneric _ _) = True isInstanceOfTp _ TPNil (TPClass TPMGeneric _ _) = True isInstanceOfTp env cl (TPClass TPMGeneric _ t) = dataTypeClass env cl `isInstanceOf` t isInstanceOfTp _ (TPClass _ _ _) (TPClass _ _ Class{className = "Object"}) = True isInstanceOfTp env cl target -- | trace (show cl ++ " isInstanceOfTp " ++ show target ++ " / " ++ className (dataTypeClass env cl) ++ " isInstanceOf " ++ className (dataTypeClass env target)) False = undefined | dataTypeClass env cl == dataTypeClass env target = all (\(clg, tg) -> isInstanceOfTp env clg tg ) $ zip (dataTypeGenerics cl) (dataTypeGenerics target) -- | otherwise = dataTypeClass env cl `isInstanceOf` dataTypeClass env target | otherwise = any (\tp -> isInstanceOfTp env tp target) $ superDataTypes env cl isInstanceOfCheck :: Env -> DataType -> DataType -> Bool isInstanceOfCheck env l r = isInstanceOfTp env l r baseDataType :: Env -> DataType baseDataType env = TPClass TPMClass [] $ classFind (envIndex env) "Object" commonSuperDataType :: Env -> DataType -> DataType -> [DataType] -- commonSuperDataType _ a b | trace ("commonSuperDataType: " ++ show a ++ " and " ++ show b) False = undefined commonSuperDataType _ a b | a == b = [a] commonSuperDataType env (TPGenericWrap _ a) b = commonSuperDataType env a b commonSuperDataType env a (TPGenericWrap _ b) = commonSuperDataType env a b commonSuperDataType env TPNil a = commonSuperDataType env a TPNil commonSuperDataType _ TPAny a = [a] commonSuperDataType _ TPThrow a = [a] commonSuperDataType _ a@(TPOption _ _) TPNil = [a] commonSuperDataType _ TPVoid TPNil = [TPVoid] commonSuperDataType _ a TPNil = [option False a] commonSuperDataType _ a TPAny = [a] commonSuperDataType _ a TPThrow = [a] commonSuperDataType _ TPNumber{} f@TPFloatNumber{} = [f] commonSuperDataType _ f@TPFloatNumber{} TPNumber{} = [f] commonSuperDataType _ (TPNumber as an) (TPNumber bs bn) = [TPNumber (as || bs) (max an bn)] commonSuperDataType _ (TPFloatNumber an) (TPFloatNumber bn) = [TPFloatNumber (max an bn)] commonSuperDataType env (TPOption ca a) (TPOption cb b) = map (option (ca && cb)) $ commonSuperDataType env a b commonSuperDataType env a (TPOption c b) = map (option c) $ commonSuperDataType env a b commonSuperDataType env (TPOption c a) b = map (option c) $ commonSuperDataType env a b commonSuperDataType env _ TPVoid = [baseDataType env] commonSuperDataType env TPVoid _ = [baseDataType env] commonSuperDataType env a b | a == b = [a] | dataTypeClass env a == dataTypeClass env b = [mapDataTypeGenerics (map (\(ag, bg) -> wrapGeneric $ head $ commonSuperDataType env ag bg) . zip (dataTypeGenerics a) ) b] | isInstanceOfTp env a b = [b] | isInstanceOfTp env b a = [a] | otherwise = let commons = nub $ concatMap (uncurry $ commonSuperDataType env) $ [(a', b) |a' <- superDataTypes env a] ++ [(a, b') |b' <- superDataTypes env b] removeCommonCommons [] = [] removeCommonCommons (x:xs) | any (\xx -> isInstanceOfTp env xx x) xs = removeCommonCommons xs | otherwise = x:removeCommonCommons xs in map (isolateTraitImpl env) $ removeCommonCommons commons isolateTraitImpl :: Env -> DataType -> DataType isolateTraitImpl env tp@(TPClass _ _ cl) | ClassModTraitImpl `elem` classMods cl = case classExtends cl of Extends _ [r] -> superDataType env tp r _ -> tp isolateTraitImpl _ tp = tp firstCommonSuperDataType :: Env -> DataType -> DataType -> DataType firstCommonSuperDataType env a b = case commonSuperDataType env a b of [] -> TPUnknown $ "No common super data type for " ++ show a ++ " and " ++ show b x:_ -> x reduceDataTypes :: Env -> [DataType] -> DataType reduceDataTypes env tps = foldl1 (firstCommonSuperDataType env) tps
antonzherdev/objd
src/ObjD/Link/Extends.hs
lgpl-3.0
6,341
24
16
1,085
2,383
1,198
1,185
109
2
module Main where import System.Environment import Data.Char main = do (args) <- getArgs xs <- getContents putStr (redact xs (map lwr args)) redact input ws = unlines [ process line | line <- lines input ] where process line = unwords [ f word | word <- words line ] f w | lwr w `elem` ws = replicate (length w) '*' | otherwise = w lwr xs = map toLower xs
Some-T/Portfolio
HASKELL/Labs/H7/H7.2.hsproj/H7_2.hs
unlicense
391
0
11
107
174
84
90
12
1
{-# LANGUAGE OverloadedStrings #-} -- ###################################################### -- # # -- # == LambdaList == # -- # # -- # Ein kleines Haskellprogramm; geeignet um die # -- # Getränkeliste der Fachschaft Technik an der # -- # Uni Bielefeld zu managen. # -- # # -- # Geschrieben von Jonas Betzendahl, 2013-15 # -- # [email protected] # -- # # -- # Lizenz: CC0 / Public Domain # -- # # -- ###################################################### module Main where import Data.Time import Data.List (intercalate, sort) import Data.List.Split (splitOn) import qualified Data.Text as T import qualified Data.Text.Lazy as TL import System.IO import System.Exit import System.Directory import System.Posix.Files import Network.Mail.SMTP -- NICE TO HAVES: -- --> ausführliche Dokumentation -- Kung-Fu mit Typen type Name = String type User = String type Domain = String newtype Guthaben = Guthaben Int data NInterp = NNull | NNothing data NumberType = Money | Amount data MailAdress = Adress User Domain -- user provided an e-mail adress | DefaultAdress -- user has the standard e-mail pattern | NoAdress -- user provided no e-mail adress | Mty -- E-mail adress was not evaluated until now data TColor = TBlau | TGruen | TRot | TGelb data Trinker = Trinker { name :: String , guthaben :: Guthaben , mailadr :: MailAdress , counter :: Int , inactive :: Bool } data Config = Config { stdDomain :: String , stdHost :: String , absender :: String , logcc :: String , grenze :: Int , extra :: Int , kontodaten :: String } instance Eq Trinker where t0 == t1 = (name t0) == (name t1) instance Ord Trinker where compare t0 t1 = compare (name t0) (name t1) instance Show Trinker where show (Trinker a b c d f) = intercalate ";" updatedWerte where updatedWerte = if not f then [a, show b, showMail c a, show (d+1)] else [a, show b, showMail c a, show d] showMail :: MailAdress -> String -> String showMail (Adress u d) _ = u ++ '@':d showMail (DefaultAdress) nm = nm ++ " auf der Standarddomain " showMail (NoAdress) _ = "n/a" showMail (Mty) _ = "" instance Show Guthaben where show (Guthaben n) = addMinus $ show (div (abs n - a) 100) ++ "." ++ addZeros (show a) where a = abs n `mod` 100 addMinus = if n >= 0 then id else ("-" ++) addZeros | abs a <= 9 = ("0" ++) | otherwise = id -- Datei - Ein- und Ausgabe parseListe :: FilePath -> IO [Trinker] parseListe fp = do a <- readFile fp return $ map (parseTrinker . splitOn ";") (lines a) where parseTrinker :: [String] -> Trinker parseTrinker [a,b,c] = parseTrinker [a,b,"",c] parseTrinker [a,b,c,d] = case cleanGuthaben b of Just u -> case readInt NNothing d of Just k -> case splitOn "@" c of [y,z] -> Trinker a (Guthaben u) (Adress y z) k False -- with E-Mail ["n/a"] -> Trinker a (Guthaben u) NoAdress k False -- without E-Mail (silent) [""] -> Trinker a (Guthaben u) Mty k False -- without E-Mail (vocal) _ -> error $ "Parsingfehler (E-Mail) hier: " ++ c Nothing -> error $ "Parsingfehler (Counter) hier: " ++ d Nothing -> error $ "Parsingfehler (Guthaben) hier: " ++ b parseTrinker _ = error "Parsingfehler: inkorrekte Anzahl Elemente in mindestens einer Zeile" writeFiles :: [Trinker] -> Config -> IO() writeFiles trinker c = let sortedTrinker = sort trinker in do putStr "\nSchreibe .txt und .tex auf Festplatte ... " -- Removing old files so we're owners of the new ones ifM (doesFileExist "mateliste.txt") (removeFile "mateliste.txt") (return ()) ifM (doesFileExist "mateliste.tex") (removeFile "mateliste.tex") (return ()) -- Creating new files! writeFile "mateliste.txt" $ unlines $ map show sortedTrinker writeFile "mateliste.tex" $ unlines $ [latexHeader] ++ (map (toLaTeX c)) (zip [1..] sortedTrinker) ++ [latexFooter] setFileMode "mateliste.txt" stdFileMode setFileMode "mateliste.tex" stdFileMode putStrLn "fertig!" putStrLn "\nZuletzt müssen Benachrichtigungen verschickt werden." sendAllMails sortedTrinker c putStrLn "Das Programm wird hiermit beendet. Ich hoffe es ist alles zu Ihrer Zufriedenheit. Bis zum nächsten Mal! :-)" toLaTeX :: Config -> (Int, Trinker) -> String toLaTeX conf (num, Trinker nm gb@(Guthaben b) _ _ _) | b < (grenze conf) = "\\rowcolor{dunkelrot}\n" ++ latexRow | b < 0 = "\\rowcolor{hellrot}\n" ++ latexRow | even num = "\\rowcolor{hellgrau}\n" ++ latexRow | otherwise = latexRow where latexRow :: String latexRow = nm ++ "&" ++ show gb ++ "& & & & & & \\\\\n" ++ if b > (extra conf) then "& & & & & & & \\\\\n\\hline" else "\\hline" latexHeader :: String latexHeader = "\\documentclass[a4paper,10pt,landscape]{article}\n\\usepackage[utf8]{inputenc}\n" ++ "\\usepackage{german}\n\\usepackage{longtable}\n\\usepackage{eurosym}\n" ++ "\\usepackage{color}\n\\usepackage{colortbl}\n\\usepackage{geometry}" ++ "\n\\geometry{a4paper,left=0mm,right=0mm, top=0.5cm, bottom=0.75cm}" ++ "\n\n\\definecolor{dunkelgrau}{rgb}{0.6,0.6,0.6}\n\\definecolor{hellgrau}{rgb}{0.8,0.8,0.8}\n" ++ "\n\n\\definecolor{dunkelrot}{rgb}{0.75,0.15,0.15}\n\\definecolor{hellrot}{rgb}{1.0,0.3,0.3}\n" ++ "\n\\begin{document}\n\\begin{longtable}{|l|p{3cm}|p{5cm}|l|l|p{2cm}|p{2cm}|p{2cm}|}\n\\hline" ++ "\n\\textbf{Login} & Guthaben & Club Mate (0,90 \\euro) & Cola \\slash\\ Brause (0,70 \\euro)" ++ "& Schokor. (0,50 \\euro) & 0,20 \\euro & 0,10 \\euro & 0,05 \\euro\\\\\n\\hline\n\\hline\n\\endhead\n" latexFooter :: String latexFooter = concat (replicate 10 "& & & & & & & \\\\\n\\hline\n") ++ "\\end{longtable}\\bigskip" ++ "\n\\begin{center} \n Neue Trinker tragen sich bitte im Stil vom TechFak-Login ein.\\\\ \n" ++ "\n(1. Buchstabe des Vornamens + 7 Buchstaben des Nachnamens (oder voller Nachname)) \\bigskip \\\\ \n" ++ "\\textbf{Je mehr Geld in der Kasse, desto schneller gibt es neue Getränke!} \\\\ \n" ++ "\\textbf{Also seid so freundlich und übt bitte ein bisschen \\glqq peer pressure\\grqq\\ auf die Leute im Minus aus.}\n" ++ "\\end{center} \n \\end{document}" -- Alles um Mails herum processList :: Config -> [Trinker] -> Bool -> IO [Trinker] processList c xs sh = do let fl = filterList c xs case sh of True -> putStrLn ("Ermittele alle Trinker mit einem Guthaben von " ++ show (Guthaben (grenze c)) ++ " oder weniger:\n") >> showList fl 0 False -> putStrLn "Eingabe nicht erkannt. Ich wiederhole:" putStrLn "\nBitte geben Sie ein, an wen alles böse E-Mails verschickt werden sollen." putStr "(Durch Kommata getrennte Liste von Nummern, \"none\" für keine oder \"all\" für alle)\nEingabe: " line <- getLine case line of "none" -> putStrLn "--> Es werden keine bösen Mails verschickt." >> return [] "all" -> putStrLn "--> Böse Mails werden an alle verschickt.\n" >> return fl _ -> case reads ("[" ++ line ++ "]") of [(ys, "")] -> putStrLn "--> Böse Mails werden an ausgewählte Empfänger verschickt.\n" >> return (map (fl !!) ys) _ -> processList c xs False where showList :: [Trinker] -> Int -> IO () showList [] _ = return () showList (t@(Trinker nm g mMail c f):xs) n = do putStrLn $ " " ++ show n ++ ": (" ++ showFarbe TRot (show g) ++ ") " ++ showFarbe TBlau nm showList xs (n+1) filterList :: Config -> [Trinker] -> [Trinker] filterList _ [] = [] filterList conf (t:xs) = let rl = filterList conf xs in if (unwrapGuthaben . guthaben) t < (grenze conf) then t:rl else rl sendAllMails :: [Trinker] -> Config -> IO () sendAllMails xs c = do lst <- processList c xs True mapM_ (sendEvilEmail c) lst putStrLn "\nSendevorgang abgeschlossen." sendEvilEmail :: Config -> Trinker -> IO () sendEvilEmail config t = case mailadr t of Mty -> putStrLn $ showFarbe TRot " ->" ++ " Konnte keine böse E-Mail an " ++ showFarbe TBlau (name t) ++ " senden, da noch keine E-Mail-Adresse angegeben wurde." NoAdress -> putStrLn $ showFarbe TRot " ->" ++ " Konnte keine böse E-Mail an " ++ showFarbe TBlau (name t) ++ " senden, da keine E-Mail-Adresse eingetragen wurde." mMail -> do let from = Address (Just "Fachschaft Technik") ((T.pack . absender) config) let to = case mMail of DefaultAdress -> (Address Nothing (T.pack ((name t) ++ '@':(stdDomain config)))) (Adress u d) -> (Address Nothing (T.pack (u ++ '@':d))) let cc = [(Address (Just "Getränkefuzzi") ((T.pack . logcc) config))] -- Empty list if no logging emails are desired let bcc = [] let subject = "[Fachschaft Technik] Mate-Konto ausgleichen!" let body = plainTextPart $ TL.pack $ composeEvilEmail (name t) (guthaben t) let mail = simpleMail from [to] cc bcc subject [body] sendMail (stdHost config) mail putStrLn $ showFarbe TGruen " ->" ++ " Böse E-Mail an " ++ showFarbe TBlau (name t) ++ " erfolgreich versendet." where composeEvilEmail :: Name -> Guthaben -> String composeEvilEmail nm g = "Hallo " ++ nm ++ "!\n\nWenn du diese Mail erhältst bedeutet das, dass du mit deinem Matekonto\n(eventuell sogar deutlich) im Minus bist." ++ "\nGenauer gesagt ist dein Guthaben auf der Mateliste aktuell: EUR " ++ show g ++ "\n\n" ++ "Es handelt sich hier generell um ein Prepaid-Konto und wenn zu viele\nLeute zu stark im Minus sind, bedeutet das, dass wir keine Mate" ++ "\nbestellen können oder wir sie teurer verkaufen müssen. Ich würde dich\nalso bitten, fluchs wieder etwas einzuzahlen.\n\n" ++ "Du kannst uns natürlich auch einfach etwas überweisen. Kontoverbindung:\n\n" ++ (kontodaten config) ++ "\n\n" ++ "Bitte nicht vergessen, euren Login oder Namen in den Verwendungszweck\nzu packen, sodass man euch identifizieren kann. Inzwischen kann man\n" ++ "auch in der Fachschaft Bargeld hinterlegen, wenn mal der Mate-Fuzzi\nnicht da ist. Bittet dazu einfach einen beliebigen Fachschaftler\n" ++ "das Geld im entsprechenden Briefumschlag in der Protokollkasse zu\ndeponieren.\n\n" ++ "Vergesst bitte auch nicht euch auf der Liste in der Fachschaft euer\nentsprechendes Plus unter \"Guthaben\" zu notieren, damit es nicht zu\n" ++ "Missverständnissen kommt.\n\nVielen Dank!\n\nLiebe Grüße,\n euer automatisiertes Matekonto-Benachrichtigungsprogramm\n (i.A. für die Fachschaft Technik)" -- Helferfunktionen und Trivialitäten: unwrapGuthaben :: Guthaben -> Int unwrapGuthaben (Guthaben g) = g readInt :: NInterp -> String -> Maybe Int readInt NNull "" = Just 0 readInt NNothing "" = Nothing readInt _ xs = case reads xs of [(n, "")] -> Just n _ -> Nothing showFarbe :: TColor -> String -> String showFarbe clr txt = case clr of TRot -> "\x1b[31m" ++ txt ++ "\x1b[0m" TGruen -> "\x1b[32m" ++ txt ++ "\x1b[0m" TGelb -> "\x1b[33m" ++ txt ++ "\x1b[0m" TBlau -> "\x1b[36m" ++ txt ++ "\x1b[0m" showGuthaben :: Guthaben -> String showGuthaben gld@(Guthaben betr) | betr < 0 = showFarbe TRot $ show gld | otherwise = showFarbe TGruen $ show gld showTrinkerInfo :: Trinker -> IO () showTrinkerInfo t = putStrLn $ "\nDer User " ++ showFarbe TBlau (name t) ++ inac ++ " hat derzeit einen Kontostand von " ++ showGuthaben (guthaben t) ++ "." where inac :: String inac = if (counter t) == 0 then "" else " (" ++ show (counter t) ++ " Mal inaktiv)" cleanGuthaben :: String -> Maybe Int cleanGuthaben s = case readInt NNull $ filter (\c -> (c /= '.') && (c /= ',') ) s of {Just n -> Just n ; _ -> Nothing} parseNumber:: NumberType -> String -> IO Int parseNumber nmbt str = let retry = putStrLn "-- Eingabe ungültig!" >> parseNumber nmbt str in do putStr str ; x <- getLine case nmbt of Money -> let ps = splitOn "," x in case length ps of 1 -> case readInt NNull x of -- parse cents only Nothing -> retry Just n -> if n == 0 then return 0 else do putStr $ "Eingabe unklar: " ++ show n ++ " (E)uro oder (C)ents? " y <- getLine case y of "E" -> return $ 100*n "C" -> return n _ -> retry 2 -> let h = head ps ; t = last ps -- parse euros in case readInt NNull h of Nothing -> retry Just eur -> case readInt NNothing t of Nothing -> retry Just ct -> case length t of 1 -> return $ 100*eur + 10*ct 2 -> return $ 100*eur + ct _ -> retry _ -> retry -- more than one ',' fails Amount -> case readInt NNull x of {Just n -> return n ; Nothing -> retry} frage :: String -> IO Bool frage fr = do putStr fr ; q <- getLine return (q == "ok") ifM :: Monad m => m Bool -> m b -> m b -> m b ifM p a b = do { p' <- p ; if p' then a else b } parseConfig :: String -> String -> Config parseConfig mconf kconf = Config (ls !! 0) (ls !! 1) (ls !! 2) (ls !! 3) threshold extra ks where ls = let content = (lines . clearConf) mconf in if length content == 6 then content else error "Fehler in Konfigurationsdatei!" ks = clearConf kconf extra = case readInt NNothing (ls !! 5) of { Just n -> n ; Nothing -> 5000 } threshold = case readInt NNothing (ls !! 4) of { Just n -> n ; Nothing -> 0 } clearConf :: String -> String clearConf = unlines . (filter (\l -> not ((null l) || (head l == '#')))) . lines -- Hauptprogrammlogik: processTrinker :: Trinker -> [Int] -> IO Trinker processTrinker t werte@[enzhlng, nnzg, sbzg, fnfzg, zwnzg, zhn, fnf] = return $ if all (==0) werte then Trinker (name t) (guthaben t) (mailadr t) ((counter t) + 1) True else Trinker (name t) (Guthaben ((unwrapGuthaben . guthaben) t + enzhlng - vertrunken)) (mailadr t) 0 True where vertrunken = sum $ zipWith (*) [90, 70, 50, 20, 10, 5] (tail werte) getAmounts :: Name -> IO [Int] getAmounts nm = do a <- parseNumber Money ("-- Wie viel Geld hat " ++ nm ++ " eingezahlt? ") b <- mapM (parseNumber Amount) $ map (strichFragen nm) ["90", "70", "50", "20", "10", " 5"] return $ a:b where strichFragen :: Name -> String -> String strichFragen nm amnt = "-- Wie viele Striche hat " ++ nm ++ " in der Spalte für " ++ amnt ++ " Cent? " askEmail :: Trinker -> IO Trinker askEmail t@(Trinker nm gthb (Adress u d) c f) = return t askEmail t@(Trinker nm gthb DefaultAdress c f) = return t askEmail t@(Trinker nm gthb NoAdress c f) = return t askEmail t@(Trinker nm gthb Mty c f) = do putStrLn $ "\n Für diesen Trinker wurde noch " ++ showFarbe TRot "keine E-Mail-Adresse" ++ " eingetragen." putStr " Bitte geben Sie eine gültige Adresse ein (\"default\" für den Standard, \"none\" für keine): " l <- getLine case splitOn "@" l of ["default"] -> return (Trinker nm gthb DefaultAdress c f) ["none"] -> return (Trinker nm gthb NoAdress c f) [""] -> return (Trinker nm gthb Mty c f) [x,y] -> return (Trinker nm gthb (Adress x y) c f) _ -> do putStrLn "Eingabe nicht verstanden. Ich wiederhole:\n" askEmail t -- Backups current state of MateListe backupData :: Bool -> Bool -> IO () backupData False False = putStrLn $ "Lege Sicherungskopie der aktuellen Daten an ..." ++ (showFarbe TGelb "nicht möglich") ++ ", da keine Daten vorhanden." backupData txt pdf = do putStr "Lege Sicherungskopie der aktuellen Daten an ..." timestamp <- getCurrentTime let name = show timestamp createDirectoryIfMissing True ("./backups/" ++ name) -- will always be missing due to timestamp precision, but creates parents as well this way if txt then copyFile "./mateliste.txt" ("./backups/" ++ name ++ "/mateliste.txt") else return () if pdf then copyFile "./mateliste.pdf" ("./backups/" ++ name ++ "/mateliste.pdf") else return () putStrLn $ showFarbe TGruen " OK" ++ "!" clearPermissions :: Bool -> IO Bool clearPermissions x = do ptxt <- getPermissions "./mateliste.txt" if x then do ptex <- getPermissions "./mateliste.tex" return $ and [readable ptxt, readable ptex, writable ptxt, writable ptex] else return $ and [readable ptxt, writable ptxt] neuTrinker :: IO Trinker neuTrinker = do putStrLn "Neuer Trinker wird erstellt." x <- askName y <- askKontostand z <- askMailAdress putStr $ "Bitte geben Sie \"ok\" zum Bestätigen ein: Trinker " ++ showFarbe TBlau x ++ " mit einem Kontostand von " ++ showGuthaben (Guthaben y) ++ " " o <- getLine if o == "ok" then return $ Trinker x (Guthaben y) z 0 True else putStrLn "Bestätigung nicht erhalten. Neuer Versuch:\n" >> neuTrinker where askName :: IO String askName = do putStr "Bitte geben Sie einen Nicknamen ein: " ; n <- getLine case n of {"" -> askName ; x -> return x} askKontostand :: IO Int askKontostand = parseNumber Money "Bitte geben Sie einen validen Kontostand ein: " askMailAdress :: IO MailAdress askMailAdress = do putStr "Bitte geben Sie eine gültige E-Mail-Adresse ein (\"default\" für Standard, \"none\" für keine): " ; l <- getLine case splitOn "@" l of {[""] -> return Mty ; ["none"] -> return NoAdress ; ["default"] -> return DefaultAdress ; [x,y] -> return (Adress x y) ; _ -> askMailAdress} listLoop :: [Trinker] -> Config -> Int -> IO () listLoop xs conf i = do if i >= length xs then do putStrLn $ "\n!! Sie haben das " ++ showFarbe TGelb "Ende" ++ " der aktuellen Liste erreicht. !!" putStr "!! Bitte wählen sie aus: speichern/b(e)enden | (a)bbrechen | (n)euer Trinker | (z)urück : " c <- getLine case c of "e" -> ifM (frage "Wirklich beenden (bisherige Änderungen werden geschrieben)? Bitte geben Sie \"ok\" ein: ") (writeFiles xs conf) (putStrLn "Doch nicht? Okay, weiter geht's!" >> listLoop xs conf i) "a" -> ifM (frage "Wirklich abbrechen (bisherige Änderungen werden verworfen)? Bitte geben Sie \"ok\" ein: ") (putStrLn "Dann bis zum nächsten Mal! :)") (putStrLn "Doch nicht? Okay, weiter geht's!" >> listLoop xs conf i) "n" -> do neu <- neuTrinker ; listLoop (xs ++ [neu]) conf i 'z':bs -> let z q = max (i-q) 0 in case (readInt NNothing . tail) c of {Nothing -> listLoop xs conf (z 1); Just n -> listLoop xs conf (z n)} _ -> putStrLn "Eingabe nicht verstanden. Ich wiederhole: " >> listLoop xs conf i else do let tr = (head . drop i) xs showTrinkerInfo tr putStr "Bitte wählen Sie aus! (a)bbrechen | (b)earbeiten | b(e)enden | (l)öschen | übe(r)schreiben | (v)or | (z)urück : " c <- getLine case c of "a" -> ifM (frage "Wirklich abbrechen (bisherige Änderungen werden verworfen)? Bitte geben Sie \"ok\" ein: ") (putStrLn "Dann bis zum nächsten Mal! :)") (putStrLn "Doch nicht? Okay, weiter geht's!" >> listLoop xs conf i) "e" -> ifM (frage "Wirklich beenden (bisherige Änderungen werden gespeichert)? Bitte geben Sie \"ok\" ein: ") (writeFiles xs conf) (putStrLn "Doch nicht? Okay, weiter geht's!" >> listLoop xs conf i) "l" -> do putStr $ "Bitte geben Sie \"ok\" ein um " ++ showFarbe TBlau ((\(Trinker nm _ _ _ _) -> nm) tr) ++ " aus der Liste entfernen: " ; q <- getLine if q == "ok" then listLoop (take i xs ++ drop (i+1) xs) conf i else listLoop xs conf i "r" -> do neu <- neuTrinker ; listLoop (take i xs ++ neu:drop (i+1) xs) conf i "b" -> let foobar ti p = do putStr "Bitte geben Sie \"ok\" zum Bestätigen ein: " ; q <- getLine case q of "ok" -> do k <- askEmail p listLoop (take i xs ++ k : drop (i+1) xs) conf (i+1) "" -> foobar ti p _ -> putStr "Vorgang abgebrochen. Wiederhole:" >> listLoop xs conf i in do p <- (\(Trinker name gth mMail ctr f) -> (getAmounts name >>= processTrinker (Trinker name gth mMail ctr True))) tr showTrinkerInfo p ; foobar tr p 'v':bs -> let z q = min (i+q) (length xs) in case (readInt NNothing . tail) c of {Nothing -> listLoop xs conf (z 1); Just n -> listLoop xs conf (z n)} 'z':bs -> let z q = max (i-q) 0 in case (readInt NNothing . tail) c of {Nothing -> listLoop xs conf (z 1); Just n -> listLoop xs conf (z n)} "" -> listLoop xs conf (min (i+1) (length xs)) _ -> putStr "Eingabe nicht verstanden. Ich wiederhole: " >> listLoop xs conf i main :: IO () main = do hSetBuffering stdout NoBuffering putStrLn "++ LambdaList v. 1.2 ++ \n\nWillkommen, User!" putStrLn "Dies ist ein automatisches Matelistenprogramm. Bitte beantworten Sie die Fragen auf dem Schirm.\n" putStr "Scanne Verzeichnis nach vorhandener Mateliste ... " mc <- doesFileExist "./mail.conf" kc <- doesFileExist "./konto.conf" conf <- if not (mc && kc) then putStrLn "Konfigurationsdateien nicht vorhanden, bite Getränkefuzzi alarmieren!\n\nProgramm wird nun beendet!" >> exitFailure else do mcs <- readFile "./mail.conf" kcs <- readFile "./konto.conf" return $ parseConfig mcs kcs l <- doesFileExist "./mateliste.txt" t <- doesFileExist "./mateliste.tex" p <- doesFileExist "./mateliste.pdf" list <- case l of True -> do putStrLn ((showFarbe TGruen "OK") ++ "!") putStr "Überprüfe Berechtigungen auf relevanten Dateien ... " permsok <- if t then clearPermissions True -- check tex else clearPermissions False -- don't check tex case permsok of True -> putStrLn ((showFarbe TGruen "OK") ++ "!") >> parseListe "./mateliste.txt" False -> do putStrLn $ (showFarbe TRot "Fehlschlag") ++ "!\nBerechtigungen nicht vorhanden, bitte Getränkefuzzi alarmieren!\n\nProgramm wird nun beendet!" exitFailure return [] False -> putStrLn ((showFarbe TRot "Fehlschlag") ++ "! Beim Beenden wird eine neue Datei angelegt werden.") >> return [] backupData l p listLoop list conf 0
jbetzend/LambdaList
LambdaList.hs
unlicense
29,586
0
31
12,685
6,428
3,200
3,228
345
20
import Control.Exception import Control.Monad import qualified Graphics.Rendering.OpenGL as GL import Graphics.Rendering.OpenGL (($=)) import qualified Graphics.UI.GLFW as GLFW import Prelude import Util main = do window <- initialize "Test" -- Use `$=` for assigning to GL values, `get` to read them. -- These functions basically hide IORefs. GL.depthFunc $= Just GL.Less -- Use `finally` so that `quit` is called whether or -- not `mainLoop` throws an exception Just now <- GLFW.getTime finally (mainLoop (draw window) window now) (cleanup window) -- | This will print and clear the OpenGL errors printErrors = GL.get GL.errors >>= mapM_ print -- | Draw a frame draw :: GLFW.Window -> Double -> IO () draw window t = do -- Again, the functions in GL almost all map to standard OpenGL functions GL.clear [GL.ColorBuffer, GL.DepthBuffer] GL.loadIdentity GL.translate $ GL.Vector3 0 0 (-50 :: GL.GLfloat) GL.scale 10 10 (1 :: GL.GLfloat) GL.rotate theta axis -- renderPrimitive wraps the supplied action with glBegin and glEnd. -- We'll stop using this when we switch to shaders and vertex buffers. GL.renderPrimitive GL.Quads $ -- Draw a unit square centered on the origin forM_ [(0, 0), (1, 0), (1, 1), (0, 1)] $ \(x, y) -> -- Note that we have to explicitly type Vertex* and Vector*, because -- they are polymorphic in number field. let vtx = GL.Vertex3 (x - 0.5) (y - 0.5) 0 :: GL.Vertex3 GL.GLfloat in GL.vertex vtx printErrors GL.flush GLFW.swapBuffers window where -- GL.rotate takes the angle in degrees, not radians theta = realToFrac t * 360 axis = GL.Vector3 0 1 0 :: GL.Vector3 GL.GLfloat
pharaun/hCraft
src/Main.hs
apache-2.0
1,799
0
15
459
433
230
203
29
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} module Kubernetes.V1.Binding where import GHC.Generics import Data.Text import Kubernetes.V1.ObjectMeta import Kubernetes.V1.ObjectReference import qualified Data.Aeson -- | Binding ties one object to another. For example, a pod is bound to a node by a scheduler. data Binding = Binding { kind :: Maybe Text -- ^ Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds , apiVersion :: Maybe Text -- ^ APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#resources , metadata :: Maybe ObjectMeta -- ^ Standard object's metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata , target :: ObjectReference -- ^ The target object that you want to bind to the standard object. } deriving (Show, Eq, Generic) instance Data.Aeson.FromJSON Binding instance Data.Aeson.ToJSON Binding
minhdoboi/deprecated-openshift-haskell-api
kubernetes/lib/Kubernetes/V1/Binding.hs
apache-2.0
1,412
0
9
203
122
75
47
19
0
module Main where import Control.Monad.Trans.Class import Control.Monad.Trans.State.Lazy import qualified Data.ByteString as BS import qualified Data.ByteString.Char8 as BSC import System.Exit import System.Random import RL_Glue.Agent import RL_Glue.Network main = loadAgent (Agent onInit onStart onStep onEnd onCleanup onMessage) () onInit :: BS.ByteString -> StateT () IO () onInit taskSpec = return () onStart :: Observation -> StateT () IO Action onStart obs = do dir <- lift $ getStdRandom (randomR (0,1)) return (Action $ RLAbstractType [dir] [] BS.empty) onStep :: (Reward, Observation) -> StateT () IO Action onStep (reward, obs) = do dir <- lift $ getStdRandom (randomR (0,1)) return (Action $ RLAbstractType [dir] [] BS.empty) onEnd :: Reward -> StateT () IO () onEnd reward = return () onCleanup :: (StateT () IO ()) onCleanup = return () onMessage :: BS.ByteString -> StateT () IO BS.ByteString onMessage msg = return $ BSC.pack $ if msg == BSC.pack "what is your name?" then "my name is skeleton_agent, Haskell edition!" else "I don't know how to respond to your message"
rhofour/rlglue-haskell-codec
src/RL_Glue/Example/SkeletonAgent.hs
apache-2.0
1,112
0
12
193
408
216
192
29
2
{-# LANGUAGE CPP #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NamedFieldPuns #-} module TTY #ifdef TEST ( TTY(..) , nullDevice #else ( TTY , winHeight , winWidth #endif , TTYException(..) , withTTY , Key(..) , getKey , putText , putTextLine , putLine , clearScreenBottom , withHiddenCursor , getCursorRow , moveCursor ) where import Control.Exception (Exception(..), IOException) import qualified Control.Exception as E import Control.Monad import Control.Monad.IO.Class (MonadIO(..)) import Control.Monad.Trans.Resource (MonadResource) import Data.Char (isPrint, isDigit, chr, ord) import Data.Conduit (Conduit) import qualified Data.Conduit as C import Data.Text (Text) import qualified Data.Text as Text import qualified Data.Text.IO as Text import Data.Typeable (Typeable) import Prelude hiding (getChar) import System.Console.ANSI as Ansi import System.Console.Terminal.Size (Window(..), hSize) import qualified System.IO as IO import qualified System.IO.Error as IO import qualified System.Posix as Posix import System.Timeout (timeout) import Text.Read (readMaybe) data TTY = TTY { inHandle, outHandle :: IO.Handle , winHeight, winWidth :: Int } deriving (Show, Eq) -- | Exceptions thrown while manipulating @\/dev\/tty@ device newtype TTYException = TTYIOException IOException deriving (Show, Eq, Typeable, Exception) withTTY :: MonadResource m => (TTY -> Conduit i m o) -> Conduit i m o withTTY f = withFile ttyDevice IO.ReadMode $ \inHandle -> withFile ttyDevice IO.WriteMode $ \outHandle -> do setBuffering outHandle IO.NoBuffering withConfiguredTTY $ do mw <- hWindow outHandle case mw of Nothing -> liftIO (ioError (notATTY outHandle)) Just Window { height, width } -> f TTY { inHandle, outHandle, winHeight = height, winWidth = width } withFile :: MonadResource m => FilePath -> IO.IOMode -> (IO.Handle -> Conduit i m o) -> Conduit i m o withFile name mode = C.bracketP (IO.openFile name mode) IO.hClose withConfiguredTTY :: MonadResource m => Conduit i m o -> Conduit i m o withConfiguredTTY = C.bracketP (withFd ttyDevice Posix.ReadOnly $ \fd -> do s <- getAttrs fd; configure fd s; return s) (\as -> withFd ttyDevice Posix.ReadOnly (\fd -> setAttrs fd as)) . const withFd :: FilePath -> Posix.OpenMode -> (Posix.Fd -> IO a) -> IO a withFd name mode = E.bracket (Posix.openFd name mode Nothing Posix.defaultFileFlags) Posix.closeFd setBuffering :: MonadIO m => IO.Handle -> IO.BufferMode -> m () setBuffering h m = liftIO (IO.hSetBuffering h m) hWindow :: (Integral n, MonadIO m) => IO.Handle -> m (Maybe (Window n)) hWindow = liftIO . hSize getAttrs :: Posix.Fd -> IO Posix.TerminalAttributes getAttrs = Posix.getTerminalAttributes configure :: Posix.Fd -> Posix.TerminalAttributes -> IO () configure fd as = setAttrs fd (withoutModes as [Posix.EnableEcho, Posix.ProcessInput]) withoutModes :: Posix.TerminalAttributes -> [Posix.TerminalMode] -> Posix.TerminalAttributes withoutModes = foldr (flip Posix.withoutMode) setAttrs :: Posix.Fd -> Posix.TerminalAttributes -> IO () setAttrs fd as = Posix.setTerminalAttributes fd as Posix.Immediately data Key = Print Char | Ctrl Char -- invariant: this character is in ['A'..'Z'] range | Bksp | ArrowUp | ArrowDown | ArrowLeft | ArrowRight deriving (Show, Eq) getKey :: MonadIO m => TTY -> m (Maybe Key) getKey tty = liftIO . fmap join . timeout 100000 $ getChar tty >>= \case '\DEL' -> return (Just Bksp) '\ESC' -> getChar tty >>= \case '[' -> getChar tty >>= \case 'A' -> return (Just ArrowUp) 'B' -> return (Just ArrowDown) 'C' -> return (Just ArrowRight) 'D' -> return (Just ArrowLeft) _ -> return Nothing _ -> return Nothing c | c `elem` ['\SOH'..'\SUB'] -> return (Just (Ctrl (chr (ord c + 64)))) | isPrint c -> return (Just (Print c)) | otherwise -> return Nothing getChar :: MonadIO m => TTY -> m Char getChar = liftIO . IO.hGetChar . inHandle putText :: MonadIO m => TTY -> Text -> m () putText TTY { outHandle } = liftIO . Text.hPutStr outHandle putTextLine :: MonadIO m => TTY -> Text -> m () putTextLine TTY { outHandle } = liftIO . Text.hPutStrLn outHandle putLine :: MonadIO m => TTY -> m () putLine TTY { outHandle } = liftIO (Text.hPutStrLn outHandle Text.empty) clearScreenBottom :: MonadIO m => TTY -> m () clearScreenBottom TTY { outHandle } = liftIO $ do Ansi.hSetCursorColumn outHandle 0 Ansi.hClearFromCursorToScreenEnd outHandle withHiddenCursor :: TTY -> IO a -> IO a withHiddenCursor TTY { outHandle = h } = E.bracket_ (Ansi.hHideCursor h) (Ansi.hShowCursor h) getCursorRow :: MonadIO m => TTY -> m Int getCursorRow tty = do putText tty magicCursorPositionSequence res <- parseAnsiResponse tty case res of Just r -> return (r - 1) -- the response is 1-based Nothing -> liftIO (ioError (notATTY (inHandle tty))) where magicCursorPositionSequence = Text.pack "\ESC[6n" parseAnsiResponse :: (MonadIO m, Read a) => TTY -> m (Maybe a) parseAnsiResponse tty = liftM parse (go []) where go acc = do c <- getChar tty if c == 'R' then return (reverse acc) else go (c : acc) parse ('\ESC' : '[' : xs) = readMaybe (takeWhile isDigit xs) parse _ = Nothing moveCursor :: TTY -> Int -> Int -> IO () moveCursor = Ansi.hSetCursorPosition . outHandle notATTY :: IO.Handle -> IOException notATTY h = IO.mkIOError IO.illegalOperationErrorType "Not a TTY" (Just h) Nothing ttyDevice, nullDevice :: FilePath ttyDevice = "/dev/tty" nullDevice = "/dev/null"
supki/wybor
src/TTY.hs
bsd-2-clause
5,821
0
21
1,248
2,002
1,045
957
137
8
-- | 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 lollerskates.hs file. module Settings ( widgetFile , staticRoot , staticDir ) where import Prelude (FilePath, String) import Text.Shakespeare.Text (st) import Language.Haskell.TH.Syntax import Yesod.Default.Config import qualified Yesod.Default.Util import Data.Text (Text) -- | The location of static files on your system. This is a file system -- path. The default value works properly with your scaffolded site. staticDir :: FilePath staticDir = "static" -- | The base URL for your static files. As you can see by the default -- value, this can simply be "static" appended to your application root. -- A powerful optimization can be serving static files from a separate -- domain name. This allows you to use a web server optimized for static -- files, more easily set expires and cache values, and avoid possibly -- costly transference of cookies on static files. For more information, -- please see: -- http://code.google.com/speed/page-speed/docs/request.html#ServeFromCookielessDomain -- -- If you change the resource pattern for StaticR in lollerskates.hs, you will -- have to make a corresponding change here. -- -- To see how this value is used, see urlRenderOverride in lollerskates.hs staticRoot :: AppConfig DefaultEnv a -> Text staticRoot conf = [st|#{appRoot conf}/static|] widgetFile :: String -> Q Exp #if DEVELOPMENT widgetFile = Yesod.Default.Util.widgetFileReload #else widgetFile = Yesod.Default.Util.widgetFileNoReload #endif
MostAwesomeDude/lollerskates
Settings.hs
bsd-2-clause
1,771
0
6
278
146
99
47
-1
-1
{-# LANGUAGE RecordWildCards #-} -- Generic `Tree` type with different leaf and internal values. module NLP.FTB.Tree ( -- * Tree Tree (..) , showTree , showTree' , toWord ) where import Control.Applicative ((<$>)) import Control.Arrow (first) import Control.Monad (foldM) -- | A tree with values of type 'a' kept in the interior nodes, -- and values of type 'b' kept in the leaf nodes. data Tree a b = INode -- ^ Interior node { labelI :: a , subTrees :: [Tree a b] } | FNode -- ^ Frontier node { labelF :: b } deriving (Show, Eq, Ord) -- | List of frontier values. toWord :: Tree a b -> [b] toWord t = case t of INode{..} -> concatMap toWord subTrees FNode{..} -> [labelF] -- | Show a tree given the showing functions for label values. showTree :: (a -> String) -> (b -> String) -> Tree a b -> String showTree f g = unlines . go where go t = case t of INode{..} -> ("INode " ++ f labelI) : map (" " ++) (concatMap go subTrees) FNode{..} -> ["FNode " ++ g labelF] -- | Like `showTree`, but using the default `Show` instances -- to present label values. showTree' :: (Show a, Show b) => Tree a b -> String showTree' = showTree show show
kawu/ftb
src/NLP/FTB/Tree.hs
bsd-2-clause
1,277
0
13
363
354
199
155
29
2
{-# LANGUAGE DeriveDataTypeable, GeneralizedNewtypeDeriving, ScopedTypeVariables #-} module Oracles.ModuleFiles (moduleFiles, haskellModuleFiles, moduleFilesOracle) where import Base import Oracles.PackageData import Package import Stage import Settings.TargetDirectory newtype ModuleFilesKey = ModuleFilesKey ([String], [FilePath]) deriving (Show, Typeable, Eq, Hashable, Binary, NFData) moduleFiles :: Stage -> Package -> Action [FilePath] moduleFiles stage pkg = do let path = targetPath stage pkg srcDirs <- fmap sort . pkgDataList $ SrcDirs path modules <- fmap sort . pkgDataList $ Modules path let dirs = [ pkgPath pkg -/- dir | dir <- srcDirs ] found :: [(String, FilePath)] <- askOracle $ ModuleFilesKey (modules, dirs) return $ map snd found haskellModuleFiles :: Stage -> Package -> Action ([FilePath], [String]) haskellModuleFiles stage pkg = do let path = targetPath stage pkg autogen = path -/- "build/autogen" dropPkgPath = drop $ length (pkgPath pkg) + 1 srcDirs <- fmap sort . pkgDataList $ SrcDirs path modules <- fmap sort . pkgDataList $ Modules path let dirs = [ pkgPath pkg -/- dir | dir <- srcDirs ] foundSrcDirs <- askOracle $ ModuleFilesKey (modules, dirs ) foundAutogen <- askOracle $ ModuleFilesKey (modules, [autogen]) let found = foundSrcDirs ++ foundAutogen missingMods = modules `minusOrd` (sort $ map fst found) otherFileToMod = replaceEq '/' '.' . dropExtension . dropPkgPath (haskellFiles, otherFiles) = partition ("//*hs" ?==) (map snd found) return (haskellFiles, missingMods ++ map otherFileToMod otherFiles) moduleFilesOracle :: Rules () moduleFilesOracle = do answer <- newCache $ \(modules, dirs) -> do let decodedPairs = map decodeModule modules modDirFiles = map (bimap head sort . unzip) . groupBy ((==) `on` fst) $ decodedPairs result <- fmap concat . forM dirs $ \dir -> do todo <- filterM (doesDirectoryExist . (dir -/-) . fst) modDirFiles forM todo $ \(mDir, mFiles) -> do let fullDir = dir -/- mDir files <- getDirectoryFiles fullDir ["*"] let noBoot = filter (not . (isSuffixOf "-boot")) files cmp fe f = compare (dropExtension fe) f found = intersectOrd cmp noBoot mFiles return (map (fullDir -/-) found, mDir) return $ sort [ (encodeModule d f, f) | (fs, d) <- result, f <- fs ] _ <- addOracle $ \(ModuleFilesKey query) -> answer query return ()
quchen/shaking-up-ghc
src/Oracles/ModuleFiles.hs
bsd-3-clause
2,641
0
28
696
895
454
441
50
1
module Main where import Telem main :: IO () main = runTelemetry
zool-of-bears/Telemetry
app/Main.hs
bsd-3-clause
67
0
6
14
22
13
9
4
1
{-| Module : Numeric.MixedType.LiteralsSpec Description : hspec tests for Literals Copyright : (c) Michal Konecny License : BSD3 Maintainer : [email protected] Stability : experimental Portability : portable -} module Numeric.MixedTypes.LiteralsSpec (spec) where import MixedTypesNumPrelude import qualified Prelude as P -- import Text.Printf import Control.Exception (evaluate) import Test.Hspec -- import qualified Test.QuickCheck as QC -- import qualified Test.Hspec.SmallCheck as SC spec :: Spec spec = do specCanBeInteger tInt specCanBeInteger tInteger specConversions specConversions :: Spec specConversions = do specConversion tInt tInteger integer int it "converting large integer to int throws exception" $ do (evaluate $ int (integer (maxBound :: Int) P.+ 1)) `shouldThrow` anyException specConversion tInt tRational rational (int . round) specConversion tInteger tRational rational round specConversion tDouble tRational toRational double
michalkonecny/mixed-types-num
test/Numeric/MixedTypes/LiteralsSpec.hs
bsd-3-clause
1,031
0
17
197
177
93
84
19
1
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DeriveAnyClass #-} --huh? {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleInstances #-} module Interp ( getType, getType', TypeSig ) where import Data.Typeable import Language.Haskell.Exts.Parser import Language.Haskell.Exts.Syntax import qualified Language.Haskell.Interpreter as Hint import qualified Text.Show.Pretty as Pr import Control.Monad import Data.Aeson.Types import Data.Aeson import GHC.Generics -- typeOfAST :: Typeable a => a -> ParseResult Type -- typeOfAST = parseType . show . typeOf -- foo :: ParseResult Type -- foo = parseType "a -> a" getType :: String -> IO (Either Hint.InterpreterError String) getType = hrun . Hint.typeOf type TypeSig = Maybe Type deriving instance Generic Type -- TODO: make Type generic? ToJSON? -- deriving instance ToJSON Type getType' :: String -> IO (Either Hint.InterpreterError TypeSig) getType' x = fmap f $ hrun . Hint.typeOf $ x where f (Left l) = Left l f (Right r) = Right . g . parseType $ r where g (ParseOk y) = Just y g (ParseFailed _ _) = Nothing hrun :: Hint.Interpreter a -> IO (Either Hint.InterpreterError a) hrun x = Hint.runInterpreter $ Hint.setImports ["Prelude"] >> x -- mon :: IO () -- mon = forever $ do -- putStr "λλλ: " -- l <- getLine -- elt :: Either Hint.InterpreterError String <- hrun . Hint.typeOf $ l -- case elt of -- Left _ -> putStrLn "error!" -- Right lt -> do -- let lt_ast :: ParseResult Type = parseType lt -- putStrLn "" -- putStrLn lt -- putStrLn "" -- putStrLn $ Pr.ppShow lt_ast
sleexyz/typegrams
src/Interp.hs
bsd-3-clause
1,765
0
11
420
329
190
139
34
3
-- Copyright 2019 Google LLC -- -- Use of this source code is governed by a BSD-style -- license that can be found in the LICENSE file or at -- https://developers.google.com/open-source/licenses/bsd {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE UndecidableInstances #-} module Actor (Actor, Proc, PChan, CanTrap (..), Msg (..), runActor, spawn, spawnLink, send, receive, receiveF, receiveErr, receiveErrF, myChan, subChan, sendFromIO, ServerMsg (..), logServer, ReqChan, subscribe) where import Control.Concurrent import Control.Monad import Control.Monad.State.Strict import Control.Monad.Reader import Control.Exception import Data.IORef import Cat import Util data Msg a = ErrMsg Proc String | NormalMsg a data CanTrap = Trap | NoTrap deriving (Show, Ord, Eq) newtype PChan a = PChan { sendPChan :: a -> IO () } data Proc = Proc CanTrap ThreadId (PChan (Proc, String)) -- TODO: Ord instance data BackChan a = BackChan (IORef [a]) (Chan a) data ActorConfig m = ActorConfig { selfProc :: Proc , selfChan :: BackChan (Msg m) , linksPtr :: IORef [Proc] } newtype Actor m a = Actor (ReaderT (ActorConfig m) IO a) deriving (Functor, Applicative, Monad, MonadIO) runActor :: Actor msg a -> IO a runActor (Actor m) = do linksRef <- newIORef [] chan <- newBackChan tid <- myThreadId let p = Proc Trap tid (asErrPChan chan) runReaderT m (ActorConfig p chan linksRef) subChan :: (a -> b) -> PChan b -> PChan a subChan f chan = PChan (sendPChan chan . f) -- TODO: kill :: Proc -> Actor m () spawn :: MonadActor msg m => CanTrap -> Actor msg' () -> m (Proc, PChan msg') spawn canTrap body = liftIO $ spawnIO canTrap [] body spawnLink :: MonadActor msg m => CanTrap -> Actor msg' () -> m (Proc, PChan msg') spawnLink canTrap body = do cfg <- actorCfg liftIO $ do links <- readIORef (linksPtr cfg) (child, childChan) <- spawnIO canTrap [selfProc cfg] body -- potential bug if we get killed right here, before we've linked the child. -- 'mask' from Control.Exception might be a solution writeIORef (linksPtr cfg) (child : links) return (child, childChan) spawnIO :: CanTrap -> [Proc] -> Actor msg () -> IO (Proc, PChan msg) spawnIO canTrap links (Actor m) = do linksRef <- newIORef links chan <- newBackChan tid <- forkIO $ do tid <- myThreadId let self = Proc canTrap tid (asErrPChan chan) runReaderT m (ActorConfig self chan linksRef) `catch` (\e -> do linked <- readIORef linksRef putStrLn $ "Error:\n" ++ show (e::SomeException) mapM_ (cleanup (show (e::SomeException)) self) linked) return (Proc canTrap tid (asErrPChan chan), asPChan chan) where cleanup :: String -> Proc -> Proc -> IO () cleanup s failed (Proc Trap _ errChan) = sendFromIO errChan (failed, s) cleanup _ _ (Proc NoTrap linked _) = void $ forkIO $ killThread linked asPChan :: BackChan (Msg a) -> PChan a asPChan (BackChan _ chan) = PChan (writeChan chan . NormalMsg) asErrPChan :: BackChan (Msg a) -> PChan (Proc, String) asErrPChan (BackChan _ chan) = PChan (writeChan chan . uncurry ErrMsg) send :: MonadActor msg' m => PChan msg -> msg -> m () send p x = liftIO (sendFromIO p x) sendFromIO :: PChan msg -> msg -> IO () sendFromIO = sendPChan myChan :: MonadActor msg m => m (PChan msg) myChan = do cfg <- actorCfg return $ asPChan (selfChan cfg) -- TODO: make a construct to receive in a loop to avoid repeated linear search receiveErrF :: MonadActor msg m => (Msg msg -> Maybe a) -> m a receiveErrF filterFn = do cfg <- actorCfg liftIO $ find (selfChan cfg) [] where find chan skipped = do x <- readBackChan chan case filterFn x of Just y -> do pushBackChan chan (reverse skipped) return y Nothing -> find chan (x:skipped) receiveErr :: MonadActor msg m => m (Msg msg) receiveErr = receiveErrF Just receiveF :: MonadActor msg m => (msg -> Maybe a) -> m a receiveF filterFn = receiveErrF (skipErr >=> filterFn) where skipErr msg = case msg of NormalMsg x -> Just x ErrMsg _ _ -> Nothing receive :: MonadActor msg m => m msg receive = receiveF Just newBackChan :: IO (BackChan a) newBackChan = liftM2 BackChan (newIORef []) newChan readBackChan :: BackChan a -> IO a readBackChan (BackChan ptr chan) = do xs <- readIORef ptr case xs of [] -> readChan chan x:rest -> do writeIORef ptr rest return x pushBackChan :: BackChan a -> [a] -> IO () pushBackChan (BackChan ptr _) xs = do xs' <- readIORef ptr writeIORef ptr (xs ++ xs') class (MonadIO m, Monad m) => MonadActor msg m | m -> msg where actorCfg :: m (ActorConfig msg) instance MonadActor msg (Actor msg) where actorCfg = Actor ask instance MonadActor msg m => MonadActor msg (StateT s m) where actorCfg = lift actorCfg instance MonadActor msg m => MonadActor msg (ReaderT r m) where actorCfg = lift actorCfg instance MonadActor msg m => MonadActor msg (CatT env m) where actorCfg = lift actorCfg -- === ready-made actors for common patterns === -- similar to a CPS transformation a ==> (a -> r) -> r type ReqChan a = PChan (PChan a) data ServerMsg a = Request (PChan a) | Push a subscribe :: MonadActor msg m => ReqChan msg -> m () subscribe chan = myChan >>= send chan -- combines inputs monoidally and pushes incremental updates to subscribers logServer :: Monoid a => Actor (ServerMsg a) () logServer = flip evalStateT (mempty, []) $ forever $ do msg <- receive case msg of Request chan -> do curVal <- gets fst chan `send` curVal modify $ onSnd (chan:) Push x -> do modify $ onFst (<> x) subscribers <- gets snd mapM_ (`send` x) subscribers -- TODO: state machine?
google-research/dex-lang
src/lib/Actor.hs
bsd-3-clause
6,184
0
21
1,630
2,131
1,074
1,057
129
2
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE MultiParamTypeClasses #-} module Mental.Decl ( Module(..) , Decl(..) , UntypedModule , TypedModule , UntypedDecl , TypedDecl ) where import Protolude import Text.Megaparsec (SourcePos) import Mental.Name import Mental.Tree import Mental.Type data Module a = Module { _modName :: ModuleName , _modDecls :: [Decl a] } deriving (Eq, Ord, Show, Read, Generic, Typeable) type UntypedModule = Module SourcePos type TypedModule = Module Ty data Decl a = FunDecl !VarName !(Maybe Ty) !(AnnTree a) | TyDecl !TyName !Ty deriving (Eq, Ord, Show, Read, Generic, Typeable) type UntypedDecl = Decl SourcePos type TypedDecl = Decl Ty
romac/mental
src/Mental/Decl.hs
bsd-3-clause
794
0
10
197
221
126
95
38
0
r = reverse c = concat s = show b = "reeb fo selttob" v x = [a | a <- b, a /= 's' || x > 1] main = putStrLn $ c $ [c [s x, r $ " ,llaw eht no " ++ v x ++ " ", s x, r $ " ,dnuora ti ssap dna nwod eno ekaT\n." ++ v x ++ " ", if x > 1 then s $ x - 1 else r "erom on", r $ "\n\n." ++ b ++ " "] | x <- r [1..99]] ++ [r $ c ["llaw eht no ", b, " 99 ,erom emos yub dna erots eht ot oG\n.", b, " erom on ,", b, " erom oN"]]
eeue56/code-golf
bottles-of-bear/bottles.hs
bsd-3-clause
434
12
12
142
227
121
106
13
2
-------------------------------------------------------------------------------- {-# LANGUAGE OverloadedStrings #-} module NumberSix.Handlers.Weather ( handler ) where -------------------------------------------------------------------------------- import Control.Monad.Trans (liftIO) import Data.Text (Text) import qualified Data.Text as T import Text.XmlHtml import Text.XmlHtml.Cursor -------------------------------------------------------------------------------- import NumberSix.Bang import NumberSix.Irc import NumberSix.Message import NumberSix.Util.Error import NumberSix.Util.Http -------------------------------------------------------------------------------- weather :: Text -> IO Text weather query = do result <- httpScrape Html url id $ \cursor -> do -- Find content div con <- findRec (byTagNameAttrs "div" [("class", "content")]) cursor temp <- findRec (byTagNameAttrs "span" [("class", "temperature")]) con remark <- findRec (byTagNameAttrs "p" [("class", "remark")]) con return $ (nodeText $ current temp) <> "°?! " <> (nodeText $ current remark) maybe randomError return result where loc = if T.null query then "ghent" else query url = "http://thefuckingweather.com/?unit=c&where=" <> loc -------------------------------------------------------------------------------- handler :: UninitializedHandler handler = makeBangHandler "Weather" ["!weather"] $ liftIO . weather
itkovian/number-six
src/NumberSix/Handlers/Weather.hs
bsd-3-clause
1,610
0
17
350
316
175
141
27
2
module Network.Sieve.Test ( addressS, addressL, addHeader, addHeaders, Config(..), nilMail, Action(..), assertMailActions, assertMailStoredIn, assertHeaderStoredIn, assertHeadersStoredIn ) where import Control.Applicative ((*>), (<$>), (<*)) import Control.Monad (void, when) import Control.Monad.IO.Class (liftIO) import Control.Monad.Reader (ReaderT, asks) import qualified Data.ByteString.Char8 as BSC (ByteString, pack) import qualified Data.ByteString.Lazy.Char8 as BSLC (hPutStr, pack) import qualified Data.Text as T (Text, pack) import GHC.IO.Exception (ExitCode (ExitFailure, ExitSuccess)) import Network.Mail.Mime (Address (Address), Encoding (QuotedPrintableText), Mail (mailHeaders, mailParts), Part (Part, partContent, partEncoding, partFilename, partHeaders, partType), emptyMail, renderMail') import System.Directory (getTemporaryDirectory, removeFile) import System.IO (hClose) import System.IO.Temp (openBinaryTempFile) import System.Process (readProcessWithExitCode) import Test.HUnit.Base (assertEqual, assertFailure) import Text.Parsec (parse) import Text.Parsec.Char (char, noneOf, string) import Text.Parsec.Combinator (choice, many1) import Text.Parsec.Error () import Text.Parsec.Prim (try) import Text.Parsec.String (Parser) data Config = Config { extensions :: String, sieveFile :: FilePath } deriving (Show) addressS :: String -> Address addressS s = Address Nothing $ T.pack s addressL :: String -> String -> Address addressL s t = Address (Just $ T.pack s) $ T.pack t type Header = (BSC.ByteString, T.Text) packHeader :: (String, String) -> Header packHeader (name, value) = (BSC.pack name, T.pack value) addHeader :: Mail -> (String, String) -> Mail addHeader mail header = addHeaders mail [header] addHeaders :: Mail -> [(String, String)] -> Mail addHeaders mail headers = mail { mailHeaders = new } where new :: [Header] new = mailHeaders mail ++ fmap packHeader headers textPart :: String -> Part textPart t = Part { partType = T.pack "text/plain", partEncoding = QuotedPrintableText, partFilename = Nothing, partHeaders = [], partContent = BSLC.pack t } nilMail :: Mail nilMail = (emptyMail $ addressS "[email protected]") { mailParts = [[textPart ""]] } writeMailTemp :: Mail -> IO FilePath writeMailTemp mail = do tempDir <- getTemporaryDirectory pathAndHandle <- openBinaryTempFile tempDir "testsieve.mail" renderedMail <- renderMail' mail BSLC.hPutStr (snd pathAndHandle) renderedMail hClose $ snd pathAndHandle return $ fst pathAndHandle runSieveTestWithMail :: Mail -> ReaderT Config IO String runSieveTestWithMail mail = do cfg_sieveFile <- asks sieveFile cfg_extensions <- asks extensions liftIO $ run cfg_sieveFile cfg_extensions where run :: FilePath -> String -> IO String run cfg_sieveFile cfg_extensions = do mailFile <- writeMailTemp mail result@(exitCode, stdout, _) <- readProcessWithExitCode "sieve-test" ["-x", cfg_extensions, cfg_sieveFile, mailFile] "" when (exitCode /= ExitSuccess) $ assertFailure $ formatFailure result mailFile removeFile mailFile return stdout formatFailure :: (ExitCode, String, String) -> FilePath -> String formatFailure (ExitFailure code, stdout, stderr) mailFile = "error code " ++ show code ++ " for sieve-test on '" ++ mailFile ++ "':\n" ++ "stdout:\n" ++ stdout ++ "\nstderr:\n" ++ stderr formatFailure _ _ = error "this should never happen :-)" data Action = -- actions Store String | Discard -- side effects | CreateMailboxIfNotExist deriving (Show, Eq, Ord) type Actions = ([Action], [Action]) parseSieveTestResult :: Parser Actions parseSieveTestResult = do void $ string "\nPerformed actions:\n\n" performedActions <- actionLines void $ string "\nImplicit keep:\n\n" implicitKeep <- actionLines void $ char '\n' return (performedActions, implicitKeep) where actionLines :: Parser [Action] actionLines = fmap concat $ many1 actionLine actionLine :: Parser [Action] actionLine = char ' ' *> action <* char '\n' action :: Parser [Action] action = choice [none, someAction, someSideEffect] none :: Parser [Action] none = do void $ try $ string " (none)" return [] -- sieve_result_action_printf in src/lib-sieve/sieve-result.c someAction :: Parser [Action] someAction = do void $ try $ string "* " (:[]) <$> choice [ storeAction, discardAction ] storeAction :: Parser Action storeAction = Store <$> (string "store message in folder: " *> many1 (noneOf "\n")) discardAction :: Parser Action discardAction = string "discard" *> return Discard -- sieve_result_seffect_printf in src/lib-sieve/sieve-result.c someSideEffect :: Parser [Action] someSideEffect = do void $ try $ string " + " (:[]) <$> choice [ createMailboxAction ] createMailboxAction :: Parser Action createMailboxAction = string "create mailbox if it does not exist" *> return CreateMailboxIfNotExist assertMailActions :: Mail -> Actions -> ReaderT Config IO () assertMailActions mail expectedActions = do sieveTestOut <- runSieveTestWithMail mail liftIO $ do actualActions <- parseSieveTestOut sieveTestOut assertEqual ("unexpected Actions: " ++ sieveTestOut) expectedActions actualActions where parseSieveTestOut :: String -> IO Actions parseSieveTestOut s = case parse parseSieveTestResult "" s of (Left err) -> do assertFailure $ "could not parse output from sieve-test:\n" ++ show err ++ "output was:\n" ++ s return ([], []) (Right actions) -> return actions assertMailStoredIn :: Mail -> String -> ReaderT Config IO () assertMailStoredIn mail folder = assertMailActions mail ([Store folder, CreateMailboxIfNotExist], []) assertHeaderStoredIn :: (String, String) -> String -> ReaderT Config IO () assertHeaderStoredIn header = assertMailStoredIn (addHeader nilMail header) assertHeadersStoredIn :: [(String, String)] -> String -> ReaderT Config IO () assertHeadersStoredIn headers = assertMailStoredIn (addHeaders nilMail headers)
thkoch2001/sieve-test-hs
src/Network/Sieve/Test.hs
bsd-3-clause
6,813
0
15
1,784
1,830
993
837
152
2
-- | -- Copyright : (C) 2013 Xyratex Technology Limited. -- License : All rights reserved. {-# LANGUAGE RankNTypes #-} module Options.Schema.Builder ( Mod -- * Basic options , option , strOption , intOption , flag , switch , compositeOption -- * Alternatives , oneOf , many , some , defaultable , optional -- * Modifiers , name , long , short , desc , summary , detail -- * Argument modifiers , arg , metavar , reader , argDesc , value , valueShow , argSummary , argDetail ) where import Control.Applicative ( (<|>) , empty , many , optional , some ) import Control.Alternative.Freer import Data.Defaultable import Data.List (foldl') import Data.Monoid import Options.Schema -- This should really be MonadFail... type Reader a = forall m. Monad m => String -> m a -- Option modifier. data Mod a = Mod (Option a -> Option a) instance Monoid (Mod a) where mempty = Mod id (Mod f) `mappend` (Mod g) = Mod $ f . g ------------ Basic Options --------------------- -- | Construct a basic option given a reader for the type. option :: Reader a -> Mod a -> Schema a option rdr (Mod f) = liftAlt . f $ Option { oNames = mempty , oDescription = mempty , oBlock = SingleArgument $ Argument { aMetavar = mempty , aReader = rdr , aDefault = ArgumentDefault Nothing Nothing , aDescr = mempty } } -- | Construct an option using the default 'String' reader. strOption :: Mod String -> Schema String strOption = option (return . id) -- TODO This should not be partial - should have a sensible reader -- | Construct an option using the default 'Int' reader. intOption :: Mod Int -> Schema Int intOption = option (return . read) -- | Construct an option whose presence sets a flag. This may be treated -- specially by the underlying parser. flag :: a -- ^ Value when the flag is set. -> a -- ^ Value when the flag is missing. -> Mod a -> Schema a flag active def (Mod f) = liftAlt . f $ Option { oNames = mempty , oDescription = mempty , oBlock = Flag active def } -- | Construct a flag for bools. switch :: Mod Bool -> Schema Bool switch = flag True False -- | Construct an option from a sub-schema. compositeOption :: Schema a -> Mod a -> Schema a compositeOption group (Mod f) = liftAlt . f $ Option { oNames = mempty , oDescription = mempty , oBlock = Subsection group } ------ Lifting options into Schemata -------- -- | Construct an @OptionGroup@ consisting of a number of -- alternate options. oneOf :: [Schema a] -> Schema a oneOf = foldl' (<|>) empty ------------- Option Modifiers ------------------ name :: Name -> Mod a name n = Mod $ \a -> a { oNames = n : oNames a } -- | Specify a long name for the option. long :: String -> Mod a long = name . LongName -- | Specify a short name for the option. Short names are mostly used in -- command-line parsers. short :: Char -> Mod a short = name . ShortName -- | Specify the option description. This description applies to the whole -- option, not simply the argument value. desc :: Description -> Mod a desc str = Mod $ \a -> a { oDescription = oDescription a <> str } -- | Specify the option summary. This should be a short precis of the option. summary :: String -> Mod a summary d = desc (Description (Just d) Nothing) -- | Specify the option detail. This should be a full explanation of the option, -- its use, and its effect on the application. detail :: String -> Mod a detail d = desc (Description Nothing (Just d)) --- Must be a better way of doing these, surely? type ArgMod a = (Argument a -> Argument a) arg :: ArgMod a -> Mod a arg md = Mod $ \a -> case oBlock a of SingleArgument b -> a { oBlock = SingleArgument (md b) } _ -> a -- | Specify the default name for the argument - e.g. for a command-line parser, -- this might appear as '--foo FOO', where 'FOO' is the metavar. metavar :: String -> Mod a metavar str = arg $ \b -> b { aMetavar = Just str } -- | Specify the option reader. The reader is used to construct a value of -- correct type from a string. reader :: Reader a -> Mod a reader r = arg $ \b -> b { aReader = r } argDesc :: Description -> Mod a argDesc d = arg $ \b -> b { aDescr = aDescr b <> d } -- | Specify the default value for the argument. value :: a -> Mod a value d = arg $ \b -> let (ArgumentDefault _ y) = aDefault b def' = ArgumentDefault (Just d) y in b { aDefault = def' } -- | Specify a function used to display the default argument. Note that, -- confusingly, this must be specified *before* the default value. valueShow :: (a -> String) -> Mod a valueShow d = arg $ \b -> let (ArgumentDefault x _) = aDefault b def' = ArgumentDefault x (fmap d x) in b { aDefault = def' } -- | Specify the argument summary. This description applies only to the -- argument. Eg. one may have "Set the message timeout" as the option summary, -- with "Number of seconds" as the argument summary. argSummary :: String -> Mod a argSummary d = argDesc (Description (Just d) Nothing) -- | Specify the argument detail. This description applies only to the -- argument. argDetail :: String -> Mod a argDetail d = argDesc (Description Nothing (Just d))
seagate-ssg/options-schema
src/Options/Schema/Builder.hs
bsd-3-clause
5,232
0
14
1,203
1,305
714
591
110
2
module InsideOut where import Control.Monad.Trans.Except import Control.Monad.Trans.Maybe import Control.Monad.Trans.Reader -- newtype ExceptT e m a = ExceptT { runExceptT :: m (Either e a) } -- newtype MaybeT m a = MaybeT { runMaybeT :: m (Maybe a) } -- newtype ReaderT r m a = ReaderT { runReaderT :: r -> m a } -- base monad here is structurally outmost, but lexically inner: IO embedded :: MaybeT (ExceptT String (ReaderT () IO)) Int embedded = return 1 maybeUnwrap :: ExceptT String (ReaderT () IO) (Maybe Int) maybeUnwrap = runMaybeT embedded eitherUnwrap :: ReaderT () IO (Either String (Maybe Int)) eitherUnwrap = runExceptT maybeUnwrap readerUnwrap :: () -> IO (Either String (Maybe Int)) readerUnwrap = runReaderT eitherUnwrap embedded' :: MaybeT (ExceptT String (ReaderT () IO)) Int -- explicitly write down the type, which will help you figure out the solution embedded' = let a = (return . const (Right (Just (1 :: Int)))) -- () -> IO (Either String (Maybe Int)) b = ReaderT a -- ReaderT () IO (Either String (Maybe Int)) c = ExceptT b -- ExceptT String (ReaderT () IO) (Maybe Int) in MaybeT c {- -- in another way embedded' = MaybeT $ ExceptT $ ReaderT $ (return . const (Right (Just 1))) -}
chengzh2008/hpffp
src/ch26-MonadTransformers/insideOut.hs
bsd-3-clause
1,263
0
16
266
269
145
124
17
1
{-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleInstances #-} -- | Abstraction over the most general type in Javascript. module Language.Sunroof.JS.Object ( JSObject , object , this ) where import Data.Boolean ( BooleanOf, IfB(..), EqB(..) ) import Language.Sunroof.JavaScript ( Expr, showExpr, literal, binOp ) import Language.Sunroof.Classes ( Sunroof(..) ) import Language.Sunroof.JS.Bool ( JSBool, jsIfB ) -- ------------------------------------------------------------- -- JSObject Type -- ------------------------------------------------------------- -- | Data type for all Javascript objects. data JSObject = JSObject Expr instance Show JSObject where show (JSObject v) = showExpr False v instance Sunroof JSObject where box = JSObject unbox (JSObject o) = o type instance BooleanOf JSObject = JSBool instance IfB JSObject where ifB = jsIfB -- | Reference equality, not value equality. instance EqB JSObject where (JSObject a) ==* (JSObject b) = box $ binOp "==" a b -- ------------------------------------------------------------- -- JSObject Combinators -- ------------------------------------------------------------- -- | Create an arbitrary object from a literal in form of a string. object :: String -> JSObject object = box . literal -- | The @this@ reference. this :: JSObject this = object "this"
ku-fpg/sunroof-compiler
Language/Sunroof/JS/Object.hs
bsd-3-clause
1,386
0
8
212
266
158
108
26
1
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TupleSections #-} module Tinc.GitSpec (spec) where import Prelude () import Prelude.Compat import Helper import MockedEnv import MockedProcess import Test.Mockery.Action import Safe import System.Directory import System.FilePath import System.IO.Error import System.IO.Temp import Test.Mockery.Directory import Tinc.Git import Tinc.Hpack spec :: Spec spec = do describe "clone" $ do let url = "https://github.com/haskell-tinc/hpack" rev = "6bebd90d1e22901e94460c02bba9d0fa5b343f81" cachedGitDependency = CachedGitDependency "hpack" rev mockedCallProcess command args = do let dst = atDef "/path/to/some/tmp/dir" args 2 gitClone = ("git", ["clone", url, dst], ) $ do createDirectory $ dst </> ".git" writeFile (dst </> "hpack.cabal") "name: hpack" gitCheckout = ("git", ["reset", "--hard", "0.1.0"], writeFile "rev" (rev ++ "\n")) mockMany [gitClone, gitCheckout] command args mockedReadProcess = mock ("git", ["rev-parse", "HEAD"], "", readFile "rev") mockedEnv = env {envReadProcess = mockedReadProcess, envCallProcess = mockedCallProcess} context "with a tag" $ do let action = clone "git-cache" (GitDependency "hpack" url "0.1.0") it "adds specified git ref to cache" $ do inTempDirectory $ do actualRev <- withEnv mockedEnv action actualRev `shouldBe` cachedGitDependency doesDirectoryExist ("git-cache" </> "hpack" </> rev) `shouldReturn` True doesDirectoryExist ("git-cache" </> "hpack" </> rev </> ".git") `shouldReturn` False it "is idempotent" $ do inTempDirectory $ do withEnv mockedEnv (action >> action) `shouldReturn` cachedGitDependency context "with a git revision" $ do let action = clone "git-cache" (GitDependency "hpack" url rev) context "when the revision is already cached" $ do it "does nothing" $ do inTempDirectory $ do createDirectoryIfMissing True ("git-cache" </> "hpack" </> rev) withEnv env {envReadProcess = undefined, envCallProcess = undefined} action `shouldReturn` cachedGitDependency describe "checkCabalName" $ do context "when git dependency name and cabal package name match" $ do it "succeeds" $ do withSystemTempDirectory "tinc" $ \ dir -> do let cabalFile = dir </> "foo.cabal" writeFile cabalFile "name: foo" checkCabalName dir (GitDependency "foo" "<url>" "<ref>") context "when git dependency name and cabal package name differ" $ do it "fails" $ do withSystemTempDirectory "tinc" $ \ dir -> do let cabalFile = dir </> "foo.cabal" writeFile cabalFile "name: foo" checkCabalName dir (GitDependency "bar" "<url>" "<ref>") `shouldThrow` errorCall "the git repository <url> contains package \"foo\", expected: \"bar\"" describe "determinePackageName" $ do it "complains about invalid cabal files" $ do withSystemTempDirectory "tinc" $ \ dir -> do let cabalFile = dir </> "foo.cabal" writeFile cabalFile "library\n build-depends: foo bar" determinePackageName dir "<repo>" `shouldThrow` isUserError describe "getCabalFile" $ do it "finds cabal files in given directory" $ do withSystemTempDirectory "tinc" $ \ dir -> do let cabalFile = dir </> "foo.cabal" touch cabalFile findCabalFile dir "<repo>" `shouldReturn` cabalFile context "when there is no cabal file" $ do it "reports an error" $ do withSystemTempDirectory "tinc" $ \ dir -> do findCabalFile dir "<repo>" `shouldThrow` errorCall "Couldn't find .cabal file in git repository: <repo>" context "when there are multiple cabal files" $ do it "reports an error" $ do withSystemTempDirectory "tinc" $ \ dir -> do touch (dir </> "foo.cabal") touch (dir </> "bar.cabal") findCabalFile dir "<repo>" `shouldThrow` errorCall "Multiple cabal files found in git repository: <repo>"
beni55/tinc
test/Tinc/GitSpec.hs
bsd-3-clause
4,355
0
25
1,196
1,004
492
512
88
1
-- Borrowed from sample code for Parallel and Concurrent Programming in -- Haskell - Simon Marlow -- https://github.com/simonmar/parconc-examples -- {-# LANGUAGE CPP, MagicHash, UnboxedTuples #-} module ConcurrentUtils ( -- * Variants of forkIO forkFinally ) where import Control.Concurrent.STM import Control.Exception import Control.Concurrent import Prelude hiding (catch) import Control.Monad import Control.Applicative import GHC.Exts import GHC.IO hiding (finally) import GHC.Conc #if __GLASGOW_HASKELL__ < 706 -- | fork a thread and call the supplied function when the thread is about -- to terminate, with an exception or a returned value. The function is -- called with asynchronous exceptions masked. forkFinally :: IO a -> (Either SomeException a -> IO ()) -> IO ThreadId forkFinally action and_then = mask $ \restore -> forkIO $ try (restore action) >>= and_then #endif
shterrett/peer-chat
src/ConcurrentUtils.hs
bsd-3-clause
903
0
11
147
148
87
61
16
1
-- | Fields. module Math.Algebra.Field where import qualified Math.Algebra.AbelianMonoid as AbM import qualified Math.Algebra.Ring as R import qualified Math.Algebra.Monoid as M class (AbM.AbelianMultiplicativeMonoid a, R.Ring a) => Field a where -- | 'reciprocal' must be defined for every ring element different -- from the additive neutral element. It is the user's -- responsibility that 'reciprocal' is never called for this -- element. In such cases, behavior is undefined. reciprocal :: a -> a infixr 7 </> -- | @x </> y = x <*> ('reciprocal' y)@. (</>) :: (Field a) => a -> a -> a x </> y = x M.<*> (reciprocal y)
michiexile/hplex
pershom/src/Math/Algebra/Field.hs
bsd-3-clause
647
0
7
129
129
79
50
9
1
{-# LANGUAGE CPP #-} -- | -- Module : Data.Time.Locale.Compat -- Copyright : 2014 Kei Hibino -- License : BSD3 -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : unknown -- -- This module provides compatibility module name -- for TimeLocale of old-locale or time-1.5. module Data.Time.Locale.Compat ( -- * Time locale interface names TimeLocale, defaultTimeLocale, -- * Date format interface names iso8601DateFormat, rfc822DateFormat, ) where #if MIN_VERSION_time(1,5,0) import Data.Time.Format (TimeLocale, defaultTimeLocale, iso8601DateFormat, rfc822DateFormat) #else import System.Locale (TimeLocale, defaultTimeLocale, iso8601DateFormat, rfc822DateFormat) #endif
juhp/haskell-time-locale-compat
src/Data/Time/Locale/Compat.hs
bsd-3-clause
732
0
5
115
60
46
14
7
0
module InsAt where -- P21 Insert an element at a given position into a list insertAt :: [a] -> [a] -> Int -> [a] insertAt s y@(x:xs) k | k > 0 = take k y ++ s ++ drop k y | otherwise = error "k cannot be negative"
michael-j-clark/hjs99
src/21to30/InsAt.hs
bsd-3-clause
228
0
8
64
93
48
45
5
1
module MCTS.GameState where data Player = Player1 | Player2 deriving (Eq, Show) data Winner = Only Player | None | Both deriving (Eq, Show) class GameState a where choices :: a -> [a] gameOver :: a -> Bool winner :: a -> Maybe Winner turn :: a -> Player opponent :: Player -> Player opponent Player1 = Player2 opponent Player2 = Player1
rudyardrichter/MCTS
src/MCTS/GameState.hs
mit
424
0
8
149
129
71
58
16
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} {-| Basic building blocks for writing graphs with the Dot syntax. This contains only the basic building blocks of to Dot syntax, and it does __not__ provide conventions to print particular kinds of graphs. -} module Image.Dot.TypedGraph ( NamingContext(..) , makeNamingContext , typedGraph , typedGraphMorphism , graphRule , sndOrderRule ) where import Data.Text.Prettyprint.Doc (Doc, Pretty (..), (<+>), (<>)) import qualified Data.Text.Prettyprint.Doc as PP import Abstract.Category import Category.TypedGraphRule import qualified Data.Graphs as Graph import Data.TypedGraph import Data.TypedGraph.Morphism import qualified Image.Dot.Prettyprint as Dot import Rewriting.DPO.TypedGraph import Rewriting.DPO.TypedGraphRule data NamingContext n e ann = Ctx { getNodeTypeName :: Graph.NodeInContext (Maybe n) (Maybe e) -> Doc ann , getEdgeTypeName :: Graph.EdgeInContext (Maybe n) (Maybe e) -> Doc ann , getNodeName :: Doc ann -> NodeInContext n e -> Doc ann , getNodeLabel :: Doc ann -> NodeInContext n e -> Maybe (Doc ann) , getEdgeLabel :: Doc ann -> EdgeInContext n e -> Maybe (Doc ann) } -- TODO: move this to XML parsing module makeNamingContext :: [(String, String)] -> NamingContext n e ann makeNamingContext assocList = Ctx { getNodeTypeName = nameForId . normalizeId . nodeId , getEdgeTypeName = nameForId . normalizeId . edgeId , getNodeName = \idPrefix (Node n _, _, _) -> idPrefix <> pretty n , getNodeLabel = \_ (_,Node ntype _,_) -> Just . nameForId $ normalizeId ntype , getEdgeLabel = \_ (_,_,Edge etype _ _ _,_) -> Just . nameForId $ normalizeId etype } where nodeId (node, _) = Graph.nodeId node edgeId (_, edge, _) = Graph.edgeId edge normalizeId id = "I" ++ show id nameForId id = case lookup id assocList of Nothing -> error $ "Name for '" ++ id ++ "' not found." Just name -> pretty $ takeWhile (/= '%') name -- | Create a dotfile representation of the given typed graph, labeling nodes with their types typedGraph :: NamingContext n e ann -> Doc ann -> TypedGraph n e -> Doc ann typedGraph context name graph = Dot.digraph name (typedGraphBody context name graph) typedGraphBody :: NamingContext n e ann -> Doc ann -> TypedGraph n e -> [Doc ann] typedGraphBody context idPrefix graph = nodeAttrs : map prettyNode (nodes graph) ++ map prettyEdge (edges graph) where nodeAttrs = "node" <+> Dot.attrList [("shape", "box")] prettyNode (Node n _, _) = Dot.node name attrs where node = lookupNodeInContext n graph Just name = getNodeName context idPrefix <$> node attrs = case getNodeLabel context idPrefix =<< node of Nothing -> [] Just label -> [("label", PP.dquotes label)] prettyEdge (Edge e src tgt _, _) = Dot.dirEdge srcName tgtName attrs where Just srcName = getNodeName context idPrefix <$> lookupNodeInContext src graph Just tgtName = getNodeName context idPrefix <$> lookupNodeInContext tgt graph attrs = case getEdgeLabel context idPrefix =<< lookupEdgeInContext e graph of Nothing -> [] Just label -> [("label", PP.dquotes label)] -- | Create a dotfile representation of the given typed graph morphism typedGraphMorphism :: NamingContext n e ann -> Doc ann -> TypedGraphMorphism n e -> Doc ann typedGraphMorphism context name morphism = Dot.digraph name (typedGraphMorphismBody context morphism) typedGraphMorphismBody :: NamingContext n e ann -> TypedGraphMorphism n e -> [Doc ann] typedGraphMorphismBody context morphism = Dot.subgraph "dom" (typedGraphBody context "dom" (domain morphism)) : Dot.subgraph "cod" (typedGraphBody context "cod" (codomain morphism)) : map (prettyNodeMapping [("style", "dotted")] "dom" "cod") (nodeMapping morphism) prettyNodeMapping :: (Pretty a) => [(Doc ann, Doc ann)] -> Doc ann -> Doc ann -> (a, a) -> Doc ann prettyNodeMapping attrs idSrc idTgt (src, tgt) = Dot.dirEdge (idSrc <> pretty src) (idTgt <> pretty tgt) attrs -- | Create a dotfile representation of the given graph rule graphRule :: NamingContext n e ann -> Doc ann -> TypedGraphRule n e -> Doc ann graphRule context ruleName rule = Dot.digraph ruleName (graphRuleBody context ruleName rule) graphRuleBody :: NamingContext n e ann -> Doc ann -> TypedGraphRule n e -> [Doc ann] graphRuleBody context ruleName rule = Dot.subgraph leftName (typedGraphBody context leftName (leftObject rule)) : Dot.subgraph interfaceName (typedGraphBody context interfaceName (interfaceObject rule)) : Dot.subgraph rightName (typedGraphBody context rightName (rightObject rule)) : map (prettyNodeMapping [("style", "dotted")] interfaceName leftName) (nodeMapping $ leftMorphism rule) ++ map (prettyNodeMapping [("style", "dotted"), ("dir", "back")] interfaceName rightName) (nodeMapping $ rightMorphism rule) where (leftName, interfaceName, rightName) = ("L_" <> ruleName, "K_" <> ruleName, "R_" <> ruleName) -- | Create a dotfile representation of the given second-order rule sndOrderRule :: NamingContext n e ann -> Doc ann -> SndOrderRule n e -> Doc ann sndOrderRule context ruleName rule = Dot.digraph ruleName (sndOrderRuleBody context ruleName rule) sndOrderRuleBody :: NamingContext n e ann -> Doc ann -> SndOrderRule n e -> [Doc ann] sndOrderRuleBody context ruleName rule = Dot.subgraph leftName (graphRuleBody context leftName (leftObject rule)) : Dot.subgraph interfaceName (graphRuleBody context interfaceName (interfaceObject rule)) : Dot.subgraph rightName (graphRuleBody context rightName (rightObject rule)) : map (prettyNodeMapping [("style", "dashed")] (ruleName <> "KL") (ruleName <> "LL")) (nodeMapping . mappingLeft $ leftMorphism rule) ++ map (prettyNodeMapping [("style", "dashed")] (ruleName <> "KK") (ruleName <> "LK")) (nodeMapping . mappingInterface $ leftMorphism rule) ++ map (prettyNodeMapping [("style", "dashed")] (ruleName <> "KR") (ruleName <> "LR")) (nodeMapping . mappingRight $ leftMorphism rule) ++ map (prettyNodeMapping [("style", "dashed"), ("dir", "back")] (ruleName <> "KL") (ruleName <> "RL")) (nodeMapping . mappingLeft $ rightMorphism rule) ++ map (prettyNodeMapping [("style", "dashed"), ("dir", "back")] (ruleName <> "KK") (ruleName <> "RK")) (nodeMapping . mappingInterface $ rightMorphism rule) ++ map (prettyNodeMapping [("style", "dashed"), ("dir", "back")] (ruleName <> "KR") (ruleName <> "RR")) (nodeMapping . mappingRight $ rightMorphism rule) where (leftName, interfaceName, rightName) = ("L_" <> ruleName, "K_" <> ruleName, "R_" <> ruleName) prettyNodeMapping attrs idSrc idTgt (src, tgt) = Dot.dirEdge (idSrc <> pretty src) (idTgt <> pretty tgt) attrs
rodrigo-machado/verigraph
src/library/Image/Dot/TypedGraph.hs
gpl-3.0
6,924
0
17
1,366
2,245
1,172
1,073
102
3
module TransCFSpec (transSpec, testConcreteSyn) where import BackEnd import FrontEnd (source2core) import JavaUtils (getClassPath) import MonadLib import OptiUtils (Exp(Hide)) import PartialEvaluator (rewriteAndEval) import SpecHelper import StringPrefixes (namespace) import StringUtils (capitalize) import TestTerms import Language.Java.Pretty (prettyPrint) import System.Directory import System.FilePath import System.IO import System.Process import Test.Tasty.Hspec testCasesPath = "testsuite/tests/should_run" fetchResult :: Handle -> IO String fetchResult outP = do msg <- hGetLine outP if msg == "exit" then fetchResult outP else return msg -- java compilation + run compileAndRun inP outP name compileF exp = do let source = prettyPrint (fst (compileF name (rewriteAndEval exp))) let jname = name ++ ".java" hPutStrLn inP jname hPutStrLn inP (source ++ "\n" ++ "//end of file") fetchResult outP testAbstractSyn inP outP compilation (name, filePath, ast, expectedOutput) = do let className = capitalize $ dropExtension (takeFileName filePath) output <- runIO (compileAndRun inP outP className compilation ast) it ("should compile and run " ++ name ++ " and get \"" ++ expectedOutput ++ "\"") $ return output `shouldReturn` expectedOutput testConcreteSyn inP outP compilation (name, filePath) = do source <- runIO (readFile filePath) case parseExpectedOutput source of Nothing -> error (filePath ++ ": " ++ "The integration test file should start with '-->', \ \followed by the expected output") Just expectedOutput -> do ast <- runIO (source2core NoDump (filePath, source)) testAbstractSyn inP outP compilation (name, filePath, ast, expectedOutput) abstractCases = [ ("factorial 10", "main_1", Hide factApp, "3628800") , ("fibonacci 10", "main_2", Hide fiboApp, "55") , ("idF Int 10", "main_3", Hide idfNum, "10") , ("const Int 10 20", "main_4", Hide constNum, "10") , ("program1 Int 5", "main_5", Hide program1Num, "5") , ("program2", "main_6", Hide program2, "5") , ("program4", "main_7", Hide program4, "11") ] transSpec = do concreteCases <- runIO (discoverTestCases testCasesPath) -- change to testing directory for module testing curr <- runIO (getCurrentDirectory) runIO (setCurrentDirectory $ curr </> testCasesPath) forM_ [("BaseTransCF" , compileN) ,("ApplyTransCF", compileAO) ,("StackTransCF", compileS)] (\(name, compilation) -> describe name $ do cp <- runIO getClassPath let p = (proc "java" ["-cp", cp, namespace ++ "FileServer", cp]) {std_in = CreatePipe, std_out = CreatePipe} (Just inP, Just outP, _, proch) <- runIO $ createProcess p runIO $ hSetBuffering inP NoBuffering runIO $ hSetBuffering outP NoBuffering forM_ abstractCases (testAbstractSyn inP outP compilation) forM_ concreteCases (testConcreteSyn inP outP compilation)) runIO (setCurrentDirectory curr)
zhiyuanshi/fcore
testsuite/TransCFSpec.hs
bsd-2-clause
3,133
0
20
715
897
475
422
68
2
{-# LANGUAGE CPP, NondecreasingIndentation, ScopedTypeVariables #-} {-# LANGUAGE TupleSections, NamedFieldPuns #-} -- ----------------------------------------------------------------------------- -- -- (c) The University of Glasgow, 2005-2012 -- -- The GHC API -- -- ----------------------------------------------------------------------------- module GHC ( -- * Initialisation defaultErrorHandler, defaultCleanupHandler, prettyPrintGhcErrors, withSignalHandlers, withCleanupSession, -- * GHC Monad Ghc, GhcT, GhcMonad(..), HscEnv, runGhc, runGhcT, initGhcMonad, gcatch, gbracket, gfinally, printException, handleSourceError, needsTemplateHaskellOrQQ, -- * Flags and settings DynFlags(..), GeneralFlag(..), Severity(..), HscTarget(..), gopt, GhcMode(..), GhcLink(..), defaultObjectTarget, parseDynamicFlags, getSessionDynFlags, setSessionDynFlags, getProgramDynFlags, setProgramDynFlags, setLogAction, getInteractiveDynFlags, setInteractiveDynFlags, -- * Targets Target(..), TargetId(..), Phase, setTargets, getTargets, addTarget, removeTarget, guessTarget, -- * Loading\/compiling the program depanal, load, LoadHowMuch(..), InteractiveImport(..), SuccessFlag(..), succeeded, failed, defaultWarnErrLogger, WarnErrLogger, workingDirectoryChanged, parseModule, typecheckModule, desugarModule, loadModule, ParsedModule(..), TypecheckedModule(..), DesugaredModule(..), TypecheckedSource, ParsedSource, RenamedSource, -- ditto TypecheckedMod, ParsedMod, moduleInfo, renamedSource, typecheckedSource, parsedSource, coreModule, -- ** Compiling to Core CoreModule(..), compileToCoreModule, compileToCoreSimplified, -- * Inspecting the module structure of the program ModuleGraph, emptyMG, mapMG, mkModuleGraph, mgModSummaries, mgLookupModule, ModSummary(..), ms_mod_name, ModLocation(..), getModSummary, getModuleGraph, isLoaded, topSortModuleGraph, -- * Inspecting modules ModuleInfo, getModuleInfo, modInfoTyThings, modInfoTopLevelScope, modInfoExports, modInfoExportsWithSelectors, modInfoInstances, modInfoIsExportedName, modInfoLookupName, modInfoIface, modInfoSafe, lookupGlobalName, findGlobalAnns, mkPrintUnqualifiedForModule, ModIface(..), SafeHaskellMode(..), -- * Querying the environment -- packageDbModules, -- * Printing PrintUnqualified, alwaysQualify, -- * Interactive evaluation -- ** Executing statements execStmt, ExecOptions(..), execOptions, ExecResult(..), resumeExec, -- ** Adding new declarations runDecls, runDeclsWithLocation, -- ** Get/set the current context parseImportDecl, setContext, getContext, setGHCiMonad, getGHCiMonad, -- ** Inspecting the current context getBindings, getInsts, getPrintUnqual, findModule, lookupModule, isModuleTrusted, moduleTrustReqs, getNamesInScope, getRdrNamesInScope, getGRE, moduleIsInterpreted, getInfo, showModule, moduleIsBootOrNotObjectLinkable, getNameToInstancesIndex, -- ** Inspecting types and kinds exprType, TcRnExprMode(..), typeKind, -- ** Looking up a Name parseName, lookupName, -- ** Compiling expressions HValue, parseExpr, compileParsedExpr, InteractiveEval.compileExpr, dynCompileExpr, ForeignHValue, compileExprRemote, compileParsedExprRemote, -- ** Other runTcInteractive, -- Desired by some clients (Trac #8878) isStmt, hasImport, isImport, isDecl, -- ** The debugger SingleStep(..), Resume(..), History(historyBreakInfo, historyEnclosingDecls), GHC.getHistorySpan, getHistoryModule, abandon, abandonAll, getResumeContext, GHC.obtainTermFromId, GHC.obtainTermFromVal, reconstructType, modInfoModBreaks, ModBreaks(..), BreakIndex, BreakInfo(breakInfo_number, breakInfo_module), InteractiveEval.back, InteractiveEval.forward, -- * Abstract syntax elements -- ** Packages UnitId, -- ** Modules Module, mkModule, pprModule, moduleName, moduleUnitId, ModuleName, mkModuleName, moduleNameString, -- ** Names Name, isExternalName, nameModule, pprParenSymName, nameSrcSpan, NamedThing(..), RdrName(Qual,Unqual), -- ** Identifiers Id, idType, isImplicitId, isDeadBinder, isExportedId, isLocalId, isGlobalId, isRecordSelector, isPrimOpId, isFCallId, isClassOpId_maybe, isDataConWorkId, idDataCon, isBottomingId, isDictonaryId, recordSelectorTyCon, -- ** Type constructors TyCon, tyConTyVars, tyConDataCons, tyConArity, isClassTyCon, isTypeSynonymTyCon, isTypeFamilyTyCon, isNewTyCon, isPrimTyCon, isFunTyCon, isFamilyTyCon, isOpenFamilyTyCon, isOpenTypeFamilyTyCon, tyConClass_maybe, synTyConRhs_maybe, synTyConDefn_maybe, tyConKind, -- ** Type variables TyVar, alphaTyVars, -- ** Data constructors DataCon, dataConSig, dataConType, dataConTyCon, dataConFieldLabels, dataConIsInfix, isVanillaDataCon, dataConUserType, dataConSrcBangs, StrictnessMark(..), isMarkedStrict, -- ** Classes Class, classMethods, classSCTheta, classTvsFds, classATs, pprFundeps, -- ** Instances ClsInst, instanceDFunId, pprInstance, pprInstanceHdr, pprFamInst, FamInst, -- ** Types and Kinds Type, splitForAllTys, funResultTy, pprParendType, pprTypeApp, Kind, PredType, ThetaType, pprForAll, pprThetaArrowTy, -- ** Entities TyThing(..), -- ** Syntax module HsSyn, -- ToDo: remove extraneous bits -- ** Fixities FixityDirection(..), defaultFixity, maxPrecedence, negateFixity, compareFixity, LexicalFixity(..), -- ** Source locations SrcLoc(..), RealSrcLoc, mkSrcLoc, noSrcLoc, srcLocFile, srcLocLine, srcLocCol, SrcSpan(..), RealSrcSpan, mkSrcSpan, srcLocSpan, isGoodSrcSpan, noSrcSpan, srcSpanStart, srcSpanEnd, srcSpanFile, srcSpanStartLine, srcSpanEndLine, srcSpanStartCol, srcSpanEndCol, -- ** Located GenLocated(..), Located, -- *** Constructing Located noLoc, mkGeneralLocated, -- *** Deconstructing Located getLoc, unLoc, -- *** Combining and comparing Located values eqLocated, cmpLocated, combineLocs, addCLoc, leftmost_smallest, leftmost_largest, rightmost, spans, isSubspanOf, -- * Exceptions GhcException(..), showGhcException, -- * Token stream manipulations Token, getTokenStream, getRichTokenStream, showRichTokenStream, addSourceToTokens, -- * Pure interface to the parser parser, -- * API Annotations ApiAnns,AnnKeywordId(..),AnnotationComment(..), getAnnotation, getAndRemoveAnnotation, getAnnotationComments, getAndRemoveAnnotationComments, unicodeAnn, -- * Miscellaneous --sessionHscEnv, cyclicModuleErr, ) where {- ToDo: * inline bits of HscMain here to simplify layering: hscTcExpr, hscStmt. -} #include "HsVersions.h" import GhcPrelude hiding (init) import ByteCodeTypes import InteractiveEval import InteractiveEvalTypes import TcRnDriver ( runTcInteractive ) import GHCi import GHCi.RemoteTypes import PprTyThing ( pprFamInst ) import HscMain import GhcMake import DriverPipeline ( compileOne' ) import GhcMonad import TcRnMonad ( finalSafeMode, fixSafeInstances ) import TcRnTypes import Packages import NameSet import RdrName import HsSyn import Type hiding( typeKind ) import TcType hiding( typeKind ) import Id import TysPrim ( alphaTyVars ) import TyCon import Class import DataCon import Name hiding ( varName ) import Avail import InstEnv import FamInstEnv ( FamInst ) import SrcLoc import CoreSyn import TidyPgm import DriverPhases ( Phase(..), isHaskellSrcFilename ) import Finder import HscTypes import CmdLineParser import DynFlags hiding (WarnReason(..)) import SysTools import Annotations import Module import Panic import Platform import Bag ( listToBag, unitBag ) import ErrUtils import MonadUtils import Util import StringBuffer import Outputable import BasicTypes import Maybes ( expectJust ) import FastString import qualified Parser import Lexer import ApiAnnotation import qualified GHC.LanguageExtensions as LangExt import NameEnv import CoreFVs ( orphNamesOfFamInst ) import FamInstEnv ( famInstEnvElts ) import TcRnDriver import Inst import FamInst import FileCleanup import Data.Foldable import qualified Data.Map.Strict as Map import Data.Set (Set) import qualified Data.Sequence as Seq import System.Directory ( doesFileExist ) import Data.Maybe import Data.List ( find ) import Data.Time import Data.Typeable ( Typeable ) import Data.Word ( Word8 ) import Control.Monad import System.Exit ( exitWith, ExitCode(..) ) import Exception import Data.IORef import System.FilePath -- %************************************************************************ -- %* * -- Initialisation: exception handlers -- %* * -- %************************************************************************ -- | Install some default exception handlers and run the inner computation. -- Unless you want to handle exceptions yourself, you should wrap this around -- the top level of your program. The default handlers output the error -- message(s) to stderr and exit cleanly. defaultErrorHandler :: (ExceptionMonad m) => FatalMessager -> FlushOut -> m a -> m a defaultErrorHandler fm (FlushOut flushOut) inner = -- top-level exception handler: any unrecognised exception is a compiler bug. ghandle (\exception -> liftIO $ do flushOut case fromException exception of -- an IO exception probably isn't our fault, so don't panic Just (ioe :: IOException) -> fatalErrorMsg'' fm (show ioe) _ -> case fromException exception of Just UserInterrupt -> -- Important to let this one propagate out so our -- calling process knows we were interrupted by ^C liftIO $ throwIO UserInterrupt Just StackOverflow -> fatalErrorMsg'' fm "stack overflow: use +RTS -K<size> to increase it" _ -> case fromException exception of Just (ex :: ExitCode) -> liftIO $ throwIO ex _ -> fatalErrorMsg'' fm (show (Panic (show exception))) exitWith (ExitFailure 1) ) $ -- error messages propagated as exceptions handleGhcException (\ge -> liftIO $ do flushOut case ge of Signal _ -> exitWith (ExitFailure 1) _ -> do fatalErrorMsg'' fm (show ge) exitWith (ExitFailure 1) ) $ inner -- | This function is no longer necessary, cleanup is now done by -- runGhc/runGhcT. {-# DEPRECATED defaultCleanupHandler "Cleanup is now done by runGhc/runGhcT" #-} defaultCleanupHandler :: (ExceptionMonad m) => DynFlags -> m a -> m a defaultCleanupHandler _ m = m where _warning_suppression = m `gonException` undefined -- %************************************************************************ -- %* * -- The Ghc Monad -- %* * -- %************************************************************************ -- | Run function for the 'Ghc' monad. -- -- It initialises the GHC session and warnings via 'initGhcMonad'. Each call -- to this function will create a new session which should not be shared among -- several threads. -- -- Any errors not handled inside the 'Ghc' action are propagated as IO -- exceptions. runGhc :: Maybe FilePath -- ^ See argument to 'initGhcMonad'. -> Ghc a -- ^ The action to perform. -> IO a runGhc mb_top_dir ghc = do ref <- newIORef (panic "empty session") let session = Session ref flip unGhc session $ withSignalHandlers $ do -- catch ^C initGhcMonad mb_top_dir withCleanupSession ghc -- | Run function for 'GhcT' monad transformer. -- -- It initialises the GHC session and warnings via 'initGhcMonad'. Each call -- to this function will create a new session which should not be shared among -- several threads. runGhcT :: ExceptionMonad m => Maybe FilePath -- ^ See argument to 'initGhcMonad'. -> GhcT m a -- ^ The action to perform. -> m a runGhcT mb_top_dir ghct = do ref <- liftIO $ newIORef (panic "empty session") let session = Session ref flip unGhcT session $ withSignalHandlers $ do -- catch ^C initGhcMonad mb_top_dir withCleanupSession ghct withCleanupSession :: GhcMonad m => m a -> m a withCleanupSession ghc = ghc `gfinally` cleanup where cleanup = do hsc_env <- getSession let dflags = hsc_dflags hsc_env liftIO $ do cleanTempFiles dflags cleanTempDirs dflags stopIServ hsc_env -- shut down the IServ log_finaliser dflags dflags -- exceptions will be blocked while we clean the temporary files, -- so there shouldn't be any difficulty if we receive further -- signals. -- | Initialise a GHC session. -- -- If you implement a custom 'GhcMonad' you must call this function in the -- monad run function. It will initialise the session variable and clear all -- warnings. -- -- The first argument should point to the directory where GHC's library files -- reside. More precisely, this should be the output of @ghc --print-libdir@ -- of the version of GHC the module using this API is compiled with. For -- portability, you should use the @ghc-paths@ package, available at -- <http://hackage.haskell.org/package/ghc-paths>. initGhcMonad :: GhcMonad m => Maybe FilePath -> m () initGhcMonad mb_top_dir = do { env <- liftIO $ do { mySettings <- initSysTools mb_top_dir ; myLlvmTargets <- initLlvmTargets mb_top_dir ; dflags <- initDynFlags (defaultDynFlags mySettings myLlvmTargets) ; checkBrokenTablesNextToCode dflags ; setUnsafeGlobalDynFlags dflags -- c.f. DynFlags.parseDynamicFlagsFull, which -- creates DynFlags and sets the UnsafeGlobalDynFlags ; newHscEnv dflags } ; setSession env } -- | The binutils linker on ARM emits unnecessary R_ARM_COPY relocations which -- breaks tables-next-to-code in dynamically linked modules. This -- check should be more selective but there is currently no released -- version where this bug is fixed. -- See https://sourceware.org/bugzilla/show_bug.cgi?id=16177 and -- https://ghc.haskell.org/trac/ghc/ticket/4210#comment:29 checkBrokenTablesNextToCode :: MonadIO m => DynFlags -> m () checkBrokenTablesNextToCode dflags = do { broken <- checkBrokenTablesNextToCode' dflags ; when broken $ do { _ <- liftIO $ throwIO $ mkApiErr dflags invalidLdErr ; fail "unsupported linker" } } where invalidLdErr = text "Tables-next-to-code not supported on ARM" <+> text "when using binutils ld (please see:" <+> text "https://sourceware.org/bugzilla/show_bug.cgi?id=16177)" checkBrokenTablesNextToCode' :: MonadIO m => DynFlags -> m Bool checkBrokenTablesNextToCode' dflags | not (isARM arch) = return False | WayDyn `notElem` ways dflags = return False | not (tablesNextToCode dflags) = return False | otherwise = do linkerInfo <- liftIO $ getLinkerInfo dflags case linkerInfo of GnuLD _ -> return True _ -> return False where platform = targetPlatform dflags arch = platformArch platform -- %************************************************************************ -- %* * -- Flags & settings -- %* * -- %************************************************************************ -- $DynFlags -- -- The GHC session maintains two sets of 'DynFlags': -- -- * The "interactive" @DynFlags@, which are used for everything -- related to interactive evaluation, including 'runStmt', -- 'runDecls', 'exprType', 'lookupName' and so on (everything -- under \"Interactive evaluation\" in this module). -- -- * The "program" @DynFlags@, which are used when loading -- whole modules with 'load' -- -- 'setInteractiveDynFlags', 'getInteractiveDynFlags' work with the -- interactive @DynFlags@. -- -- 'setProgramDynFlags', 'getProgramDynFlags' work with the -- program @DynFlags@. -- -- 'setSessionDynFlags' sets both @DynFlags@, and 'getSessionDynFlags' -- retrieves the program @DynFlags@ (for backwards compatibility). -- | Updates both the interactive and program DynFlags in a Session. -- This also reads the package database (unless it has already been -- read), and prepares the compilers knowledge about packages. It can -- be called again to load new packages: just add new package flags to -- (packageFlags dflags). -- -- Returns a list of new packages that may need to be linked in using -- the dynamic linker (see 'linkPackages') as a result of new package -- flags. If you are not doing linking or doing static linking, you -- can ignore the list of packages returned. -- setSessionDynFlags :: GhcMonad m => DynFlags -> m [InstalledUnitId] setSessionDynFlags dflags = do dflags' <- checkNewDynFlags dflags (dflags'', preload) <- liftIO $ initPackages dflags' modifySession $ \h -> h{ hsc_dflags = dflags'' , hsc_IC = (hsc_IC h){ ic_dflags = dflags'' } } invalidateModSummaryCache return preload -- | Sets the program 'DynFlags'. Note: this invalidates the internal -- cached module graph, causing more work to be done the next time -- 'load' is called. setProgramDynFlags :: GhcMonad m => DynFlags -> m [InstalledUnitId] setProgramDynFlags dflags = setProgramDynFlags_ True dflags -- | Set the action taken when the compiler produces a message. This -- can also be accomplished using 'setProgramDynFlags', but using -- 'setLogAction' avoids invalidating the cached module graph. setLogAction :: GhcMonad m => LogAction -> LogFinaliser -> m () setLogAction action finaliser = do dflags' <- getProgramDynFlags void $ setProgramDynFlags_ False $ dflags' { log_action = action , log_finaliser = finaliser } setProgramDynFlags_ :: GhcMonad m => Bool -> DynFlags -> m [InstalledUnitId] setProgramDynFlags_ invalidate_needed dflags = do dflags' <- checkNewDynFlags dflags dflags_prev <- getProgramDynFlags (dflags'', preload) <- if (packageFlagsChanged dflags_prev dflags') then liftIO $ initPackages dflags' else return (dflags', []) modifySession $ \h -> h{ hsc_dflags = dflags'' } when invalidate_needed $ invalidateModSummaryCache return preload -- When changing the DynFlags, we want the changes to apply to future -- loads, but without completely discarding the program. But the -- DynFlags are cached in each ModSummary in the hsc_mod_graph, so -- after a change to DynFlags, the changes would apply to new modules -- but not existing modules; this seems undesirable. -- -- Furthermore, the GHC API client might expect that changing -- log_action would affect future compilation messages, but for those -- modules we have cached ModSummaries for, we'll continue to use the -- old log_action. This is definitely wrong (#7478). -- -- Hence, we invalidate the ModSummary cache after changing the -- DynFlags. We do this by tweaking the date on each ModSummary, so -- that the next downsweep will think that all the files have changed -- and preprocess them again. This won't necessarily cause everything -- to be recompiled, because by the time we check whether we need to -- recopmile a module, we'll have re-summarised the module and have a -- correct ModSummary. -- invalidateModSummaryCache :: GhcMonad m => m () invalidateModSummaryCache = modifySession $ \h -> h { hsc_mod_graph = mapMG inval (hsc_mod_graph h) } where inval ms = ms { ms_hs_date = addUTCTime (-1) (ms_hs_date ms) } -- | Returns the program 'DynFlags'. getProgramDynFlags :: GhcMonad m => m DynFlags getProgramDynFlags = getSessionDynFlags -- | Set the 'DynFlags' used to evaluate interactive expressions. -- Note: this cannot be used for changes to packages. Use -- 'setSessionDynFlags', or 'setProgramDynFlags' and then copy the -- 'pkgState' into the interactive @DynFlags@. setInteractiveDynFlags :: GhcMonad m => DynFlags -> m () setInteractiveDynFlags dflags = do dflags' <- checkNewDynFlags dflags dflags'' <- checkNewInteractiveDynFlags dflags' modifySession $ \h -> h{ hsc_IC = (hsc_IC h) { ic_dflags = dflags'' }} -- | Get the 'DynFlags' used to evaluate interactive expressions. getInteractiveDynFlags :: GhcMonad m => m DynFlags getInteractiveDynFlags = withSession $ \h -> return (ic_dflags (hsc_IC h)) parseDynamicFlags :: MonadIO m => DynFlags -> [Located String] -> m (DynFlags, [Located String], [Warn]) parseDynamicFlags = parseDynamicFlagsCmdLine -- | Checks the set of new DynFlags for possibly erroneous option -- combinations when invoking 'setSessionDynFlags' and friends, and if -- found, returns a fixed copy (if possible). checkNewDynFlags :: MonadIO m => DynFlags -> m DynFlags checkNewDynFlags dflags = do -- See Note [DynFlags consistency] let (dflags', warnings) = makeDynFlagsConsistent dflags liftIO $ handleFlagWarnings dflags (map (Warn NoReason) warnings) return dflags' checkNewInteractiveDynFlags :: MonadIO m => DynFlags -> m DynFlags checkNewInteractiveDynFlags dflags0 = do dflags1 <- if xopt LangExt.StaticPointers dflags0 then do liftIO $ printOrThrowWarnings dflags0 $ listToBag [mkPlainWarnMsg dflags0 interactiveSrcSpan $ text "StaticPointers is not supported in GHCi interactive expressions."] return $ xopt_unset dflags0 LangExt.StaticPointers else return dflags0 return dflags1 -- %************************************************************************ -- %* * -- Setting, getting, and modifying the targets -- %* * -- %************************************************************************ -- ToDo: think about relative vs. absolute file paths. And what -- happens when the current directory changes. -- | Sets the targets for this session. Each target may be a module name -- or a filename. The targets correspond to the set of root modules for -- the program\/library. Unloading the current program is achieved by -- setting the current set of targets to be empty, followed by 'load'. setTargets :: GhcMonad m => [Target] -> m () setTargets targets = modifySession (\h -> h{ hsc_targets = targets }) -- | Returns the current set of targets getTargets :: GhcMonad m => m [Target] getTargets = withSession (return . hsc_targets) -- | Add another target. addTarget :: GhcMonad m => Target -> m () addTarget target = modifySession (\h -> h{ hsc_targets = target : hsc_targets h }) -- | Remove a target removeTarget :: GhcMonad m => TargetId -> m () removeTarget target_id = modifySession (\h -> h{ hsc_targets = filter (hsc_targets h) }) where filter targets = [ t | t@(Target id _ _) <- targets, id /= target_id ] -- | Attempts to guess what Target a string refers to. This function -- implements the @--make@/GHCi command-line syntax for filenames: -- -- - if the string looks like a Haskell source filename, then interpret it -- as such -- -- - if adding a .hs or .lhs suffix yields the name of an existing file, -- then use that -- -- - otherwise interpret the string as a module name -- guessTarget :: GhcMonad m => String -> Maybe Phase -> m Target guessTarget str (Just phase) = return (Target (TargetFile str (Just phase)) True Nothing) guessTarget str Nothing | isHaskellSrcFilename file = return (target (TargetFile file Nothing)) | otherwise = do exists <- liftIO $ doesFileExist hs_file if exists then return (target (TargetFile hs_file Nothing)) else do exists <- liftIO $ doesFileExist lhs_file if exists then return (target (TargetFile lhs_file Nothing)) else do if looksLikeModuleName file then return (target (TargetModule (mkModuleName file))) else do dflags <- getDynFlags liftIO $ throwGhcExceptionIO (ProgramError (showSDoc dflags $ text "target" <+> quotes (text file) <+> text "is not a module name or a source file")) where (file,obj_allowed) | '*':rest <- str = (rest, False) | otherwise = (str, True) hs_file = file <.> "hs" lhs_file = file <.> "lhs" target tid = Target tid obj_allowed Nothing -- | Inform GHC that the working directory has changed. GHC will flush -- its cache of module locations, since it may no longer be valid. -- -- Note: Before changing the working directory make sure all threads running -- in the same session have stopped. If you change the working directory, -- you should also unload the current program (set targets to empty, -- followed by load). workingDirectoryChanged :: GhcMonad m => m () workingDirectoryChanged = withSession $ (liftIO . flushFinderCaches) -- %************************************************************************ -- %* * -- Running phases one at a time -- %* * -- %************************************************************************ class ParsedMod m where modSummary :: m -> ModSummary parsedSource :: m -> ParsedSource class ParsedMod m => TypecheckedMod m where renamedSource :: m -> Maybe RenamedSource typecheckedSource :: m -> TypecheckedSource moduleInfo :: m -> ModuleInfo tm_internals :: m -> (TcGblEnv, ModDetails) -- ToDo: improvements that could be made here: -- if the module succeeded renaming but not typechecking, -- we can still get back the GlobalRdrEnv and exports, so -- perhaps the ModuleInfo should be split up into separate -- fields. class TypecheckedMod m => DesugaredMod m where coreModule :: m -> ModGuts -- | The result of successful parsing. data ParsedModule = ParsedModule { pm_mod_summary :: ModSummary , pm_parsed_source :: ParsedSource , pm_extra_src_files :: [FilePath] , pm_annotations :: ApiAnns } -- See Note [Api annotations] in ApiAnnotation.hs instance ParsedMod ParsedModule where modSummary m = pm_mod_summary m parsedSource m = pm_parsed_source m -- | The result of successful typechecking. It also contains the parser -- result. data TypecheckedModule = TypecheckedModule { tm_parsed_module :: ParsedModule , tm_renamed_source :: Maybe RenamedSource , tm_typechecked_source :: TypecheckedSource , tm_checked_module_info :: ModuleInfo , tm_internals_ :: (TcGblEnv, ModDetails) } instance ParsedMod TypecheckedModule where modSummary m = modSummary (tm_parsed_module m) parsedSource m = parsedSource (tm_parsed_module m) instance TypecheckedMod TypecheckedModule where renamedSource m = tm_renamed_source m typecheckedSource m = tm_typechecked_source m moduleInfo m = tm_checked_module_info m tm_internals m = tm_internals_ m -- | The result of successful desugaring (i.e., translation to core). Also -- contains all the information of a typechecked module. data DesugaredModule = DesugaredModule { dm_typechecked_module :: TypecheckedModule , dm_core_module :: ModGuts } instance ParsedMod DesugaredModule where modSummary m = modSummary (dm_typechecked_module m) parsedSource m = parsedSource (dm_typechecked_module m) instance TypecheckedMod DesugaredModule where renamedSource m = renamedSource (dm_typechecked_module m) typecheckedSource m = typecheckedSource (dm_typechecked_module m) moduleInfo m = moduleInfo (dm_typechecked_module m) tm_internals m = tm_internals_ (dm_typechecked_module m) instance DesugaredMod DesugaredModule where coreModule m = dm_core_module m type ParsedSource = Located (HsModule GhcPs) type RenamedSource = (HsGroup GhcRn, [LImportDecl GhcRn], Maybe [(LIE GhcRn, Avails)], Maybe LHsDocString) type TypecheckedSource = LHsBinds GhcTc -- NOTE: -- - things that aren't in the output of the typechecker right now: -- - the export list -- - the imports -- - type signatures -- - type/data/newtype declarations -- - class declarations -- - instances -- - extra things in the typechecker's output: -- - default methods are turned into top-level decls. -- - dictionary bindings -- | Return the 'ModSummary' of a module with the given name. -- -- The module must be part of the module graph (see 'hsc_mod_graph' and -- 'ModuleGraph'). If this is not the case, this function will throw a -- 'GhcApiError'. -- -- This function ignores boot modules and requires that there is only one -- non-boot module with the given name. getModSummary :: GhcMonad m => ModuleName -> m ModSummary getModSummary mod = do mg <- liftM hsc_mod_graph getSession let mods_by_name = [ ms | ms <- mgModSummaries mg , ms_mod_name ms == mod , not (isBootSummary ms) ] case mods_by_name of [] -> do dflags <- getDynFlags liftIO $ throwIO $ mkApiErr dflags (text "Module not part of module graph") [ms] -> return ms multiple -> do dflags <- getDynFlags liftIO $ throwIO $ mkApiErr dflags (text "getModSummary is ambiguous: " <+> ppr multiple) -- | Parse a module. -- -- Throws a 'SourceError' on parse error. parseModule :: GhcMonad m => ModSummary -> m ParsedModule parseModule ms = do hsc_env <- getSession let hsc_env_tmp = hsc_env { hsc_dflags = ms_hspp_opts ms } hpm <- liftIO $ hscParse hsc_env_tmp ms return (ParsedModule ms (hpm_module hpm) (hpm_src_files hpm) (hpm_annotations hpm)) -- See Note [Api annotations] in ApiAnnotation.hs -- | Typecheck and rename a parsed module. -- -- Throws a 'SourceError' if either fails. typecheckModule :: GhcMonad m => ParsedModule -> m TypecheckedModule typecheckModule pmod = do let ms = modSummary pmod hsc_env <- getSession let hsc_env_tmp = hsc_env { hsc_dflags = ms_hspp_opts ms } (tc_gbl_env, rn_info) <- liftIO $ hscTypecheckRename hsc_env_tmp ms $ HsParsedModule { hpm_module = parsedSource pmod, hpm_src_files = pm_extra_src_files pmod, hpm_annotations = pm_annotations pmod } details <- liftIO $ makeSimpleDetails hsc_env_tmp tc_gbl_env safe <- liftIO $ finalSafeMode (ms_hspp_opts ms) tc_gbl_env return $ TypecheckedModule { tm_internals_ = (tc_gbl_env, details), tm_parsed_module = pmod, tm_renamed_source = rn_info, tm_typechecked_source = tcg_binds tc_gbl_env, tm_checked_module_info = ModuleInfo { minf_type_env = md_types details, minf_exports = md_exports details, minf_rdr_env = Just (tcg_rdr_env tc_gbl_env), minf_instances = fixSafeInstances safe $ md_insts details, minf_iface = Nothing, minf_safe = safe, minf_modBreaks = emptyModBreaks }} -- | Desugar a typechecked module. desugarModule :: GhcMonad m => TypecheckedModule -> m DesugaredModule desugarModule tcm = do let ms = modSummary tcm let (tcg, _) = tm_internals tcm hsc_env <- getSession let hsc_env_tmp = hsc_env { hsc_dflags = ms_hspp_opts ms } guts <- liftIO $ hscDesugar hsc_env_tmp ms tcg return $ DesugaredModule { dm_typechecked_module = tcm, dm_core_module = guts } -- | Load a module. Input doesn't need to be desugared. -- -- A module must be loaded before dependent modules can be typechecked. This -- always includes generating a 'ModIface' and, depending on the -- 'DynFlags.hscTarget', may also include code generation. -- -- This function will always cause recompilation and will always overwrite -- previous compilation results (potentially files on disk). -- loadModule :: (TypecheckedMod mod, GhcMonad m) => mod -> m mod loadModule tcm = do let ms = modSummary tcm let mod = ms_mod_name ms let loc = ms_location ms let (tcg, _details) = tm_internals tcm mb_linkable <- case ms_obj_date ms of Just t | t > ms_hs_date ms -> do l <- liftIO $ findObjectLinkable (ms_mod ms) (ml_obj_file loc) t return (Just l) _otherwise -> return Nothing let source_modified | isNothing mb_linkable = SourceModified | otherwise = SourceUnmodified -- we can't determine stability here -- compile doesn't change the session hsc_env <- getSession mod_info <- liftIO $ compileOne' (Just tcg) Nothing hsc_env ms 1 1 Nothing mb_linkable source_modified modifySession $ \e -> e{ hsc_HPT = addToHpt (hsc_HPT e) mod mod_info } return tcm -- %************************************************************************ -- %* * -- Dealing with Core -- %* * -- %************************************************************************ -- | A CoreModule consists of just the fields of a 'ModGuts' that are needed for -- the 'GHC.compileToCoreModule' interface. data CoreModule = CoreModule { -- | Module name cm_module :: !Module, -- | Type environment for types declared in this module cm_types :: !TypeEnv, -- | Declarations cm_binds :: CoreProgram, -- | Safe Haskell mode cm_safe :: SafeHaskellMode } instance Outputable CoreModule where ppr (CoreModule {cm_module = mn, cm_types = te, cm_binds = cb, cm_safe = sf}) = text "%module" <+> ppr mn <+> parens (ppr sf) <+> ppr te $$ vcat (map ppr cb) -- | This is the way to get access to the Core bindings corresponding -- to a module. 'compileToCore' parses, typechecks, and -- desugars the module, then returns the resulting Core module (consisting of -- the module name, type declarations, and function declarations) if -- successful. compileToCoreModule :: GhcMonad m => FilePath -> m CoreModule compileToCoreModule = compileCore False -- | Like compileToCoreModule, but invokes the simplifier, so -- as to return simplified and tidied Core. compileToCoreSimplified :: GhcMonad m => FilePath -> m CoreModule compileToCoreSimplified = compileCore True compileCore :: GhcMonad m => Bool -> FilePath -> m CoreModule compileCore simplify fn = do -- First, set the target to the desired filename target <- guessTarget fn Nothing addTarget target _ <- load LoadAllTargets -- Then find dependencies modGraph <- depanal [] True case find ((== fn) . msHsFilePath) (mgModSummaries modGraph) of Just modSummary -> do -- Now we have the module name; -- parse, typecheck and desugar the module (tcg, mod_guts) <- -- TODO: space leaky: call hsc* directly? do tm <- typecheckModule =<< parseModule modSummary let tcg = fst (tm_internals tm) (,) tcg . coreModule <$> desugarModule tm liftM (gutsToCoreModule (mg_safe_haskell mod_guts)) $ if simplify then do -- If simplify is true: simplify (hscSimplify), then tidy -- (tidyProgram). hsc_env <- getSession simpl_guts <- liftIO $ do plugins <- readIORef (tcg_th_coreplugins tcg) hscSimplify hsc_env plugins mod_guts tidy_guts <- liftIO $ tidyProgram hsc_env simpl_guts return $ Left tidy_guts else return $ Right mod_guts Nothing -> panic "compileToCoreModule: target FilePath not found in\ module dependency graph" where -- two versions, based on whether we simplify (thus run tidyProgram, -- which returns a (CgGuts, ModDetails) pair, or not (in which case -- we just have a ModGuts. gutsToCoreModule :: SafeHaskellMode -> Either (CgGuts, ModDetails) ModGuts -> CoreModule gutsToCoreModule safe_mode (Left (cg, md)) = CoreModule { cm_module = cg_module cg, cm_types = md_types md, cm_binds = cg_binds cg, cm_safe = safe_mode } gutsToCoreModule safe_mode (Right mg) = CoreModule { cm_module = mg_module mg, cm_types = typeEnvFromEntities (bindersOfBinds (mg_binds mg)) (mg_tcs mg) (mg_fam_insts mg), cm_binds = mg_binds mg, cm_safe = safe_mode } -- %************************************************************************ -- %* * -- Inspecting the session -- %* * -- %************************************************************************ -- | Get the module dependency graph. getModuleGraph :: GhcMonad m => m ModuleGraph -- ToDo: DiGraph ModSummary getModuleGraph = liftM hsc_mod_graph getSession -- | Return @True@ <==> module is loaded. isLoaded :: GhcMonad m => ModuleName -> m Bool isLoaded m = withSession $ \hsc_env -> return $! isJust (lookupHpt (hsc_HPT hsc_env) m) -- | Return the bindings for the current interactive session. getBindings :: GhcMonad m => m [TyThing] getBindings = withSession $ \hsc_env -> return $ icInScopeTTs $ hsc_IC hsc_env -- | Return the instances for the current interactive session. getInsts :: GhcMonad m => m ([ClsInst], [FamInst]) getInsts = withSession $ \hsc_env -> return $ ic_instances (hsc_IC hsc_env) getPrintUnqual :: GhcMonad m => m PrintUnqualified getPrintUnqual = withSession $ \hsc_env -> return (icPrintUnqual (hsc_dflags hsc_env) (hsc_IC hsc_env)) -- | Container for information about a 'Module'. data ModuleInfo = ModuleInfo { minf_type_env :: TypeEnv, minf_exports :: [AvailInfo], minf_rdr_env :: Maybe GlobalRdrEnv, -- Nothing for a compiled/package mod minf_instances :: [ClsInst], minf_iface :: Maybe ModIface, minf_safe :: SafeHaskellMode, minf_modBreaks :: ModBreaks } -- We don't want HomeModInfo here, because a ModuleInfo applies -- to package modules too. -- | Request information about a loaded 'Module' getModuleInfo :: GhcMonad m => Module -> m (Maybe ModuleInfo) -- XXX: Maybe X getModuleInfo mdl = withSession $ \hsc_env -> do let mg = hsc_mod_graph hsc_env if mgElemModule mg mdl then liftIO $ getHomeModuleInfo hsc_env mdl else do {- if isHomeModule (hsc_dflags hsc_env) mdl then return Nothing else -} liftIO $ getPackageModuleInfo hsc_env mdl -- ToDo: we don't understand what the following comment means. -- (SDM, 19/7/2011) -- getPackageModuleInfo will attempt to find the interface, so -- we don't want to call it for a home module, just in case there -- was a problem loading the module and the interface doesn't -- exist... hence the isHomeModule test here. (ToDo: reinstate) getPackageModuleInfo :: HscEnv -> Module -> IO (Maybe ModuleInfo) getPackageModuleInfo hsc_env mdl = do eps <- hscEPS hsc_env iface <- hscGetModuleInterface hsc_env mdl let avails = mi_exports iface pte = eps_PTE eps tys = [ ty | name <- concatMap availNames avails, Just ty <- [lookupTypeEnv pte name] ] -- return (Just (ModuleInfo { minf_type_env = mkTypeEnv tys, minf_exports = avails, minf_rdr_env = Just $! availsToGlobalRdrEnv (moduleName mdl) avails, minf_instances = error "getModuleInfo: instances for package module unimplemented", minf_iface = Just iface, minf_safe = getSafeMode $ mi_trust iface, minf_modBreaks = emptyModBreaks })) getHomeModuleInfo :: HscEnv -> Module -> IO (Maybe ModuleInfo) getHomeModuleInfo hsc_env mdl = case lookupHpt (hsc_HPT hsc_env) (moduleName mdl) of Nothing -> return Nothing Just hmi -> do let details = hm_details hmi iface = hm_iface hmi return (Just (ModuleInfo { minf_type_env = md_types details, minf_exports = md_exports details, minf_rdr_env = mi_globals $! hm_iface hmi, minf_instances = md_insts details, minf_iface = Just iface, minf_safe = getSafeMode $ mi_trust iface ,minf_modBreaks = getModBreaks hmi })) -- | The list of top-level entities defined in a module modInfoTyThings :: ModuleInfo -> [TyThing] modInfoTyThings minf = typeEnvElts (minf_type_env minf) modInfoTopLevelScope :: ModuleInfo -> Maybe [Name] modInfoTopLevelScope minf = fmap (map gre_name . globalRdrEnvElts) (minf_rdr_env minf) modInfoExports :: ModuleInfo -> [Name] modInfoExports minf = concatMap availNames $! minf_exports minf modInfoExportsWithSelectors :: ModuleInfo -> [Name] modInfoExportsWithSelectors minf = concatMap availNamesWithSelectors $! minf_exports minf -- | Returns the instances defined by the specified module. -- Warning: currently unimplemented for package modules. modInfoInstances :: ModuleInfo -> [ClsInst] modInfoInstances = minf_instances modInfoIsExportedName :: ModuleInfo -> Name -> Bool modInfoIsExportedName minf name = elemNameSet name (availsToNameSet (minf_exports minf)) mkPrintUnqualifiedForModule :: GhcMonad m => ModuleInfo -> m (Maybe PrintUnqualified) -- XXX: returns a Maybe X mkPrintUnqualifiedForModule minf = withSession $ \hsc_env -> do return (fmap (mkPrintUnqualified (hsc_dflags hsc_env)) (minf_rdr_env minf)) modInfoLookupName :: GhcMonad m => ModuleInfo -> Name -> m (Maybe TyThing) -- XXX: returns a Maybe X modInfoLookupName minf name = withSession $ \hsc_env -> do case lookupTypeEnv (minf_type_env minf) name of Just tyThing -> return (Just tyThing) Nothing -> do eps <- liftIO $ readIORef (hsc_EPS hsc_env) return $! lookupType (hsc_dflags hsc_env) (hsc_HPT hsc_env) (eps_PTE eps) name modInfoIface :: ModuleInfo -> Maybe ModIface modInfoIface = minf_iface -- | Retrieve module safe haskell mode modInfoSafe :: ModuleInfo -> SafeHaskellMode modInfoSafe = minf_safe modInfoModBreaks :: ModuleInfo -> ModBreaks modInfoModBreaks = minf_modBreaks isDictonaryId :: Id -> Bool isDictonaryId id = case tcSplitSigmaTy (idType id) of { (_tvs, _theta, tau) -> isDictTy tau } -- | Looks up a global name: that is, any top-level name in any -- visible module. Unlike 'lookupName', lookupGlobalName does not use -- the interactive context, and therefore does not require a preceding -- 'setContext'. lookupGlobalName :: GhcMonad m => Name -> m (Maybe TyThing) lookupGlobalName name = withSession $ \hsc_env -> do liftIO $ lookupTypeHscEnv hsc_env name findGlobalAnns :: (GhcMonad m, Typeable a) => ([Word8] -> a) -> AnnTarget Name -> m [a] findGlobalAnns deserialize target = withSession $ \hsc_env -> do ann_env <- liftIO $ prepareAnnotations hsc_env Nothing return (findAnns deserialize ann_env target) -- | get the GlobalRdrEnv for a session getGRE :: GhcMonad m => m GlobalRdrEnv getGRE = withSession $ \hsc_env-> return $ ic_rn_gbl_env (hsc_IC hsc_env) -- | Retrieve all type and family instances in the environment, indexed -- by 'Name'. Each name's lists will contain every instance in which that name -- is mentioned in the instance head. getNameToInstancesIndex :: GhcMonad m => [Module] -- ^ visible modules. An orphan instance will be returned if and -- only it is visible from at least one module in the list. -> m (Messages, Maybe (NameEnv ([ClsInst], [FamInst]))) getNameToInstancesIndex visible_mods = do hsc_env <- getSession liftIO $ runTcInteractive hsc_env $ do { loadUnqualIfaces hsc_env (hsc_IC hsc_env) ; InstEnvs {ie_global, ie_local} <- tcGetInstEnvs ; let visible_mods' = mkModuleSet visible_mods ; (pkg_fie, home_fie) <- tcGetFamInstEnvs -- We use Data.Sequence.Seq because we are creating left associated -- mappends. -- cls_index and fam_index below are adapted from TcRnDriver.lookupInsts ; let cls_index = Map.fromListWith mappend [ (n, Seq.singleton ispec) | ispec <- instEnvElts ie_local ++ instEnvElts ie_global , instIsVisible visible_mods' ispec , n <- nameSetElemsStable $ orphNamesOfClsInst ispec ] ; let fam_index = Map.fromListWith mappend [ (n, Seq.singleton fispec) | fispec <- famInstEnvElts home_fie ++ famInstEnvElts pkg_fie , n <- nameSetElemsStable $ orphNamesOfFamInst fispec ] ; return $ mkNameEnv $ [ (nm, (toList clss, toList fams)) | (nm, (clss, fams)) <- Map.toList $ Map.unionWith mappend (fmap (,Seq.empty) cls_index) (fmap (Seq.empty,) fam_index) ] } -- ----------------------------------------------------------------------------- {- ToDo: Move the primary logic here to compiler/main/Packages.hs -- | Return all /external/ modules available in the package database. -- Modules from the current session (i.e., from the 'HomePackageTable') are -- not included. This includes module names which are reexported by packages. packageDbModules :: GhcMonad m => Bool -- ^ Only consider exposed packages. -> m [Module] packageDbModules only_exposed = do dflags <- getSessionDynFlags let pkgs = eltsUFM (pkgIdMap (pkgState dflags)) return $ [ mkModule pid modname | p <- pkgs , not only_exposed || exposed p , let pid = packageConfigId p , modname <- exposedModules p ++ map exportName (reexportedModules p) ] -} -- ----------------------------------------------------------------------------- -- Misc exported utils dataConType :: DataCon -> Type dataConType dc = idType (dataConWrapId dc) -- | print a 'NamedThing', adding parentheses if the name is an operator. pprParenSymName :: NamedThing a => a -> SDoc pprParenSymName a = parenSymOcc (getOccName a) (ppr (getName a)) -- ---------------------------------------------------------------------------- -- ToDo: -- - Data and Typeable instances for HsSyn. -- ToDo: check for small transformations that happen to the syntax in -- the typechecker (eg. -e ==> negate e, perhaps for fromIntegral) -- ToDo: maybe use TH syntax instead of IfaceSyn? There's already a way -- to get from TyCons, Ids etc. to TH syntax (reify). -- :browse will use either lm_toplev or inspect lm_interface, depending -- on whether the module is interpreted or not. -- Extract the filename, stringbuffer content and dynflags associed to a module -- -- XXX: Explain pre-conditions getModuleSourceAndFlags :: GhcMonad m => Module -> m (String, StringBuffer, DynFlags) getModuleSourceAndFlags mod = do m <- getModSummary (moduleName mod) case ml_hs_file $ ms_location m of Nothing -> do dflags <- getDynFlags liftIO $ throwIO $ mkApiErr dflags (text "No source available for module " <+> ppr mod) Just sourceFile -> do source <- liftIO $ hGetStringBuffer sourceFile return (sourceFile, source, ms_hspp_opts m) -- | Return module source as token stream, including comments. -- -- The module must be in the module graph and its source must be available. -- Throws a 'HscTypes.SourceError' on parse error. getTokenStream :: GhcMonad m => Module -> m [Located Token] getTokenStream mod = do (sourceFile, source, flags) <- getModuleSourceAndFlags mod let startLoc = mkRealSrcLoc (mkFastString sourceFile) 1 1 case lexTokenStream source startLoc flags of POk _ ts -> return ts PFailed _ span err -> do dflags <- getDynFlags liftIO $ throwIO $ mkSrcErr (unitBag $ mkPlainErrMsg dflags span err) -- | Give even more information on the source than 'getTokenStream' -- This function allows reconstructing the source completely with -- 'showRichTokenStream'. getRichTokenStream :: GhcMonad m => Module -> m [(Located Token, String)] getRichTokenStream mod = do (sourceFile, source, flags) <- getModuleSourceAndFlags mod let startLoc = mkRealSrcLoc (mkFastString sourceFile) 1 1 case lexTokenStream source startLoc flags of POk _ ts -> return $ addSourceToTokens startLoc source ts PFailed _ span err -> do dflags <- getDynFlags liftIO $ throwIO $ mkSrcErr (unitBag $ mkPlainErrMsg dflags span err) -- | Given a source location and a StringBuffer corresponding to this -- location, return a rich token stream with the source associated to the -- tokens. addSourceToTokens :: RealSrcLoc -> StringBuffer -> [Located Token] -> [(Located Token, String)] addSourceToTokens _ _ [] = [] addSourceToTokens loc buf (t@(L span _) : ts) = case span of UnhelpfulSpan _ -> (t,"") : addSourceToTokens loc buf ts RealSrcSpan s -> (t,str) : addSourceToTokens newLoc newBuf ts where (newLoc, newBuf, str) = go "" loc buf start = realSrcSpanStart s end = realSrcSpanEnd s go acc loc buf | loc < start = go acc nLoc nBuf | start <= loc && loc < end = go (ch:acc) nLoc nBuf | otherwise = (loc, buf, reverse acc) where (ch, nBuf) = nextChar buf nLoc = advanceSrcLoc loc ch -- | Take a rich token stream such as produced from 'getRichTokenStream' and -- return source code almost identical to the original code (except for -- insignificant whitespace.) showRichTokenStream :: [(Located Token, String)] -> String showRichTokenStream ts = go startLoc ts "" where sourceFile = getFile $ map (getLoc . fst) ts getFile [] = panic "showRichTokenStream: No source file found" getFile (UnhelpfulSpan _ : xs) = getFile xs getFile (RealSrcSpan s : _) = srcSpanFile s startLoc = mkRealSrcLoc sourceFile 1 1 go _ [] = id go loc ((L span _, str):ts) = case span of UnhelpfulSpan _ -> go loc ts RealSrcSpan s | locLine == tokLine -> ((replicate (tokCol - locCol) ' ') ++) . (str ++) . go tokEnd ts | otherwise -> ((replicate (tokLine - locLine) '\n') ++) . ((replicate (tokCol - 1) ' ') ++) . (str ++) . go tokEnd ts where (locLine, locCol) = (srcLocLine loc, srcLocCol loc) (tokLine, tokCol) = (srcSpanStartLine s, srcSpanStartCol s) tokEnd = realSrcSpanEnd s -- ----------------------------------------------------------------------------- -- Interactive evaluation -- | Takes a 'ModuleName' and possibly a 'UnitId', and consults the -- filesystem and package database to find the corresponding 'Module', -- using the algorithm that is used for an @import@ declaration. findModule :: GhcMonad m => ModuleName -> Maybe FastString -> m Module findModule mod_name maybe_pkg = withSession $ \hsc_env -> do let dflags = hsc_dflags hsc_env this_pkg = thisPackage dflags -- case maybe_pkg of Just pkg | fsToUnitId pkg /= this_pkg && pkg /= fsLit "this" -> liftIO $ do res <- findImportedModule hsc_env mod_name maybe_pkg case res of Found _ m -> return m err -> throwOneError $ noModError dflags noSrcSpan mod_name err _otherwise -> do home <- lookupLoadedHomeModule mod_name case home of Just m -> return m Nothing -> liftIO $ do res <- findImportedModule hsc_env mod_name maybe_pkg case res of Found loc m | moduleUnitId m /= this_pkg -> return m | otherwise -> modNotLoadedError dflags m loc err -> throwOneError $ noModError dflags noSrcSpan mod_name err modNotLoadedError :: DynFlags -> Module -> ModLocation -> IO a modNotLoadedError dflags m loc = throwGhcExceptionIO $ CmdLineError $ showSDoc dflags $ text "module is not loaded:" <+> quotes (ppr (moduleName m)) <+> parens (text (expectJust "modNotLoadedError" (ml_hs_file loc))) -- | Like 'findModule', but differs slightly when the module refers to -- a source file, and the file has not been loaded via 'load'. In -- this case, 'findModule' will throw an error (module not loaded), -- but 'lookupModule' will check to see whether the module can also be -- found in a package, and if so, that package 'Module' will be -- returned. If not, the usual module-not-found error will be thrown. -- lookupModule :: GhcMonad m => ModuleName -> Maybe FastString -> m Module lookupModule mod_name (Just pkg) = findModule mod_name (Just pkg) lookupModule mod_name Nothing = withSession $ \hsc_env -> do home <- lookupLoadedHomeModule mod_name case home of Just m -> return m Nothing -> liftIO $ do res <- findExposedPackageModule hsc_env mod_name Nothing case res of Found _ m -> return m err -> throwOneError $ noModError (hsc_dflags hsc_env) noSrcSpan mod_name err lookupLoadedHomeModule :: GhcMonad m => ModuleName -> m (Maybe Module) lookupLoadedHomeModule mod_name = withSession $ \hsc_env -> case lookupHpt (hsc_HPT hsc_env) mod_name of Just mod_info -> return (Just (mi_module (hm_iface mod_info))) _not_a_home_module -> return Nothing -- | Check that a module is safe to import (according to Safe Haskell). -- -- We return True to indicate the import is safe and False otherwise -- although in the False case an error may be thrown first. isModuleTrusted :: GhcMonad m => Module -> m Bool isModuleTrusted m = withSession $ \hsc_env -> liftIO $ hscCheckSafe hsc_env m noSrcSpan -- | Return if a module is trusted and the pkgs it depends on to be trusted. moduleTrustReqs :: GhcMonad m => Module -> m (Bool, Set InstalledUnitId) moduleTrustReqs m = withSession $ \hsc_env -> liftIO $ hscGetSafe hsc_env m noSrcSpan -- | Set the monad GHCi lifts user statements into. -- -- Checks that a type (in string form) is an instance of the -- @GHC.GHCi.GHCiSandboxIO@ type class. Sets it to be the GHCi monad if it is, -- throws an error otherwise. setGHCiMonad :: GhcMonad m => String -> m () setGHCiMonad name = withSession $ \hsc_env -> do ty <- liftIO $ hscIsGHCiMonad hsc_env name modifySession $ \s -> let ic = (hsc_IC s) { ic_monad = ty } in s { hsc_IC = ic } -- | Get the monad GHCi lifts user statements into. getGHCiMonad :: GhcMonad m => m Name getGHCiMonad = fmap (ic_monad . hsc_IC) getSession getHistorySpan :: GhcMonad m => History -> m SrcSpan getHistorySpan h = withSession $ \hsc_env -> return $ InteractiveEval.getHistorySpan hsc_env h obtainTermFromVal :: GhcMonad m => Int -> Bool -> Type -> a -> m Term obtainTermFromVal bound force ty a = withSession $ \hsc_env -> liftIO $ InteractiveEval.obtainTermFromVal hsc_env bound force ty a obtainTermFromId :: GhcMonad m => Int -> Bool -> Id -> m Term obtainTermFromId bound force id = withSession $ \hsc_env -> liftIO $ InteractiveEval.obtainTermFromId hsc_env bound force id -- | Returns the 'TyThing' for a 'Name'. The 'Name' may refer to any -- entity known to GHC, including 'Name's defined using 'runStmt'. lookupName :: GhcMonad m => Name -> m (Maybe TyThing) lookupName name = withSession $ \hsc_env -> liftIO $ hscTcRcLookupName hsc_env name -- ----------------------------------------------------------------------------- -- Pure API -- | A pure interface to the module parser. -- parser :: String -- ^ Haskell module source text (full Unicode is supported) -> DynFlags -- ^ the flags -> FilePath -- ^ the filename (for source locations) -> (WarningMessages, Either ErrorMessages (Located (HsModule GhcPs))) parser str dflags filename = let loc = mkRealSrcLoc (mkFastString filename) 1 1 buf = stringToStringBuffer str in case unP Parser.parseModule (mkPState dflags buf loc) of PFailed warnFn span err -> let (warns,_) = warnFn dflags in (warns, Left $ unitBag (mkPlainErrMsg dflags span err)) POk pst rdr_module -> let (warns,_) = getMessages pst dflags in (warns, Right rdr_module)
shlevy/ghc
compiler/main/GHC.hs
bsd-3-clause
59,874
4
28
16,211
10,935
5,857
5,078
-1
-1
{-# LANGUAGE Safe #-} ----------------------------------------------------------------------------- -- | -- Module : Text.ParserCombinators.Parsec -- Copyright : (c) Paolo Martini 2007 -- License : BSD-style (see the LICENSE file) -- -- Maintainer : [email protected] -- Stability : provisional -- Portability : portable -- -- Parsec compatibility module -- ----------------------------------------------------------------------------- module Text.ParserCombinators.Parsec ( -- complete modules module Text.ParserCombinators.Parsec.Prim , module Text.ParserCombinators.Parsec.Combinator , module Text.ParserCombinators.Parsec.Char -- module Text.ParserCombinators.Parsec.Error , ParseError , errorPos -- module Text.ParserCombinators.Parsec.Pos , SourcePos , SourceName, Line, Column , sourceName, sourceLine, sourceColumn , incSourceLine, incSourceColumn , setSourceLine, setSourceColumn, setSourceName ) where import Text.Parsec.String() import Text.ParserCombinators.Parsec.Prim import Text.ParserCombinators.Parsec.Combinator import Text.ParserCombinators.Parsec.Char import Text.ParserCombinators.Parsec.Error import Text.ParserCombinators.Parsec.Pos
aslatter/parsec
src/Text/ParserCombinators/Parsec.hs
bsd-2-clause
1,249
0
5
187
136
100
36
19
0
-------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.GL.Antialiasing -- Copyright : (c) Sven Panne 2002-2013 -- License : BSD3 -- -- Maintainer : Sven Panne <[email protected]> -- Stability : stable -- Portability : portable -- -- This module corresponds to section 3.2 (Antialiasing) of the OpenGL 2.1 -- specs. -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.GL.Antialiasing ( sampleBuffers, samples, multisample, subpixelBits ) where import Graphics.Rendering.OpenGL.GL.StateVar import Graphics.Rendering.OpenGL.GL.Capability import Graphics.Rendering.OpenGL.GL.QueryUtils import Graphics.Rendering.OpenGL.Raw -------------------------------------------------------------------------------- sampleBuffers :: GettableStateVar GLsizei sampleBuffers = antialiasingInfo GetSampleBuffers samples :: GettableStateVar GLsizei samples = antialiasingInfo GetSamples multisample :: StateVar Capability multisample = makeCapability CapMultisample subpixelBits :: GettableStateVar GLsizei subpixelBits = antialiasingInfo GetSubpixelBits antialiasingInfo :: GetPName1I p => p -> GettableStateVar GLsizei antialiasingInfo = makeGettableStateVar . getSizei1 id
hesiod/OpenGL
src/Graphics/Rendering/OpenGL/GL/Antialiasing.hs
bsd-3-clause
1,322
0
7
146
164
101
63
16
1
{-# LANGUAGE CPP #-} module Distribution.Solver.Modular.Preference ( avoidReinstalls , deferSetupChoices , deferWeakFlagChoices , enforceManualFlags , enforcePackageConstraints , enforceSingleInstanceRestriction , firstGoal , preferBaseGoalChoice , preferEasyGoalChoices , preferLinked , preferPackagePreferences , preferReallyEasyGoalChoices , requireInstalled ) where -- Reordering or pruning the tree in order to prefer or make certain choices. import qualified Data.List as L import qualified Data.Map as M #if !MIN_VERSION_base(4,8,0) import Data.Monoid import Control.Applicative #endif import Prelude hiding (sequence) import Control.Monad.Reader hiding (sequence) import Data.Map (Map) import Data.Traversable (sequence) import Distribution.Solver.Types.ConstraintSource import Distribution.Solver.Types.InstalledPreference import Distribution.Solver.Types.LabeledPackageConstraint import Distribution.Solver.Types.OptionalStanza import Distribution.Solver.Types.PackageConstraint import Distribution.Solver.Types.PackagePreferences import Distribution.Solver.Modular.Dependency import Distribution.Solver.Modular.Flag import Distribution.Solver.Modular.Package import qualified Distribution.Solver.Modular.PSQ as P import Distribution.Solver.Modular.Tree import Distribution.Solver.Modular.Version import qualified Distribution.Solver.Modular.ConflictSet as CS -- | Generic abstraction for strategies that just rearrange the package order. -- Only packages that match the given predicate are reordered. packageOrderFor :: (PN -> Bool) -> (PN -> I -> I -> Ordering) -> Tree a -> Tree a packageOrderFor p cmp' = trav go where go (PChoiceF v@(Q _ pn) r cs) | p pn = PChoiceF v r (P.sortByKeys (flip (cmp pn)) cs) | otherwise = PChoiceF v r cs go x = x cmp :: PN -> POption -> POption -> Ordering cmp pn (POption i _) (POption i' _) = cmp' pn i i' -- | Prefer to link packages whenever possible preferLinked :: Tree a -> Tree a preferLinked = trav go where go (PChoiceF qn a cs) = PChoiceF qn a (P.sortByKeys cmp cs) go x = x cmp (POption _ linkedTo) (POption _ linkedTo') = cmpL linkedTo linkedTo' cmpL Nothing Nothing = EQ cmpL Nothing (Just _) = GT cmpL (Just _) Nothing = LT cmpL (Just _) (Just _) = EQ -- | Ordering that treats versions satisfying more preferred ranges as greater -- than versions satisfying less preferred ranges. preferredVersionsOrdering :: [VR] -> Ver -> Ver -> Ordering preferredVersionsOrdering vrs v1 v2 = compare (check v1) (check v2) where check v = Prelude.length . Prelude.filter (==True) . Prelude.map (flip checkVR v) $ vrs -- | Traversal that tries to establish package preferences (not constraints). -- Works by reordering choice nodes. Also applies stanza preferences. preferPackagePreferences :: (PN -> PackagePreferences) -> Tree a -> Tree a preferPackagePreferences pcs = preferPackageStanzaPreferences pcs . packageOrderFor (const True) preference where preference pn i1@(I v1 _) i2@(I v2 _) = let PackagePreferences vrs ipref _ = pcs pn in preferredVersionsOrdering vrs v1 v2 `mappend` -- combines lexically locationsOrdering ipref i1 i2 -- Note that we always rank installed before uninstalled, and later -- versions before earlier, but we can change the priority of the -- two orderings. locationsOrdering PreferInstalled v1 v2 = preferInstalledOrdering v1 v2 `mappend` preferLatestOrdering v1 v2 locationsOrdering PreferLatest v1 v2 = preferLatestOrdering v1 v2 `mappend` preferInstalledOrdering v1 v2 -- | Ordering that treats installed instances as greater than uninstalled ones. preferInstalledOrdering :: I -> I -> Ordering preferInstalledOrdering (I _ (Inst _)) (I _ (Inst _)) = EQ preferInstalledOrdering (I _ (Inst _)) _ = GT preferInstalledOrdering _ (I _ (Inst _)) = LT preferInstalledOrdering _ _ = EQ -- | Compare instances by their version numbers. preferLatestOrdering :: I -> I -> Ordering preferLatestOrdering (I v1 _) (I v2 _) = compare v1 v2 -- | Traversal that tries to establish package stanza enable\/disable -- preferences. Works by reordering the branches of stanza choices. preferPackageStanzaPreferences :: (PN -> PackagePreferences) -> Tree a -> Tree a preferPackageStanzaPreferences pcs = trav go where go (SChoiceF qsn@(SN (PI (Q pp pn) _) s) gr _tr ts) | primaryPP pp = let PackagePreferences _ _ spref = pcs pn enableStanzaPref = s `elem` spref -- move True case first to try enabling the stanza ts' | enableStanzaPref = P.sortByKeys (flip compare) ts | otherwise = ts in SChoiceF qsn gr True ts' -- True: now weak choice go x = x -- | Helper function that tries to enforce a single package constraint on a -- given instance for a P-node. Translates the constraint into a -- tree-transformer that either leaves the subtree untouched, or replaces it -- with an appropriate failure node. processPackageConstraintP :: PP -> ConflictSet QPN -> I -> LabeledPackageConstraint -> Tree a -> Tree a processPackageConstraintP pp _ _ (LabeledPackageConstraint _ src) r | src == ConstraintSourceUserTarget && not (primaryPP pp) = r -- the constraints arising from targets, like "foo-1.0" only apply to -- the main packages in the solution, they don't constrain setup deps processPackageConstraintP _ c i (LabeledPackageConstraint pc src) r = go i pc where go (I v _) (PackageConstraintVersion _ vr) | checkVR vr v = r | otherwise = Fail c (GlobalConstraintVersion vr src) go _ (PackageConstraintInstalled _) | instI i = r | otherwise = Fail c (GlobalConstraintInstalled src) go _ (PackageConstraintSource _) | not (instI i) = r | otherwise = Fail c (GlobalConstraintSource src) go _ _ = r -- | Helper function that tries to enforce a single package constraint on a -- given flag setting for an F-node. Translates the constraint into a -- tree-transformer that either leaves the subtree untouched, or replaces it -- with an appropriate failure node. processPackageConstraintF :: Flag -> ConflictSet QPN -> Bool -> LabeledPackageConstraint -> Tree a -> Tree a processPackageConstraintF f c b' (LabeledPackageConstraint pc src) r = go pc where go (PackageConstraintFlags _ fa) = case L.lookup f fa of Nothing -> r Just b | b == b' -> r | otherwise -> Fail c (GlobalConstraintFlag src) go _ = r -- | Helper function that tries to enforce a single package constraint on a -- given flag setting for an F-node. Translates the constraint into a -- tree-transformer that either leaves the subtree untouched, or replaces it -- with an appropriate failure node. processPackageConstraintS :: OptionalStanza -> ConflictSet QPN -> Bool -> LabeledPackageConstraint -> Tree a -> Tree a processPackageConstraintS s c b' (LabeledPackageConstraint pc src) r = go pc where go (PackageConstraintStanzas _ ss) = if not b' && s `elem` ss then Fail c (GlobalConstraintFlag src) else r go _ = r -- | Traversal that tries to establish various kinds of user constraints. Works -- by selectively disabling choices that have been ruled out by global user -- constraints. enforcePackageConstraints :: M.Map PN [LabeledPackageConstraint] -> Tree QGoalReason -> Tree QGoalReason enforcePackageConstraints pcs = trav go where go (PChoiceF qpn@(Q pp pn) gr ts) = let c = varToConflictSet (P qpn) -- compose the transformation functions for each of the relevant constraint g = \ (POption i _) -> foldl (\ h pc -> h . processPackageConstraintP pp c i pc) id (M.findWithDefault [] pn pcs) in PChoiceF qpn gr (P.mapWithKey g ts) go (FChoiceF qfn@(FN (PI (Q _ pn) _) f) gr tr m ts) = let c = varToConflictSet (F qfn) -- compose the transformation functions for each of the relevant constraint g = \ b -> foldl (\ h pc -> h . processPackageConstraintF f c b pc) id (M.findWithDefault [] pn pcs) in FChoiceF qfn gr tr m (P.mapWithKey g ts) go (SChoiceF qsn@(SN (PI (Q _ pn) _) f) gr tr ts) = let c = varToConflictSet (S qsn) -- compose the transformation functions for each of the relevant constraint g = \ b -> foldl (\ h pc -> h . processPackageConstraintS f c b pc) id (M.findWithDefault [] pn pcs) in SChoiceF qsn gr tr (P.mapWithKey g ts) go x = x -- | Transformation that tries to enforce manual flags. Manual flags -- can only be re-set explicitly by the user. This transformation should -- be run after user preferences have been enforced. For manual flags, -- it checks if a user choice has been made. If not, it disables all but -- the first choice. enforceManualFlags :: Tree QGoalReason -> Tree QGoalReason enforceManualFlags = trav go where go (FChoiceF qfn gr tr True ts) = FChoiceF qfn gr tr True $ let c = varToConflictSet (F qfn) in case span isDisabled (P.toList ts) of ([], y : ys) -> P.fromList (y : L.map (\ (b, _) -> (b, Fail c ManualFlag)) ys) _ -> ts -- something has been manually selected, leave things alone where isDisabled (_, Fail _ (GlobalConstraintFlag _)) = True isDisabled _ = False go x = x -- | Require installed packages. requireInstalled :: (PN -> Bool) -> Tree QGoalReason -> Tree QGoalReason requireInstalled p = trav go where go (PChoiceF v@(Q _ pn) gr cs) | p pn = PChoiceF v gr (P.mapWithKey installed cs) | otherwise = PChoiceF v gr cs where installed (POption (I _ (Inst _)) _) x = x installed _ _ = Fail (varToConflictSet (P v)) CannotInstall go x = x -- | Avoid reinstalls. -- -- This is a tricky strategy. If a package version is installed already and the -- same version is available from a repo, the repo version will never be chosen. -- This would result in a reinstall (either destructively, or potentially, -- shadowing). The old instance won't be visible or even present anymore, but -- other packages might have depended on it. -- -- TODO: It would be better to actually check the reverse dependencies of installed -- packages. If they're not depended on, then reinstalling should be fine. Even if -- they are, perhaps this should just result in trying to reinstall those other -- packages as well. However, doing this all neatly in one pass would require to -- change the builder, or at least to change the goal set after building. avoidReinstalls :: (PN -> Bool) -> Tree QGoalReason -> Tree QGoalReason avoidReinstalls p = trav go where go (PChoiceF qpn@(Q _ pn) gr cs) | p pn = PChoiceF qpn gr disableReinstalls | otherwise = PChoiceF qpn gr cs where disableReinstalls = let installed = [ v | (POption (I v (Inst _)) _, _) <- P.toList cs ] in P.mapWithKey (notReinstall installed) cs notReinstall vs (POption (I v InRepo) _) _ | v `elem` vs = Fail (varToConflictSet (P qpn)) CannotReinstall notReinstall _ _ x = x go x = x -- | Always choose the first goal in the list next, abandoning all -- other choices. -- -- This is unnecessary for the default search strategy, because -- it descends only into the first goal choice anyway, -- but may still make sense to just reduce the tree size a bit. firstGoal :: Tree a -> Tree a firstGoal = trav go where go (GoalChoiceF xs) = GoalChoiceF (P.firstOnly xs) go x = x -- Note that we keep empty choice nodes, because they mean success. -- | Transformation that tries to make a decision on base as early as -- possible. In nearly all cases, there's a single choice for the base -- package. Also, fixing base early should lead to better error messages. preferBaseGoalChoice :: Tree a -> Tree a preferBaseGoalChoice = trav go where go (GoalChoiceF xs) = GoalChoiceF (P.preferByKeys isBase xs) go x = x isBase :: Goal QPN -> Bool isBase (Goal (P (Q _pp pn)) _) = unPN pn == "base" isBase _ = False -- | Deal with setup dependencies after regular dependencies, so that we can -- will link setup depencencies against package dependencies when possible deferSetupChoices :: Tree a -> Tree a deferSetupChoices = trav go where go (GoalChoiceF xs) = GoalChoiceF (P.preferByKeys noSetup xs) go x = x noSetup :: Goal QPN -> Bool noSetup (Goal (P (Q (PP _ns (Setup _)) _)) _) = False noSetup _ = True -- | Transformation that tries to avoid making weak flag choices early. -- Weak flags are trivial flags (not influencing dependencies) or such -- flags that are explicitly declared to be weak in the index. deferWeakFlagChoices :: Tree a -> Tree a deferWeakFlagChoices = trav go where go (GoalChoiceF xs) = GoalChoiceF (P.prefer noWeakStanza (P.prefer noWeakFlag xs)) go x = x noWeakStanza :: Tree a -> Bool noWeakStanza (SChoice _ _ True _) = False noWeakStanza _ = True noWeakFlag :: Tree a -> Bool noWeakFlag (FChoice _ _ True _ _) = False noWeakFlag _ = True -- | Transformation that sorts choice nodes so that -- child nodes with a small branching degree are preferred. -- -- Only approximates the number of choices in the branches. -- In particular, we try to take any goal immediately if it has -- a branching degree of 0 (guaranteed failure) or 1 (no other -- choice possible). -- -- Returns at most one choice. -- preferEasyGoalChoices :: Tree a -> Tree a preferEasyGoalChoices = trav go where go (GoalChoiceF xs) = GoalChoiceF (P.dminimumBy dchoices xs) -- (a different implementation that seems slower): -- GoalChoiceF (P.firstOnly (P.preferOrElse zeroOrOneChoices (P.minimumBy choices) xs)) go x = x -- | A variant of 'preferEasyGoalChoices' that just keeps the -- ones with a branching degree of 0 or 1. Note that unlike -- 'preferEasyGoalChoices', this may return more than one -- choice. -- preferReallyEasyGoalChoices :: Tree a -> Tree a preferReallyEasyGoalChoices = trav go where go (GoalChoiceF xs) = GoalChoiceF (P.prefer zeroOrOneChoices xs) go x = x -- | Monad used internally in enforceSingleInstanceRestriction -- -- For each package instance we record the goal for which we picked a concrete -- instance. The SIR means that for any package instance there can only be one. type EnforceSIR = Reader (Map (PI PN) QPN) -- | Enforce ghc's single instance restriction -- -- From the solver's perspective, this means that for any package instance -- (that is, package name + package version) there can be at most one qualified -- goal resolving to that instance (there may be other goals _linking_ to that -- instance however). enforceSingleInstanceRestriction :: Tree QGoalReason -> Tree QGoalReason enforceSingleInstanceRestriction = (`runReader` M.empty) . cata go where go :: TreeF QGoalReason (EnforceSIR (Tree QGoalReason)) -> EnforceSIR (Tree QGoalReason) -- We just verify package choices. go (PChoiceF qpn gr cs) = PChoice qpn gr <$> sequence (P.mapWithKey (goP qpn) cs) go _otherwise = innM _otherwise -- The check proper goP :: QPN -> POption -> EnforceSIR (Tree QGoalReason) -> EnforceSIR (Tree QGoalReason) goP qpn@(Q _ pn) (POption i linkedTo) r = do let inst = PI pn i env <- ask case (linkedTo, M.lookup inst env) of (Just _, _) -> -- For linked nodes we don't check anything r (Nothing, Nothing) -> -- Not linked, not already used local (M.insert inst qpn) r (Nothing, Just qpn') -> do -- Not linked, already used. This is an error return $ Fail (CS.union (varToConflictSet (P qpn)) (varToConflictSet (P qpn'))) MultipleInstances
headprogrammingczar/cabal
cabal-install/Distribution/Solver/Modular/Preference.hs
bsd-3-clause
17,089
0
21
4,730
3,869
1,991
1,878
233
5